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