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