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