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