Merge remote-tracking branch 'upstream/4.4' into 4.4-master-2014-04-07-15-32-51
[civicrm-core.git] / CRM / Contact / BAO / Query.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035 32 * $Id$
314dbef8 33 *
6a488035
TO
34 */
35
36/**
37 * This class is a heart of search query building mechanism.
38 */
39class CRM_Contact_BAO_Query {
40
41 /**
42 * The various search modes
43 *
44 * @var int
45 */
46 CONST
47 MODE_CONTACTS = 1,
48 MODE_CONTRIBUTE = 2,
49 MODE_MEMBER = 8,
50 MODE_EVENT = 16,
51 MODE_GRANT = 128,
52 MODE_PLEDGEBANK = 256,
53 MODE_PLEDGE = 512,
54 MODE_CASE = 2048,
55 MODE_ALL = 17407,
56 MODE_ACTIVITY = 4096,
57 MODE_CAMPAIGN = 8192,
58 MODE_MAILING = 16384;
59
60 /**
61 * the default set of return properties
62 *
63 * @var array
64 * @static
65 */
66 static $_defaultReturnProperties = NULL;
67
68 /**
69 * the default set of hier return properties
70 *
71 * @var array
72 * @static
73 */
74 static $_defaultHierReturnProperties;
75
76 /**
77 * the set of input params
78 *
79 * @var array
80 */
81 public $_params;
82
83 public $_cfIDs;
84
85 public $_paramLookup;
86
87 /**
88 * the set of output params
89 *
90 * @var array
91 */
92 public $_returnProperties;
93
94 /**
95 * the select clause
96 *
97 * @var array
98 */
99 public $_select;
100
101 /**
102 * the name of the elements that are in the select clause
103 * used to extract the values
104 *
105 * @var array
106 */
107 public $_element;
108
109 /**
110 * the tables involved in the query
111 *
112 * @var array
113 */
114 public $_tables;
115
116 /**
117 * the table involved in the where clause
118 *
119 * @var array
120 */
121 public $_whereTables;
122
123 /**
124 * the where clause
125 *
126 * @var array
127 */
128 public $_where;
129
130 /**
131 * the where string
132 *
133 * @var string
134 *
135 */
136 public $_whereClause;
137
138 /**
139 * additional permission Where Clause
140 *
141 * @var string
142 *
143 */
144 public $_permissionWhereClause;
a30e57e0 145
6a488035
TO
146 /**
147 * the from string
148 *
149 * @var string
150 *
151 */
152 public $_fromClause;
153
154 /**
155 * additional permission from clause
156 *
157 * @var string
158 *
159 */
160 public $_permissionFromClause;
161
162 /**
163 * the from clause for the simple select and alphabetical
164 * select
165 *
166 * @var string
167 */
168 public $_simpleFromClause;
169
170 /**
171 * the having values
172 *
173 * @var string
174 *
175 */
176 public $_having;
177
178 /**
179 * The english language version of the query
180 *
181 * @var array
182 */
183 public $_qill;
184
185 /**
186 * All the fields that could potentially be involved in
187 * this query
188 *
189 * @var array
190 */
191 public $_fields;
192
193 /**
194 * The cache to translate the option values into labels
195 *
196 * @var array
197 */
198 public $_options;
199
200 /**
201 * are we in search mode
202 *
203 * @var boolean
204 */
205 public $_search = TRUE;
206
207 /**
208 * should we skip permission checking
209 *
210 * @var boolean
211 */
212 public $_skipPermission = FALSE;
213
214 /**
215 * should we skip adding of delete clause
216 *
217 * @var boolean
218 */
219 public $_skipDeleteClause = FALSE;
220
221 /**
222 * are we in strict mode (use equality over LIKE)
223 *
224 * @var boolean
225 */
226 public $_strict = FALSE;
227
228 /**
229 * What operator to use to group the clauses
230 *
231 * @var string
232 */
233 public $_operator = 'AND';
234
235 public $_mode = 1;
236
237 /**
238 * Should we only search on primary location
239 *
240 * @var boolean
241 */
242 public $_primaryLocation = TRUE;
243
244 /**
245 * are contact ids part of the query
246 *
247 * @var boolean
248 */
249 public $_includeContactIds = FALSE;
250
251 /**
252 * Should we use the smart group cache
253 *
254 * @var boolean
255 */
256 public $_smartGroupCache = TRUE;
257
258 /**
259 * Should we display contacts with a specific relationship type
260 *
261 * @var string
262 */
263 public $_displayRelationshipType = NULL;
264
265 /**
266 * reference to the query object for custom values
267 *
268 * @var Object
269 */
270 public $_customQuery;
271
272 /**
273 * should we enable the distinct clause, used if we are including
274 * more than one group
275 *
276 * @var boolean
277 */
278 public $_useDistinct = FALSE;
279
280 /**
281 * Should we just display one contact record
282 */
283 public $_useGroupBy = FALSE;
284
285 /**
286 * the relationship type direction
287 *
288 * @var array
289 * @static
290 */
291 static $_relType;
292
293 /**
294 * the activity role
295 *
296 * @var array
297 * @static
298 */
299 static $_activityRole;
300
301 /**
302 * Consider the component activity type
303 * during activity search.
304 *
305 * @var array
306 * @static
307 */
308 static $_considerCompActivities;
309
310 /**
311 * Consider with contact activities only,
312 * during activity search.
313 *
314 * @var array
315 * @static
316 */
317 static $_withContactActivitiesOnly;
318
319 /**
320 * use distinct component clause for component searches
321 *
322 * @var string
323 */
324 public $_distinctComponentClause;
325
3dbf477c
DS
326 public $_rowCountClause;
327
6a488035
TO
328 /**
329 * use groupBy component clause for component searches
330 *
331 * @var string
332 */
333 public $_groupByComponentClause;
334
335 /**
336 * Track open panes, useful in advance search
337 *
338 * @var array
339 * @static
340 */
341 public static $_openedPanes = array();
342
343 /**
344 * The tables which have a dependency on location and/or address
345 *
346 * @var array
347 * @static
348 */
349 static $_dependencies = array(
350 'civicrm_state_province' => 1,
351 'civicrm_country' => 1,
352 'civicrm_county' => 1,
353 'civicrm_address' => 1,
354 'civicrm_location_type' => 1,
355 );
356
357 /**
358 * List of location specific fields
359 */
360 static $_locationSpecificFields = array(
361 'street_address',
362 'street_number',
363 'street_name',
364 'street_unit',
365 'supplemental_address_1',
366 'supplemental_address_2',
367 'city',
368 'postal_code',
369 'postal_code_suffix',
370 'geo_code_1',
371 'geo_code_2',
372 'state_province',
373 'country',
374 'county',
375 'phone',
376 'email',
377 'im',
378 'address_name',
379 );
380
381 /**
382 * Rememeber if we handle either end of a number or date range
383 * so we can skip the other
384 */
385 protected $_rangeCache = array();
d9ab802d
PJ
386 /**
387 * Set to true when $this->relationship is run to avoid adding twice
388 * @var Boolean
389 */
ad682134 390 protected $_relationshipValuesAdded = FALSE;
d9ab802d 391
7c96365b 392 /**
393 * Set to the name of the temp table if one has been created
394 * @var String
395 */
396 static $_relationshipTempTable = NULL;
d9ab802d 397
7c96365b 398 public $_pseudoConstantsSelect = array();
9131c564 399
6a488035
TO
400 /**
401 * class constructor which also does all the work
402 *
403 * @param array $params
404 * @param array $returnProperties
405 * @param array $fields
406 * @param boolean $includeContactIds
407 * @param boolean $strict
408 * @param boolean $mode - mode the search is operating on
409 *
410 * @return Object
411 * @access public
412 */
413 function __construct(
414 $params = NULL, $returnProperties = NULL, $fields = NULL,
415 $includeContactIds = FALSE, $strict = FALSE, $mode = 1,
416 $skipPermission = FALSE, $searchDescendentGroups = TRUE,
417 $smartGroupCache = TRUE, $displayRelationshipType = NULL,
418 $operator = 'AND'
419 ) {
420 $this->_params = &$params;
421 if ($this->_params == NULL) {
422 $this->_params = array();
423 }
424
425 if (empty($returnProperties)) {
426 $this->_returnProperties = self::defaultReturnProperties($mode);
427 }
428 else {
429 $this->_returnProperties = &$returnProperties;
430 }
431
432 $this->_includeContactIds = $includeContactIds;
433 $this->_strict = $strict;
434 $this->_mode = $mode;
435 $this->_skipPermission = $skipPermission;
436 $this->_smartGroupCache = $smartGroupCache;
437 $this->_displayRelationshipType = $displayRelationshipType;
438 $this->setOperator($operator);
439
440 if ($fields) {
441 $this->_fields = &$fields;
442 $this->_search = FALSE;
443 $this->_skipPermission = TRUE;
444 }
445 else {
446 $this->_fields = CRM_Contact_BAO_Contact::exportableFields('All', FALSE, TRUE, TRUE);
447
448 $fields = CRM_Core_Component::getQueryFields();
449 unset($fields['note']);
450 $this->_fields = array_merge($this->_fields, $fields);
451
452 // add activity fields
453 $fields = CRM_Activity_BAO_Activity::exportableFields();
454 $this->_fields = array_merge($this->_fields, $fields);
f2a9b25c 455
99e9587a
DS
456 // add any fields provided by hook implementers
457 $extFields = CRM_Contact_BAO_Query_Hook::singleton()->getFields();
f2a9b25c 458 $this->_fields = array_merge($this->_fields, $extFields);
6a488035
TO
459 }
460
461 // basically do all the work once, and then reuse it
462 $this->initialize();
463 }
464
465 /**
466 * function which actually does all the work for the constructor
467 *
468 * @return void
469 * @access private
470 */
471 function initialize() {
472 $this->_select = array();
473 $this->_element = array();
474 $this->_tables = array();
475 $this->_whereTables = array();
476 $this->_where = array();
477 $this->_qill = array();
478 $this->_options = array();
479 $this->_cfIDs = array();
480 $this->_paramLookup = array();
481 $this->_having = array();
482
483 $this->_customQuery = NULL;
484
485 // reset cached static variables - CRM-5803
486 self::$_activityRole = NULL;
487 self::$_considerCompActivities = NULL;
488 self::$_withContactActivitiesOnly = NULL;
489
490 $this->_select['contact_id'] = 'contact_a.id as contact_id';
491 $this->_element['contact_id'] = 1;
492 $this->_tables['civicrm_contact'] = 1;
493
494 if (!empty($this->_params)) {
495 $this->buildParamsLookup();
496 }
497
498 $this->_whereTables = $this->_tables;
499
500 $this->selectClause();
501 $this->_whereClause = $this->whereClause();
502
503 $this->_fromClause = self::fromClause($this->_tables, NULL, NULL, $this->_primaryLocation, $this->_mode);
504 $this->_simpleFromClause = self::fromClause($this->_whereTables, NULL, NULL, $this->_primaryLocation, $this->_mode);
505
506 $this->openedSearchPanes(TRUE);
507 }
508
509 function buildParamsLookup() {
510 // first fix and handle contact deletion nicely
511 // this code is primarily for search builder use case
512 // where different clauses can specify if they want deleted
513 // contacts or not
514 // CRM-11971
515 $trashParamExists = FALSE;
516 $paramByGroup = array();
517 foreach ( $this->_params as $k => $param ) {
e6f3f602 518 if (!empty($param[0]) && $param[0] == 'contact_is_deleted' ) {
6a488035
TO
519 $trashParamExists = TRUE;
520 }
e6f3f602 521 if (!empty($param[3])) {
522 $paramByGroup[$param[3]][$k] = $param;
523 }
6a488035
TO
524 }
525
526 if ( $trashParamExists ) {
527 $this->_skipDeleteClause = TRUE;
528
529 //cycle through group sets and explicitly add trash param if not set
530 foreach ( $paramByGroup as $setID => $set ) {
531 if (
532 !in_array(array('contact_is_deleted', '=', '1', $setID, '0'), $this->_params) &&
533 !in_array(array('contact_is_deleted', '=', '0', $setID, '0'), $this->_params) ) {
534 $this->_params[] = array(
535 'contact_is_deleted',
536 '=',
537 '0',
538 $setID,
539 '0',
540 );
541 }
542 }
543 }
544
545 foreach ($this->_params as $value) {
a7488080 546 if (empty($value[0])) {
6a488035
TO
547 continue;
548 }
549 $cfID = CRM_Core_BAO_CustomField::getKeyID($value[0]);
550 if ($cfID) {
551 if (!array_key_exists($cfID, $this->_cfIDs)) {
552 $this->_cfIDs[$cfID] = array();
553 }
554 $this->_cfIDs[$cfID][] = $value;
555 }
556
557 if (!array_key_exists($value[0], $this->_paramLookup)) {
558 $this->_paramLookup[$value[0]] = array();
559 }
560 $this->_paramLookup[$value[0]][] = $value;
561 }
562 }
563
564 /**
565 * Some composite fields do not appear in the fields array
566 * hack to make them part of the query
567 *
568 * @return void
569 * @access public
570 */
571 function addSpecialFields() {
572 static $special = array('contact_type', 'contact_sub_type', 'sort_name', 'display_name');
573 foreach ($special as $name) {
a7488080 574 if (!empty($this->_returnProperties[$name])) {
6a488035
TO
575 $this->_select[$name] = "contact_a.{$name} as $name";
576 $this->_element[$name] = 1;
577 }
578 }
579 }
580
581 /**
582 * Given a list of conditions in params and a list of desired
583 * return Properties generate the required select and from
584 * clauses. Note that since the where clause introduces new
585 * tables, the initial attempt also retrieves all variables used
586 * in the params list
587 *
588 * @return void
589 * @access public
590 */
591 function selectClause() {
6a488035
TO
592
593 $this->addSpecialFields();
594
595 foreach ($this->_fields as $name => $field) {
6a488035
TO
596 // skip component fields
597 // there are done by the alter query below
598 // and need not be done on every field
1071730c
DL
599 if (
600 (substr($name, 0, 12) == 'participant_') ||
6a488035
TO
601 (substr($name, 0, 7) == 'pledge_') ||
602 (substr($name, 0, 5) == 'case_')
603 ) {
604 continue;
605 }
606
607 // redirect to activity select clause
608 if (substr($name, 0, 9) == 'activity_') {
609 CRM_Activity_BAO_Query::select($this);
610 continue;
611 }
612
613 // if this is a hierarchical name, we ignore it
614 $names = explode('-', $name);
615 if (count($names > 1) && isset($names[1]) && is_numeric($names[1])) {
616 continue;
617 }
618
c6ff5b0d 619 // make an exception for special cases, to add the field in select clause
fd18baa6 620 $makeException = FALSE;
c6ff5b0d
KJ
621
622 //special handling for groups/tags
623 if (in_array($name, array('groups', 'tags', 'notes'))
fd18baa6
KJ
624 && isset($this->_returnProperties[substr($name, 0, -1)])
625 ) {
626 $makeException = TRUE;
627 }
628
c6ff5b0d
KJ
629 // since note has 3 different options we need special handling
630 // note / note_subject / note_body
631 if ($name == 'notes') {
632 foreach (array('note', 'note_subject', 'note_body') as $noteField) {
633 if (isset($this->_returnProperties[$noteField])) {
634 $makeException = TRUE;
635 break;
636 }
637 }
638 }
a87ba7c0 639
78b80a99 640 if (in_array($name, array('prefix_id', 'suffix_id', 'gender_id'))) {
a87ba7c0 641 if (CRM_Utils_Array::value($field['pseudoconstant']['optionGroupName'], $this->_returnProperties)) {
78b80a99
JHE
642 $makeException = TRUE;
643 }
644 }
645
6a488035 646 $cfID = CRM_Core_BAO_CustomField::getKeyID($name);
8cc574cf 647 if (!empty($this->_paramLookup[$name]) || !empty($this->_returnProperties[$name]) ||
fd18baa6 648 $makeException
6a488035 649 ) {
6a488035
TO
650 if ($cfID) {
651 // add to cfIDs array if not present
652 if (!array_key_exists($cfID, $this->_cfIDs)) {
653 $this->_cfIDs[$cfID] = array();
654 }
655 }
656 elseif (isset($field['where'])) {
657 list($tableName, $fieldName) = explode('.', $field['where'], 2);
658 if (isset($tableName)) {
6a488035
TO
659 if (CRM_Utils_Array::value($tableName, self::$_dependencies)) {
660 $this->_tables['civicrm_address'] = 1;
661 $this->_select['address_id'] = 'civicrm_address.id as address_id';
662 $this->_element['address_id'] = 1;
663 }
664
d9ab802d
PJ
665 if ($tableName == 'im_provider' || $tableName == 'email_greeting' ||
666 $tableName == 'postal_greeting' || $tableName == 'addressee'
6a488035 667 ) {
d9ab802d
PJ
668 if ($tableName == 'im_provider') {
669 CRM_Core_OptionValue::select($this);
670 }
671
672 if (in_array($tableName,
673 array('email_greeting', 'postal_greeting', 'addressee'))) {
674 $this->_element["{$name}_id"] = 1;
675 $this->_select["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
676 $this->_pseudoConstantsSelect[$name] = array('pseudoField' => $tableName, 'idCol' => "{$name}_id");
677 $this->_pseudoConstantsSelect[$name]['select'] = "{$name}.{$fieldName} as $name";
678 $this->_pseudoConstantsSelect[$name]['element'] = $name;
679
680 if ($tableName == 'email_greeting') {
681 $this->_pseudoConstantsSelect[$name]['join'] =
682 " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
683 $this->_pseudoConstantsSelect[$name]['join'] .=
684 " LEFT JOIN civicrm_option_value email_greeting ON (contact_a.email_greeting_id = email_greeting.value AND option_group_email_greeting.id = email_greeting.option_group_id ) ";
685 }
686 elseif ($tableName == 'postal_greeting') {
687 $this->_pseudoConstantsSelect[$name]['join'] =
688 " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
689 $this->_pseudoConstantsSelect[$name]['join'] .=
690 " LEFT JOIN civicrm_option_value postal_greeting ON (contact_a.postal_greeting_id = postal_greeting.value AND option_group_postal_greeting.id = postal_greeting.option_group_id ) ";
691 }
692 elseif ($tableName == 'addressee') {
693 $this->_pseudoConstantsSelect[$name]['join'] =
694 " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
695 $this->_pseudoConstantsSelect[$name]['join'] .=
696 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
697 }
698 $this->_pseudoConstantsSelect[$name]['table'] = $tableName;
699
6a488035
TO
700 //get display
701 $greetField = "{$name}_display";
702 $this->_select[$greetField] = "contact_a.{$greetField} as {$greetField}";
703 $this->_element[$greetField] = 1;
704 //get custom
705 $greetField = "{$name}_custom";
706 $this->_select[$greetField] = "contact_a.{$greetField} as {$greetField}";
707 $this->_element[$greetField] = 1;
708 }
709 }
710 else {
d9ab802d
PJ
711 if (!in_array($tableName, array('civicrm_state_province', 'civicrm_country', 'civicrm_county'))) {
712 $this->_tables[$tableName] = 1;
713 }
6a488035
TO
714
715 // also get the id of the tableName
716 $tName = substr($tableName, 8);
d9ab802d 717 if (in_array($tName, array('country', 'state_province', 'county'))) {
d9ab802d 718 if ($tName == 'state_province') {
7f84f734
EM
719 $this->_pseudoConstantsSelect['state_province_name'] =
720 array('pseudoField' => "{$tName}", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address',
721 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
722
d9ab802d 723 $this->_pseudoConstantsSelect[$tName] =
04ffef8d
CW
724 array('pseudoField' => 'state_province_abbreviation', 'idCol' => "{$tName}_id",
725 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
d9ab802d 726 }
7f84f734
EM
727 else {
728 $this->_pseudoConstantsSelect[$name] =
729 array('pseudoField' => "{$tName}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address',
730 'table' => "civicrm_{$tName}", 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ");
731 }
6a488035 732
d9ab802d
PJ
733 $this->_select["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
734 $this->_element["{$tName}_id"] = 1;
735 }
736 elseif ($tName != 'contact') {
6a488035
TO
737 $this->_select["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
738 $this->_element["{$tName}_id"] = 1;
739 }
740
741 //special case for phone
742 if ($name == 'phone') {
743 $this->_select['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
744 $this->_element['phone_type_id'] = 1;
745 }
746
747 // if IM then select provider_id also
748 // to get "IM Service Provider" in a file to be exported, CRM-3140
749 if ($name == 'im') {
750 $this->_select['provider_id'] = "civicrm_im.provider_id as provider_id";
751 $this->_element['provider_id'] = 1;
752 }
753
d9ab802d 754 if ($tName == 'contact') {
6a488035
TO
755 // special case, when current employer is set for Individual contact
756 if ($fieldName == 'organization_name') {
757 $this->_select[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
758 }
759 elseif ($fieldName != 'id') {
04ffef8d 760 if ($fieldName == 'prefix_id') {
a87ba7c0 761 $this->_pseudoConstantsSelect['individual_prefix'] = array('pseudoField' => 'prefix_id', 'idCol' => "prefix_id", 'bao' => 'CRM_Contact_BAO_Contact');
d9ab802d 762 }
04ffef8d 763 if ($fieldName == 'suffix_id') {
a87ba7c0 764 $this->_pseudoConstantsSelect['individual_suffix'] = array('pseudoField' => 'suffix_id', 'idCol' => "suffix_id", 'bao' => 'CRM_Contact_BAO_Contact');
d9ab802d 765 }
04ffef8d 766 if ($fieldName == 'gender_id') {
a87ba7c0 767 $this->_pseudoConstantsSelect['gender'] = array('pseudoField' => 'gender_id', 'idCol' => "gender_id", 'bao' => 'CRM_Contact_BAO_Contact');
d9ab802d 768 }
aa62b355
OB
769 if ($name == 'communication_style_id') {
770 $this->_pseudoConstantsSelect['communication_style'] = array('pseudoField' => 'communication_style_id', 'idCol' => "communication_style_id", 'bao' => 'CRM_Contact_BAO_Contact');
771 }
6a488035
TO
772 $this->_select[$name] = "contact_a.{$fieldName} as `$name`";
773 }
774 }
4e6490d4
E
775 elseif (in_array($tName, array('country', 'county'))) {
776 $this->_pseudoConstantsSelect[$name]['select'] = "{$field['where']} as `$name`";
777 $this->_pseudoConstantsSelect[$name]['element'] = $name;
778 }
779 elseif ($tName == 'state_province') {
780 $this->_pseudoConstantsSelect[$tName]['select'] = "{$field['where']} as `$name`";
781 $this->_pseudoConstantsSelect[$tName]['element'] = $name;
d9ab802d 782 }
6a488035
TO
783 else {
784 $this->_select[$name] = "{$field['where']} as `$name`";
785 }
d9ab802d
PJ
786 if (!in_array($tName, array('state_province', 'country', 'county'))) {
787 $this->_element[$name] = 1;
788 }
6a488035
TO
789 }
790 }
791 }
792 elseif ($name === 'tags') {
793 $this->_useGroupBy = TRUE;
794 $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
795 $this->_element[$name] = 1;
796 $this->_tables['civicrm_tag'] = 1;
797 $this->_tables['civicrm_entity_tag'] = 1;
798 }
799 elseif ($name === 'groups') {
800 $this->_useGroupBy = TRUE;
801 $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_group.title)) as groups";
802 $this->_element[$name] = 1;
803 $this->_tables['civicrm_group'] = 1;
804 }
805 elseif ($name === 'notes') {
e3199114 806 // if note field is subject then return subject else body of the note
807 $noteColumn = 'note';
808 if (isset($noteField) && $noteField == 'note_subject') {
809 $noteColumn = 'subject';
810 }
811
6a488035 812 $this->_useGroupBy = TRUE;
e3199114 813 $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
6a488035
TO
814 $this->_element[$name] = 1;
815 $this->_tables['civicrm_note'] = 1;
816 }
817 elseif ($name === 'current_employer') {
818 $this->_select[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
819 $this->_element[$name] = 1;
820 }
821 }
822
8cc574cf 823 if ($cfID && !empty($field['is_search_range'])) {
6a488035 824 // this is a custom field with range search enabled, so we better check for two/from values
a7488080 825 if (!empty($this->_paramLookup[$name . '_from'])) {
6a488035
TO
826 if (!array_key_exists($cfID, $this->_cfIDs)) {
827 $this->_cfIDs[$cfID] = array();
828 }
829 foreach ($this->_paramLookup[$name . '_from'] as $pID => $p) {
830 // search in the cdID array for the same grouping
831 $fnd = FALSE;
832 foreach ($this->_cfIDs[$cfID] as $cID => $c) {
833 if ($c[3] == $p[3]) {
834 $this->_cfIDs[$cfID][$cID][2]['from'] = $p[2];
835 $fnd = TRUE;
836 }
837 }
838 if (!$fnd) {
839 $p[2] = array('from' => $p[2]);
840 $this->_cfIDs[$cfID][] = $p;
841 }
842 }
843 }
a7488080 844 if (!empty($this->_paramLookup[$name . '_to'])) {
6a488035
TO
845 if (!array_key_exists($cfID, $this->_cfIDs)) {
846 $this->_cfIDs[$cfID] = array();
847 }
848 foreach ($this->_paramLookup[$name . '_to'] as $pID => $p) {
849 // search in the cdID array for the same grouping
850 $fnd = FALSE;
851 foreach ($this->_cfIDs[$cfID] as $cID => $c) {
852 if ($c[4] == $p[4]) {
853 $this->_cfIDs[$cfID][$cID][2]['to'] = $p[2];
854 $fnd = TRUE;
855 }
856 }
857 if (!$fnd) {
858 $p[2] = array('to' => $p[2]);
859 $this->_cfIDs[$cfID][] = $p;
860 }
861 }
862 }
863 }
864 }
865
866 // add location as hierarchical elements
867 $this->addHierarchicalElements();
868
869 // add multiple field like website
870 $this->addMultipleElements();
871
872 //fix for CRM-951
873 CRM_Core_Component::alterQuery($this, 'select');
874
99e9587a 875 CRM_Contact_BAO_Query_Hook::singleton()->alterSearchQuery($this, 'select');
f2a9b25c 876
6a488035
TO
877 if (!empty($this->_cfIDs)) {
878 $this->_customQuery = new CRM_Core_BAO_CustomQuery($this->_cfIDs, TRUE);
879 $this->_customQuery->query();
880 $this->_select = array_merge($this->_select, $this->_customQuery->_select);
881 $this->_element = array_merge($this->_element, $this->_customQuery->_element);
882 $this->_tables = array_merge($this->_tables, $this->_customQuery->_tables);
883 $this->_whereTables = array_merge($this->_whereTables, $this->_customQuery->_whereTables);
884 $this->_options = $this->_customQuery->_options;
885 }
886 }
887
888 /**
889 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
890 * the return values
891 *
892 * @return void
893 * @access public
894 */
895 function addHierarchicalElements() {
a7488080 896 if (empty($this->_returnProperties['location'])) {
6a488035
TO
897 return;
898 }
899 if (!is_array($this->_returnProperties['location'])) {
900 return;
901 }
902
b2b0530a 903 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
6a488035
TO
904 $processed = array();
905 $index = 0;
906
907 $addressCustomFields = CRM_Core_BAO_CustomField::getFieldsForImport('Address');
908 $addressCustomFieldIds = array();
909
910 foreach ($this->_returnProperties['location'] as $name => $elements) {
911 $lCond = self::getPrimaryCondition($name);
912
913 if (!$lCond) {
914 $locationTypeId = array_search($name, $locationTypes);
915 if ($locationTypeId === FALSE) {
916 continue;
917 }
918 $lCond = "location_type_id = $locationTypeId";
919 $this->_useDistinct = TRUE;
920
921 //commented for CRM-3256
922 $this->_useGroupBy = TRUE;
923 }
924
925 $name = str_replace(' ', '_', $name);
926
927 $tName = "$name-location_type";
928 $ltName = "`$name-location_type`";
929 $this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
930 $this->_select["{$tName}"] = "`$tName`.name as `{$tName}`";
931 $this->_element["{$tName}_id"] = 1;
932 $this->_element["{$tName}"] = 1;
933
934 $locationTypeName = $tName;
935 $locationTypeJoin = array();
936
937 $addAddress = FALSE;
938 $addWhereCount = 0;
939 foreach ($elements as $elementFullName => $dontCare) {
940 $index++;
941 $elementName = $elementCmpName = $elementFullName;
942
943 if (substr($elementCmpName, 0, 5) == 'phone') {
944 $elementCmpName = 'phone';
945 }
946
947 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
948 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($elementCmpName)) {
949 $addressCustomFieldIds[$cfID][$name] = 1;
950 }
951 }
952 //add address table only once
953 if ((in_array($elementCmpName, self::$_locationSpecificFields) || !empty($addressCustomFieldIds))
954 && !$addAddress
955 && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))
956 ) {
957 $tName = "$name-address";
958 $aName = "`$name-address`";
959 $this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
960 $this->_element["{$tName}_id"] = 1;
961 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$lCond)";
962 $this->_tables[$tName] = $addressJoin;
963 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
964 $processed[$aName] = 1;
965 $addAddress = TRUE;
966 }
967
968 $cond = $elementType = '';
969 if (strpos($elementName, '-') !== FALSE) {
970 // this is either phone, email or IM
971 list($elementName, $elementType) = explode('-', $elementName);
972
973
974 if (($elementName != 'phone') && ($elementName != 'im')) {
975 $cond = self::getPrimaryCondition($elementType);
976 }
6e7e6dc0
PJ
977 // CRM-13011 : If location type is primary, do not restrict search to the phone
978 // type id - we want the primary phone, regardless of what type it is.
979 // Otherwise, restrict to the specified phone type for the given field.
980 if ((!$cond) && ($elementName == 'phone') && $elements['location_type'] != 'Primary') {
6a488035
TO
981 $cond = "phone_type_id = '$elementType'";
982 }
983 elseif ((!$cond) && ($elementName == 'im')) {
984 // IM service provider id, CRM-3140
985 $cond = "provider_id = '$elementType'";
986 }
987 $elementType = '-' . $elementType;
988 }
989
990 $field = CRM_Utils_Array::value($elementName, $this->_fields);
991
992 // hack for profile, add location id
993 if (!$field) {
994 if ($elementType &&
995 // fix for CRM-882( to handle phone types )
996 !is_numeric($elementType)
997 ) {
998 if (is_numeric($name)) {
999 $field = CRM_Utils_Array::value($elementName . "-Primary$elementType", $this->_fields);
1000 }
1001 else {
1002 $field = CRM_Utils_Array::value($elementName . "-$locationTypeId$elementType", $this->_fields);
1003 }
1004 }
1005 elseif (is_numeric($name)) {
1006 //this for phone type to work
1007 if (in_array($elementName, array('phone', 'phone_ext'))) {
1008 $field = CRM_Utils_Array::value($elementName . "-Primary" . $elementType, $this->_fields);
1009 }
1010 else {
1011 $field = CRM_Utils_Array::value($elementName . "-Primary", $this->_fields);
1012 }
1013 }
1014 else {
1015 //this is for phone type to work for profile edit
1016 if (in_array($elementName, array('phone', 'phone_ext'))) {
1017 $field = CRM_Utils_Array::value($elementName . "-$locationTypeId$elementType", $this->_fields);
1018 }
1019 else {
1020 $field = CRM_Utils_Array::value($elementName . "-$locationTypeId", $this->_fields);
1021 }
1022 }
1023 }
1024
314dbef8 1025 // Check if there is a value, if so also add to where Clause
6a488035
TO
1026 $addWhere = FALSE;
1027 if ($this->_params) {
1028 $nm = $elementName;
1029 if (isset($locationTypeId)) {
1030 $nm .= "-$locationTypeId";
1031 }
1032 if (!is_numeric($elementType)) {
1033 $nm .= "$elementType";
1034 }
1035
1036 foreach ($this->_params as $id => $values) {
8af73472 1037 if ((is_array($values) && $values[0] == $nm) ||
6a488035
TO
1038 (in_array($elementName, array('phone', 'im'))
1039 && (strpos($values[0], $nm) !== FALSE)
1040 )
1041 ) {
1042 $addWhere = TRUE;
1043 $addWhereCount++;
1044 break;
1045 }
1046 }
1047 }
1048
1049 if ($field && isset($field['where'])) {
1050 list($tableName, $fieldName) = explode('.', $field['where'], 2);
d9ab802d
PJ
1051 $pf = substr($tableName, 8);
1052 $tName = $name . '-' . $pf . $elementType;
6a488035 1053 if (isset($tableName)) {
d9ab802d
PJ
1054 if ($tableName == 'civicrm_state_province' || $tableName == 'civicrm_country' || $tableName == 'civicrm_county') {
1055 $this->_select["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1056 }
1057 else {
1058 $this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1059 }
1060
6a488035
TO
1061 $this->_element["{$tName}_id"] = 1;
1062 if (substr($tName, -15) == '-state_province') {
1063 // FIXME: hack to fix CRM-1900
1064 $a = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
1065 'address_format'
1066 );
1067
1068 if (substr_count($a, 'state_province_name') > 0) {
d9ab802d 1069 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"] =
09aefef4 1070 array('pseudoField' => '{$pf}_id', 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address');
d9ab802d 1071 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
6a488035
TO
1072 }
1073 else {
d9ab802d
PJ
1074 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"] =
1075 array('pseudoField' => 'state_province_abbreviation', 'idCol' => "{$tName}_id");
1076 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
6a488035
TO
1077 }
1078 }
1079 else {
1080 if (substr($elementFullName, 0, 2) == 'im') {
1081 $provider = "{$name}-{$elementFullName}-provider_id";
1082 $this->_select[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1083 $this->_element[$provider] = 1;
1084 }
d9ab802d 1085 if ($pf == 'country' || $pf == 'county') {
09aefef4 1086 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"] = array('pseudoField' => "{$pf}_id", 'idCol' => "{$tName}_id", 'bao' => 'CRM_Core_BAO_Address');
d9ab802d
PJ
1087 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1088 }
1089 else {
1090 $this->_select["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1091 }
1092 }
6a488035 1093
d9ab802d
PJ
1094 if (in_array($pf, array('state_province', 'country', 'county'))) {
1095 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1096 }
1097 else {
1098 $this->_element["{$name}-{$elementFullName}"] = 1;
6a488035
TO
1099 }
1100
a7488080 1101 if (empty($processed["`$tName`"])) {
6a488035
TO
1102 $processed["`$tName`"] = 1;
1103 $newName = $tableName . '_' . $index;
1104 switch ($tableName) {
1105 case 'civicrm_phone':
1106 case 'civicrm_email':
1107 case 'civicrm_im':
1108 case 'civicrm_openid':
1109
1110 $this->_tables[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id AND `$tName`.$lCond";
1111 // this special case to add phone type
1112 if ($cond) {
1113 $phoneTypeCondition = " AND `$tName`.$cond ";
1114 //gross hack to pickup corrupted data also, CRM-7603
1115 if (strpos($cond, 'phone_type_id') !== FALSE) {
1116 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1117 }
1118 $this->_tables[$tName] .= $phoneTypeCondition;
1119 }
1120
1121 //build locationType join
1122 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1123
1124 if ($addWhere) {
1125 $this->_whereTables[$tName] = $this->_tables[$tName];
1126 }
1127 break;
1128
1129 case 'civicrm_state_province':
d9ab802d
PJ
1130 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['table'] = $tName;
1131 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['join'] =
1132 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
6a488035
TO
1133 if ($addWhere) {
1134 $this->_whereTables["{$name}-address"] = $addressJoin;
6a488035
TO
1135 }
1136 break;
1137
1138 case 'civicrm_country':
d9ab802d
PJ
1139 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['table'] = $newName;
1140 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['join'] =
1141 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
6a488035
TO
1142 if ($addWhere) {
1143 $this->_whereTables["{$name}-address"] = $addressJoin;
6a488035
TO
1144 }
1145 break;
1146
1147 case 'civicrm_county':
d9ab802d
PJ
1148 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['table'] = $newName;
1149 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['join'] =
1150 "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
6a488035
TO
1151 if ($addWhere) {
1152 $this->_whereTables["{$name}-address"] = $addressJoin;
6a488035
TO
1153 }
1154 break;
1155
1156 default:
1157 if ($addWhere) {
1158 $this->_whereTables["{$name}-address"] = $addressJoin;
1159 }
1160 break;
1161 }
1162 }
1163 }
1164 }
1165 }
1166
1167 // add location type join
1168 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1169 $this->_tables[$locationTypeName] = $ltypeJoin;
1170
1171 // table should be present in $this->_whereTables,
1172 // to add its condition in location type join, CRM-3939.
1173 if ($addWhereCount) {
1174 $locClause = array();
1175 foreach ($this->_whereTables as $tableName => $clause) {
a7488080 1176 if (!empty($locationTypeJoin[$tableName])) {
6a488035
TO
1177 $locClause[] = $locationTypeJoin[$tableName];
1178 }
1179 }
1180
1181 if (!empty($locClause)) {
1182 $this->_whereTables[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1183 }
1184 }
1185 }
1186
1187 if (!empty($addressCustomFieldIds)) {
1188 $cfIDs = $addressCustomFieldIds;
1189 $customQuery = new CRM_Core_BAO_CustomQuery($cfIDs);
1190 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1191 foreach ($locTypeName as $name => $dnc) {
1192 $fieldName = "$name-custom_{$cfID}";
1193 $tName = "$name-address-custom-{$cfID}";
1194 $aName = "`$name-address-custom-{$cfID}`";
1195 $this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1196 $this->_element["{$tName}_id"] = 1;
1197 $this->_select[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1198 $this->_element[$fieldName] = 1;
1199 $this->_tables[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1200 }
1201 }
1202 }
1203 }
1204
1205 /**
1206 * If the return Properties are set in a hierarchy, traverse the hierarchy to get
1207 * the return values
1208 *
1209 * @return void
1210 * @access public
1211 */
1212 function addMultipleElements() {
a7488080 1213 if (empty($this->_returnProperties['website'])) {
6a488035
TO
1214 return;
1215 }
1216 if (!is_array($this->_returnProperties['website'])) {
1217 return;
1218 }
1219
1220 foreach ($this->_returnProperties['website'] as $key => $elements) {
1221 foreach ($elements as $elementFullName => $dontCare) {
1222 $tName = "website-{$key}-{$elementFullName}";
1223 $this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1224 $this->_select["{$tName}"] = "`$tName`.url as `{$tName}`";
1225 $this->_element["{$tName}_id"] = 1;
1226 $this->_element["{$tName}"] = 1;
1227
1228 $type = "website-{$key}-website_type_id";
1229 $this->_select[$type] = "`$tName`.website_type_id as `{$type}`";
1230 $this->_element[$type] = 1;
1231 $this->_tables[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id )";
1232 }
1233 }
1234 }
1235
1236 /**
1237 * generate the query based on what type of query we need
1238 *
1239 * @param boolean $count
1240 * @param boolean $sortByChar
1241 * @param boolean $groupContacts
1242 *
1243 * @return the sql string for that query (this will most likely
1244 * change soon)
1245 * @access public
1246 */
1247 function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE) {
1248 if ($count) {
3dbf477c
DS
1249 if (isset($this->_rowCountClause)) {
1250 $select = "SELECT {$this->_rowCountClause}";
1251 } else if (isset($this->_distinctComponentClause)) {
6a488035
TO
1252 // we add distinct to get the right count for components
1253 // for the more complex result set, we use GROUP BY the same id
1254 // CRM-9630
1255 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} )";
1256 }
1257 else {
1258 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1259 }
1260 $from = $this->_simpleFromClause;
1261 if ($this->_useDistinct) {
1262 $this->_useGroupBy = TRUE;
1263 }
1264 }
1265 elseif ($sortByChar) {
1266 $select = 'SELECT DISTINCT UPPER(LEFT(contact_a.sort_name, 1)) as sort_name';
1267 $from = $this->_simpleFromClause;
1268 }
1269 elseif ($groupContacts) {
1270 $select = 'SELECT contact_a.id as id';
1271 if ($this->_useDistinct) {
1272 $this->_useGroupBy = TRUE;
1273 }
1274 $from = $this->_simpleFromClause;
1275 }
1276 else {
a7488080 1277 if (!empty($this->_paramLookup['group'])) {
6a488035
TO
1278 // make sure there is only one element
1279 // this is used when we are running under smog and need to know
1280 // how the contact was added (CRM-1203)
1281 if ((count($this->_paramLookup['group']) == 1) &&
1282 (count($this->_paramLookup['group'][0][2]) == 1)
1283 ) {
1284 $groups = array_keys($this->_paramLookup['group'][0][2]);
1285 $groupId = $groups[0];
1286
1287 //check if group is saved search
1288 $group = new CRM_Contact_BAO_Group();
1289 $group->id = $groupId;
1290 $group->find(TRUE);
1291
1292 if (!isset($group->saved_search_id)) {
1293 $tbName = "`civicrm_group_contact-{$groupId}`";
1294 $this->_select['group_contact_id'] = "$tbName.id as group_contact_id";
1295 $this->_element['group_contact_id'] = 1;
1296 $this->_select['status'] = "$tbName.status as status";
1297 $this->_element['status'] = 1;
6a488035
TO
1298 }
1299 }
1300 $this->_useGroupBy = TRUE;
1301 }
1302 if ($this->_useDistinct && !isset($this->_distinctComponentClause)) {
1303 if (!($this->_mode & CRM_Contact_BAO_Query::MODE_ACTIVITY)) {
1304 // CRM-5954
1305 $this->_select['contact_id'] = 'contact_a.id as contact_id';
1306 $this->_useDistinct = FALSE;
1307 $this->_useGroupBy = TRUE;
1308 }
1309 }
1310
1311 $select = "SELECT ";
1312 if (isset($this->_distinctComponentClause)) {
1313 $select .= "{$this->_distinctComponentClause}, ";
1314 }
1315 $select .= implode(', ', $this->_select);
1316 $from = $this->_fromClause;
1317 }
1318
1319 $where = '';
1320 if (!empty($this->_whereClause)) {
1321 $where = "WHERE {$this->_whereClause}";
1322 }
1323
1324 $having = '';
1325 if (!empty($this->_having)) {
1326 foreach ($this->_having as $havingsets) {
1327 foreach ($havingsets as $havingset) {
1328 $havingvalue[] = $havingset;
1329 }
1330 }
1331 $having = ' HAVING ' . implode(' AND ', $havingvalue);
1332 }
1333
1334 // if we are doing a transform, do it here
1335 // use the $from, $where and $having to get the contact ID
1336 if ($this->_displayRelationshipType) {
1337 $this->filterRelatedContacts($from, $where, $having);
1338 }
1339
1340 return array($select, $from, $where, $having);
1341 }
1342
1343 function &getWhereValues($name, $grouping) {
1344 $result = NULL;
f4bff68a 1345 foreach ($this->_params as $values) {
6a488035
TO
1346 if ($values[0] == $name && $values[3] == $grouping) {
1347 return $values;
1348 }
1349 }
1350
1351 return $result;
1352 }
1353
1354 static function fixDateValues($relative, &$from, &$to) {
1355 if ($relative) {
1356 list($from, $to) = CRM_Utils_Date::getFromTo($relative, $from, $to);
1357 }
1358 }
1359
1360 static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE) {
1361 $params = array();
1362 if (empty($formValues)) {
1363 return $params;
1364 }
1365
1366 foreach ($formValues as $id => $values) {
1367 if ($id == 'privacy') {
1368 if (is_array($formValues['privacy'])) {
0d8afee2 1369 $op = !empty($formValues['privacy']['do_not_toggle']) ? '=' : '!=';
6a488035
TO
1370 foreach ($formValues['privacy'] as $key => $value) {
1371 if ($value) {
1372 $params[] = array($key, $op, $value, 0, 0);
1373 }
1374 }
1375 }
1376 }
1377 elseif ($id == 'email_on_hold') {
1378 if ($formValues['email_on_hold']['on_hold']) {
1379 $params[] = array('on_hold', '=', $formValues['email_on_hold']['on_hold'], 0, 0);
1380 }
1381 }
1382 elseif (preg_match('/_date_relative$/', $id) ||
1383 $id == 'event_relative' ||
1384 $id == 'case_from_relative' ||
1385 $id == 'case_to_relative'
1386 ) {
1387 if ($id == 'event_relative') {
1388 $fromRange = 'event_start_date_low';
1389 $toRange = 'event_end_date_high';
1390 }
1391 else if ($id == 'case_from_relative') {
1392 $fromRange = 'case_from_start_date_low';
1393 $toRange = 'case_from_start_date_high';
1394 }
1395 else if ($id == 'case_to_relative') {
1396 $fromRange = 'case_to_end_date_low';
1397 $toRange = 'case_to_end_date_high';
1398 }
1399 else {
1400 $dateComponent = explode('_date_relative', $id);
1401 $fromRange = "{$dateComponent[0]}_date_low";
1402 $toRange = "{$dateComponent[0]}_date_high";
1403 }
1404
1405 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1406 CRM_Contact_BAO_Query::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1407 continue;
1408 }
1409 }
1410 else {
1411 $values = CRM_Contact_BAO_Query::fixWhereValues($id, $values, $wildcard, $useEquals);
1412
1413 if (!$values) {
1414 continue;
1415 }
1416 $params[] = $values;
1417 }
1418 }
1419 return $params;
1420 }
1421
1422 static function &fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE) {
1423 // skip a few search variables
1424 static $skipWhere = NULL;
1425 static $arrayValues = NULL;
1426 static $likeNames = NULL;
1427 $result = NULL;
1428
1429 if (CRM_Utils_System::isNull($values)) {
1430 return $result;
1431 }
1432
1433 if (!$skipWhere) {
1434 $skipWhere = array(
1435 'task', 'radio_ts', 'uf_group_id',
1436 'component_mode', 'qfKey', 'operator',
1437 'display_relationship_type',
1438 );
1439 }
1440
1441 if (in_array($id, $skipWhere) ||
1442 substr($id, 0, 4) == '_qf_' ||
1443 substr($id, 0, 7) == 'hidden_'
1444 ) {
1445 return $result;
1446 }
1447
1448 if (!$likeNames) {
1449 $likeNames = array('sort_name', 'email', 'note', 'display_name');
1450 }
1451
1452 // email comes in via advanced search
1453 // so use wildcard always
1454 if ($id == 'email') {
1455 $wildcard = 1;
1456 }
1457
1458 if (!$useEquals && in_array($id, $likeNames)) {
1459 $result = array($id, 'LIKE', $values, 0, 1);
1460 }
1461 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1462 $result = array($id, 'LIKE', $values, 0, 0);
1463 }
1464 elseif ($id == 'group') {
1465 if (is_array($values)) {
1466 foreach ($values as $groupIds => $val) {
1467 $matches = array();
1468 if (preg_match('/-(\d+)$/', $groupIds, $matches)) {
1469 if (strlen($matches[1]) > 0) {
1470 $values[$matches[1]] = 1;
1471 unset($values[$groupIds]);
1472 }
1473 }
1474 }
1475 }
1476 else {
1477 $groupIds = explode(',', $values);
1478 unset($values);
1479 foreach ($groupIds as $groupId) {
1480 $values[$groupId] = 1;
1481 }
1482 }
1483
1484 $result = array($id, 'IN', $values, 0, 0);
1485 }
1486 elseif ($id == 'contact_tags' || $id == 'tag') {
1487 if (!is_array($values)) {
1488 $tagIds = explode(',', $values);
1489 unset($values);
1490 foreach ($tagIds as $tagId) {
1491 $values[$tagId] = 1;
1492 }
1493 }
1494 $result = array($id, 'IN', $values, 0, 0);
1495 }
1496 else {
1497 $result = array($id, '=', $values, 0, $wildcard);
1498 }
1499
1500 return $result;
1501 }
1502
1503 function whereClauseSingle(&$values) {
1504 // do not process custom fields or prefixed contact ids or component params
1505 if (CRM_Core_BAO_CustomField::getKeyID($values[0]) ||
1506 (substr($values[0], 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) ||
1507 (substr($values[0], 0, 13) == 'contribution_') ||
1508 (substr($values[0], 0, 6) == 'event_') ||
1509 (substr($values[0], 0, 12) == 'participant_') ||
1510 (substr($values[0], 0, 7) == 'member_') ||
1511 (substr($values[0], 0, 6) == 'grant_') ||
1512 (substr($values[0], 0, 7) == 'pledge_') ||
289c8051 1513 (substr($values[0], 0, 5) == 'case_') ||
3c53f77e
DL
1514 (substr($values[0], 0, 10) == 'financial_') ||
1515 (substr($values[0], 0, 11) == 'membership_')
6a488035
TO
1516 ) {
1517 return;
1518 }
1519
efa3a566
DS
1520 // skip for hook injected fields / params
1521 $extFields = CRM_Contact_BAO_Query_Hook::singleton()->getFields();
1522 if (array_key_exists($values[0], $extFields)) {
1523 return;
1524 }
1525
6a488035
TO
1526 switch ($values[0]) {
1527 case 'deleted_contacts':
1528 $this->deletedContacts($values);
1529 return;
1530
1531 case 'contact_type':
1532 $this->contactType($values);
1533 return;
1534
1535 case 'contact_sub_type':
1536 $this->contactSubType($values);
1537 return;
1538
1539 case 'group':
6a488035
TO
1540 $this->group($values);
1541 return;
c905b59f 1542
6a488035
TO
1543 case 'group_type':
1544 // so we resolve this into a list of groups & proceed as if they had been
1545 // handed in
1546 list($name, $op, $value, $grouping, $wildcard) = $values;
1547 $values[0] = 'group';
1548 $values[1] = 'IN';
1549 $this->_paramLookup['group'][0][0] ='group';
1550 $this->_paramLookup['group'][0][1] = 'IN';
1551 $this->_paramLookup['group'][0][2] = $values[2] = $this->getGroupsFromTypeCriteria($value);
1552 $this->group($values);
1553 return;
6a488035 1554
c905b59f 1555 // case tag comes from find contacts
6a488035
TO
1556 case 'tag_search':
1557 $this->tagSearch($values);
1558 return;
1559
1560 case 'tag':
1561 case 'contact_tags':
1562 $this->tag($values);
1563 return;
1564
1565 case 'note':
1566 case 'note_body':
1567 case 'note_subject':
1568 $this->notes($values);
1569 return;
1570
1571 case 'uf_user':
1572 $this->ufUser($values);
1573 return;
1574
1575 case 'sort_name':
1576 case 'display_name':
1577 $this->sortName($values);
6a488035
TO
1578 return;
1579
1580 case 'email':
1581 $this->email($values);
1582 return;
1583
1584 case 'phone_numeric':
1585 $this->phone_numeric($values);
1586 return;
1587
1588 case 'phone_phone_type_id':
1589 case 'phone_location_type_id':
1590 $this->phone_option_group($values);
1591 return;
1592
1593 case 'street_address':
1594 $this->street_address($values);
1595 return;
1596
1597 case 'street_number':
1598 $this->street_number($values);
1599 return;
1600
1601 case 'sortByCharacter':
1602 $this->sortByCharacter($values);
1603 return;
1604
1605 case 'location_type':
1606 $this->locationType($values);
1607 return;
1608
1609 case 'county':
1610 $this->county($values);
1611 return;
1612
1613 case 'state_province':
1614 $this->stateProvince($values);
1615 return;
1616
1617 case 'country':
1618 $this->country($values, FALSE);
1619 return;
1620
1621 case 'postal_code':
1622 case 'postal_code_low':
1623 case 'postal_code_high':
1624 $this->postalCode($values);
1625 return;
1626
1627 case 'activity_date':
1628 case 'activity_date_low':
1629 case 'activity_date_high':
1630 case 'activity_role':
1631 case 'activity_status':
1632 case 'activity_subject':
1633 case 'test_activities':
1634 case 'activity_type_id':
3e4a4597 1635 case 'activity_type':
6a488035
TO
1636 case 'activity_survey_id':
1637 case 'activity_tags':
1638 case 'activity_taglist':
1639 case 'activity_test':
6a488035
TO
1640 case 'activity_campaign_id':
1641 case 'activity_engagement_level':
1642 case 'activity_id':
4041c9b6 1643 case 'activity_result':
6a488035
TO
1644 case 'source_contact':
1645 CRM_Activity_BAO_Query::whereClauseSingle($values, $this);
1646 return;
1647
1648 case 'birth_date_low':
1649 case 'birth_date_high':
1650 case 'deceased_date_low':
1651 case 'deceased_date_high':
1652 $this->demographics($values);
1653 return;
1654
1655 case 'log_date_low':
1656 case 'log_date_high':
1657 $this->modifiedDates($values);
1658 return;
1659
1660 case 'changed_by':
1661 $this->changeLog($values);
1662 return;
1663
1664 case 'do_not_phone':
1665 case 'do_not_email':
1666 case 'do_not_mail':
1667 case 'do_not_sms':
1668 case 'do_not_trade':
1669 case 'is_opt_out':
1670 $this->privacy($values);
1671 return;
1672
1673 case 'privacy_options':
1674 $this->privacyOptions($values);
1675 return;
1676
1677 case 'privacy_operator':
1678 case 'privacy_toggle':
1679 // these are handled by privacy options
1680 return;
1681
1682 case 'preferred_communication_method':
1683 $this->preferredCommunication($values);
1684 return;
1685
1686 case 'relation_type_id':
ad682134 1687 case 'relation_start_date_high':
1688 case 'relation_start_date_low':
1689 case 'relation_end_date_high':
1690 case 'relation_end_date_low':
6a488035
TO
1691 case 'relation_target_name':
1692 case 'relation_status':
1693 case 'relation_date_low':
1694 case 'relation_date_high':
7c96365b 1695 $this->relationship($values);
1696 $this->_relationshipValuesAdded = TRUE;
6a488035
TO
1697 return;
1698
1699 case 'task_status_id':
1700 $this->task($values);
1701 return;
1702
1703 case 'task_id':
1704 // since this case is handled with the above
1705 return;
1706
1707 case 'prox_distance':
1708 CRM_Contact_BAO_ProximityQuery::process($this, $values);
1709 return;
1710
1711 case 'prox_street_address':
1712 case 'prox_city':
1713 case 'prox_postal_code':
1714 case 'prox_state_province_id':
1715 case 'prox_country_id':
1716 // handled by the proximity_distance clause
1717 return;
1718
1719 default:
1720 $this->restWhere($values);
1721 return;
1722 }
1723 }
1724
1725 /**
1726 * Given a list of conditions in params generate the required
1727 * where clause
1728 *
1729 * @return void
1730 * @access public
1731 */
1732 function whereClause() {
1733 $this->_where[0] = array();
1734 $this->_qill[0] = array();
1735
6a488035
TO
1736 $this->includeContactIds();
1737 if (!empty($this->_params)) {
6a488035 1738 foreach (array_keys($this->_params) as $id) {
a7488080 1739 if (empty($this->_params[$id][0])) {
6a488035
TO
1740 continue;
1741 }
1742 // check for both id and contact_id
1743 if ($this->_params[$id][0] == 'id' || $this->_params[$id][0] == 'contact_id') {
a7516181
DL
1744 if (
1745 $this->_params[$id][1] == 'IS NULL' ||
6a488035
TO
1746 $this->_params[$id][1] == 'IS NOT NULL'
1747 ) {
1748 $this->_where[0][] = "contact_a.id {$this->_params[$id][1]}";
1749 }
a7516181
DL
1750 elseif (is_array($this->_params[$id][2])) {
1751 $idList = implode("','", $this->_params[$id][2]);
78c0bfc0 1752 //why on earth do they put ' in the middle & not on the outside? We have to assume it's
1753 //to support 'something' so lets add them conditionally to support the api (which is a tested flow
1754 // so if you are looking to alter this check api test results
1755 if(strpos(trim($idList), "'") > 0) {
1756 $idList = "'" . $idList . "'";
1757 }
1758
a7516181
DL
1759 $this->_where[0][] = "contact_a.id IN ({$idList})";
1760 }
6a488035
TO
1761 else {
1762 $this->_where[0][] = "contact_a.id {$this->_params[$id][1]} {$this->_params[$id][2]}";
1763 }
1764 }
1765 else {
1766 $this->whereClauseSingle($this->_params[$id]);
1767 }
1768 }
1769
1770 CRM_Core_Component::alterQuery($this, 'where');
f2a9b25c 1771
99e9587a 1772 CRM_Contact_BAO_Query_Hook::singleton()->alterSearchQuery($this, 'where');
6a488035
TO
1773 }
1774
1775 if ($this->_customQuery) {
1776 // Added following if condition to avoid the wrong value diplay for 'myaccount' / any UF info.
1777 // Hope it wont affect the other part of civicrm.. if it does please remove it.
1778 if (!empty($this->_customQuery->_where)) {
1779 $this->_where = CRM_Utils_Array::crmArrayMerge($this->_where, $this->_customQuery->_where);
1780 }
1781
1782 $this->_qill = CRM_Utils_Array::crmArrayMerge($this->_qill, $this->_customQuery->_qill);
1783 }
1784
1785 $clauses = array();
1786 $andClauses = array();
1787
1788 $validClauses = 0;
1789 if (!empty($this->_where)) {
1790 foreach ($this->_where as $grouping => $values) {
1791 if ($grouping > 0 && !empty($values)) {
1792 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
1793 $validClauses++;
1794 }
1795 }
1796
1797 if (!empty($this->_where[0])) {
1798 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where[0]) . ' ) ';
1799 }
1800 if (!empty($clauses)) {
1801 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
1802 }
1803
1804 if ($validClauses > 1) {
1805 $this->_useDistinct = TRUE;
1806 }
1807 }
1808
1809 return implode(' AND ', $andClauses);
1810 }
1811
1812 function restWhere(&$values) {
1813 $name = CRM_Utils_Array::value(0, $values);
1814 $op = CRM_Utils_Array::value(1, $values);
1815 $value = CRM_Utils_Array::value(2, $values);
1816 $grouping = CRM_Utils_Array::value(3, $values);
1817 $wildcard = CRM_Utils_Array::value(4, $values);
1818
8cc574cf 1819 if (isset($grouping) && empty($this->_where[$grouping])) {
6a488035
TO
1820 $this->_where[$grouping] = array();
1821 }
1822
1823 $multipleFields = array('url');
1824
1825 //check if the location type exits for fields
1826 $lType = '';
1827 $locType = explode('-', $name);
1828
1829 if (!in_array($locType[0], $multipleFields)) {
1830 //add phone type if exists
1831 if (isset($locType[2]) && $locType[2]) {
1832 $locType[2] = CRM_Core_DAO::escapeString($locType[2]);
1833 }
1834 }
1835
1836 $field = CRM_Utils_Array::value($name, $this->_fields);
1837
1838 if (!$field) {
1839 $field = CRM_Utils_Array::value($locType[0], $this->_fields);
1840
1841 if (!$field) {
1842 return;
1843 }
1844 }
1845
1846 $setTables = TRUE;
1847
1848 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
d9ab802d 1849 $locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
6a488035
TO
1850
1851 if (substr($name, 0, 14) === 'state_province') {
1852 if (isset($locType[1]) && is_numeric($locType[1])) {
2e155dbd 1853 $setTables = FALSE;
d9ab802d
PJ
1854 $aName = "{$locationType[$locType[1]]}-address";
1855 $where = "`$aName`.state_province_id";
6a488035
TO
1856 }
1857 else {
d9ab802d 1858 $where = "civicrm_address.state_province_id";
6a488035
TO
1859 }
1860
d9ab802d 1861 $states = CRM_Core_PseudoConstant::stateProvince();
6a488035 1862 if (is_numeric($value)) {
6a488035 1863 $this->_where[$grouping][] = self::buildClause($where, $op, $value, 'Positive');
6a488035
TO
1864 $value = $states[(int ) $value];
1865 }
1866 else {
d9ab802d
PJ
1867 $intVal = CRM_Utils_Array::key($value, $states);
1868 $this->_where[$grouping][] = self::buildClause($where, $op, $intVal, 'Positive');
6a488035
TO
1869 }
1870 if (!$lType) {
1871 $this->_qill[$grouping][] = ts('State') . " $op '$value'";
1872 }
1873 else {
1874 $this->_qill[$grouping][] = ts('State') . " ($lType) $op '$value'";
1875 }
1876 }
1c1a84a2 1877 elseif (!empty($field['pseudoconstant'])) {
1071730c
DL
1878 $this->optionValueQuery(
1879 $name, $op, $value, $grouping,
9df8a11d 1880 CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', $field['name']),
1071730c 1881 $field,
a30e57e0
DL
1882 $field['title'],
1883 'String',
1884 TRUE
1071730c 1885 );
9df8a11d 1886 if ($name == 'gender_id') {
1071730c
DL
1887 self::$_openedPanes[ts('Demographics')] = TRUE;
1888 }
1889 }
6a488035
TO
1890 elseif (substr($name, 0, 7) === 'country') {
1891 if (isset($locType[1]) && is_numeric($locType[1])) {
2e155dbd 1892 $setTables = FALSE;
d9ab802d
PJ
1893 $aName = "{$locationType[$locType[1]]}-address";
1894 $where = "`$aName`.country_id";
6a488035
TO
1895 }
1896 else {
d9ab802d 1897 $where = "civicrm_address.country_id";
6a488035
TO
1898 }
1899
d9ab802d 1900 $countries = CRM_Core_PseudoConstant::country();
6a488035 1901 if (is_numeric($value)) {
6a488035 1902 $this->_where[$grouping][] = self::buildClause($where, $op, $value, 'Positive');
6a488035
TO
1903 $value = $countries[(int ) $value];
1904 }
1905 else {
d9ab802d
PJ
1906 $intVal = CRM_Utils_Array::key($value, $countries);
1907 $this->_where[$grouping][] = self::buildClause($where, $op, $intVal, 'Positive');
6a488035 1908 }
2e155dbd 1909
6a488035
TO
1910 if (!$lType) {
1911 $this->_qill[$grouping][] = ts('Country') . " $op '$value'";
1912 }
1913 else {
1914 $this->_qill[$grouping][] = ts('Country') . " ($lType) $op '$value'";
1915 }
1916 }
1917 elseif (substr($name, 0, 6) === 'county') {
1918 if (isset($locType[1]) && is_numeric($locType[1])) {
2e155dbd 1919 $setTables = FALSE;
d9ab802d
PJ
1920 $aName = "{$locationType[$locType[1]]}-address";
1921 $where = "`$aName`.county_id";
6a488035
TO
1922 }
1923 else {
d9ab802d 1924 $where = "civicrm_address.county_id";
6a488035 1925 }
d9ab802d
PJ
1926
1927 $counties = CRM_Core_PseudoConstant::county();
6a488035 1928 if (is_numeric($value)) {
6a488035 1929 $this->_where[$grouping][] = self::buildClause($where, $op, $value, 'Positive');
6a488035
TO
1930 $value = $counties[(int ) $value];
1931 }
1932 else {
d9ab802d
PJ
1933 $intVal = CRM_Utils_Array::key($value, $counties);
1934 $this->_where[$grouping][] = self::buildClause($where, $op, $intVal, 'Positive');
6a488035
TO
1935 }
1936
1937 if (!$lType) {
1938 $this->_qill[$grouping][] = ts('County') . " $op '$value'";
1939 }
1940 else {
1941 $this->_qill[$grouping][] = ts('County') . " ($lType) $op '$value'";
1942 }
1943 }
1944 elseif ($name === 'world_region') {
9324df01 1945 $field['where'] = 'civicrm_worldregion.id';
6a488035
TO
1946 $this->optionValueQuery(
1947 $name, $op, $value, $grouping,
1948 CRM_Core_PseudoConstant::worldRegion(),
1949 $field,
1950 ts('World Region')
1951 );
1952 }
6a488035
TO
1953 elseif ($name === 'birth_date') {
1954 $date = CRM_Utils_Date::processDate($value);
1955 $this->_where[$grouping][] = self::buildClause("contact_a.{$name}", $op, $date);
1956
1957 if ($date) {
1958 $date = CRM_Utils_Date::customFormat($date);
1959 $this->_qill[$grouping][] = "$field[title] $op \"$date\"";
1960 }
1961 else {
1962 $this->_qill[$grouping][] = "$field[title] $op";
1963 }
1964 self::$_openedPanes[ts('Demographics')] = TRUE;
1965 }
1966 elseif ($name === 'deceased_date') {
1967 $date = CRM_Utils_Date::processDate($value);
1968 $this->_where[$grouping][] = self::buildClause("contact_a.{$name}", $op, $date);
1969 if ($date) {
1970 $date = CRM_Utils_Date::customFormat($date);
1971 $this->_qill[$grouping][] = "$field[title] $op \"$date\"";
1972 }
1973 else {
1974 $this->_qill[$grouping][] = "$field[title] $op";
1975 }
1976 self::$_openedPanes[ts('Demographics')] = TRUE;
1977 }
1978 elseif ($name === 'is_deceased') {
1979 $this->_where[$grouping][] = self::buildClause("contact_a.{$name}", $op, $value);
1980 $this->_qill[$grouping][] = "$field[title] $op \"$value\"";
1981 self::$_openedPanes[ts('Demographics')] = TRUE;
1982 }
1983 elseif ($name === 'contact_id') {
1984 if (is_int($value)) {
1985 $this->_where[$grouping][] = self::buildClause($field['where'], $op, $value);
1986 $this->_qill[$grouping][] = "$field[title] $op $value";
1987 }
1988 }
1989 elseif ($name === 'name') {
1990 $value = $strtolower(CRM_Core_DAO::escapeString($value));
1991 if ($wildcard) {
1992 $value = "%$value%";
1993 $op = 'LIKE';
1994 }
1995 $wc = self::caseImportant($op) ? "LOWER({$field['where']})" : "{$field['where']}";
1996 $this->_where[$grouping][] = self::buildClause($wc, $op, "'$value'");
1997 $this->_qill[$grouping][] = "$field[title] $op \"$value\"";
1998 }
1999 elseif ($name === 'current_employer') {
2000 $value = $strtolower(CRM_Core_DAO::escapeString($value));
2001 if ($wildcard) {
2002 $value = "%$value%";
2003 $op = 'LIKE';
2004 }
2005 $wc = self::caseImportant($op) ? "LOWER(contact_a.organization_name)" : "contact_a.organization_name";
0d77b56a
PJ
2006 $ceWhereClause = self::buildClause($wc, $op,
2007 $value
6a488035 2008 );
0d77b56a
PJ
2009 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2010 $this->_where[$grouping][] = $ceWhereClause;
6a488035
TO
2011 $this->_qill[$grouping][] = "$field[title] $op \"$value\"";
2012 }
2013 elseif ($name === 'email_greeting') {
2014 $filterCondition = array('greeting_type' => 'email_greeting');
2015 $this->optionValueQuery(
2016 $name, $op, $value, $grouping,
2017 CRM_Core_PseudoConstant::greeting($filterCondition),
2018 $field,
2019 ts('Email Greeting')
2020 );
2021 }
2022 elseif ($name === 'postal_greeting') {
2023 $filterCondition = array('greeting_type' => 'postal_greeting');
2024 $this->optionValueQuery(
2025 $name, $op, $value, $grouping,
2026 CRM_Core_PseudoConstant::greeting($filterCondition),
2027 $field,
2028 ts('Postal Greeting')
2029 );
2030 }
2031 elseif ($name === 'addressee') {
2032 $filterCondition = array('greeting_type' => 'addressee');
2033 $this->optionValueQuery(
2034 $name, $op, $value, $grouping,
2035 CRM_Core_PseudoConstant::greeting($filterCondition),
2036 $field,
2037 ts('Addressee')
2038 );
2039 }
2040 elseif (substr($name, 0, 4) === 'url-') {
2041 $tName = 'civicrm_website';
2042 $this->_whereTables[$tName] = $this->_tables[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2043 $value = $strtolower(CRM_Core_DAO::escapeString($value));
2044 if ($wildcard) {
2045 $value = "%$value%";
2046 $op = 'LIKE';
2047 }
2048
2049 $wc = 'civicrm_website.url';
0d77b56a 2050 $this->_where[$grouping][] = $d = self::buildClause($wc, $op, $value);
6a488035
TO
2051 $this->_qill[$grouping][] = "$field[title] $op \"$value\"";
2052 }
2053 elseif ($name === 'contact_is_deleted') {
2054 $this->_where[$grouping][] = self::buildClause("contact_a.is_deleted", $op, $value);
2055 $this->_qill[$grouping][] = "$field[title] $op \"$value\"";
2056 }
2057 else {
2058 // sometime the value is an array, need to investigate and fix
2059 if (is_array($value)) {
2060 CRM_Core_Error::fatal();
2061 }
2062
2063 if (!empty($field['where'])) {
2064 if ($op != 'IN') {
2065 $value = $strtolower($value);
2066 }
2067 if ($wildcard) {
2068 $value = "%$value%";
2069 $op = 'LIKE';
2070 }
2071
2072 if (isset($locType[1]) &&
2073 is_numeric($locType[1])
2074 ) {
2075 $setTables = FALSE;
2076
2077 //get the location name
6a488035
TO
2078 list($tName, $fldName) = self::getLocationTableName($field['where'], $locType);
2079
2080 $where = "`$tName`.$fldName";
2081
2082 $this->_where[$grouping][] = self::buildClause("LOWER($where)", $op, $value);
2083 $this->_whereTables[$tName] = $this->_tables[$tName];
2084 $this->_qill[$grouping][] = "$field[title] $op '$value'";
2085 }
2086 else {
2087 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2088 if ($tableName == 'civicrm_contact') {
2089 $fieldName = "LOWER(contact_a.{$fieldName})";
2090 }
2091 else {
2092 if ($op != 'IN' && !is_numeric($value)) {
2093 $fieldName = "LOWER({$field['where']})";
2094 }
2095 else {
2096 $fieldName = "{$field['where']}";
2097 }
2098 }
2099
2100 $type = NULL;
a7488080 2101 if (!empty($field['type'])) {
6a488035
TO
2102 $type = CRM_Utils_Type::typeToString($field['type']);
2103 }
2104
2105 $this->_where[$grouping][] = self::buildClause($fieldName, $op, $value, $type);
2106 $this->_qill[$grouping][] = "$field[title] $op $value";
2107 }
2108 }
2109 }
2110
2111 if ($setTables && isset($field['where'])) {
2112 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2113 if (isset($tableName)) {
2114 $this->_tables[$tableName] = 1;
2115 $this->_whereTables[$tableName] = 1;
2116 }
2117 }
2118 }
2119
2120
2121 static function getLocationTableName(&$where, &$locType) {
2122 if (isset($locType[1]) && is_numeric($locType[1])) {
2123 list($tbName, $fldName) = explode(".", $where);
2124
2125 //get the location name
b2b0530a 2126 $locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
6a488035
TO
2127 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2128 if (in_array($locType[0], $specialFields)) {
2129 //hack to fix / special handing for phone_ext
2130 if ($locType[0] == 'phone_ext') {
2131 $locType[0] = 'phone';
2132 }
2133 if (isset($locType[2]) && $locType[2]) {
2134 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2135 }
2136 else {
2137 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2138 }
2139 }
2140 elseif (in_array($locType[0],
2141 array(
2142 'address_name', 'street_address', 'supplemental_address_1', 'supplemental_address_2',
2143 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2',
2144 )
2145 )) {
2146 //fix for search by profile with address fields.
2147 $tName = "{$locationType[$locType[1]]}-address";
2148 }
2149 elseif ($locType[0] == 'on_hold') {
2150 $tName = "{$locationType[$locType[1]]}-email";
2151 }
2152 else {
2153 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2154 }
2155 $tName = str_replace(' ', '_', $tName);
2156 return array($tName, $fldName);
2157 }
2158 CRM_Core_Error::fatal();
2159 }
2160
2161 /**
2162 * Given a result dao, extract the values and return that array
2163 *
2164 * @param Object $dao
2165 *
2166 * @return array values for this query
2167 */
2168 function store($dao) {
2169 $value = array();
2170
2171 foreach ($this->_element as $key => $dontCare) {
2172 if (property_exists($dao, $key)) {
2173 if (strpos($key, '-') !== FALSE) {
2174 $values = explode('-', $key);
2175 $lastElement = array_pop($values);
2176 $current = &$value;
2177 $cnt = count($values);
2178 $count = 1;
2179 foreach ($values as $v) {
2180 if (!array_key_exists($v, $current)) {
2181 $current[$v] = array();
2182 }
2183 //bad hack for im_provider
2184 if ($lastElement == 'provider_id') {
2185 if ($count < $cnt) {
2186 $current = &$current[$v];
2187 }
2188 else {
2189 $lastElement = "{$v}_{$lastElement}";
2190 }
2191 }
2192 else {
2193 $current = &$current[$v];
2194 }
2195 $count++;
2196 }
2197
2198 $current[$lastElement] = $dao->$key;
2199 }
2200 else {
2201 $value[$key] = $dao->$key;
2202 }
2203 }
2204 }
2205 return $value;
2206 }
2207
2208 /**
2209 * getter for tables array
2210 *
2211 * @return array
2212 * @access public
2213 */
2214 function tables() {
2215 return $this->_tables;
2216 }
2217
2218 function whereTables() {
2219 return $this->_whereTables;
2220 }
2221
2222 /**
2223 * generate the where clause (used in match contacts and permissions)
2224 *
2225 * @param array $params
2226 * @param array $fields
2227 * @param array $tables
2228 * @param boolean $strict
2229 *
2230 * @return string
2231 * @access public
2232 * @static
2233 */
2234 static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2235 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2236 FALSE, $strict
2237 );
2238
2239 $tables = array_merge($query->tables(), $tables);
2240 $whereTables = array_merge($query->whereTables(), $whereTables);
2241
2242 return $query->_whereClause;
2243 }
2244
2245 /**
2246 * create the from clause
2247 *
2248 * @param array $tables tables that need to be included in this from clause
2249 * if null, return mimimal from clause (i.e. civicrm_contact)
2250 * @param array $inner tables that should be inner-joined
2251 * @param array $right tables that should be right-joined
2252 *
2253 * @return string the from clause
2254 * @access public
2255 * @static
2256 */
2257 static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1) {
2258
2259 $from = ' FROM civicrm_contact contact_a';
2260 if (empty($tables)) {
2261 return $from;
2262 }
2263
a7488080 2264 if (!empty($tables['civicrm_worldregion'])) {
6a488035
TO
2265 $tables = array_merge(array('civicrm_country' => 1), $tables);
2266 }
2267
8cc574cf 2268 if ((!empty($tables['civicrm_state_province']) || !empty($tables['civicrm_country']) ||
6a488035 2269 CRM_Utils_Array::value('civicrm_county', $tables)
8cc574cf 2270 ) && empty($tables['civicrm_address'])) {
6a488035
TO
2271 $tables = array_merge(array('civicrm_address' => 1),
2272 $tables
2273 );
2274 }
2275
2276 // add group_contact table if group table is present
8cc574cf 2277 if (!empty($tables['civicrm_group']) && empty($tables['civicrm_group_contact'])) {
6a488035
TO
2278 $tables['civicrm_group_contact'] = " LEFT JOIN civicrm_group_contact ON civicrm_group_contact.contact_id = contact_a.id AND civicrm_group_contact.status = 'Added'";
2279 }
2280
2281 // add group_contact and group table is subscription history is present
8cc574cf 2282 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
6a488035
TO
2283 $tables = array_merge(array(
2284 'civicrm_group' => 1,
2285 'civicrm_group_contact' => 1,
2286 ),
2287 $tables
2288 );
2289 }
2290
2291 // to handle table dependencies of components
2292 CRM_Core_Component::tableNames($tables);
efa3a566
DS
2293 // to handle table dependencies of hook injected tables
2294 CRM_Contact_BAO_Query_Hook::singleton()->setTableDependency($tables);
6a488035
TO
2295
2296 //format the table list according to the weight
2297 $info = CRM_Core_TableHierarchy::info();
2298
2299 foreach ($tables as $key => $value) {
2300 $k = 99;
2301 if (strpos($key, '-') !== FALSE) {
2302 $keyArray = explode('-', $key);
2303 $k = CRM_Utils_Array::value('civicrm_' . $keyArray[1], $info, 99);
2304 }
2305 elseif (strpos($key, '_') !== FALSE) {
2306 $keyArray = explode('_', $key);
2307 if (is_numeric(array_pop($keyArray))) {
2308 $k = CRM_Utils_Array::value(implode('_', $keyArray), $info, 99);
2309 }
2310 else {
2311 $k = CRM_Utils_Array::value($key, $info, 99);
2312 }
2313 }
2314 else {
2315 $k = CRM_Utils_Array::value($key, $info, 99);
2316 }
2317 $tempTable[$k . ".$key"] = $key;
2318 }
2319 ksort($tempTable);
2320 $newTables = array();
2321 foreach ($tempTable as $key) {
2322 $newTables[$key] = $tables[$key];
2323 }
2324
2325 $tables = $newTables;
2326
2327 foreach ($tables as $name => $value) {
2328 if (!$value) {
2329 continue;
2330 }
2331
a7488080 2332 if (!empty($inner[$name])) {
6a488035
TO
2333 $side = 'INNER';
2334 }
a7488080 2335 elseif (!empty($right[$name])) {
6a488035
TO
2336 $side = 'RIGHT';
2337 }
2338 else {
2339 $side = 'LEFT';
2340 }
2341
2342 if ($value != 1) {
2343 // if there is already a join statement in value, use value itself
2344 if (strpos($value, 'JOIN')) {
2345 $from .= " $value ";
2346 }
2347 else {
2348 $from .= " $side JOIN $name ON ( $value ) ";
2349 }
2350 continue;
2351 }
2352 switch ($name) {
2353 case 'civicrm_address':
2354 if ($primaryLocation) {
2355 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )";
2356 }
2357 else {
2358 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id ) ";
2359 }
2360 continue;
2361
2362 case 'civicrm_phone':
2363 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) ";
2364 continue;
2365
2366 case 'civicrm_email':
2367 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) ";
2368 continue;
2369
2370 case 'civicrm_im':
2371 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) ";
2372 continue;
2373
2374 case 'im_provider':
2375 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2376 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2377 $from .= " $side JOIN civicrm_option_value im_provider ON (civicrm_im.provider_id = im_provider.value AND option_group_imProvider.id = im_provider.option_group_id)";
2378 continue;
2379
2380 case 'civicrm_openid':
2381 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id AND civicrm_openid.is_primary = 1 )";
2382 continue;
2383
6a488035 2384 case 'civicrm_worldregion':
d9ab802d 2385 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
6a488035
TO
2386 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2387 continue;
2388
6a488035
TO
2389 case 'civicrm_location_type':
2390 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2391 continue;
2392
2393 case 'civicrm_group':
2394 $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2395 continue;
2396
2397 case 'civicrm_group_contact':
2398 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2399 continue;
2400
2401 case 'civicrm_activity':
2402 case 'civicrm_activity_tag':
2403 case 'activity_type':
2404 case 'activity_status':
2405 case 'civicrm_activity_contact':
2406 case 'source_contact':
2407 $from .= CRM_Activity_BAO_Query::from($name, $mode, $side);
2408 continue;
2409
2410 case 'civicrm_entity_tag':
2411 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2412 civicrm_entity_tag.entity_id = contact_a.id ) ";
2413 continue;
2414
2415 case 'civicrm_note':
2416 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2417 contact_a.id = civicrm_note.entity_id ) ";
2418 continue;
2419
2420 case 'civicrm_subscription_history':
2421 $from .= " $side JOIN civicrm_subscription_history
2422 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2423 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2424 continue;
2425
6a488035
TO
2426 case 'civicrm_relationship':
2427 if (self::$_relType == 'reciprocal') {
7c96365b 2428 if(self::$_relationshipTempTable) {
2429 // we have a temptable to join on
2430 $tbl = self::$_relationshipTempTable;
2431 $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2432 }
2433 else {
2434 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2435 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id OR civicrm_relationship.contact_id_b = contact_b.id)";
2436 }
6a488035
TO
2437 }
2438 elseif (self::$_relType == 'b') {
2439 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2440 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2441 }
2442 else {
2443 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2444 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2445 }
2446 continue;
2447
2448 case 'civicrm_log':
f391b06e 2449 $from .= " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2450 $from .= " INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
6a488035
TO
2451 continue;
2452
2453 case 'civicrm_tag':
2454 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2455 continue;
2456
6a488035
TO
2457 case 'civicrm_grant':
2458 $from .= CRM_Grant_BAO_Query::from($name, $mode, $side);
2459 continue;
2460
6a488035
TO
2461 case 'civicrm_website':
2462 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2463 continue;
2464
2465 default:
2466 $from .= CRM_Core_Component::from($name, $mode, $side);
99e9587a
DS
2467 $from .= CRM_Contact_BAO_Query_Hook::singleton()->buildSearchfrom($name, $mode, $side);
2468
6a488035
TO
2469 continue;
2470 }
2471 }
2472
2473 return $from;
2474 }
2475
2476 /**
2477 * WHERE / QILL clause for deleted_contacts
2478 *
2479 * @return void
2480 */
2481 function deletedContacts($values) {
2482 list($_, $_, $value, $grouping, $_) = $values;
2483 if ($value) {
2484 // *prepend* to the relevant grouping as this is quite an important factor
2485 array_unshift($this->_qill[$grouping], ts('Search in Trash'));
2486 }
2487 }
2488
2489 /**
2490 * where / qill clause for contact_type
2491 *
2492 * @return void
2493 * @access public
2494 */
2495 function contactType(&$values) {
2496 list($name, $op, $value, $grouping, $wildcard) = $values;
2497
2498 $subTypes = array();
2499 $clause = array();
2500
2501 // account for search builder mapping multiple values
2502 if (!is_array($value)) {
2503 $values = self::parseSearchBuilderString($value, 'String');
2504 if (is_array($values)) {
2505 $value = array_flip($values);
2506 }
2507 }
2508
2509 if (is_array($value)) {
2510 foreach ($value as $k => $v) {
2511 // fix for CRM-771
2512 if ($k) {
2513 $subType = NULL;
2514 $contactType = $k;
2515 if (strpos($k, CRM_Core_DAO::VALUE_SEPARATOR)) {
2516 list($contactType, $subType) = explode(CRM_Core_DAO::VALUE_SEPARATOR, $k, 2);
2517 }
2518
2519 if (!empty($subType)) {
2520 $subTypes[$subType] = 1;
2521 }
2522 $clause[$contactType] = "'" . CRM_Utils_Type::escape($contactType, 'String') . "'";
2523 }
2524 }
2525 }
2526 else {
2527 $contactTypeANDSubType = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value, 2);
2528 $contactType = $contactTypeANDSubType[0];
2529 $subType = CRM_Utils_Array::value(1, $contactTypeANDSubType);
2530 if (!empty($subType)) {
2531 $subTypes[$subType] = 1;
2532 }
2533 $clause[$contactType] = "'" . CRM_Utils_Type::escape($contactType, 'String') . "'";
2534 }
2535
2536 // fix for CRM-771
2537 if (!empty($clause)) {
3b3bc827
CW
2538 if ($op == 'IN' || $op == 'NOT IN') {
2539 $this->_where[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2540 }
2541 else {
d4b81b9a 2542 $quill = $clause;
3b3bc827
CW
2543 $type = array_pop($clause);
2544 $this->_where[$grouping][] = "contact_a.contact_type $op $type";
2545 }
d4b81b9a 2546
2547 $this->_qill[$grouping][] = ts('Contact Type') . ' - ' . implode(' ' . ts('or') . ' ', $quill);
6a488035
TO
2548
2549 if (!empty($subTypes)) {
2550 $this->includeContactSubTypes($subTypes, $grouping);
2551 }
2552 }
2553 }
2554
2555 /**
2556 * where / qill clause for contact_sub_type
2557 *
2558 * @return void
2559 * @access public
2560 */
2561 function contactSubType(&$values) {
2562 list($name, $op, $value, $grouping, $wildcard) = $values;
2563 $this->includeContactSubTypes($value, $grouping);
2564 }
2565
2566 function includeContactSubTypes($value, $grouping) {
2567
2568 $clause = array();
2569 $alias = "contact_a.contact_sub_type";
2570
2571 if (is_array($value)) {
2572 foreach ($value as $k => $v) {
2573 if (!empty($k)) {
2574 $clause[$k] = "($alias like '%" . CRM_Core_DAO::VALUE_SEPARATOR . CRM_Utils_Type::escape($k, 'String') . CRM_Core_DAO::VALUE_SEPARATOR . "%')";
2575 }
2576 }
2577 }
2578 else {
2579 $clause[$value] = "($alias like '%" . CRM_Core_DAO::VALUE_SEPARATOR . CRM_Utils_Type::escape($value, 'String') . CRM_Core_DAO::VALUE_SEPARATOR . "%')";
2580 }
2581
2582 if (!empty($clause)) {
2583 $this->_where[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2584 $this->_qill[$grouping][] = ts('Contact Subtype') . ' - ' . implode(' ' . ts('or') . ' ', array_keys($clause));
2585 }
2586 }
2587
2588 /**
2589 * where / qill clause for groups
2590 *
2591 * @return void
2592 * @access public
2593 */
2594 function group(&$values) {
2595 list($name, $op, $value, $grouping, $wildcard) = $values;
2596
2597 if (count($value) > 1) {
2598 $this->_useDistinct = TRUE;
2599 }
2600
2601 $groupNames = CRM_Core_PseudoConstant::group();
2602 $groupIds = implode(',', array_keys($value));
2603
2604 $names = array();
2605 foreach ($value as $id => $dontCare) {
2606 if (array_key_exists($id, $groupNames) && $dontCare) {
2607 $names[] = $groupNames[$id];
2608 }
2609 }
2610
2611 $statii = array();
2612 $in = FALSE;
2613 $gcsValues = &$this->getWhereValues('group_contact_status', $grouping);
2614 if ($gcsValues &&
2615 is_array($gcsValues[2])
2616 ) {
2617 foreach ($gcsValues[2] as $k => $v) {
2618 if ($v) {
2619 if ($k == 'Added') {
2620 $in = TRUE;
2621 }
2622 $statii[] = "'" . CRM_Utils_Type::escape($k, 'String') . "'";
2623 }
2624 }
2625 }
2626 else {
2627 $statii[] = '"Added"';
2628 $in = TRUE;
2629 }
2630
2631 $skipGroup = FALSE;
2632 if (count($value) == 1 &&
2633 count($statii) == 1 &&
2634 $statii[0] == '"Added"'
2635 ) {
2636 // check if smart group, if so we can get rid of that one additional
2637 // left join
2638 $groupIDs = array_keys($value);
2639
a7488080 2640 if (!empty($groupIDs[0]) &&
6a488035
TO
2641 CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group',
2642 $groupIDs[0],
2643 'saved_search_id'
2644 )
2645 ) {
2646 $skipGroup = TRUE;
2647 }
2648 }
2649
2650 if (!$skipGroup) {
2651 $gcTable = "`civicrm_group_contact-{$groupIds}`";
c905b59f 2652 $this->_tables[$gcTable] = $this->_whereTables[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON ( contact_a.id = {$gcTable}.contact_id AND {$gcTable}.group_id $op ( $groupIds ) )";
6a488035
TO
2653 }
2654
2655 $qill = ts('Contacts %1', array(1 => $op));
2656 $qill .= ' ' . implode(' ' . ts('or') . ' ', $names);
2657
2658 $groupClause = NULL;
2659
2660 if (!$skipGroup) {
2661 $groupClause = "{$gcTable}.group_id $op ( $groupIds )";
2662 if (!empty($statii)) {
2663 $groupClause .= " AND {$gcTable}.status IN (" . implode(', ', $statii) . ")";
2664 $qill .= " " . ts('AND') . " " . ts('Group Status') . ' - ' . implode(' ' . ts('or') . ' ', $statii);
2665 }
2666 }
2667
2668 if ($in) {
2669 $ssClause = $this->savedSearch($values);
2670 if ($ssClause) {
2671 if ($groupClause) {
2672 $groupClause = "( ( $groupClause ) OR ( $ssClause ) )";
2673 }
2674 else {
2675 $groupClause = $ssClause;
2676 }
2677 }
2678 }
2679
2680 $this->_where[$grouping][] = $groupClause;
2681 $this->_qill[$grouping][] = $qill;
2682 }
2683 /*
2684 * Function translates selection of group type into a list of groups
2685 */
2686 function getGroupsFromTypeCriteria($value){
2687 $groupIds = array();
2688 foreach ($value as $groupTypeValue) {
2689 $groupList = CRM_Core_PseudoConstant::group($groupTypeValue);
2690 $groupIds = ($groupIds + $groupList);
2691 }
2692 return $groupIds;
2693 }
2694
2695 /**
2696 * where / qill clause for smart groups
2697 *
2698 * @return void
2699 * @access public
2700 */
2701 function savedSearch(&$values) {
2702 list($name, $op, $value, $grouping, $wildcard) = $values;
2703 return $this->addGroupContactCache(array_keys($value));
2704 }
2705
e6b676a0 2706 /**
2707 * @param array $groups
2708 * @param string $tableAlias
2709 * @param string $joinTable
2710 *
2711 * @return null|string
2712 */
6a488035
TO
2713 function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a") {
2714 $config = CRM_Core_Config::singleton();
2715
e6b676a0 2716 // Find all the groups that are part of a saved search.
6a488035
TO
2717 $groupIDs = implode(',', $groups);
2718 if (empty($groupIDs)) {
2719 return NULL;
2720 }
2721
2722 $sql = "
2723SELECT id, cache_date, saved_search_id, children
2724FROM civicrm_group
2725WHERE id IN ( $groupIDs )
2726 AND ( saved_search_id != 0
2727 OR saved_search_id IS NOT NULL
2728 OR children IS NOT NULL )
2729";
e6b676a0 2730
2731 $group = CRM_Core_DAO::executeQuery($sql);
2732 $groupsFiltered = array();
2733
6a488035 2734 while ($group->fetch()) {
e6b676a0 2735 $groupsFiltered[] = $group->id;
6a488035
TO
2736
2737 $this->_useDistinct = TRUE;
2738
2739 if (!$this->_smartGroupCache || $group->cache_date == NULL) {
2740 CRM_Contact_BAO_GroupContactCache::load($group);
2741 }
6a488035
TO
2742 }
2743
e6b676a0 2744 if (count($groupsFiltered)) {
2745 $groupIDsFiltered = implode(',', $groupsFiltered);
2746
2747 if ($tableAlias == NULL) {
2748 $tableAlias = "civicrm_group_contact_cache_{$groupIDsFiltered}";
2749 }
2750
2751 $this->_tables[$tableAlias] = $this->_whereTables[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache `{$tableAlias}` ON {$joinTable}.id = `{$tableAlias}`.contact_id ";
2752
2753 return "`{$tableAlias}`.group_id IN (" . $groupIDsFiltered . ")";
6a488035 2754 }
e6b676a0 2755
6a488035
TO
2756 return NULL;
2757 }
2758
2759 /**
2760 * where / qill clause for cms users
2761 *
2762 * @return void
2763 * @access public
2764 */
2765 function ufUser(&$values) {
2766 list($name, $op, $value, $grouping, $wildcard) = $values;
2767
2768 if ($value == 1) {
2769 $this->_tables['civicrm_uf_match'] = $this->_whereTables['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2770
2771 $this->_qill[$grouping][] = ts('CMS User');
2772 }
2773 elseif ($value == 0) {
2774 $this->_tables['civicrm_uf_match'] = $this->_whereTables['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2775
2776 $this->_where[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
2777 $this->_qill[$grouping][] = ts('Not a CMS User');
2778 }
2779 }
2780
2781 /**
2782 * all tag search specific
2783 *
2784 * @return void
2785 * @access public
2786 */
2787 function tagSearch(&$values) {
2788 list($name, $op, $value, $grouping, $wildcard) = $values;
2789
2790 $op = "LIKE";
2791 $value = "%{$value}%";
2792
2793
2794 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2795 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2796
2797 $etTable = "`civicrm_entity_tag-" . $value . "`";
2798 $tTable = "`civicrm_tag-" . $value . "`";
2799
2800 if ($useAllTagTypes[2]) {
2801 $this->_tables[$etTable] =
2802 $this->_whereTables[$etTable] =
2803 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
2804 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
2805
2806 // search tag in cases
2807 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
2808 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
2809 $this->_tables[$etCaseTable] =
2810 $this->_whereTables[$etCaseTable] =
2811 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
2812 LEFT JOIN civicrm_case
2813 ON (civicrm_case_contact.case_id = civicrm_case.id
2814 AND civicrm_case.is_deleted = 0 )
2815 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
2816 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
2817 // search tag in activities
2818 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
2819 $tActTable = "`civicrm_act_tag-" . $value . "`";
e7e657f0 2820 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
9e74e3ce 2821 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1071730c 2822
6a488035
TO
2823 $this->_tables[$etActTable] =
2824 $this->_whereTables[$etActTable] =
91da6cd5 2825 " LEFT JOIN civicrm_activity_contact
9e74e3ce 2826 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
6a488035 2827 LEFT JOIN civicrm_activity
91da6cd5 2828 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
6a488035
TO
2829 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
2830 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
2831 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
2832
2833 $this->_where[$grouping][] = "({$tTable}.name $op '". $value . "' OR {$tCaseTable}.name $op '". $value . "' OR {$tActTable}.name $op '". $value . "')";
10a5be27 2834 $this->_qill[$grouping][] = ts('Tag %1 %2 ', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
6a488035
TO
2835 } else {
2836 $etTable = "`civicrm_entity_tag-" . $value . "`";
2837 $tTable = "`civicrm_tag-" . $value . "`";
2838 $this->_tables[$etTable] = $this->_whereTables[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
2839 {$etTable}.entity_table = 'civicrm_contact' )
2840 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
2841
2842 $this->_where[$grouping][] = self::buildClause("{$tTable}.name", $op, $value, 'String');
2843 $this->_qill[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
2844 }
2845 }
2846
2847 /**
2848 * where / qill clause for tag
2849 *
2850 * @return void
2851 * @access public
2852 */
2853 function tag(&$values) {
2854 list($name, $op, $value, $grouping, $wildcard) = $values;
2855
cd43c5e3 2856 $tagNames = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
6a488035
TO
2857 if (is_array($value)) {
2858 if (count($value) > 1) {
2859 $this->_useDistinct = TRUE;
2860 }
2861 foreach ($value as $id => $dontCare) {
2862 $names[] = CRM_Utils_Array::value($id, $tagNames);
2863 }
2864 $names = implode(' ' . ts('or') . ' ', $names);
2865 $value = implode(',', array_keys($value));
2866 }
2867 else {
2868 $names = CRM_Utils_Array::value($value, $tagNames);
2869 }
2870
2871
2872 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2873 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2874
2875 $etTable = "`civicrm_entity_tag-" . $value . "`";
2876
2877 if ($useAllTagTypes[2]) {
2878 $this->_tables[$etTable] =
2879 $this->_whereTables[$etTable] =
2880 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
2881
2882 // search tag in cases
2883 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
e7e657f0 2884 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
9e74e3ce 2885 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
2886
6a488035
TO
2887 $this->_tables[$etCaseTable] =
2888 $this->_whereTables[$etCaseTable] =
2889 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
2890 LEFT JOIN civicrm_case
2891 ON (civicrm_case_contact.case_id = civicrm_case.id
2892 AND civicrm_case.is_deleted = 0 )
2893 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
2894 // search tag in activities
2895 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
2896 $this->_tables[$etActTable] =
2897 $this->_whereTables[$etActTable] =
91da6cd5 2898 " LEFT JOIN civicrm_activity_contact
9e74e3ce 2899 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
6a488035 2900 LEFT JOIN civicrm_activity
91da6cd5 2901 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
6a488035
TO
2902 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
2903 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
2904
2905 // CRM-10338
2906 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
2907 $this->_where[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
2908 }
2909 else {
2910 $this->_where[$grouping][] = "({$etTable}.tag_id $op (". $value . ") OR {$etCaseTable}.tag_id $op (". $value . ") OR {$etActTable}.tag_id $op (". $value . "))";
2911 }
10a5be27 2912 $this->_qill[$grouping][] = ts('Tag %1 %2', array(1 => $op, 2 => $tagTypesText[2])) . ' ' . $names;
6a488035
TO
2913 } else {
2914 $this->_tables[$etTable] =
2915 $this->_whereTables[$etTable] =
2916 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
2917
2918 // CRM-10338
2919 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
2920 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
2921 $op = str_replace('EMPTY', 'NULL', $op);
2922 $this->_where[$grouping][] = "{$etTable}.tag_id $op";
2923 }
2924 else {
2925 $this->_where[$grouping][] = "{$etTable}.tag_id $op (" . $value . ')';
2926 }
2927 $this->_qill[$grouping][] = ts('Tagged %1', array( 1 => $op)) . ' ' . $names;
2928 }
2929
2930 }
2931
2932 /**
2933 * where/qill clause for notes
2934 *
2935 * @return void
2936 * @access public
2937 */
2938 function notes(&$values) {
2939 list($name, $op, $value, $grouping, $wildcard) = $values;
2940
2941 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
2942 $noteOption = CRM_Utils_Array::value('2', $noteOptionValues, '6');
2943 $noteOption = ($name == 'note_body') ? 2 : (($name == 'note_subject') ? 3 : $noteOption);
2944
2945 $this->_useDistinct = TRUE;
2946
2947 $this->_tables['civicrm_note'] =
2948 $this->_whereTables['civicrm_note'] =
2949 " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
2950
2951 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
2952 $n = trim($value);
2953 $value = $strtolower(CRM_Core_DAO::escapeString($n));
2954 if ($wildcard || $op == 'LIKE') {
2955 if (strpos($value, '%') === FALSE) {
2956 $value = "%$value%";
2957 }
2958 $op = 'LIKE';
2959 }
2960 elseif ($op == 'IS NULL' || $op == 'IS NOT NULL') {
2961 $value = NULL;
2962 }
2963
2964 $label = NULL;
2965 $clauses = array();
2966 if ( $noteOption % 2 == 0 ) {
2967 $clauses[] = self::buildClause('civicrm_note.note', $op, $value, 'String');
2968 $label = ts('Note: Body Only');
2969 }
2970 if ( $noteOption % 3 == 0 ) {
2971 $clauses[] = self::buildClause('civicrm_note.subject', $op, $value, 'String');
2972 $label = $label ? ts('Note: Body and Subject') : ts('Note: Subject Only');
2973 }
2974 $this->_where[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
2975 $this->_qill[$grouping][] = $label . " $op - '$n'";
2976 }
2977
2978 function nameNullOrEmptyOp($name, $op, $grouping) {
2979 switch ( $op ) {
2980 case 'IS NULL':
2981 case 'IS NOT NULL':
2982 $this->_where[$grouping][] = "contact_a.$name $op";
2983 $this->_qill[$grouping][] = ts('Name') . ' ' . $op;
2984 return true;
2985
2986 case 'IS EMPTY':
2987 $this->_where[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
2988 $this->_qill[$grouping][] = ts('Name') . ' ' . $op;
2989 return true;
2990
2991 case 'IS NOT EMPTY':
2992 $this->_where[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
2993 $this->_qill[$grouping][] = ts('Name') . ' ' . $op;
2994 return true;
2995
2996 default:
2997 return false;
2998 }
2999 }
3000
3001 /**
3002 * where / qill clause for sort_name
3003 *
3004 * @return void
3005 * @access public
3006 */
3007 function sortName(&$values) {
3008 list($name, $op, $value, $grouping, $wildcard) = $values;
3009
3010 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3011 if ( $this->nameNullOrEmptyOp( $name, $op, $grouping ) ) {
3012 return;
3013 }
3014
3015 $newName = $name;
3016 $name = trim($value);
3017
3018 if (empty($name)) {
3019 return;
3020 }
3021
3022 $config = CRM_Core_Config::singleton();
3023
3024 $sub = array();
3025
3026 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3027 $subGlue = ' OR ';
3028
3029 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
d9ab802d 3030 $locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
6a488035
TO
3031
3032 if (substr($name, 0, 1) == '"' &&
3033 substr($name, -1, 1) == '"'
3034 ) {
3035 //If name is encased in double quotes, the value should be taken to be the string in entirety and the
3036 $value = substr($name, 1, -1);
3037 $value = $strtolower(CRM_Core_DAO::escapeString($value));
3038 $wc = ($newName == 'sort_name') ? 'LOWER(contact_a.sort_name)' : 'LOWER(contact_a.display_name)';
3039 $sub[] = " ( $wc = '$value' ) ";
3040 if ($config->includeEmailInName) {
3041 $sub[] = " ( civicrm_email.email = '$value' ) ";
3042 }
3043 }
3044 elseif (strpos($name, ',') !== FALSE) {
3045 // if we have a comma in the string, search for the entire string
3046 $value = $strtolower(CRM_Core_DAO::escapeString($name));
3047 if ($wildcard) {
3048 if ($config->includeWildCardInName) {
3049 $value = "'%$value%'";
3050 }
3051 else {
3052 $value = "'$value%'";
3053 }
3054 $op = 'LIKE';
3055 }
3056 else {
3057 $value = "'$value'";
3058 }
3059 if ($newName == 'sort_name') {
3060 $wc = self::caseImportant($op) ? "LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3061 }
3062 else {
3063 $wc = self::caseImportant($op) ? "LOWER(contact_a.display_name)" : "contact_a.display_name";
3064 }
3065 $sub[] = " ( $wc $op $value )";
3066 if ($config->includeNickNameInName) {
3067 $wc = self::caseImportant($op) ? "LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3068 $sub[] = " ( $wc $op $value )";
3069 }
3070 if ($config->includeEmailInName) {
3071 $sub[] = " ( civicrm_email.email $op $value ) ";
3072 }
3073 }
3074 else {
3075 // the string should be treated as a series of keywords to be matched with match ANY OR
3076 // match ALL depending on Civi config settings (see CiviAdmin)
3077
3078 // The Civi configuration setting can be overridden if the string *starts* with the case
3079 // insenstive strings 'AND:' or 'OR:'TO THINK ABOUT: what happens when someone searches
3080 // for the following "AND: 'a string in quotes'"? - probably nothing - it would make the
3081 // AND OR variable reduntant because there is only one search string?
3082
3083 // Check to see if the $subGlue is overridden in the search text
3084 if (strtolower(substr($name, 0, 4)) == 'and:') {
3085 $name = substr($name, 4);
3086 $subGlue = ' AND ';
3087 }
3088 if (strtolower(substr($name, 0, 3)) == 'or:') {
3089 $name = substr($name, 3);
3090 $subGlue = ' OR ';
3091 }
3092
3093 $firstChar = substr($name, 0, 1);
3094 $lastChar = substr($name, -1, 1);
3095 $quotes = array("'", '"');
3096 if ((strlen($name) > 2) && in_array($firstChar, $quotes) &&
3097 in_array($lastChar, $quotes)
3098 ) {
3099 $name = substr($name, 1);
3100 $name = substr($name, 0, -1);
3101 $pieces = array($name);
3102 }
3103 else {
3104 $pieces = explode(' ', $name);
3105 }
3106 foreach ($pieces as $piece) {
3107 $value = $strtolower(CRM_Core_DAO::escapeString(trim($piece)));
3108 if (strlen($value)) {
3109 // Added If as a sanitization - without it, when you do an OR search, any string with
3110 // double spaces (i.e. " ") or that has a space after the keyword (e.g. "OR: ") will
3111 // return all contacts because it will include a condition similar to "OR contact
3112 // name LIKE '%'". It might be better to replace this with array_filter.
3113 $fieldsub = array();
3114 if ($wildcard) {
3115 if ($config->includeWildCardInName) {
3116 $value = "'%$value%'";
3117 }
3118 else {
3119 $value = "'$value%'";
3120 }
3121 $op = 'LIKE';
3122 }
3123 else {
3124 $value = "'$value'";
3125 }
3126 if ($newName == 'sort_name') {
3127 $wc = self::caseImportant($op) ? "LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3128 }
3129 else {
3130 $wc = self::caseImportant($op) ? "LOWER(contact_a.display_name)" : "contact_a.display_name";
3131 }
3132 $fieldsub[] = " ( $wc $op $value )";
3133 if ($config->includeNickNameInName) {
3134 $wc = self::caseImportant($op) ? "LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3135 $fieldsub[] = " ( $wc $op $value )";
3136 }
3137 if ($config->includeEmailInName) {
3138 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3139 }
3140 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3141 // I seperated the glueing in two. The first stage should always be OR because we are searching for matches in *ANY* of these fields
3142 }
3143 }
3144 }
3145
3146 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3147
3148 $this->_where[$grouping][] = $sub;
3149 if ($config->includeEmailInName) {
3150 $this->_tables['civicrm_email'] = $this->_whereTables['civicrm_email'] = 1;
3151 $this->_qill[$grouping][] = ts('Name or Email ') . "$op - '$name'";
3152 }
3153 else {
3154 $this->_qill[$grouping][] = ts('Name like') . " - '$name'";
3155 }
3156 }
3157
3158 /**
3159 * where / qill clause for email
3160 *
3161 * @return void
3162 * @access public
3163 */
3164 function email(&$values) {
3165 list($name, $op, $value, $grouping, $wildcard) = $values;
3166
3167 $n = trim($value);
3168 if ($n) {
3169 $config = CRM_Core_Config::singleton();
3170
3171 if (substr($n, 0, 1) == '"' &&
3172 substr($n, -1, 1) == '"'
3173 ) {
3174 $n = substr($n, 1, -1);
3175 $value = strtolower(CRM_Core_DAO::escapeString($n));
3176 $value = "'$value'";
3177 $op = '=';
3178 }
3179 else {
3180 $value = strtolower($n);
3181 if ($wildcard) {
3182 if (strpos($value, '%') === FALSE) {
3183 $value = "%{$value}%";
3184 }
3185 $op = 'LIKE';
3186 }
3187 }
3188 $this->_qill[$grouping][] = ts('Email') . " $op '$n'";
3189 $this->_where[$grouping][] = self::buildClause('civicrm_email.email', $op, $value, 'String');
3190 }
3191 else {
3192 $this->_qill[$grouping][] = ts('Email') . " $op ";
3193 $this->_where[$grouping][] = self::buildClause('civicrm_email.email', $op, NULL, 'String');
3194 }
3195
3196 $this->_tables['civicrm_email'] = $this->_whereTables['civicrm_email'] = 1;
3197 }
3198
3199 /**
3200 * where / qill clause for phone number
3201 *
3202 * @return void
3203 * @access public
3204 */
3205 function phone_numeric(&$values) {
3206 list($name, $op, $value, $grouping, $wildcard) = $values;
a195fab2
BS
3207 // Strip non-numeric characters; allow wildcards
3208 $number = preg_replace('/[^\d%]/', '', $value);
6a488035 3209 if ($number) {
a195fab2
BS
3210 if ( strpos($number, '%') === FALSE ) {
3211 $number = "%$number%";
3212 }
3213
6a488035 3214 $this->_qill[$grouping][] = ts('Phone number contains') . " $number";
a195fab2 3215 $this->_where[$grouping][] = self::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
6a488035
TO
3216 $this->_tables['civicrm_phone'] = $this->_whereTables['civicrm_phone'] = 1;
3217 }
3218 }
3219
3220 /**
3221 * where / qill clause for phone type/location
3222 *
3223 * @return void
3224 * @access public
3225 */
3226 function phone_option_group($values) {
3227 list($name, $op, $value, $grouping, $wildcard) = $values;
cbf48754
AS
3228 $option = ($name == 'phone_phone_type_id' ? 'phone_type_id' : 'location_type_id');
3229 $options = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', $option);
6a488035
TO
3230 $optionName = $options[$value];
3231 $this->_qill[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ? ts('type') : ('location')) . " $op $optionName";
3232 $this->_where[$grouping][] = self::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3233 $this->_tables['civicrm_phone'] = $this->_whereTables['civicrm_phone'] = 1;
3234 }
3235
3236 /**
3237 * where / qill clause for street_address
3238 *
3239 * @return void
3240 * @access public
3241 */
3242 function street_address(&$values) {
3243 list($name, $op, $value, $grouping, $wildcard) = $values;
3244
3245 if (!$op) {
3246 $op = 'LIKE';
3247 }
3248
3249 $n = trim($value);
3250
3251 if ($n) {
3252 $value = strtolower($n);
3253 if (strpos($value, '%') === FALSE) {
3254 // only add wild card if not there
3255 $value = "%{$value}%";
3256 }
3257 $op = 'LIKE';
3258 $this->_where[$grouping][] = self::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3259 $this->_qill[$grouping][] = ts('Street') . " $op '$n'";
3260 }
3261 else {
3262 $this->_where[$grouping][] = self::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3263 $this->_qill[$grouping][] = ts('Street') . " $op ";
3264 }
3265
3266 $this->_tables['civicrm_address'] = $this->_whereTables['civicrm_address'] = 1;
3267 }
3268
3269 /**
3270 * where / qill clause for street_unit
3271 *
3272 * @return void
3273 * @access public
3274 */
3275 function street_number(&$values) {
3276 list($name, $op, $value, $grouping, $wildcard) = $values;
3277
3278 if (!$op) {
3279 $op = '=';
3280 }
3281
3282 $n = trim($value);
3283
3284 if (strtolower($n) == 'odd') {
3285 $this->_where[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3286 $this->_qill[$grouping][] = ts('Street Number is odd');
3287 }
3288 elseif (strtolower($n) == 'even') {
3289 $this->_where[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3290 $this->_qill[$grouping][] = ts('Street Number is even');
3291 }
3292 else {
3293 $value = strtolower($n);
3294
3295 $this->_where[$grouping][] = self::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3296 $this->_qill[$grouping][] = ts('Street Number') . " $op '$n'";
3297 }
3298
3299 $this->_tables['civicrm_address'] = $this->_whereTables['civicrm_address'] = 1;
3300 }
3301
3302 /**
3303 * where / qill clause for sorting by character
3304 *
3305 * @return void
3306 * @access public
3307 */
3308 function sortByCharacter(&$values) {
3309 list($name, $op, $value, $grouping, $wildcard) = $values;
3310
3311 $name = trim($value);
3312 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO::escapeWildCardString($name)) . "%'";
3313 $this->_where[$grouping][] = $cond;
3314 $this->_qill[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3315 }
3316
3317 /**
3318 * where / qill clause for including contact ids
3319 *
3320 * @return void
3321 * @access public
3322 */
3323 function includeContactIDs() {
3324 if (!$this->_includeContactIds || empty($this->_params)) {
3325 return;
3326 }
3327
3328 $contactIds = array();
3329 foreach ($this->_params as $id => $values) {
3330 if (substr($values[0], 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
3331 $contactIds[] = substr($values[0], CRM_Core_Form::CB_PREFIX_LEN);
3332 }
3333 }
3334 if (!empty($contactIds)) {
3335 $this->_where[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3336 }
3337 }
3338
3339 /**
3340 * where / qill clause for postal code
3341 *
3342 * @return void
3343 * @access public
3344 */
3345 function postalCode(&$values) {
3346 // skip if the fields dont have anything to do with postal_code
a7488080 3347 if (empty($this->_fields['postal_code'])) {
6a488035
TO
3348 return;
3349 }
3350
3351 list($name, $op, $value, $grouping, $wildcard) = $values;
3352
3353 // Handle numeric postal code range searches properly by casting the column as numeric
3354 if (is_numeric($value)) {
3355 $field = 'ROUND(civicrm_address.postal_code)';
3356 $val = CRM_Utils_Type::escape($value, 'Integer');
3357 }
3358 else {
3359 $field = 'civicrm_address.postal_code';
3360 $val = CRM_Utils_Type::escape($value, 'String');
3361 }
3362
3363 $this->_tables['civicrm_address'] = $this->_whereTables['civicrm_address'] = 1;
3364
3365 if ($name == 'postal_code') {
3366 $this->_where[$grouping][] = self::buildClause($field, $op, $val, 'String');
3367 $this->_qill[$grouping][] = ts('Postal code') . " {$op} {$value}";
3368 }
3369 elseif ($name == 'postal_code_low') {
3370 $this->_where[$grouping][] = " ( $field >= '$val' ) ";
3371 $this->_qill[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3372 }
3373 elseif ($name == 'postal_code_high') {
3374 $this->_where[$grouping][] = " ( $field <= '$val' ) ";
3375 $this->_qill[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3376 }
3377 }
3378
3379 /**
3380 * where / qill clause for location type
3381 *
3382 * @return void
3383 * @access public
3384 */
3385 function locationType(&$values, $status = NULL) {
3386 list($name, $op, $value, $grouping, $wildcard) = $values;
3387
3388 if (is_array($value)) {
3389 $this->_where[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', array_keys($value)) . ')';
3390 $this->_tables['civicrm_address'] = 1;
3391 $this->_whereTables['civicrm_address'] = 1;
3392
b2b0530a 3393 $locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
6a488035
TO
3394 $names = array();
3395 foreach (array_keys($value) as $id) {
3396 $names[] = $locationType[$id];
3397 }
3398
3399 $this->_primaryLocation = FALSE;
3400
3401 if (!$status) {
3402 $this->_qill[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3403 }
3404 else {
3405 return implode(' ' . ts('or') . ' ', $names);
3406 }
3407 }
3408 }
3409
3410 function country(&$values, $fromStateProvince = TRUE) {
3411 list($name, $op, $value, $grouping, $wildcard) = $values;
3412
3413 if (!$fromStateProvince) {
3414 $stateValues = $this->getWhereValues('state_province', $grouping);
3415 if (!empty($stateValues)) {
3416 // return back to caller if there are state province values
3417 // since that handles this case
3418 return;
3419 }
3420 }
3421
3422 $countryClause = $countryQill = NULL;
3423 if (
3424 $values &&
3425 !empty($value)
3426 ) {
d9ab802d
PJ
3427
3428 $this->_tables['civicrm_address'] = 1;
3429 $this->_whereTables['civicrm_address'] = 1;
6a488035
TO
3430
3431 $countries = CRM_Core_PseudoConstant::country();
3432 if (is_numeric($value)) {
3433 $countryClause = self::buildClause(
d9ab802d 3434 'civicrm_address.country_id',
6a488035
TO
3435 $op,
3436 $value,
3437 'Positive'
3438 );
3439 $countryName = $countries[(int ) $value];
3440 }
3441
3442 else {
3443 $intValues = self::parseSearchBuilderString($value);
3444 if ($intValues && ($op == 'IN' || $op == 'NOT IN')) {
3445 $countryClause = self::buildClause(
d9ab802d 3446 'civicrm_address.country_id',
6a488035
TO
3447 $op,
3448 $intValues,
3449 'Positive'
3450 );
3451 $countryNames = array();
3452 foreach ($intValues as $v) {
3453 $countryNames[] = $countries[$v];
3454 }
3455 $countryName = implode(',', $countryNames);
3456 }
3457 else {
d9ab802d
PJ
3458 $countries = CRM_Core_PseudoConstant::country();
3459 $intVal = CRM_Utils_Array::key($value, $countries);
6a488035 3460 $countryClause = self::buildClause(
d9ab802d 3461 'civicrm_address.country_id',
6a488035 3462 $op,
d9ab802d
PJ
3463 $intVal,
3464 'Integer'
6a488035
TO
3465 );
3466 $countryName = $value;
3467 }
3468 }
3469 $countryQill = ts('Country') . " {$op} '$countryName'";
3470
3471 if (!$fromStateProvince) {
3472 $this->_where[$grouping][] = $countryClause;
3473 $this->_qill[$grouping][] = $countryQill;
3474 }
3475 }
3476
3477 if ($fromStateProvince) {
3478 if (!empty($countryClause)) {
3479 return array(
3480 $countryClause,
3481 " ...AND... " . $countryQill,
3482 );
3483 }
3484 else {
3485 return array(NULL, NULL);
3486 }
3487 }
3488 }
3489
3490 /**
3491 * where / qill clause for county (if present)
3492 *
3493 * @return void
3494 * @access public
3495 */
3496 function county(&$values, $status = null) {
3497 list($name, $op, $value, $grouping, $wildcard) = $values;
3498
3499 if (! is_array($value)) {
3500 // force the county to be an array
3501 $value = array($value);
3502 }
3503
3504 // check if the values are ids OR names of the counties
3505 $inputFormat = 'id';
3506 foreach ($value as $v) {
3507 if (!is_numeric($v)) {
3508 $inputFormat = 'name';
3509 break;
3510 }
3511 }
3512 $names = array();
d9ab802d
PJ
3513 if ($op == '=') {
3514 $op = 'IN';
3515 }
3516 else if ($op == '!=') {
3517 $op = 'NOT IN';
3518 }
3519 else {
3520 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3521 $op = str_replace('EMPTY', 'NULL', $op);
3522 }
3523
3524 if (in_array( $op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3525 $clause = "civicrm_address.county_id $op";
3526 }
3527 elseif ($inputFormat == 'id') {
3528 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
6a488035
TO
3529
3530 $county = CRM_Core_PseudoConstant::county();
3531 foreach ($value as $id) {
3532 $names[] = CRM_Utils_Array::value($id, $county);
3533 }
3534 }
3535 else {
3536 $inputClause = array();
d9ab802d 3537 $county = CRM_Core_PseudoConstant::county();
6a488035
TO
3538 foreach ($value as $name) {
3539 $name = trim($name);
d9ab802d 3540 $inputClause[] = CRM_Utils_Array::key($name, $county);
6a488035 3541 }
d9ab802d 3542 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
6a488035
TO
3543 $names = $value;
3544 }
d9ab802d
PJ
3545 $this->_tables['civicrm_address'] = 1;
3546 $this->_whereTables['civicrm_address'] = 1;
6a488035
TO
3547
3548 $this->_where[$grouping][] = $clause;
d9ab802d 3549 if (!$status) {
6a488035
TO
3550 $this->_qill[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3551 } else {
3552 return implode(' ' . ts('or') . ' ', $names);
3553 }
3554 }
3555
3556 /**
3557 * where / qill clause for state/province AND country (if present)
3558 *
3559 * @return void
3560 * @access public
3561 */
3562 function stateProvince(&$values, $status = NULL) {
3563 list($name, $op, $value, $grouping, $wildcard) = $values;
3564
3565 // quick escape for IS NULL
3566 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3567 $value = NULL;
3568 }
3569 else if (!is_array($value)) {
3570 // force the state to be an array
3571 // check if its in the mapper format!
3572 $values = self::parseSearchBuilderString($value);
3573 if (is_array($values)) {
3574 $value = $values;
3575 }
3576 else {
3577 $value = array($value);
3578 }
3579 }
3580
3581 // check if the values are ids OR names of the states
3582 $inputFormat = 'id';
3583 if ($value) {
3584 foreach ($value as $v) {
3585 if (!is_numeric($v)) {
3586 $inputFormat = 'name';
3587 break;
3588 }
3589 }
3590 }
3591
3592 $names = array();
3593 if ($op == '=') {
3594 $op = 'IN';
3595 }
3596 else if ($op == '!=') {
3597 $op = 'NOT IN';
3598 }
3599 else {
3600 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3601 $op = str_replace('EMPTY', 'NULL', $op);
3602 }
3603 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
d9ab802d 3604 $stateClause = "civicrm_address.state_province_id $op";
6a488035
TO
3605 }
3606 else if ($inputFormat == 'id') {
3607 if ($op != 'NOT IN') {
3608 $op = 'IN';
3609 }
d9ab802d 3610 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $value) . ')';
6a488035
TO
3611
3612 $stateProvince = CRM_Core_PseudoConstant::stateProvince();
3613 foreach ($value as $id) {
3614 $names[] = CRM_Utils_Array::value($id, $stateProvince);
3615 }
3616 }
3617 else {
3618 $inputClause = array();
d9ab802d 3619 $stateProvince = CRM_Core_PseudoConstant::stateProvince();
6a488035
TO
3620 foreach ($value as $name) {
3621 $name = trim($name);
d9ab802d 3622 $inputClause[] = CRM_Utils_Array::key($name, $stateProvince);
6a488035 3623 }
d9ab802d 3624 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $inputClause) . ')';
6a488035
TO
3625 $names = $value;
3626 }
d9ab802d
PJ
3627 $this->_tables['civicrm_address'] = 1;
3628 $this->_whereTables['civicrm_address'] = 1;
6a488035
TO
3629
3630 $countryValues = $this->getWhereValues('country', $grouping);
3631 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3632
3633 if ($countryClause) {
3634 $clause = "( $stateClause AND $countryClause )";
3635 }
3636 else {
3637 $clause = $stateClause;
3638 }
3639
3640 $this->_where[$grouping][] = $clause;
3641 if (!$status) {
3642 $this->_qill[$grouping][] = ts('State/Province') . " $op " . implode(' ' . ts('or') . ' ', $names) . $countryQill;
3643 }
3644 else {
9fd71915 3645 return implode(' ' . ts('or') . ' ', $names) . $countryQill;
6a488035
TO
3646 }
3647 }
3648
3649 /**
3650 * where / qill clause for change log
3651 *
3652 * @return void
3653 * @access public
3654 */
3655 function changeLog(&$values) {
3656 list($name, $op, $value, $grouping, $wildcard) = $values;
3657
3658 $targetName = $this->getWhereValues('changed_by', $grouping);
3659 if (!$targetName) {
3660 return;
3661 }
3662
3663 $name = trim($targetName[2]);
3664 $name = strtolower(CRM_Core_DAO::escapeString($name));
3665 $name = $targetName[4] ? "%$name%" : $name;
3666 $this->_where[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3667 $this->_tables['civicrm_log'] = $this->_whereTables['civicrm_log'] = 1;
f391b06e 3668 $this->_qill[$grouping][] = ts('Modified by') . ": $name";
6a488035
TO
3669 }
3670
3671 function modifiedDates($values) {
3672 $this->_useDistinct = TRUE;
9e9b8fdb
DL
3673
3674 // CRM-11281, default to added date if not set
228917cd 3675 $fieldTitle = ts('Added Date');
06103b23 3676 $fieldName = 'created_date';
6a488035
TO
3677 foreach (array_keys($this->_params) as $id) {
3678 if ($this->_params[$id][0] == 'log_date') {
228917cd
DL
3679 if ($this->_params[$id][2] == 2) {
3680 $fieldTitle = ts('Modified Date');
06103b23 3681 $fieldName = 'modified_date';
6a488035
TO
3682 }
3683 }
3684 }
3685
06103b23 3686
3687 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3688
3689 self::$_openedPanes[ts('Change Log')] = TRUE;
6a488035
TO
3690 }
3691
3692 function demographics(&$values) {
3693 list($name, $op, $value, $grouping, $wildcard) = $values;
3694
3695 if (($name == 'birth_date_low') || ($name == 'birth_date_high')) {
3696
3697 $this->dateQueryBuilder($values,
3698 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3699 );
3700 }
3701 elseif (($name == 'deceased_date_low') || ($name == 'deceased_date_high')) {
3702
3703 $this->dateQueryBuilder($values,
3704 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3705 );
3706 }
3707
3708 self::$_openedPanes[ts('Demographics')] = TRUE;
3709 }
3710
3711 function privacy(&$values) {
3712 list($name, $op, $value, $grouping, $wildcard) = $values;
3713 //fixed for profile search listing CRM-4633
3714 if (strpbrk($value, "[")) {
3715 $value = "'{$value}'";
3716 $op = "!{$op}";
3717 $this->_where[$grouping][] = "contact_a.{$name} $op $value";
3718 }
3719 else {
3720 $this->_where[$grouping][] = "contact_a.{$name} $op $value";
3721 }
3722 $field = CRM_Utils_Array::value($name, $this->_fields);
3723 $title = $field ? $field['title'] : $name;
3724 $this->_qill[$grouping][] = "$title $op $value";
3725 }
3726
3727 function privacyOptions($values) {
3728 list($name, $op, $value, $grouping, $wildcard) = $values;
3729
9fd71915
CW
3730 if (empty($value) || !is_array($value)) {
3731 return;
6a488035
TO
3732 }
3733
3734 // get the operator and toggle values
3735 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3736 $operator = 'OR';
3737 if ($opValues &&
3738 strtolower($opValues[2] == 'AND')
3739 ) {
3740 $operator = 'AND';
3741 }
3742
3743 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3744 $compareOP = '!=';
3745 if ($toggleValues &&
3746 $toggleValues[2] == 2
3747 ) {
3748 $compareOP = '=';
3749 }
3750
3751 $clauses = array();
3752 $qill = array();
3753 foreach ($value as $dontCare => $pOption) {
3754 $clauses[] = " ( contact_a.{$pOption} $compareOP 1 ) ";
3755 $field = CRM_Utils_Array::value($pOption, $this->_fields);
3756 $title = $field ? $field['title'] : $pOption;
3757 $qill[] = " $title $compareOP 1 ";
3758 }
3759
3760 $this->_where[$grouping][] = '( ' . implode($operator, $clauses) . ' )';
3761 $this->_qill[$grouping][] = implode($operator, $qill);
3762 }
3763
3764 function preferredCommunication(&$values) {
3765 list($name, $op, $value, $grouping, $wildcard) = $values;
3766
3767 $pref = array();
4b20f7df
PJ
3768 if (in_array($op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3769 $value = NULL;
3770 }
3771 elseif (!is_array($value)) {
6a488035
TO
3772 $v = array();
3773 $value = trim($value, ' ()');
3774 if (strpos($value, CRM_Core_DAO::VALUE_SEPARATOR) !== FALSE) {
3775 $v = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
3776 }
3777 else {
3778 $v = explode(",", $value);
3779 }
3780
3781 foreach ($v as $item) {
3782 if ($item) {
3783 $pref[] = $item;
3784 }
3785 }
3786 }
3787 else {
3788 foreach ($value as $key => $checked) {
3789 if ($checked) {
3790 $pref[] = $key;
3791 }
3792 }
3793 }
3794
e7e657f0 3795 $commPref = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
6a488035
TO
3796
3797 $sqlValue = array();
4b20f7df 3798 $showValue = array();
6a488035 3799 $sql = "contact_a.preferred_communication_method";
4b20f7df
PJ
3800 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3801 $sqlValue[] = "{$sql} {$op}";
3802 }
3803 else {
3804 foreach ($pref as $val) {
3805 $sqlValue[] = "( $sql like '%" . CRM_Core_DAO::VALUE_SEPARATOR . $val . CRM_Core_DAO::VALUE_SEPARATOR . "%' ) ";
3806 $showValue[] = $commPref[$val];
3807 }
6a488035
TO
3808 }
3809 $this->_where[$grouping][] = "( " . implode(' OR ', $sqlValue) . " )";
3810 $this->_qill[$grouping][] = ts('Preferred Communication Method') . " $op " . implode(' ' . ts('or') . ' ', $showValue);
3811 }
3812
6a488035
TO
3813 /**
3814 * where / qill clause for relationship
3815 *
3816 * @return void
3817 * @access public
3818 */
3819 function relationship(&$values) {
3820 list($name, $op, $value, $grouping, $wildcard) = $values;
ad682134 3821 if($this->_relationshipValuesAdded){
3822 return;
3823 }
6a488035
TO
3824 // also get values array for relation_target_name
3825 // for relatinship search we always do wildcard
3826 $targetName = $this->getWhereValues('relation_target_name', $grouping);
3827 $relStatus = $this->getWhereValues('relation_status', $grouping);
5ea73a9f 3828 $relPermission = $this->getWhereValues('relation_permission', $grouping);
6a488035 3829 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
6a488035
TO
3830
3831 $nameClause = $name = NULL;
3832 if ($targetName) {
3833 $name = trim($targetName[2]);
3834 if (substr($name, 0, 1) == '"' &&
3835 substr($name, -1, 1) == '"'
3836 ) {
3837 $name = substr($name, 1, -1);
3838 $name = strtolower(CRM_Core_DAO::escapeString($name));
3839 $nameClause = "= '$name'";
3840 }
3841 else {
3842 $name = strtolower(CRM_Core_DAO::escapeString($name));
3843 $nameClause = "LIKE '%{$name}%'";
3844 }
3845 }
3846
3847 $rel = explode('_', $value);
3848
3849 self::$_relType = $rel[1];
ad682134 3850 $params = array('id' => $rel[0]);
3851 $rTypeValues = array();
3852 $rType = CRM_Contact_BAO_RelationshipType::retrieve($params, $rTypeValues);
3853 if ($rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
7c96365b 3854 // if we don't know which end of the relationship we are dealing with we'll create a temp table
3855 //@todo unless we are dealing with a target group
ad682134 3856 self::$_relType = 'reciprocal';
3857 }
7c96365b 3858 // if we are creating a temp table we build our own where for the relationship table
085e6226 3859 $relationshipTempTable = NULL;
7c96365b 3860 if(self::$_relType == 'reciprocal' && empty($targetGroup)) {
3861 $where = array();
085e6226
DL
3862 self::$_relationshipTempTable =
3863 $relationshipTempTable =
3864 CRM_Core_DAO::createTempTableName( 'civicrm_rel');
7c96365b 3865 if($nameClause) {
3866 $where[$grouping][] = " sort_name $nameClause ";
3867 }
6a488035 3868 }
7c96365b 3869 else {
3870 $where = &$this->_where;
3871 if ($nameClause) {
3872 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
3873 }
3874 }
3875
04ffef8d 3876
6a488035
TO
3877 $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
3878 $relTypeOrg = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
3879 $relTypeHou = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Household');
3880 $allRelationshipType = array();
3881 $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
3882 $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
3883
3884 if ($nameClause || !$targetGroup) {
3885 $this->_qill[$grouping][] = "$allRelationshipType[$value] $name";
3886 }
3887
3888
3889 //check to see if the target contact is in specified group
3890 if ($targetGroup) {
3891 //add contacts from static groups
3892 $this->_tables['civicrm_relationship_group_contact'] =
3893 $this->_whereTables['civicrm_relationship_group_contact'] =
085e6226
DL
3894 " LEFT JOIN civicrm_group_contact civicrm_relationship_group_contact ON civicrm_relationship_group_contact.contact_id = contact_b.id AND civicrm_relationship_group_contact.status = 'Added'";
3895 $groupWhere[] =
3896 "( civicrm_relationship_group_contact.group_id IN (" .
3897 implode(",", $targetGroup[2]) . ") ) ";
6a488035
TO
3898
3899 //add contacts from saved searches
3900 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b");
3901
3902 //set the group where clause
3903 if ($ssWhere) {
3904 $groupWhere[] = "( " . $ssWhere . " )";
3905 }
3906 $this->_where[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
3907
3908 //Get the names of the target groups for the qill
085e6226 3909 $groupNames = CRM_Core_PseudoConstant::group();
6a488035
TO
3910 $qillNames = array();
3911 foreach ($targetGroup[2] as $groupId) {
3912 if (array_key_exists($groupId, $groupNames)) {
3913 $qillNames[] = $groupNames[$groupId];
3914 }
3915 }
3916 $this->_qill[$grouping][] = "$allRelationshipType[$value] ( " . implode(", ", $qillNames) . " )";
3917 }
3918
12ba37a0
CW
3919 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
3920 $today = date('Ymd');
6a488035
TO
3921 //check for active, inactive and all relation status
3922 if ($relStatus[2] == 0) {
7c96365b 3923 $where[$grouping][] = "(
6a488035 3924civicrm_relationship.is_active = 1 AND
12ba37a0
CW
3925( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
3926( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
6a488035
TO
3927)";
3928 $this->_qill[$grouping][] = ts('Relationship - Active and Current');
3929 }
3930 elseif ($relStatus[2] == 1) {
7c96365b 3931 $where[$grouping][] = "(
6a488035 3932civicrm_relationship.is_active = 0 OR
12ba37a0
CW
3933civicrm_relationship.end_date < {$today} OR
3934civicrm_relationship.start_date > {$today}
6a488035
TO
3935)";
3936 $this->_qill[$grouping][] = ts('Relationship - Inactive or not Current');
3937 }
3938
5ea73a9f
DG
3939 //check for permissioned, non-permissioned and all permissioned relations
3940 if ($relPermission[2] == 1) {
3941 $this->_where[$grouping][] = "(
3942civicrm_relationship.is_permission_a_b = 1
3943)";
3944 $this->_qill[$grouping][] = ts('Relationship - Permissioned');
3945 } elseif ($relPermission[2] == 2) {
3946 //non-allowed permission relationship.
3947 $this->_where[$grouping][] = "(
3948civicrm_relationship.is_permission_a_b = 0
3949)";
3950 $this->_qill[$grouping][] = ts('Relationship - Non-permissioned');
3951 }
3952
7c96365b 3953 $this->addRelationshipDateClauses($grouping, $where);
ad682134 3954 if(!empty($rType) && isset($rType->id)){
7c96365b 3955 $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id;
6a488035 3956 }
6a488035
TO
3957 $this->_tables['civicrm_relationship'] = $this->_whereTables['civicrm_relationship'] = 1;
3958 $this->_useDistinct = TRUE;
ad682134 3959 $this->_relationshipValuesAdded = TRUE;
7c96365b 3960 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
3961 // join on that,
3962 // @todo creating a temp table could be expanded to group filter
3963 // as even creating a temp table of all relationships is much much more efficient than
3964 // an OR in the join
3965 if($relationshipTempTable) {
3966 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
3967 $sql = "
3968 CREATE TEMPORARY TABLE {$relationshipTempTable}
3969 (SELECT contact_id_b as contact_id, civicrm_relationship.id
3970 FROM civicrm_relationship
3971 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
3972 $whereClause )
3973 UNION
3974 (SELECT contact_id_a as contact_id, civicrm_relationship.id
3975 FROM civicrm_relationship
3976 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
3977 $whereClause )
3978 ";
3979 CRM_Core_DAO::executeQuery($sql);
3980 }
3981
6a488035 3982 }
ad682134 3983/**
3984 * Add start & end date criteria in
3985 * @param string $grouping
7c96365b 3986 * @param array $where = array to add where clauses to, in case you are generating a temp table
3987 * not the main query.
ad682134 3988 */
7c96365b 3989 function addRelationshipDateClauses($grouping, &$where){
ad682134 3990 $dateValues = array();
3991 $dateTypes = array(
3992 'start_date',
3993 'end_date',
3994 );
6a488035 3995
ad682134 3996 foreach ($dateTypes as $dateField){
3997 $dateValueLow = $this->getWhereValues('relation_'. $dateField .'_low', $grouping);
3998 $dateValueHigh= $this->getWhereValues('relation_'. $dateField .'_high', $grouping);
3999 if(!empty($dateValueLow)){
4000 $date = date('Ymd', strtotime($dateValueLow[2]));
7c96365b 4001 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
ad682134 4002 $this->_qill[$grouping][] = ($dateField == 'end_date' ? ts('Relationship Ended on or After') : ts('Relationship Recorded Start Date On or Before')) . " " . CRM_Utils_Date::customFormat($date);
4003 }
4004 if(!empty($dateValueHigh)){
4005 $date = date('Ymd', strtotime($dateValueHigh[2]));
7c96365b 4006 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
ad682134 4007 $this->_qill[$grouping][] = ( $dateField == 'end_date' ? ts('Relationship Ended on or Before') : ts('Relationship Recorded Start Date On or After')) . " " . CRM_Utils_Date::customFormat($date);
4008 }
4009 }
4010 }
6a488035
TO
4011 /**
4012 * default set of return properties
4013 *
4014 * @return void
4015 * @access public
4016 */
4017 static function &defaultReturnProperties($mode = 1) {
4018 if (!isset(self::$_defaultReturnProperties)) {
4019 self::$_defaultReturnProperties = array();
4020 }
4021
4022 if (!isset(self::$_defaultReturnProperties[$mode])) {
4023 // add activity return properties
4024 if ($mode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
4025 self::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query::defaultReturnProperties($mode, FALSE);
4026 }
4027 else {
4028 self::$_defaultReturnProperties[$mode] = CRM_Core_Component::defaultReturnProperties($mode, FALSE);
4029 }
4030
4031 if (empty(self::$_defaultReturnProperties[$mode])) {
4032 self::$_defaultReturnProperties[$mode] = array(
4033 'home_URL' => 1,
4034 'image_URL' => 1,
4035 'legal_identifier' => 1,
4036 'external_identifier' => 1,
4037 'contact_type' => 1,
4038 'contact_sub_type' => 1,
4039 'sort_name' => 1,
4040 'display_name' => 1,
4041 'preferred_mail_format' => 1,
4042 'nick_name' => 1,
4043 'first_name' => 1,
4044 'middle_name' => 1,
4045 'last_name' => 1,
04ffef8d
CW
4046 'prefix_id' => 1,
4047 'suffix_id' => 1,
e171748b 4048 'formal_title' => 1,
aa62b355 4049 'communication_style_id' => 1,
6a488035 4050 'birth_date' => 1,
04ffef8d 4051 'gender_id' => 1,
6a488035
TO
4052 'street_address' => 1,
4053 'supplemental_address_1' => 1,
4054 'supplemental_address_2' => 1,
4055 'city' => 1,
4056 'postal_code' => 1,
4057 'postal_code_suffix' => 1,
4058 'state_province' => 1,
4059 'country' => 1,
4060 'world_region' => 1,
4061 'geo_code_1' => 1,
4062 'geo_code_2' => 1,
4063 'email' => 1,
4064 'on_hold' => 1,
4065 'phone' => 1,
4066 'im' => 1,
4067 'household_name' => 1,
4068 'organization_name' => 1,
4069 'deceased_date' => 1,
4070 'is_deceased' => 1,
4071 'job_title' => 1,
4072 'legal_name' => 1,
4073 'sic_code' => 1,
4074 'current_employer' => 1,
4075 // FIXME: should we use defaultHierReturnProperties() for the below?
4076 'do_not_email' => 1,
4077 'do_not_mail' => 1,
4078 'do_not_sms' => 1,
4079 'do_not_phone' => 1,
4080 'do_not_trade' => 1,
4081 'is_opt_out' => 1,
4082 'contact_is_deleted' => 1,
b725488f
CW
4083 'preferred_communication_method' => 1,
4084 'preferred_language' => 1,
6a488035
TO
4085 );
4086 }
4087 }
4088 return self::$_defaultReturnProperties[$mode];
4089 }
4090
4091 /**
4092 * get primary condition for a sql clause
4093 *
4094 * @param int $value
4095 *
4096 * @return void
4097 * @access public
4098 */
4099 static function getPrimaryCondition($value) {
4100 if (is_numeric($value)) {
4101 $value = (int ) $value;
4102 return ($value == 1) ? 'is_primary = 1' : 'is_primary = 0';
4103 }
4104 return NULL;
4105 }
4106
4107 /**
4108 * wrapper for a simple search query
4109 *
4110 * @param array $params
4111 * @param array $returnProperties
837c4660 4112 * @param \bolean|bool $count
6a488035
TO
4113 *
4114 * @return void
4115 * @access public
4116 */
4117 static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4118 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4119 list($select, $from, $where, $having) = $query->query();
4120
4121 return "$select $from $where $having";
4122 }
4123
4124 /**
4125 * These are stub comments as this function needs more explanation - particularly in terms of how it
4126 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4127 *
4128 * This function was originally written as a wrapper for the api query but is called from multiple places
4129 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4130 * but it is unclear as to whehter that is historical or there is a reason
4131 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4132 *
837c4660
E
4133 * @param array $params
4134 * @param array $returnProperties
4135 * @param null $fields
6a488035 4136 * @param string $sort
837c4660
E
4137 * @param int $offset
4138 * @param int $row_count
4139 * @param bool $smartGroupCache
6a488035
TO
4140 * @param bool $count return count obnly
4141 * @param bool $skipPermissions Should permissions be ignored or should the logged in user's permissions be applied
4142 *
837c4660
E
4143 * @params bool $smartGroupCache ?? update smart group cache?
4144 *
b725488f 4145 * @return array
6a488035
TO
4146 * @access public
4147 */
4148 static function apiQuery(
4149 $params = NULL,
4150 $returnProperties = NULL,
4151 $fields = NULL,
4152 $sort = NULL,
4153 $offset = 0,
4154 $row_count = 25,
4155 $smartGroupCache = TRUE,
4156 $count = FALSE,
d9ab802d 4157 $skipPermissions = TRUE
6a488035
TO
4158 ) {
4159
4160 $query = new CRM_Contact_BAO_Query(
4161 $params, $returnProperties,
4162 NULL, TRUE, FALSE, 1,
4163 $skipPermissions,
4164 TRUE, $smartGroupCache
4165 );
4166
4167 //this should add a check for view deleted if permissions are enabled
4168 if ($skipPermissions){
4169 $query->_skipDeleteClause = TRUE;
4170 }
4171 $query->generatePermissionClause(FALSE, $count);
d9ab802d
PJ
4172
4173 // note : this modifies _fromClause and _simpleFromClause
4174 $query->includePseudoFieldsJoin($sort);
4175
6a488035
TO
4176 list($select, $from, $where, $having) = $query->query($count);
4177
4178 $options = $query->_options;
4179 if(!empty($query->_permissionWhereClause)){
4180 if (empty($where)) {
4181 $where = "WHERE $query->_permissionWhereClause";
4182 }
4183 else {
4184 $where = "$where AND $query->_permissionWhereClause";
4185 }
4186 }
4187
4188 $sql = "$select $from $where $having";
4189
4190 // add group by
4191 if ($query->_useGroupBy) {
4192 $sql .= ' GROUP BY contact_a.id';
4193 }
4194 if (!empty($sort)) {
bd9a3dd5 4195 $sort = CRM_Utils_Type::escape($sort, 'String');
6a488035
TO
4196 $sql .= " ORDER BY $sort ";
4197 }
4198 if ($row_count > 0 && $offset >= 0) {
bf00d1b6 4199 $offset = CRM_Utils_Type::escape($offset, 'Int');
c95d144e 4200 $rowCount = CRM_Utils_Type::escape($row_count, 'Int');
6a488035
TO
4201 $sql .= " LIMIT $offset, $row_count ";
4202 }
4203
4204 $dao = CRM_Core_DAO::executeQuery($sql);
4205
4206 $values = array();
4207 while ($dao->fetch()) {
4208 if ($count) {
4209 $noRows = $dao->rowCount;
4210 $dao->free();
4211 return array($noRows,NULL);
4212 }
d9ab802d 4213 $val = $query->store($dao);
b719f000 4214 $convertedVals = $query->convertToPseudoNames($dao, TRUE);
d9ab802d
PJ
4215
4216 if (!empty($convertedVals)) {
e3571aca 4217 $val = array_replace_recursive($val, $convertedVals);
d9ab802d
PJ
4218 }
4219 $values[$dao->contact_id] = $val;
6a488035
TO
4220 }
4221 $dao->free();
4222 return array($values, $options);
4223 }
4224
4225 /**
4226 * create and query the db for an contact search
4227 *
4228 * @param int $offset the offset for the query
4229 * @param int $rowCount the number of rows to return
4230 * @param string $sort the order by string
4231 * @param boolean $count is this a count only query ?
4232 * @param boolean $includeContactIds should we include contact ids?
4233 * @param boolean $sortByChar if true returns the distinct array of first characters for search results
4234 * @param boolean $groupContacts if true, return only the contact ids
4235 * @param boolean $returnQuery should we return the query as a string
4236 * @param string $additionalWhereClause if the caller wants to further restrict the search (used for components)
4237 * @param string $additionalFromClause should be clause with proper joins, effective to reduce where clause load.
4238 *
4239 * @return CRM_Contact_DAO_Contact
4240 * @access public
4241 */
4242 function searchQuery(
4243 $offset = 0, $rowCount = 0, $sort = NULL,
4244 $count = FALSE, $includeContactIds = FALSE,
4245 $sortByChar = FALSE, $groupContacts = FALSE,
4246 $returnQuery = FALSE,
4247 $additionalWhereClause = NULL, $sortOrder = NULL,
4248 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4249 ) {
4250
4251 if ($includeContactIds) {
4252 $this->_includeContactIds = TRUE;
4253 $this->_whereClause = $this->whereClause();
4254 }
4255
6a488035
TO
4256 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params);
4257
f4bff68a 4258 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
6a488035
TO
4259 // and that contact happens to be deleted, set $onlyDeleted to true
4260 foreach ($this->_params as $values) {
4261 $name = CRM_Utils_Array::value(0, $values);
4262 $op = CRM_Utils_Array::value(1, $values);
4263 $value = CRM_Utils_Array::value(2, $values);
4264 if ($name == 'contact_id' and $op == '=') {
4265 if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4266 $onlyDeleted = TRUE;
4267 }
4268 break;
4269 }
4270 }
4271 $this->generatePermissionClause($onlyDeleted, $count);
4272
6a488035
TO
4273 // building the query string
4274 $groupBy = NULL;
4275 if (!$count) {
4276 if (isset($this->_groupByComponentClause)) {
4277 $groupBy = $this->_groupByComponentClause;
4278 }
4279 elseif ($this->_useGroupBy) {
4280 $groupBy = ' GROUP BY contact_a.id';
4281 }
4282 }
4283 if ($this->_mode & CRM_Contact_BAO_Query::MODE_ACTIVITY && (!$count)) {
4284 $groupBy = 'GROUP BY civicrm_activity.id ';
4285 }
4286
4287 $order = $orderBy = $limit = '';
4288 if (!$count) {
4289 $config = CRM_Core_Config::singleton();
4290 if ($config->includeOrderByClause ||
4291 isset($this->_distinctComponentClause)
4292 ) {
4293 if ($sort) {
4294 if (is_string($sort)) {
4295 $orderBy = $sort;
4296 }
4297 else {
4298 $orderBy = trim($sort->orderBy());
4299 }
4300 if (!empty($orderBy)) {
4301 // this is special case while searching for
4302 // changelog CRM-1718
4303 if (preg_match('/sort_name/i', $orderBy)) {
4304 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
4305 }
4306
bd9a3dd5 4307 $orderBy = CRM_Utils_Type::escape($orderBy, 'String');
6a488035
TO
4308 $order = " ORDER BY $orderBy";
4309
4310 if ($sortOrder) {
bd9a3dd5 4311 $sortOrder = CRM_Utils_Type::escape($sortOrder, 'String');
6a488035
TO
4312 $order .= " $sortOrder";
4313 }
4314
4315 // always add contact_a.id to the ORDER clause
4316 // so the order is deterministic
4317 if (strpos('contact_a.id', $order) === FALSE) {
4318 $order .= ", contact_a.id";
4319 }
4320 }
4321 }
4322 elseif ($sortByChar) {
4323 $order = " ORDER BY UPPER(LEFT(contact_a.sort_name, 1)) asc";
4324 }
4325 else {
4326 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
4327 }
4328 }
4329
6a488035
TO
4330 // hack for order clause
4331 if ($order) {
4332 $fieldStr = trim(str_replace('ORDER BY', '', $order));
4333 $fieldOrder = explode(' ', $fieldStr);
4334 $field = $fieldOrder[0];
4335
4336 if ($field) {
4337 switch ($field) {
6a488035
TO
4338 case 'city':
4339 case 'postal_code':
4340 $this->_whereTables["civicrm_address"] = 1;
4341 $order = str_replace($field, "civicrm_address.{$field}", $order);
4342 break;
4343
4344 case 'country':
4345 case 'state_province':
4346 $this->_whereTables["civicrm_{$field}"] = 1;
4347 $order = str_replace($field, "civicrm_{$field}.name", $order);
4348 break;
4349
4350 case 'email':
4351 $this->_whereTables["civicrm_email"] = 1;
4352 $order = str_replace($field, "civicrm_email.{$field}", $order);
4353 break;
6a488035 4354 }
4243847f
CW
4355 $this->_fromClause = self::fromClause($this->_tables, NULL, NULL, $this->_primaryLocation, $this->_mode);
4356 $this->_simpleFromClause = self::fromClause($this->_whereTables, NULL, NULL, $this->_primaryLocation, $this->_mode);
6a488035
TO
4357 }
4358 }
4359
6a488035 4360 if ($rowCount > 0 && $offset >= 0) {
bf00d1b6
DL
4361 $offset = CRM_Utils_Type::escape($offset, 'Int');
4362 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
6a488035 4363 $limit = " LIMIT $offset, $rowCount ";
4243847f
CW
4364 }
4365 }
6a488035 4366
b1be45a0 4367 // note : this modifies _fromClause and _simpleFromClause
d9ab802d
PJ
4368 $this->includePseudoFieldsJoin($sort);
4369
4243847f 4370 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts);
6a488035 4371
1939d296 4372 if(!empty($this->_permissionWhereClause)){
4373 if (empty($where)) {
4374 $where = "WHERE $this->_permissionWhereClause";
4375 }
4376 else {
4377 $where = "$where AND $this->_permissionWhereClause";
4378 }
4379 }
4380
4381 if ($additionalWhereClause) {
4382 $where = $where . ' AND ' . $additionalWhereClause;
4383 }
4384
4385 //additional from clause should be w/ proper joins.
4243847f
CW
4386 if ($additionalFromClause) {
4387 $from .= "\n" . $additionalFromClause;
6a488035
TO
4388 }
4389
4390 // if we are doing a transform, do it here
4391 // use the $from, $where and $having to get the contact ID
4392 if ($this->_displayRelationshipType) {
4393 $this->filterRelatedContacts($from, $where, $having);
4394 }
4395
4396 if ($skipOrderAndLimit) {
4397 $query = "$select $from $where $having $groupBy";
4398 }
4399 else {
4400 $query = "$select $from $where $having $groupBy $order $limit";
4401 }
4402
4403 if ($returnQuery) {
4404 return $query;
4405 }
4406
4407 if ($count) {
4408 return CRM_Core_DAO::singleValueQuery($query);
4409 }
4410
6a488035
TO
4411 $dao = CRM_Core_DAO::executeQuery($query);
4412 if ($groupContacts) {
4413 $ids = array();
4414 while ($dao->fetch()) {
4415 $ids[] = $dao->id;
4416 }
4417 return implode(',', $ids);
4418 }
4419
4420 return $dao;
4421 }
4422
4243847f
CW
4423 /**
4424 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4425 *
4426 * @param string $cacheKey
4427 * @param int $offset
4428 * @param int $rowCount
4429 * @param bool $includeContactIds
4430 * @return CRM_Core_DAO
4431 */
4432 function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4433 $this->_includeContactIds = $includeContactIds;
23379b49 4434 list($select, $from, $where) = $this->query();
4243847f
CW
4435 $from = " FROM civicrm_prevnext_cache pnc INNER JOIN civicrm_contact contact_a ON contact_a.id = pnc.entity_id1 AND pnc.cacheKey = '$cacheKey' " . substr($from, 31);
4436 $order = " ORDER BY pnc.id";
1e7a8a53 4437 $groupBy = " GROUP BY contact_a.id";
4243847f 4438 $limit = " LIMIT $offset, $rowCount";
23379b49 4439 $query = "$select $from $where $groupBy $order $limit";
4440
4243847f
CW
4441 return CRM_Core_DAO::executeQuery($query);
4442 }
4443
6a488035
TO
4444 /**
4445 * Populate $this->_permissionWhereClause with permission related clause and update other
4446 * query related properties.
4447 *
4448 * Function calls ACL permission class and hooks to filter the query appropriately
4449 *
4450 * Note that these 2 params were in the code when extracted from another function
4451 * and a second round extraction would be to make them properties of the class
4452 *
4453 * @param bool $onlyDeleted Only get deleted contacts
4454 * @param bool $count Return Count only
4455 *
4456 * @return null
4457 */
4458 function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4459 if (!$this->_skipPermission) {
4460 $this->_permissionWhereClause = CRM_ACL_API::whereClause(
4461 CRM_Core_Permission::VIEW,
4462 $this->_tables,
4463 $this->_whereTables,
4464 NULL,
4465 $onlyDeleted,
4466 $this->_skipDeleteClause
4467 );
4468
4469 // regenerate fromClause since permission might have added tables
4470 if ($this->_permissionWhereClause) {
4471 //fix for row count in qill (in contribute/membership find)
4472 if (!$count) {
4473 $this->_useDistinct = TRUE;
4474 }
4475 $this->_fromClause = self::fromClause($this->_tables, NULL, NULL, $this->_primaryLocation, $this->_mode);
4476 $this->_simpleFromClause = self::fromClause($this->_whereTables, NULL, NULL, $this->_primaryLocation, $this->_mode);
4477 }
4478 }
4479 else {
4480 // add delete clause if needed even if we are skipping permission
4481 // CRM-7639
4482 if (!$this->_skipDeleteClause) {
4483 if (CRM_Core_Permission::check('access deleted contacts') and $onlyDeleted) {
4484 $this->_permissionWhereClause = '(contact_a.is_deleted)';
4485 }
4486 else {
4487 // CRM-6181
4488 $this->_permissionWhereClause = '(contact_a.is_deleted = 0)';
4489 }
4490 }
4491 }
4492 }
4493
4494 function setSkipPermission($val) {
4495 $this->_skipPermission = $val;
4496 }
4497
4498 function &summaryContribution($context = NULL) {
d7803ec1 4499 list($innerselect, $from, $where, $having) = $this->query(TRUE);
6a488035
TO
4500
4501 // hack $select
4502 $select = "
d7803ec1
EM
4503SELECT COUNT( conts.total_amount ) as total_count,
4504 SUM( conts.total_amount ) as total_amount,
4505 AVG( conts.total_amount ) as total_avg,
4506 conts.currency as currency";
4507 if($this->_permissionWhereClause) {
4508 $where .= " AND " . $this->_permissionWhereClause;
4509 }
6a488035
TO
4510 if ($context == 'search') {
4511 $where .= " AND contact_a.is_deleted = 0 ";
4512 }
4513
d7803ec1
EM
4514 // make sure contribution is completed - CRM-4989
4515 $completedWhere = $where . " AND civicrm_contribution.contribution_status_id = 1 ";
4516
4517
6a488035
TO
4518 $summary = array();
4519 $summary['total'] = array();
4520 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
4521
d7803ec1
EM
4522 $query = "$select FROM (
4523 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $completedWhere
4524 GROUP BY civicrm_contribution.id
4525 ) as conts
4526 GROUP BY currency";
6a488035 4527
d7803ec1 4528 $dao = CRM_Core_DAO::executeQuery($query);
6a488035
TO
4529
4530 $summary['total']['count'] = 0;
4531 $summary['total']['amount'] = $summary['total']['avg'] = array();
4532 while ($dao->fetch()) {
4533 $summary['total']['count'] += $dao->total_count;
4534 $summary['total']['amount'][] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
4535 $summary['total']['avg'][] = CRM_Utils_Money::format($dao->total_avg, $dao->currency);
4536 }
4537 if (!empty($summary['total']['amount'])) {
4538 $summary['total']['amount'] = implode(',&nbsp;', $summary['total']['amount']);
4539 $summary['total']['avg'] = implode(',&nbsp;', $summary['total']['avg']);
4540 }
4541 else {
4542 $summary['total']['amount'] = $summary['total']['avg'] = 0;
4543 }
4544
d4e2b978
DS
4545 // soft credit summary
4546 if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled()) {
4547 $softCreditWhere = "{$completedWhere} AND civicrm_contribution_soft.id IS NOT NULL";
4548 $query = "
4549 $select FROM (
4550 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency $from $softCreditWhere
4551 GROUP BY civicrm_contribution_soft.id
4552 ) as conts
4553 GROUP BY currency";
4554 $dao = CRM_Core_DAO::executeQuery($query);
4555 $summary['soft_credit']['count'] = 0;
4556 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = array();
4557 while ($dao->fetch()) {
4558 $summary['soft_credit']['count'] += $dao->total_count;
4559 $summary['soft_credit']['amount'][] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
4560 $summary['soft_credit']['avg'][] = CRM_Utils_Money::format($dao->total_avg, $dao->currency);
4561 }
4562 if (!empty($summary['soft_credit']['amount'])) {
4563 $summary['soft_credit']['amount'] = implode(',&nbsp;', $summary['soft_credit']['amount']);
4564 $summary['soft_credit']['avg'] = implode(',&nbsp;', $summary['soft_credit']['avg']);
4565 }
4566 else {
4567 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
4568 }
4569 }
4570
6a488035 4571 // hack $select
d7803ec1
EM
4572 //@todo - this could be one query using the IF in mysql - eg
4573 // SELECT sum(total_completed), sum(count_completed), sum(count_cancelled), sum(total_cancelled) FROM (
4574 // SELECT civicrm_contribution.total_amount, civicrm_contribution.currency ,
4575 // IF(civicrm_contribution.contribution_status_id = 1, 1, 0 ) as count_completed,
4576 // IF(civicrm_contribution.contribution_status_id = 1, total_amount, 0 ) as total_completed,
4577 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, 1, 0 ) as count_cancelled,
4578 // IF(civicrm_contribution.cancel_date IS NOT NULL = 1, total_amount, 0 ) as total_cancelled
4579 // FROM civicrm_contact contact_a
4580 // LEFT JOIN civicrm_contribution ON civicrm_contribution.contact_id = contact_a.id
4581 // WHERE ( ... where clause....
4582 // AND (civicrm_contribution.cancel_date IS NOT NULL OR civicrm_contribution.contribution_status_id = 1)
4583 // ) as conts
4584
6a488035 4585 $select = "
d7803ec1
EM
4586SELECT COUNT( conts.total_amount ) as cancel_count,
4587 SUM( conts.total_amount ) as cancel_amount,
4588 AVG( conts.total_amount ) as cancel_avg,
4589 conts.currency as currency";
6a488035
TO
4590
4591 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
4592 if ($context == 'search') {
4593 $where .= " AND contact_a.is_deleted = 0 ";
4594 }
4595
d7803ec1
EM
4596 $query = "$select FROM (
4597 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency $from $where
4598 GROUP BY civicrm_contribution.id
4599 ) as conts
4600 GROUP BY currency";
4601
4602 $dao = CRM_Core_DAO::executeQuery($query);
6a488035
TO
4603
4604 if ($dao->N <= 1) {
4605 if ($dao->fetch()) {
4606 $summary['cancel']['count'] = $dao->cancel_count;
4607 $summary['cancel']['amount'] = $dao->cancel_amount;
4608 $summary['cancel']['avg'] = $dao->cancel_avg;
4609 }
4610 }
4611 else {
4612 $summary['cancel']['count'] = 0;
4613 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
4614 while ($dao->fetch()) {
4615 $summary['cancel']['count'] += $dao->cancel_count;
4616 $summary['cancel']['amount'][] = CRM_Utils_Money::format($dao->cancel_amount, $dao->currency);
4617 $summary['cancel']['avg'][] = CRM_Utils_Money::format($dao->cancel_avg, $dao->currency);
4618 }
4619 $summary['cancel']['amount'] = implode(',&nbsp;', $summary['cancel']['amount']);
4620 $summary['cancel']['avg'] = implode(',&nbsp;', $summary['cancel']['avg']);
4621 }
4622
4623 return $summary;
4624 }
4625
4626 /**
4627 * getter for the qill object
4628 *
4629 * @return string
4630 * @access public
4631 */
4632 function qill() {
4633 return $this->_qill;
4634 }
4635
4636 /**
4637 * default set of return default hier return properties
4638 *
4639 * @return void
4640 * @access public
4641 */
4642 static function &defaultHierReturnProperties() {
4643 if (!isset(self::$_defaultHierReturnProperties)) {
4644 self::$_defaultHierReturnProperties = array(
4645 'home_URL' => 1,
4646 'image_URL' => 1,
4647 'legal_identifier' => 1,
4648 'external_identifier' => 1,
4649 'contact_type' => 1,
4650 'contact_sub_type' => 1,
4651 'sort_name' => 1,
4652 'display_name' => 1,
4653 'nick_name' => 1,
4654 'first_name' => 1,
4655 'middle_name' => 1,
4656 'last_name' => 1,
67744c4e
CW
4657 'prefix_id' => 1,
4658 'suffix_id' => 1,
e171748b 4659 'formal_title' => 1,
aa62b355 4660 'communication_style_id' => 1,
6a488035
TO
4661 'email_greeting' => 1,
4662 'postal_greeting' => 1,
4663 'addressee' => 1,
4664 'birth_date' => 1,
67744c4e 4665 'gender_id' => 1,
6a488035
TO
4666 'preferred_communication_method' => 1,
4667 'do_not_phone' => 1,
4668 'do_not_email' => 1,
4669 'do_not_mail' => 1,
4670 'do_not_sms' => 1,
4671 'do_not_trade' => 1,
4672 'location' =>
4673 array(
4674 '1' => array('location_type' => 1,
4675 'street_address' => 1,
4676 'city' => 1,
4677 'state_province' => 1,
4678 'postal_code' => 1,
4679 'postal_code_suffix' => 1,
4680 'country' => 1,
4681 'phone-Phone' => 1,
4682 'phone-Mobile' => 1,
4683 'phone-Fax' => 1,
4684 'phone-1' => 1,
4685 'phone-2' => 1,
4686 'phone-3' => 1,
4687 'im-1' => 1,
4688 'im-2' => 1,
4689 'im-3' => 1,
4690 'email-1' => 1,
4691 'email-2' => 1,
4692 'email-3' => 1,
4693 ),
4694 '2' => array(
4695 'location_type' => 1,
4696 'street_address' => 1,
4697 'city' => 1,
4698 'state_province' => 1,
4699 'postal_code' => 1,
4700 'postal_code_suffix' => 1,
4701 'country' => 1,
4702 'phone-Phone' => 1,
4703 'phone-Mobile' => 1,
4704 'phone-1' => 1,
4705 'phone-2' => 1,
4706 'phone-3' => 1,
4707 'im-1' => 1,
4708 'im-2' => 1,
4709 'im-3' => 1,
4710 'email-1' => 1,
4711 'email-2' => 1,
4712 'email-3' => 1,
4713 ),
4714 ),
4715 );
4716 }
4717 return self::$_defaultHierReturnProperties;
4718 }
4719
4720 function dateQueryBuilder(
4721 &$values, $tableName, $fieldName,
4722 $dbFieldName, $fieldTitle,
4723 $appendTimeStamp = TRUE
4724 ) {
4725 list($name, $op, $value, $grouping, $wildcard) = $values;
4726
4727 if (!$value) {
4728 return;
4729 }
4730
4731 if ($name == "{$fieldName}_low" ||
4732 $name == "{$fieldName}_high"
4733 ) {
4734 if (isset($this->_rangeCache[$fieldName])) {
4735 return;
4736 }
4737 $this->_rangeCache[$fieldName] = 1;
4738
4739 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
4740
4741 if ($name == $fieldName . '_low') {
4742 $firstOP = '>=';
228917cd 4743 $firstPhrase = ts('greater than or equal to');
6a488035
TO
4744 $firstDate = CRM_Utils_Date::processDate($value);
4745
4746 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
228917cd 4747 if (!empty($secondValues) && $secondValues[2]) {
6a488035 4748 $secondOP = '<=';
228917cd 4749 $secondPhrase = ts('less than or equal to');
6a488035
TO
4750 $secondValue = $secondValues[2];
4751
228917cd 4752 if ($appendTimeStamp && strlen($secondValue) == 10) {
6a488035
TO
4753 $secondValue .= ' 23:59:59';
4754 }
4755 $secondDate = CRM_Utils_Date::processDate($secondValue);
4756 }
4757 }
4758 elseif ($name == $fieldName . '_high') {
4759 $firstOP = '<=';
228917cd 4760 $firstPhrase = ts('less than or equal to');
6a488035 4761
228917cd 4762 if ($appendTimeStamp && strlen($value) == 10) {
6a488035
TO
4763 $value .= ' 23:59:59';
4764 }
4765 $firstDate = CRM_Utils_Date::processDate($value);
4766
4767 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
228917cd 4768 if (!empty($secondValues) && $secondValues[2]) {
6a488035 4769 $secondOP = '>=';
228917cd 4770 $secondPhrase = ts('greater than or equal to');
6a488035
TO
4771 $secondValue = $secondValues[2];
4772 $secondDate = CRM_Utils_Date::processDate($secondValue);
4773 }
4774 }
4775
4776 if (!$appendTimeStamp) {
4777 $firstDate = substr($firstDate, 0, 8);
4778 }
4779 $firstDateFormat = CRM_Utils_Date::customFormat($firstDate);
4780
4781 if ($secondDate) {
4782 if (!$appendTimeStamp) {
4783 $secondDate = substr($secondDate, 0, 8);
4784 }
4785 $secondDateFormat = CRM_Utils_Date::customFormat($secondDate);
4786 }
4787
4788 $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
4789 if ($secondDate) {
4790 $this->_where[$grouping][] = "
4791( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
4792( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
4793";
4794 $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
4795 }
4796 else {
4797 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
4798 $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
4799 }
4800 }
4801
4802 if ($name == $fieldName) {
4803 // $op = '=';
4804 $phrase = $op;
4805
4806 $date = CRM_Utils_Date::processDate($value);
4807
4808 if (!$appendTimeStamp) {
4809 $date = substr($date, 0, 8);
4810 }
4811
4812 $format = CRM_Utils_Date::customFormat($date);
4813
4814 if ($date) {
4815 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $op '$date'";
4816 }
4817 else {
4818 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $op";
4819 }
4820 $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
4821 $this->_qill[$grouping][] = "$fieldTitle - $phrase \"$format\"";
4822 }
6a488035
TO
4823 }
4824
4825 function numberRangeBuilder(&$values,
4826 $tableName, $fieldName,
4827 $dbFieldName, $fieldTitle,
4828 $options = NULL
4829 ) {
4830 list($name, $op, $value, $grouping, $wildcard) = $values;
4831
4832 if ($name == "{$fieldName}_low" ||
4833 $name == "{$fieldName}_high"
4834 ) {
4835 if (isset($this->_rangeCache[$fieldName])) {
4836 return;
4837 }
4838 $this->_rangeCache[$fieldName] = 1;
4839
4840 $secondOP = $secondPhrase = $secondValue = NULL;
4841
4842 if ($name == "{$fieldName}_low") {
4843 $firstOP = '>=';
228917cd 4844 $firstPhrase = ts('greater than');
6a488035
TO
4845
4846 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
4847 if (!empty($secondValues)) {
4848 $secondOP = '<=';
228917cd 4849 $secondPhrase = ts('less than');
6a488035
TO
4850 $secondValue = $secondValues[2];
4851 }
4852 }
4853 else {
4854 $firstOP = '<=';
228917cd 4855 $firstPhrase = ts('less than');
6a488035
TO
4856
4857 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
4858 if (!empty($secondValues)) {
4859 $secondOP = '>=';
228917cd 4860 $secondPhrase = ts('greater than');
6a488035
TO
4861 $secondValue = $secondValues[2];
4862 }
4863 }
4864
4865 if ($secondOP) {
4866 $this->_where[$grouping][] = "
4867( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
4868( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
4869";
4870 $displayValue = $options ? $options[$value] : $value;
4871 $secondDisplayValue = $options ? $options[$secondValue] : $secondValue;
4872
228917cd
DL
4873 $this->_qill[$grouping][] =
4874 "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
6a488035
TO
4875 }
4876 else {
4877 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
4878 $displayValue = $options ? $options[$value] : $value;
4879 $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
4880 }
4881 $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
4882
4883 return;
4884 }
4885
4886 if ($name == $fieldName) {
4887 $op = '=';
4888 $phrase = '=';
4889
4890 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
4891
4892 $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
4893 $displayValue = $options ? $options[$value] : $value;
4894 $this->_qill[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
4895 }
4896
4897 return;
4898 }
4899
4900 /**
4901 * Given the field name, operator, value & its data type
4902 * builds the where Clause for the query
4903 * used for handling 'IS NULL'/'IS NOT NULL' operators
4904 *
4905 * @param string $field fieldname
4906 * @param string $op operator
4907 * @param string $value value
4908 * @param string $dataType data type of the field
4909 *
4910 * @return where clause for the query
4911 * @access public
4912 */
4913 static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
4914 $op = trim($op);
4915 $clause = "$field $op";
4916
4917 switch ($op) {
4918 case 'IS NULL':
4919 case 'IS NOT NULL':
4920 return $clause;
4921
4922 case 'IS EMPTY':
4923 $clause = " ( $field IS NULL OR $field = '' ) ";
4924 return $clause;
4925
4926 case 'IS NOT EMPTY':
4927 $clause = " ( $field IS NOT NULL AND $field <> '' ) ";
4928 return $clause;
4929
4930 case 'IN':
4931 case 'NOT IN':
4932 if (isset($dataType)) {
4933 if (is_array($value)) {
4934 $values = $value;
4935 }
4936 else {
4937 $value = CRM_Utils_Type::escape($value, "String");
4938 $values = explode(',', CRM_Utils_Array::value(0, explode(')', CRM_Utils_Array::value(1, explode('(', $value)))));
4939 }
4940 // supporting multiple values in IN clause
4941 $val = array();
4942 foreach ($values as $v) {
4943 $v = trim($v);
4944 $val[] = "'" . CRM_Utils_Type::escape($v, $dataType) . "'";
4945 }
4946 $value = "(" . implode($val, ",") . ")";
4947 }
4948 return "$clause $value";
4949
4950 default:
4951 if (empty($dataType)) {
4952 $dataType = 'String';
4953 }
4954
4955 $value = CRM_Utils_Type::escape($value, $dataType);
6a488035 4956 // if we dont have a dataType we should assume
85bdc94e 4957 if ($dataType == 'String' || $dataType == 'Text') {
6a488035
TO
4958 $value = "'" . strtolower($value) . "'";
4959 }
4960 return "$clause $value";
4961 }
4962 }
4963
4964 function openedSearchPanes($reset = FALSE) {
4965 if (!$reset || empty($this->_whereTables)) {
4966 return self::$_openedPanes;
4967 }
4968
4969 // pane name to table mapper
4970 $panesMapper = array(
4971 ts('Contributions') => 'civicrm_contribution',
4972 ts('Memberships') => 'civicrm_membership',
4973 ts('Events') => 'civicrm_participant',
4974 ts('Relationships') => 'civicrm_relationship',
4975 ts('Activities') => 'civicrm_activity',
4976 ts('Pledges') => 'civicrm_pledge',
4977 ts('Cases') => 'civicrm_case',
4978 ts('Grants') => 'civicrm_grant',
4979 ts('Address Fields') => 'civicrm_address',
4980 ts('Notes') => 'civicrm_note',
4981 ts('Change Log') => 'civicrm_log',
4982 ts('Mailings') => 'civicrm_mailing_event_queue',
4983 );
066b4d4a 4984 CRM_Contact_BAO_Query_Hook::singleton()->getPanesMapper($panesMapper);
6a488035
TO
4985
4986 foreach (array_keys($this->_whereTables) as $table) {
4987 if ($panName = array_search($table, $panesMapper)) {
4988 self::$_openedPanes[$panName] = TRUE;
4989 }
4990 }
4991
4992 return self::$_openedPanes;
4993 }
4994
4995 function setOperator($operator) {
4996 $validOperators = array('AND', 'OR');
4997 if (!in_array($operator, $validOperators)) {
4998 $operator = 'AND';
4999 }
5000 $this->_operator = $operator;
5001 }
5002
5003 function getOperator() {
5004 return $this->_operator;
5005 }
5006
5007 function filterRelatedContacts(&$from, &$where, &$having) {
5008 static $_rTypeProcessed = NULL;
5009 static $_rTypeFrom = NULL;
5010 static $_rTypeWhere = NULL;
5011
5012 if (!$_rTypeProcessed) {
5013 $_rTypeProcessed = TRUE;
5014
5015 // create temp table with contact ids
5016 $tableName = CRM_Core_DAO::createTempTableName('civicrm_transform', TRUE);
5017 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
5018 CRM_Core_DAO::executeQuery($sql);
5019
5020 $sql = "
5021REPLACE INTO $tableName ( contact_id )
5022SELECT contact_a.id
5023 $from
5024 $where
5025 $having
5026";
5027 CRM_Core_DAO::executeQuery($sql);
5028
5029 $qillMessage = ts('Contacts with a Relationship Type of: ');
5030 $rTypes = CRM_Core_PseudoConstant::relationshipType();
5031
5032 if (is_numeric($this->_displayRelationshipType)) {
5033 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType]['label_a_b'];
5034 $_rTypeFrom = "
5035INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5036INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5037";
5038 $_rTypeWhere = "
5039WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5040AND displayRelType.is_active = 1
5041";
5042 }
5043 else {
5044 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType);
5045 if ($dirOne == 'a') {
5046 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5047 $_rTypeFrom .= "
5048INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5049INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5050";
5051 }
5052 else {
5053 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5054 $_rTypeFrom .= "
5055INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5056INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5057";
5058 }
5059 $_rTypeWhere = "
5060WHERE displayRelType.relationship_type_id = $relType
5061AND displayRelType.is_active = 1
5062";
5063 }
6a488035
TO
5064 $this->_qill[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
5065 }
5066
5067 if (strpos($from, $_rTypeFrom) === FALSE) {
5068 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5069 // this happens when we have an event_type in the quert (CRM-7969)
5070 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5071 $from .= $_rTypeFrom;
5072 $where = $_rTypeWhere;
5073 }
5074
5075 $having = NULL;
5076 }
5077
5078 static function caseImportant( $op ) {
5079 return
5080 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ? FALSE : TRUE;
5081 }
5082
5083 static function componentPresent( &$returnProperties, $prefix ) {
5084 foreach ($returnProperties as $name => $dontCare ) {
5085 if (substr($name, 0, strlen($prefix)) == $prefix) {
5086 return TRUE;
5087 }
5088 }
5089 return FALSE;
5090 }
5091
5092 /**
5093 * Builds the necessary structures for all fields that are similar to option value lookups
5094 *
5095 * @param $name string the name of the field
5096 * @param $op string the sql operator, this function should handle ALL SQL operators
5097 * @param $value any string / integer / array depends on the operator and whos calling the query builder
5098 * @param $grouping int the index where to place the where clause
837c4660 5099 * @param $selectValues
6a488035
TO
5100 * @param $field array an array that contains various properties of the field identified by $name
5101 * @param $label string The label for this field element
5102 * @param $dataType string The data type for this element
5103 *
837c4660
E
5104 * @param bool $useIDsOnly
5105 *
5106 * @internal param array $selectValue the key value pairs for this element. This allows us to use this function for things besides option-value pairs
6a488035
TO
5107 * @return void adds the where clause and qill to the query object
5108 */
5109 function optionValueQuery(
5110 $name,
5111 $op,
5112 $value,
5113 $grouping,
5114 $selectValues,
5115 $field,
5116 $label,
a30e57e0
DL
5117 $dataType = 'String',
5118 $useIDsOnly = FALSE
6a488035 5119 ) {
bd3728fb 5120
5121 if (!empty($selectValues)) {
5122 $qill = $selectValues[$value];
5123 }
5124 else {
5125 $qill = $value;
5126 }
5127
aa62b355 5128 $pseudoFields = array('email_greeting', 'postal_greeting', 'addressee', 'gender_id', 'prefix_id', 'suffix_id', 'communication_style_id');
d9ab802d 5129
6a488035 5130 if (is_numeric($value)) {
a30e57e0 5131 $qill = $selectValues[(int ) $value];
6a488035
TO
5132 }
5133 elseif ($op == 'IN' || $op == 'NOT IN') {
5134 $values = self::parseSearchBuilderString($value);
5135 if (is_array($values)) {
d9ab802d 5136 $intVals = array();
6a488035
TO
5137 $newValues = array();
5138 foreach ($values as $v) {
d9ab802d 5139 $intVals[] = (int) $v;
6a488035
TO
5140 $newValues[] = $selectValues[(int ) $v];
5141 }
d9ab802d
PJ
5142
5143 $value = (in_array($name, $pseudoFields)) ? $intVals : $newValues;
5144 $qill = implode(', ', $newValues);
6a488035
TO
5145 }
5146 }
9131c564 5147 elseif (!array_key_exists($value, $selectValues)) {
a30e57e0
DL
5148 // its a string, lets get the int value
5149 $value = array_search($value, $selectValues);
5150 }
9df8a11d
DL
5151 if ($useIDsOnly) {
5152 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5153 if ($tableName == 'civicrm_contact') {
5154 $wc = "contact_a.$fieldName";
5155 }
5156 }
5157 else {
5158 $wc = self::caseImportant($op) ? "LOWER({$field['where']})" : "{$field['where']}";
5159 }
d9ab802d
PJ
5160
5161 if (in_array($name, $pseudoFields)) {
aa62b355 5162 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
d9ab802d
PJ
5163 $wc = "contact_a.{$name}_id";
5164 }
5165 $dataType = 'Positive';
5166 $value = (!$value) ? 0 : $value;
5167 }
5168
6a488035 5169 $this->_qill[$grouping][] = $label . " $op '$qill'";
d9ab802d
PJ
5170 $op = (in_array($name, $pseudoFields) && ($op == 'LIKE' || $op == 'RLIKE')) ? '=' : $op;
5171 $this->_where[$grouping][] = self::buildClause($wc, $op, $value, $dataType);
6a488035
TO
5172 }
5173
a30e57e0
DL
5174 /**
5175 * function to check and explode a user defined numeric string into an array
6a488035
TO
5176 * this was the protocol used by search builder in the old old days before we had
5177 * super nice js widgets to do the hard work
5178 *
837c4660
E
5179 * @param the $string
5180 * @param string $dataType the dataType we should check for the values, default integer
6a488035
TO
5181 *
5182 * @return FALSE if string does not match the patter
5183 * array of numeric values if string does match the pattern
5184 * @static
5185 */
5186 static function parseSearchBuilderString($string, $dataType = 'Integer') {
5187 $string = trim($string);
5188 if (substr($string, 0, 1) != '(' || substr($string, -1, 1) != ')') {
5189 Return FALSE;
5190 }
5191
5192 $string = substr($string, 1, -1);
5193 $values = explode(',', $string);
5194 if (empty($values)) {
5195 return FALSE;
5196 }
5197
5198 $returnValues = array();
5199 foreach ($values as $v) {
5200 if ($dataType == 'Integer' && ! is_numeric($v)) {
5201 return FALSE;
5202 }
5203 else if ($dataType == 'String' && ! is_string($v)) {
5204 return FALSE;
5205 }
5206 $returnValues[] = trim($v);
5207 }
5208
5209 if (empty($returnValues)) {
5210 return FALSE;
5211 }
5212
5213 return $returnValues;
5214 }
6a488035 5215
d9ab802d
PJ
5216 /**
5217 * convert the pseudo constants id's to their names
837c4660 5218 *
d9ab802d 5219 * @param reference parameter $dao
837c4660
E
5220 * @param bool $return
5221 *
5222 * @return array
d9ab802d 5223 */
b719f000 5224 function convertToPseudoNames(&$dao, $return = FALSE) {
d9ab802d
PJ
5225 if (empty($this->_pseudoConstantsSelect)) {
5226 return;
5227 }
d9ab802d
PJ
5228 $values = array();
5229 foreach ($this->_pseudoConstantsSelect as $key => $value) {
a7488080 5230 if (!empty($this->_pseudoConstantsSelect[$key]['sorting'])) {
d9ab802d
PJ
5231 continue;
5232 }
5233
5234 if (property_exists($dao, $value['idCol'])) {
5235 $val = $dao->$value['idCol'];
5236
5237 if (CRM_Utils_System::isNull($val)) {
5238 $dao->$key = NULL;
d9ab802d 5239 }
b719f000 5240 elseif ($baoName = CRM_Utils_Array::value('bao', $value, NULL)) {
827659b2 5241 //preserve id value
5242 $idColumn = "{$key}_id";
5243 $dao->$idColumn = $val;
828c974f 5244 $dao->$value['pseudoField'] = $dao->$key = CRM_Core_PseudoConstant::getLabel($baoName, $value['pseudoField'], $val);
d9ab802d
PJ
5245 }
5246 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5247 $dao->$key = CRM_Core_PseudoConstant::stateProvinceAbbreviation($val);
5248 }
d9ab802d
PJ
5249 else {
5250 $labels = CRM_Core_OptionGroup::values($value['pseudoField']);
5251 $dao->$key = $labels[$val];
5252 }
b719f000
PJ
5253
5254 // return converted values in array format
5255 if ($return) {
5256 if (strpos($key, '-') !== FALSE) {
5257 $keyVal = explode('-', $key);
5258 $current = &$values;
5259 $lastElement = array_pop($keyVal);
5260 foreach ($keyVal as $v) {
5261 if (!array_key_exists($v, $current)) {
5262 $current[$v] = array();
5263 }
5264 $current = &$current[$v];
5265 }
5266 $current[$lastElement] = $dao->$key;
5267 }
5268 else {
5269 $values[$key] = $dao->$key;
5270 }
5271 }
d9ab802d
PJ
5272 }
5273 }
5274 return $values;
5275 }
5276
837c4660 5277 /**
d9ab802d
PJ
5278 * include pseudo fields LEFT JOIN
5279 * @param $sort can be a object or string
5280 *
837c4660 5281 * @return array
d9ab802d
PJ
5282 */
5283 function includePseudoFieldsJoin($sort) {
5284 if (!$sort || empty($this->_pseudoConstantsSelect)) {
5285 return;
5286 }
5287 $sort = is_string($sort) ? $sort : $sort->orderBy();
5288 $present = array();
5289
5290 foreach ($this->_pseudoConstantsSelect as $name => $value) {
a7488080 5291 if (!empty($value['table'])) {
d9ab802d
PJ
5292 $regex = "/({$value['table']}\.|{$name})/";
5293 if (preg_match($regex, $sort)) {
5294 $this->_elemnt[$value['element']] = 1;
5295 $this->_select[$value['element']] = $value['select'];
5296 $this->_pseudoConstantsSelect[$name]['sorting'] = 1;
5297 $present[$value['table']] = $value['join'];
5298 }
5299 }
5300 }
5301 $presentSimpleFrom = $present;
5302
5303 if (array_key_exists('civicrm_worldregion', $this->_whereTables) &&
5304 array_key_exists('civicrm_country', $presentSimpleFrom)) {
5305 unset($presentSimpleFrom['civicrm_country']);
5306 }
5307 if (array_key_exists('civicrm_worldregion', $this->_tables) &&
5308 array_key_exists('civicrm_country', $present)) {
5309 unset($present['civicrm_country']);
5310 }
5311
5312 $presentClause = $presentSimpleFromClause = NULL;
5313 if (!empty($present)) {
5314 $presentClause = implode(' ', $present);
5315 }
5316 if (!empty($presentSimpleFrom)) {
5317 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
5318 }
5319
5320 $this->_fromClause = $this->_fromClause . $presentClause;
5321 $this->_simpleFromClause = $this->_simpleFromClause . $presentSimpleFromClause;
5322
5323 return array($presentClause, $presentSimpleFromClause);
5324 }
e7830dbe 5325}