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