CRM-13344 - Update search builder and other code for pseudoconstant fields
[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;
1529 case 'group_type':
1530 // so we resolve this into a list of groups & proceed as if they had been
1531 // handed in
1532 list($name, $op, $value, $grouping, $wildcard) = $values;
1533 $values[0] = 'group';
1534 $values[1] = 'IN';
1535 $this->_paramLookup['group'][0][0] ='group';
1536 $this->_paramLookup['group'][0][1] = 'IN';
1537 $this->_paramLookup['group'][0][2] = $values[2] = $this->getGroupsFromTypeCriteria($value);
1538 $this->group($values);
1539 return;
1540 // case tag comes from find contacts
1541
1542 case 'tag_search':
1543 $this->tagSearch($values);
1544 return;
1545
1546 case 'tag':
1547 case 'contact_tags':
1548 $this->tag($values);
1549 return;
1550
1551 case 'note':
1552 case 'note_body':
1553 case 'note_subject':
1554 $this->notes($values);
1555 return;
1556
1557 case 'uf_user':
1558 $this->ufUser($values);
1559 return;
1560
1561 case 'sort_name':
1562 case 'display_name':
1563 $this->sortName($values);
6a488035
TO
1564 return;
1565
1566 case 'email':
1567 $this->email($values);
1568 return;
1569
1570 case 'phone_numeric':
1571 $this->phone_numeric($values);
1572 return;
1573
1574 case 'phone_phone_type_id':
1575 case 'phone_location_type_id':
1576 $this->phone_option_group($values);
1577 return;
1578
1579 case 'street_address':
1580 $this->street_address($values);
1581 return;
1582
1583 case 'street_number':
1584 $this->street_number($values);
1585 return;
1586
1587 case 'sortByCharacter':
1588 $this->sortByCharacter($values);
1589 return;
1590
1591 case 'location_type':
1592 $this->locationType($values);
1593 return;
1594
1595 case 'county':
1596 $this->county($values);
1597 return;
1598
1599 case 'state_province':
1600 $this->stateProvince($values);
1601 return;
1602
1603 case 'country':
1604 $this->country($values, FALSE);
1605 return;
1606
1607 case 'postal_code':
1608 case 'postal_code_low':
1609 case 'postal_code_high':
1610 $this->postalCode($values);
1611 return;
1612
1613 case 'activity_date':
1614 case 'activity_date_low':
1615 case 'activity_date_high':
1616 case 'activity_role':
1617 case 'activity_status':
1618 case 'activity_subject':
1619 case 'test_activities':
1620 case 'activity_type_id':
1621 case 'activity_survey_id':
1622 case 'activity_tags':
1623 case 'activity_taglist':
1624 case 'activity_test':
6a488035
TO
1625 case 'activity_campaign_id':
1626 case 'activity_engagement_level':
1627 case 'activity_id':
1628 case 'source_contact':
1629 CRM_Activity_BAO_Query::whereClauseSingle($values, $this);
1630 return;
1631
1632 case 'birth_date_low':
1633 case 'birth_date_high':
1634 case 'deceased_date_low':
1635 case 'deceased_date_high':
1636 $this->demographics($values);
1637 return;
1638
1639 case 'log_date_low':
1640 case 'log_date_high':
1641 $this->modifiedDates($values);
1642 return;
1643
1644 case 'changed_by':
1645 $this->changeLog($values);
1646 return;
1647
1648 case 'do_not_phone':
1649 case 'do_not_email':
1650 case 'do_not_mail':
1651 case 'do_not_sms':
1652 case 'do_not_trade':
1653 case 'is_opt_out':
1654 $this->privacy($values);
1655 return;
1656
1657 case 'privacy_options':
1658 $this->privacyOptions($values);
1659 return;
1660
1661 case 'privacy_operator':
1662 case 'privacy_toggle':
1663 // these are handled by privacy options
1664 return;
1665
1666 case 'preferred_communication_method':
1667 $this->preferredCommunication($values);
1668 return;
1669
1670 case 'relation_type_id':
ad682134 1671 case 'relation_start_date_high':
1672 case 'relation_start_date_low':
1673 case 'relation_end_date_high':
1674 case 'relation_end_date_low':
6a488035
TO
1675 case 'relation_target_name':
1676 case 'relation_status':
1677 case 'relation_date_low':
1678 case 'relation_date_high':
7c96365b 1679 $this->relationship($values);
1680 $this->_relationshipValuesAdded = TRUE;
6a488035
TO
1681 return;
1682
1683 case 'task_status_id':
1684 $this->task($values);
1685 return;
1686
1687 case 'task_id':
1688 // since this case is handled with the above
1689 return;
1690
1691 case 'prox_distance':
1692 CRM_Contact_BAO_ProximityQuery::process($this, $values);
1693 return;
1694
1695 case 'prox_street_address':
1696 case 'prox_city':
1697 case 'prox_postal_code':
1698 case 'prox_state_province_id':
1699 case 'prox_country_id':
1700 // handled by the proximity_distance clause
1701 return;
1702
1703 default:
1704 $this->restWhere($values);
1705 return;
1706 }
1707 }
1708
1709 /**
1710 * Given a list of conditions in params generate the required
1711 * where clause
1712 *
1713 * @return void
1714 * @access public
1715 */
1716 function whereClause() {
1717 $this->_where[0] = array();
1718 $this->_qill[0] = array();
1719
6a488035
TO
1720 $this->includeContactIds();
1721 if (!empty($this->_params)) {
6a488035
TO
1722 foreach (array_keys($this->_params) as $id) {
1723 if (!CRM_Utils_Array::value(0, $this->_params[$id])) {
1724 continue;
1725 }
1726 // check for both id and contact_id
1727 if ($this->_params[$id][0] == 'id' || $this->_params[$id][0] == 'contact_id') {
a7516181
DL
1728 if (
1729 $this->_params[$id][1] == 'IS NULL' ||
6a488035
TO
1730 $this->_params[$id][1] == 'IS NOT NULL'
1731 ) {
1732 $this->_where[0][] = "contact_a.id {$this->_params[$id][1]}";
1733 }
a7516181
DL
1734 elseif (is_array($this->_params[$id][2])) {
1735 $idList = implode("','", $this->_params[$id][2]);
78c0bfc0 1736 //why on earth do they put ' in the middle & not on the outside? We have to assume it's
1737 //to support 'something' so lets add them conditionally to support the api (which is a tested flow
1738 // so if you are looking to alter this check api test results
1739 if(strpos(trim($idList), "'") > 0) {
1740 $idList = "'" . $idList . "'";
1741 }
1742
a7516181
DL
1743 $this->_where[0][] = "contact_a.id IN ({$idList})";
1744 }
6a488035
TO
1745 else {
1746 $this->_where[0][] = "contact_a.id {$this->_params[$id][1]} {$this->_params[$id][2]}";
1747 }
1748 }
1749 else {
1750 $this->whereClauseSingle($this->_params[$id]);
1751 }
1752 }
1753
1754 CRM_Core_Component::alterQuery($this, 'where');
f2a9b25c 1755
99e9587a 1756 CRM_Contact_BAO_Query_Hook::singleton()->alterSearchQuery($this, 'where');
6a488035
TO
1757 }
1758
1759 if ($this->_customQuery) {
1760 // Added following if condition to avoid the wrong value diplay for 'myaccount' / any UF info.
1761 // Hope it wont affect the other part of civicrm.. if it does please remove it.
1762 if (!empty($this->_customQuery->_where)) {
1763 $this->_where = CRM_Utils_Array::crmArrayMerge($this->_where, $this->_customQuery->_where);
1764 }
1765
1766 $this->_qill = CRM_Utils_Array::crmArrayMerge($this->_qill, $this->_customQuery->_qill);
1767 }
1768
1769 $clauses = array();
1770 $andClauses = array();
1771
1772 $validClauses = 0;
1773 if (!empty($this->_where)) {
1774 foreach ($this->_where as $grouping => $values) {
1775 if ($grouping > 0 && !empty($values)) {
1776 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
1777 $validClauses++;
1778 }
1779 }
1780
1781 if (!empty($this->_where[0])) {
1782 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where[0]) . ' ) ';
1783 }
1784 if (!empty($clauses)) {
1785 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
1786 }
1787
1788 if ($validClauses > 1) {
1789 $this->_useDistinct = TRUE;
1790 }
1791 }
1792
1793 return implode(' AND ', $andClauses);
1794 }
1795
1796 function restWhere(&$values) {
1797 $name = CRM_Utils_Array::value(0, $values);
1798 $op = CRM_Utils_Array::value(1, $values);
1799 $value = CRM_Utils_Array::value(2, $values);
1800 $grouping = CRM_Utils_Array::value(3, $values);
1801 $wildcard = CRM_Utils_Array::value(4, $values);
1802
1803 if (isset($grouping) && !CRM_Utils_Array::value($grouping, $this->_where)) {
1804 $this->_where[$grouping] = array();
1805 }
1806
1807 $multipleFields = array('url');
1808
1809 //check if the location type exits for fields
1810 $lType = '';
1811 $locType = explode('-', $name);
1812
1813 if (!in_array($locType[0], $multipleFields)) {
1814 //add phone type if exists
1815 if (isset($locType[2]) && $locType[2]) {
1816 $locType[2] = CRM_Core_DAO::escapeString($locType[2]);
1817 }
1818 }
1819
1820 $field = CRM_Utils_Array::value($name, $this->_fields);
1821
1822 if (!$field) {
1823 $field = CRM_Utils_Array::value($locType[0], $this->_fields);
1824
1825 if (!$field) {
1826 return;
1827 }
1828 }
1829
1830 $setTables = TRUE;
1831
1832 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
d9ab802d 1833 $locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
6a488035
TO
1834
1835 if (substr($name, 0, 14) === 'state_province') {
d9ab802d 1836 $setTables = FALSE;
6a488035 1837 if (isset($locType[1]) && is_numeric($locType[1])) {
d9ab802d
PJ
1838 $aName = "{$locationType[$locType[1]]}-address";
1839 $where = "`$aName`.state_province_id";
6a488035
TO
1840 }
1841 else {
d9ab802d 1842 $where = "civicrm_address.state_province_id";
6a488035
TO
1843 }
1844
d9ab802d 1845 $states = CRM_Core_PseudoConstant::stateProvince();
6a488035 1846 if (is_numeric($value)) {
6a488035 1847 $this->_where[$grouping][] = self::buildClause($where, $op, $value, 'Positive');
6a488035
TO
1848 $value = $states[(int ) $value];
1849 }
1850 else {
d9ab802d
PJ
1851 $intVal = CRM_Utils_Array::key($value, $states);
1852 $this->_where[$grouping][] = self::buildClause($where, $op, $intVal, 'Positive');
6a488035
TO
1853 }
1854 if (!$lType) {
1855 $this->_qill[$grouping][] = ts('State') . " $op '$value'";
1856 }
1857 else {
1858 $this->_qill[$grouping][] = ts('State') . " ($lType) $op '$value'";
1859 }
1860 }
1c1a84a2 1861 elseif (!empty($field['pseudoconstant'])) {
1071730c
DL
1862 $this->optionValueQuery(
1863 $name, $op, $value, $grouping,
9df8a11d 1864 CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', $field['name']),
1071730c 1865 $field,
a30e57e0
DL
1866 $field['title'],
1867 'String',
1868 TRUE
1071730c 1869 );
9df8a11d 1870 if ($name == 'gender_id') {
1071730c
DL
1871 self::$_openedPanes[ts('Demographics')] = TRUE;
1872 }
1873 }
6a488035 1874 elseif (substr($name, 0, 7) === 'country') {
d9ab802d 1875 $setTables = FALSE;
6a488035 1876 if (isset($locType[1]) && is_numeric($locType[1])) {
d9ab802d
PJ
1877 $aName = "{$locationType[$locType[1]]}-address";
1878 $where = "`$aName`.country_id";
6a488035
TO
1879 }
1880 else {
d9ab802d 1881 $where = "civicrm_address.country_id";
6a488035
TO
1882 }
1883
d9ab802d 1884 $countries = CRM_Core_PseudoConstant::country();
6a488035 1885 if (is_numeric($value)) {
6a488035 1886 $this->_where[$grouping][] = self::buildClause($where, $op, $value, 'Positive');
6a488035
TO
1887 $value = $countries[(int ) $value];
1888 }
1889 else {
d9ab802d
PJ
1890 $intVal = CRM_Utils_Array::key($value, $countries);
1891 $this->_where[$grouping][] = self::buildClause($where, $op, $intVal, 'Positive');
6a488035
TO
1892 }
1893 if (!$lType) {
1894 $this->_qill[$grouping][] = ts('Country') . " $op '$value'";
1895 }
1896 else {
1897 $this->_qill[$grouping][] = ts('Country') . " ($lType) $op '$value'";
1898 }
1899 }
1900 elseif (substr($name, 0, 6) === 'county') {
d9ab802d 1901 $setTables = FALSE;
6a488035 1902 if (isset($locType[1]) && is_numeric($locType[1])) {
d9ab802d
PJ
1903 $aName = "{$locationType[$locType[1]]}-address";
1904 $where = "`$aName`.county_id";
6a488035
TO
1905 }
1906 else {
d9ab802d 1907 $where = "civicrm_address.county_id";
6a488035 1908 }
d9ab802d
PJ
1909
1910 $counties = CRM_Core_PseudoConstant::county();
6a488035 1911 if (is_numeric($value)) {
6a488035 1912 $this->_where[$grouping][] = self::buildClause($where, $op, $value, 'Positive');
6a488035
TO
1913 $value = $counties[(int ) $value];
1914 }
1915 else {
d9ab802d
PJ
1916 $intVal = CRM_Utils_Array::key($value, $counties);
1917 $this->_where[$grouping][] = self::buildClause($where, $op, $intVal, 'Positive');
6a488035
TO
1918 }
1919
1920 if (!$lType) {
1921 $this->_qill[$grouping][] = ts('County') . " $op '$value'";
1922 }
1923 else {
1924 $this->_qill[$grouping][] = ts('County') . " ($lType) $op '$value'";
1925 }
1926 }
1927 elseif ($name === 'world_region') {
1928 $this->optionValueQuery(
1929 $name, $op, $value, $grouping,
1930 CRM_Core_PseudoConstant::worldRegion(),
1931 $field,
1932 ts('World Region')
1933 );
1934 }
6a488035
TO
1935 elseif ($name === 'birth_date') {
1936 $date = CRM_Utils_Date::processDate($value);
1937 $this->_where[$grouping][] = self::buildClause("contact_a.{$name}", $op, $date);
1938
1939 if ($date) {
1940 $date = CRM_Utils_Date::customFormat($date);
1941 $this->_qill[$grouping][] = "$field[title] $op \"$date\"";
1942 }
1943 else {
1944 $this->_qill[$grouping][] = "$field[title] $op";
1945 }
1946 self::$_openedPanes[ts('Demographics')] = TRUE;
1947 }
1948 elseif ($name === 'deceased_date') {
1949 $date = CRM_Utils_Date::processDate($value);
1950 $this->_where[$grouping][] = self::buildClause("contact_a.{$name}", $op, $date);
1951 if ($date) {
1952 $date = CRM_Utils_Date::customFormat($date);
1953 $this->_qill[$grouping][] = "$field[title] $op \"$date\"";
1954 }
1955 else {
1956 $this->_qill[$grouping][] = "$field[title] $op";
1957 }
1958 self::$_openedPanes[ts('Demographics')] = TRUE;
1959 }
1960 elseif ($name === 'is_deceased') {
1961 $this->_where[$grouping][] = self::buildClause("contact_a.{$name}", $op, $value);
1962 $this->_qill[$grouping][] = "$field[title] $op \"$value\"";
1963 self::$_openedPanes[ts('Demographics')] = TRUE;
1964 }
1965 elseif ($name === 'contact_id') {
1966 if (is_int($value)) {
1967 $this->_where[$grouping][] = self::buildClause($field['where'], $op, $value);
1968 $this->_qill[$grouping][] = "$field[title] $op $value";
1969 }
1970 }
1971 elseif ($name === 'name') {
1972 $value = $strtolower(CRM_Core_DAO::escapeString($value));
1973 if ($wildcard) {
1974 $value = "%$value%";
1975 $op = 'LIKE';
1976 }
1977 $wc = self::caseImportant($op) ? "LOWER({$field['where']})" : "{$field['where']}";
1978 $this->_where[$grouping][] = self::buildClause($wc, $op, "'$value'");
1979 $this->_qill[$grouping][] = "$field[title] $op \"$value\"";
1980 }
1981 elseif ($name === 'current_employer') {
1982 $value = $strtolower(CRM_Core_DAO::escapeString($value));
1983 if ($wildcard) {
1984 $value = "%$value%";
1985 $op = 'LIKE';
1986 }
1987 $wc = self::caseImportant($op) ? "LOWER(contact_a.organization_name)" : "contact_a.organization_name";
1988 $this->_where[$grouping][] = self::buildClause($wc, $op,
1989 "'$value' AND contact_a.contact_type ='Individual'"
1990 );
1991 $this->_qill[$grouping][] = "$field[title] $op \"$value\"";
1992 }
1993 elseif ($name === 'email_greeting') {
1994 $filterCondition = array('greeting_type' => 'email_greeting');
1995 $this->optionValueQuery(
1996 $name, $op, $value, $grouping,
1997 CRM_Core_PseudoConstant::greeting($filterCondition),
1998 $field,
1999 ts('Email Greeting')
2000 );
2001 }
2002 elseif ($name === 'postal_greeting') {
2003 $filterCondition = array('greeting_type' => 'postal_greeting');
2004 $this->optionValueQuery(
2005 $name, $op, $value, $grouping,
2006 CRM_Core_PseudoConstant::greeting($filterCondition),
2007 $field,
2008 ts('Postal Greeting')
2009 );
2010 }
2011 elseif ($name === 'addressee') {
2012 $filterCondition = array('greeting_type' => 'addressee');
2013 $this->optionValueQuery(
2014 $name, $op, $value, $grouping,
2015 CRM_Core_PseudoConstant::greeting($filterCondition),
2016 $field,
2017 ts('Addressee')
2018 );
2019 }
2020 elseif (substr($name, 0, 4) === 'url-') {
2021 $tName = 'civicrm_website';
2022 $this->_whereTables[$tName] = $this->_tables[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2023 $value = $strtolower(CRM_Core_DAO::escapeString($value));
2024 if ($wildcard) {
2025 $value = "%$value%";
2026 $op = 'LIKE';
2027 }
2028
2029 $wc = 'civicrm_website.url';
2030 $this->_where[$grouping][] = self::buildClause($wc, $op, "'$value'");
2031 $this->_qill[$grouping][] = "$field[title] $op \"$value\"";
2032 }
2033 elseif ($name === 'contact_is_deleted') {
2034 $this->_where[$grouping][] = self::buildClause("contact_a.is_deleted", $op, $value);
2035 $this->_qill[$grouping][] = "$field[title] $op \"$value\"";
2036 }
2037 else {
2038 // sometime the value is an array, need to investigate and fix
2039 if (is_array($value)) {
2040 CRM_Core_Error::fatal();
2041 }
2042
2043 if (!empty($field['where'])) {
2044 if ($op != 'IN') {
2045 $value = $strtolower($value);
2046 }
2047 if ($wildcard) {
2048 $value = "%$value%";
2049 $op = 'LIKE';
2050 }
2051
2052 if (isset($locType[1]) &&
2053 is_numeric($locType[1])
2054 ) {
2055 $setTables = FALSE;
2056
2057 //get the location name
6a488035
TO
2058 list($tName, $fldName) = self::getLocationTableName($field['where'], $locType);
2059
2060 $where = "`$tName`.$fldName";
2061
2062 $this->_where[$grouping][] = self::buildClause("LOWER($where)", $op, $value);
2063 $this->_whereTables[$tName] = $this->_tables[$tName];
2064 $this->_qill[$grouping][] = "$field[title] $op '$value'";
2065 }
2066 else {
2067 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2068 if ($tableName == 'civicrm_contact') {
2069 $fieldName = "LOWER(contact_a.{$fieldName})";
2070 }
2071 else {
2072 if ($op != 'IN' && !is_numeric($value)) {
2073 $fieldName = "LOWER({$field['where']})";
2074 }
2075 else {
2076 $fieldName = "{$field['where']}";
2077 }
2078 }
2079
2080 $type = NULL;
2081 if (CRM_Utils_Array::value('type', $field)) {
2082 $type = CRM_Utils_Type::typeToString($field['type']);
2083 }
2084
2085 $this->_where[$grouping][] = self::buildClause($fieldName, $op, $value, $type);
2086 $this->_qill[$grouping][] = "$field[title] $op $value";
2087 }
2088 }
2089 }
2090
2091 if ($setTables && isset($field['where'])) {
2092 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2093 if (isset($tableName)) {
2094 $this->_tables[$tableName] = 1;
2095 $this->_whereTables[$tableName] = 1;
2096 }
2097 }
2098 }
2099
2100
2101 static function getLocationTableName(&$where, &$locType) {
2102 if (isset($locType[1]) && is_numeric($locType[1])) {
2103 list($tbName, $fldName) = explode(".", $where);
2104
2105 //get the location name
b2b0530a 2106 $locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
6a488035
TO
2107 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2108 if (in_array($locType[0], $specialFields)) {
2109 //hack to fix / special handing for phone_ext
2110 if ($locType[0] == 'phone_ext') {
2111 $locType[0] = 'phone';
2112 }
2113 if (isset($locType[2]) && $locType[2]) {
2114 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2115 }
2116 else {
2117 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2118 }
2119 }
2120 elseif (in_array($locType[0],
2121 array(
2122 'address_name', 'street_address', 'supplemental_address_1', 'supplemental_address_2',
2123 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2',
2124 )
2125 )) {
2126 //fix for search by profile with address fields.
2127 $tName = "{$locationType[$locType[1]]}-address";
2128 }
2129 elseif ($locType[0] == 'on_hold') {
2130 $tName = "{$locationType[$locType[1]]}-email";
2131 }
2132 else {
2133 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2134 }
2135 $tName = str_replace(' ', '_', $tName);
2136 return array($tName, $fldName);
2137 }
2138 CRM_Core_Error::fatal();
2139 }
2140
2141 /**
2142 * Given a result dao, extract the values and return that array
2143 *
2144 * @param Object $dao
2145 *
2146 * @return array values for this query
2147 */
2148 function store($dao) {
2149 $value = array();
2150
2151 foreach ($this->_element as $key => $dontCare) {
2152 if (property_exists($dao, $key)) {
2153 if (strpos($key, '-') !== FALSE) {
2154 $values = explode('-', $key);
2155 $lastElement = array_pop($values);
2156 $current = &$value;
2157 $cnt = count($values);
2158 $count = 1;
2159 foreach ($values as $v) {
2160 if (!array_key_exists($v, $current)) {
2161 $current[$v] = array();
2162 }
2163 //bad hack for im_provider
2164 if ($lastElement == 'provider_id') {
2165 if ($count < $cnt) {
2166 $current = &$current[$v];
2167 }
2168 else {
2169 $lastElement = "{$v}_{$lastElement}";
2170 }
2171 }
2172 else {
2173 $current = &$current[$v];
2174 }
2175 $count++;
2176 }
2177
2178 $current[$lastElement] = $dao->$key;
2179 }
2180 else {
2181 $value[$key] = $dao->$key;
2182 }
2183 }
2184 }
2185 return $value;
2186 }
2187
2188 /**
2189 * getter for tables array
2190 *
2191 * @return array
2192 * @access public
2193 */
2194 function tables() {
2195 return $this->_tables;
2196 }
2197
2198 function whereTables() {
2199 return $this->_whereTables;
2200 }
2201
2202 /**
2203 * generate the where clause (used in match contacts and permissions)
2204 *
2205 * @param array $params
2206 * @param array $fields
2207 * @param array $tables
2208 * @param boolean $strict
2209 *
2210 * @return string
2211 * @access public
2212 * @static
2213 */
2214 static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2215 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2216 FALSE, $strict
2217 );
2218
2219 $tables = array_merge($query->tables(), $tables);
2220 $whereTables = array_merge($query->whereTables(), $whereTables);
2221
2222 return $query->_whereClause;
2223 }
2224
2225 /**
2226 * create the from clause
2227 *
2228 * @param array $tables tables that need to be included in this from clause
2229 * if null, return mimimal from clause (i.e. civicrm_contact)
2230 * @param array $inner tables that should be inner-joined
2231 * @param array $right tables that should be right-joined
2232 *
2233 * @return string the from clause
2234 * @access public
2235 * @static
2236 */
2237 static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1) {
2238
2239 $from = ' FROM civicrm_contact contact_a';
2240 if (empty($tables)) {
2241 return $from;
2242 }
2243
2244 if (CRM_Utils_Array::value('civicrm_worldregion', $tables)) {
2245 $tables = array_merge(array('civicrm_country' => 1), $tables);
2246 }
2247
2248 if ((CRM_Utils_Array::value('civicrm_state_province', $tables) ||
2249 CRM_Utils_Array::value('civicrm_country', $tables) ||
2250 CRM_Utils_Array::value('civicrm_county', $tables)
2251 ) &&
2252 !CRM_Utils_Array::value('civicrm_address', $tables)
2253 ) {
2254 $tables = array_merge(array('civicrm_address' => 1),
2255 $tables
2256 );
2257 }
2258
2259 // add group_contact table if group table is present
2260 if (CRM_Utils_Array::value('civicrm_group', $tables) &&
2261 !CRM_Utils_Array::value('civicrm_group_contact', $tables)
2262 ) {
2263 $tables['civicrm_group_contact'] = " LEFT JOIN civicrm_group_contact ON civicrm_group_contact.contact_id = contact_a.id AND civicrm_group_contact.status = 'Added'";
2264 }
2265
2266 // add group_contact and group table is subscription history is present
2267 if (CRM_Utils_Array::value('civicrm_subscription_history', $tables)
2268 && !CRM_Utils_Array::value('civicrm_group', $tables)
2269 ) {
2270 $tables = array_merge(array(
2271 'civicrm_group' => 1,
2272 'civicrm_group_contact' => 1,
2273 ),
2274 $tables
2275 );
2276 }
2277
2278 // to handle table dependencies of components
2279 CRM_Core_Component::tableNames($tables);
efa3a566
DS
2280 // to handle table dependencies of hook injected tables
2281 CRM_Contact_BAO_Query_Hook::singleton()->setTableDependency($tables);
6a488035
TO
2282
2283 //format the table list according to the weight
2284 $info = CRM_Core_TableHierarchy::info();
2285
2286 foreach ($tables as $key => $value) {
2287 $k = 99;
2288 if (strpos($key, '-') !== FALSE) {
2289 $keyArray = explode('-', $key);
2290 $k = CRM_Utils_Array::value('civicrm_' . $keyArray[1], $info, 99);
2291 }
2292 elseif (strpos($key, '_') !== FALSE) {
2293 $keyArray = explode('_', $key);
2294 if (is_numeric(array_pop($keyArray))) {
2295 $k = CRM_Utils_Array::value(implode('_', $keyArray), $info, 99);
2296 }
2297 else {
2298 $k = CRM_Utils_Array::value($key, $info, 99);
2299 }
2300 }
2301 else {
2302 $k = CRM_Utils_Array::value($key, $info, 99);
2303 }
2304 $tempTable[$k . ".$key"] = $key;
2305 }
2306 ksort($tempTable);
2307 $newTables = array();
2308 foreach ($tempTable as $key) {
2309 $newTables[$key] = $tables[$key];
2310 }
2311
2312 $tables = $newTables;
2313
2314 foreach ($tables as $name => $value) {
2315 if (!$value) {
2316 continue;
2317 }
2318
2319 if (CRM_Utils_Array::value($name, $inner)) {
2320 $side = 'INNER';
2321 }
2322 elseif (CRM_Utils_Array::value($name, $right)) {
2323 $side = 'RIGHT';
2324 }
2325 else {
2326 $side = 'LEFT';
2327 }
2328
2329 if ($value != 1) {
2330 // if there is already a join statement in value, use value itself
2331 if (strpos($value, 'JOIN')) {
2332 $from .= " $value ";
2333 }
2334 else {
2335 $from .= " $side JOIN $name ON ( $value ) ";
2336 }
2337 continue;
2338 }
2339 switch ($name) {
2340 case 'civicrm_address':
2341 if ($primaryLocation) {
2342 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )";
2343 }
2344 else {
2345 $from .= " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id ) ";
2346 }
2347 continue;
2348
2349 case 'civicrm_phone':
2350 $from .= " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) ";
2351 continue;
2352
2353 case 'civicrm_email':
2354 $from .= " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) ";
2355 continue;
2356
2357 case 'civicrm_im':
2358 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) ";
2359 continue;
2360
2361 case 'im_provider':
2362 $from .= " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2363 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2364 $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)";
2365 continue;
2366
2367 case 'civicrm_openid':
2368 $from .= " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id AND civicrm_openid.is_primary = 1 )";
2369 continue;
2370
6a488035 2371 case 'civicrm_worldregion':
d9ab802d 2372 $from .= " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
6a488035
TO
2373 $from .= " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2374 continue;
2375
6a488035
TO
2376 case 'civicrm_location_type':
2377 $from .= " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2378 continue;
2379
2380 case 'civicrm_group':
2381 $from .= " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2382 continue;
2383
2384 case 'civicrm_group_contact':
2385 $from .= " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2386 continue;
2387
2388 case 'civicrm_activity':
2389 case 'civicrm_activity_tag':
2390 case 'activity_type':
2391 case 'activity_status':
2392 case 'civicrm_activity_contact':
2393 case 'source_contact':
2394 $from .= CRM_Activity_BAO_Query::from($name, $mode, $side);
2395 continue;
2396
2397 case 'civicrm_entity_tag':
2398 $from .= " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND
2399 civicrm_entity_tag.entity_id = contact_a.id ) ";
2400 continue;
2401
2402 case 'civicrm_note':
2403 $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND
2404 contact_a.id = civicrm_note.entity_id ) ";
2405 continue;
2406
2407 case 'civicrm_subscription_history':
2408 $from .= " $side JOIN civicrm_subscription_history
2409 ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id
2410 AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2411 continue;
2412
6a488035
TO
2413 case 'civicrm_relationship':
2414 if (self::$_relType == 'reciprocal') {
7c96365b 2415 if(self::$_relationshipTempTable) {
2416 // we have a temptable to join on
2417 $tbl = self::$_relationshipTempTable;
2418 $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2419 }
2420 else {
2421 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2422 $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)";
2423 }
6a488035
TO
2424 }
2425 elseif (self::$_relType == 'b') {
2426 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2427 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2428 }
2429 else {
2430 $from .= " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2431 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2432 }
2433 continue;
2434
2435 case 'civicrm_log':
2436 $from .= " $side JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2437 $from .= " $side JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2438 continue;
2439
2440 case 'civicrm_tag':
2441 $from .= " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2442 continue;
2443
6a488035
TO
2444 case 'civicrm_grant':
2445 $from .= CRM_Grant_BAO_Query::from($name, $mode, $side);
2446 continue;
2447
6a488035
TO
2448 case 'civicrm_website':
2449 $from .= " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2450 continue;
2451
2452 default:
2453 $from .= CRM_Core_Component::from($name, $mode, $side);
99e9587a
DS
2454 $from .= CRM_Contact_BAO_Query_Hook::singleton()->buildSearchfrom($name, $mode, $side);
2455
6a488035
TO
2456 continue;
2457 }
2458 }
2459
2460 return $from;
2461 }
2462
2463 /**
2464 * WHERE / QILL clause for deleted_contacts
2465 *
2466 * @return void
2467 */
2468 function deletedContacts($values) {
2469 list($_, $_, $value, $grouping, $_) = $values;
2470 if ($value) {
2471 // *prepend* to the relevant grouping as this is quite an important factor
2472 array_unshift($this->_qill[$grouping], ts('Search in Trash'));
2473 }
2474 }
2475
2476 /**
2477 * where / qill clause for contact_type
2478 *
2479 * @return void
2480 * @access public
2481 */
2482 function contactType(&$values) {
2483 list($name, $op, $value, $grouping, $wildcard) = $values;
2484
2485 $subTypes = array();
2486 $clause = array();
2487
2488 // account for search builder mapping multiple values
2489 if (!is_array($value)) {
2490 $values = self::parseSearchBuilderString($value, 'String');
2491 if (is_array($values)) {
2492 $value = array_flip($values);
2493 }
2494 }
2495
2496 if (is_array($value)) {
2497 foreach ($value as $k => $v) {
2498 // fix for CRM-771
2499 if ($k) {
2500 $subType = NULL;
2501 $contactType = $k;
2502 if (strpos($k, CRM_Core_DAO::VALUE_SEPARATOR)) {
2503 list($contactType, $subType) = explode(CRM_Core_DAO::VALUE_SEPARATOR, $k, 2);
2504 }
2505
2506 if (!empty($subType)) {
2507 $subTypes[$subType] = 1;
2508 }
2509 $clause[$contactType] = "'" . CRM_Utils_Type::escape($contactType, 'String') . "'";
2510 }
2511 }
2512 }
2513 else {
2514 $contactTypeANDSubType = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value, 2);
2515 $contactType = $contactTypeANDSubType[0];
2516 $subType = CRM_Utils_Array::value(1, $contactTypeANDSubType);
2517 if (!empty($subType)) {
2518 $subTypes[$subType] = 1;
2519 }
2520 $clause[$contactType] = "'" . CRM_Utils_Type::escape($contactType, 'String') . "'";
2521 }
2522
2523 // fix for CRM-771
2524 if (!empty($clause)) {
3b3bc827
CW
2525 if ($op == 'IN' || $op == 'NOT IN') {
2526 $this->_where[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2527 }
2528 else {
d4b81b9a 2529 $quill = $clause;
3b3bc827
CW
2530 $type = array_pop($clause);
2531 $this->_where[$grouping][] = "contact_a.contact_type $op $type";
2532 }
d4b81b9a 2533
2534 $this->_qill[$grouping][] = ts('Contact Type') . ' - ' . implode(' ' . ts('or') . ' ', $quill);
6a488035
TO
2535
2536 if (!empty($subTypes)) {
2537 $this->includeContactSubTypes($subTypes, $grouping);
2538 }
2539 }
2540 }
2541
2542 /**
2543 * where / qill clause for contact_sub_type
2544 *
2545 * @return void
2546 * @access public
2547 */
2548 function contactSubType(&$values) {
2549 list($name, $op, $value, $grouping, $wildcard) = $values;
2550 $this->includeContactSubTypes($value, $grouping);
2551 }
2552
2553 function includeContactSubTypes($value, $grouping) {
2554
2555 $clause = array();
2556 $alias = "contact_a.contact_sub_type";
2557
2558 if (is_array($value)) {
2559 foreach ($value as $k => $v) {
2560 if (!empty($k)) {
2561 $clause[$k] = "($alias like '%" . CRM_Core_DAO::VALUE_SEPARATOR . CRM_Utils_Type::escape($k, 'String') . CRM_Core_DAO::VALUE_SEPARATOR . "%')";
2562 }
2563 }
2564 }
2565 else {
2566 $clause[$value] = "($alias like '%" . CRM_Core_DAO::VALUE_SEPARATOR . CRM_Utils_Type::escape($value, 'String') . CRM_Core_DAO::VALUE_SEPARATOR . "%')";
2567 }
2568
2569 if (!empty($clause)) {
2570 $this->_where[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2571 $this->_qill[$grouping][] = ts('Contact Subtype') . ' - ' . implode(' ' . ts('or') . ' ', array_keys($clause));
2572 }
2573 }
2574
2575 /**
2576 * where / qill clause for groups
2577 *
2578 * @return void
2579 * @access public
2580 */
2581 function group(&$values) {
2582 list($name, $op, $value, $grouping, $wildcard) = $values;
2583
2584 if (count($value) > 1) {
2585 $this->_useDistinct = TRUE;
2586 }
2587
2588 $groupNames = CRM_Core_PseudoConstant::group();
2589 $groupIds = implode(',', array_keys($value));
2590
2591 $names = array();
2592 foreach ($value as $id => $dontCare) {
2593 if (array_key_exists($id, $groupNames) && $dontCare) {
2594 $names[] = $groupNames[$id];
2595 }
2596 }
2597
2598 $statii = array();
2599 $in = FALSE;
2600 $gcsValues = &$this->getWhereValues('group_contact_status', $grouping);
2601 if ($gcsValues &&
2602 is_array($gcsValues[2])
2603 ) {
2604 foreach ($gcsValues[2] as $k => $v) {
2605 if ($v) {
2606 if ($k == 'Added') {
2607 $in = TRUE;
2608 }
2609 $statii[] = "'" . CRM_Utils_Type::escape($k, 'String') . "'";
2610 }
2611 }
2612 }
2613 else {
2614 $statii[] = '"Added"';
2615 $in = TRUE;
2616 }
2617
2618 $skipGroup = FALSE;
2619 if (count($value) == 1 &&
2620 count($statii) == 1 &&
2621 $statii[0] == '"Added"'
2622 ) {
2623 // check if smart group, if so we can get rid of that one additional
2624 // left join
2625 $groupIDs = array_keys($value);
2626
2627 if (CRM_Utils_Array::value(0, $groupIDs) &&
2628 CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group',
2629 $groupIDs[0],
2630 'saved_search_id'
2631 )
2632 ) {
2633 $skipGroup = TRUE;
2634 }
2635 }
2636
2637 if (!$skipGroup) {
2638 $gcTable = "`civicrm_group_contact-{$groupIds}`";
2639 $this->_tables[$gcTable] = $this->_whereTables[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON contact_a.id = {$gcTable}.contact_id ";
2640 }
2641
2642 $qill = ts('Contacts %1', array(1 => $op));
2643 $qill .= ' ' . implode(' ' . ts('or') . ' ', $names);
2644
2645 $groupClause = NULL;
2646
2647 if (!$skipGroup) {
2648 $groupClause = "{$gcTable}.group_id $op ( $groupIds )";
2649 if (!empty($statii)) {
2650 $groupClause .= " AND {$gcTable}.status IN (" . implode(', ', $statii) . ")";
2651 $qill .= " " . ts('AND') . " " . ts('Group Status') . ' - ' . implode(' ' . ts('or') . ' ', $statii);
2652 }
2653 }
2654
2655 if ($in) {
2656 $ssClause = $this->savedSearch($values);
2657 if ($ssClause) {
2658 if ($groupClause) {
2659 $groupClause = "( ( $groupClause ) OR ( $ssClause ) )";
2660 }
2661 else {
2662 $groupClause = $ssClause;
2663 }
2664 }
2665 }
2666
2667 $this->_where[$grouping][] = $groupClause;
2668 $this->_qill[$grouping][] = $qill;
2669 }
2670 /*
2671 * Function translates selection of group type into a list of groups
2672 */
2673 function getGroupsFromTypeCriteria($value){
2674 $groupIds = array();
2675 foreach ($value as $groupTypeValue) {
2676 $groupList = CRM_Core_PseudoConstant::group($groupTypeValue);
2677 $groupIds = ($groupIds + $groupList);
2678 }
2679 return $groupIds;
2680 }
2681
2682 /**
2683 * where / qill clause for smart groups
2684 *
2685 * @return void
2686 * @access public
2687 */
2688 function savedSearch(&$values) {
2689 list($name, $op, $value, $grouping, $wildcard) = $values;
2690 return $this->addGroupContactCache(array_keys($value));
2691 }
2692
2693 function addGroupContactCache($groups, $tableAlias = NULL, $joinTable = "contact_a") {
2694 $config = CRM_Core_Config::singleton();
2695
2696 // find all the groups that are part of a saved search
2697 $groupIDs = implode(',', $groups);
2698 if (empty($groupIDs)) {
2699 return NULL;
2700 }
2701
2702 $sql = "
2703SELECT id, cache_date, saved_search_id, children
2704FROM civicrm_group
2705WHERE id IN ( $groupIDs )
2706 AND ( saved_search_id != 0
2707 OR saved_search_id IS NOT NULL
2708 OR children IS NOT NULL )
2709";
2710 $group = CRM_Core_DAO::executeQuery($sql);
2711 $ssWhere = array();
2712 while ($group->fetch()) {
2713 if ($tableAlias == NULL) {
2714 $alias = "`civicrm_group_contact_cache_{$group->id}`";
2715 }
2716 else {
2717 $alias = $tableAlias;
2718 }
2719
2720 $this->_useDistinct = TRUE;
2721
2722 if (!$this->_smartGroupCache || $group->cache_date == NULL) {
2723 CRM_Contact_BAO_GroupContactCache::load($group);
2724 }
2725
2726 $this->_tables[$alias] = $this->_whereTables[$alias] = " LEFT JOIN civicrm_group_contact_cache {$alias} ON {$joinTable}.id = {$alias}.contact_id ";
2727 $ssWhere[] = "{$alias}.group_id = {$group->id}";
2728 }
2729
2730 if (!empty($ssWhere)) {
2731 return implode(' OR ', $ssWhere);
2732 }
2733 return NULL;
2734 }
2735
2736 /**
2737 * where / qill clause for cms users
2738 *
2739 * @return void
2740 * @access public
2741 */
2742 function ufUser(&$values) {
2743 list($name, $op, $value, $grouping, $wildcard) = $values;
2744
2745 if ($value == 1) {
2746 $this->_tables['civicrm_uf_match'] = $this->_whereTables['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2747
2748 $this->_qill[$grouping][] = ts('CMS User');
2749 }
2750 elseif ($value == 0) {
2751 $this->_tables['civicrm_uf_match'] = $this->_whereTables['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
2752
2753 $this->_where[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
2754 $this->_qill[$grouping][] = ts('Not a CMS User');
2755 }
2756 }
2757
2758 /**
2759 * all tag search specific
2760 *
2761 * @return void
2762 * @access public
2763 */
2764 function tagSearch(&$values) {
2765 list($name, $op, $value, $grouping, $wildcard) = $values;
2766
2767 $op = "LIKE";
2768 $value = "%{$value}%";
2769
2770
2771 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2772 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2773
2774 $etTable = "`civicrm_entity_tag-" . $value . "`";
2775 $tTable = "`civicrm_tag-" . $value . "`";
2776
2777 if ($useAllTagTypes[2]) {
2778 $this->_tables[$etTable] =
2779 $this->_whereTables[$etTable] =
2780 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
2781 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
2782
2783 // search tag in cases
2784 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
2785 $tCaseTable = "`civicrm_case_tag-" . $value . "`";
2786 $this->_tables[$etCaseTable] =
2787 $this->_whereTables[$etCaseTable] =
2788 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
2789 LEFT JOIN civicrm_case
2790 ON (civicrm_case_contact.case_id = civicrm_case.id
2791 AND civicrm_case.is_deleted = 0 )
2792 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
2793 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
2794 // search tag in activities
2795 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
2796 $tActTable = "`civicrm_act_tag-" . $value . "`";
e7e657f0 2797 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
9e74e3ce 2798 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1071730c 2799
6a488035
TO
2800 $this->_tables[$etActTable] =
2801 $this->_whereTables[$etActTable] =
91da6cd5 2802 " LEFT JOIN civicrm_activity_contact
9e74e3ce 2803 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
6a488035 2804 LEFT JOIN civicrm_activity
91da6cd5 2805 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
6a488035
TO
2806 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
2807 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
2808 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
2809
2810 $this->_where[$grouping][] = "({$tTable}.name $op '". $value . "' OR {$tCaseTable}.name $op '". $value . "' OR {$tActTable}.name $op '". $value . "')";
10a5be27 2811 $this->_qill[$grouping][] = ts('Tag %1 %2 ', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
6a488035
TO
2812 } else {
2813 $etTable = "`civicrm_entity_tag-" . $value . "`";
2814 $tTable = "`civicrm_tag-" . $value . "`";
2815 $this->_tables[$etTable] = $this->_whereTables[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
2816 {$etTable}.entity_table = 'civicrm_contact' )
2817 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
2818
2819 $this->_where[$grouping][] = self::buildClause("{$tTable}.name", $op, $value, 'String');
2820 $this->_qill[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
2821 }
2822 }
2823
2824 /**
2825 * where / qill clause for tag
2826 *
2827 * @return void
2828 * @access public
2829 */
2830 function tag(&$values) {
2831 list($name, $op, $value, $grouping, $wildcard) = $values;
2832
cd43c5e3 2833 $tagNames = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
6a488035
TO
2834 if (is_array($value)) {
2835 if (count($value) > 1) {
2836 $this->_useDistinct = TRUE;
2837 }
2838 foreach ($value as $id => $dontCare) {
2839 $names[] = CRM_Utils_Array::value($id, $tagNames);
2840 }
2841 $names = implode(' ' . ts('or') . ' ', $names);
2842 $value = implode(',', array_keys($value));
2843 }
2844 else {
2845 $names = CRM_Utils_Array::value($value, $tagNames);
2846 }
2847
2848
2849 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
2850 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
2851
2852 $etTable = "`civicrm_entity_tag-" . $value . "`";
2853
2854 if ($useAllTagTypes[2]) {
2855 $this->_tables[$etTable] =
2856 $this->_whereTables[$etTable] =
2857 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
2858
2859 // search tag in cases
2860 $etCaseTable = "`civicrm_entity_case_tag-" . $value . "`";
e7e657f0 2861 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
9e74e3ce 2862 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
2863
6a488035
TO
2864 $this->_tables[$etCaseTable] =
2865 $this->_whereTables[$etCaseTable] =
2866 " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
2867 LEFT JOIN civicrm_case
2868 ON (civicrm_case_contact.case_id = civicrm_case.id
2869 AND civicrm_case.is_deleted = 0 )
2870 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
2871 // search tag in activities
2872 $etActTable = "`civicrm_entity_act_tag-" . $value . "`";
2873 $this->_tables[$etActTable] =
2874 $this->_whereTables[$etActTable] =
91da6cd5 2875 " LEFT JOIN civicrm_activity_contact
9e74e3ce 2876 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
6a488035 2877 LEFT JOIN civicrm_activity
91da6cd5 2878 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
6a488035
TO
2879 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
2880 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
2881
2882 // CRM-10338
2883 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
2884 $this->_where[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
2885 }
2886 else {
2887 $this->_where[$grouping][] = "({$etTable}.tag_id $op (". $value . ") OR {$etCaseTable}.tag_id $op (". $value . ") OR {$etActTable}.tag_id $op (". $value . "))";
2888 }
10a5be27 2889 $this->_qill[$grouping][] = ts('Tag %1 %2', array(1 => $op, 2 => $tagTypesText[2])) . ' ' . $names;
6a488035
TO
2890 } else {
2891 $this->_tables[$etTable] =
2892 $this->_whereTables[$etTable] =
2893 " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
2894
2895 // CRM-10338
2896 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
2897 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
2898 $op = str_replace('EMPTY', 'NULL', $op);
2899 $this->_where[$grouping][] = "{$etTable}.tag_id $op";
2900 }
2901 else {
2902 $this->_where[$grouping][] = "{$etTable}.tag_id $op (" . $value . ')';
2903 }
2904 $this->_qill[$grouping][] = ts('Tagged %1', array( 1 => $op)) . ' ' . $names;
2905 }
2906
2907 }
2908
2909 /**
2910 * where/qill clause for notes
2911 *
2912 * @return void
2913 * @access public
2914 */
2915 function notes(&$values) {
2916 list($name, $op, $value, $grouping, $wildcard) = $values;
2917
2918 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
2919 $noteOption = CRM_Utils_Array::value('2', $noteOptionValues, '6');
2920 $noteOption = ($name == 'note_body') ? 2 : (($name == 'note_subject') ? 3 : $noteOption);
2921
2922 $this->_useDistinct = TRUE;
2923
2924 $this->_tables['civicrm_note'] =
2925 $this->_whereTables['civicrm_note'] =
2926 " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
2927
2928 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
2929 $n = trim($value);
2930 $value = $strtolower(CRM_Core_DAO::escapeString($n));
2931 if ($wildcard || $op == 'LIKE') {
2932 if (strpos($value, '%') === FALSE) {
2933 $value = "%$value%";
2934 }
2935 $op = 'LIKE';
2936 }
2937 elseif ($op == 'IS NULL' || $op == 'IS NOT NULL') {
2938 $value = NULL;
2939 }
2940
2941 $label = NULL;
2942 $clauses = array();
2943 if ( $noteOption % 2 == 0 ) {
2944 $clauses[] = self::buildClause('civicrm_note.note', $op, $value, 'String');
2945 $label = ts('Note: Body Only');
2946 }
2947 if ( $noteOption % 3 == 0 ) {
2948 $clauses[] = self::buildClause('civicrm_note.subject', $op, $value, 'String');
2949 $label = $label ? ts('Note: Body and Subject') : ts('Note: Subject Only');
2950 }
2951 $this->_where[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
2952 $this->_qill[$grouping][] = $label . " $op - '$n'";
2953 }
2954
2955 function nameNullOrEmptyOp($name, $op, $grouping) {
2956 switch ( $op ) {
2957 case 'IS NULL':
2958 case 'IS NOT NULL':
2959 $this->_where[$grouping][] = "contact_a.$name $op";
2960 $this->_qill[$grouping][] = ts('Name') . ' ' . $op;
2961 return true;
2962
2963 case 'IS EMPTY':
2964 $this->_where[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
2965 $this->_qill[$grouping][] = ts('Name') . ' ' . $op;
2966 return true;
2967
2968 case 'IS NOT EMPTY':
2969 $this->_where[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
2970 $this->_qill[$grouping][] = ts('Name') . ' ' . $op;
2971 return true;
2972
2973 default:
2974 return false;
2975 }
2976 }
2977
2978 /**
2979 * where / qill clause for sort_name
2980 *
2981 * @return void
2982 * @access public
2983 */
2984 function sortName(&$values) {
2985 list($name, $op, $value, $grouping, $wildcard) = $values;
2986
2987 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
2988 if ( $this->nameNullOrEmptyOp( $name, $op, $grouping ) ) {
2989 return;
2990 }
2991
2992 $newName = $name;
2993 $name = trim($value);
2994
2995 if (empty($name)) {
2996 return;
2997 }
2998
2999 $config = CRM_Core_Config::singleton();
3000
3001 $sub = array();
3002
3003 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3004 $subGlue = ' OR ';
3005
3006 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
d9ab802d 3007 $locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
6a488035
TO
3008
3009 if (substr($name, 0, 1) == '"' &&
3010 substr($name, -1, 1) == '"'
3011 ) {
3012 //If name is encased in double quotes, the value should be taken to be the string in entirety and the
3013 $value = substr($name, 1, -1);
3014 $value = $strtolower(CRM_Core_DAO::escapeString($value));
3015 $wc = ($newName == 'sort_name') ? 'LOWER(contact_a.sort_name)' : 'LOWER(contact_a.display_name)';
3016 $sub[] = " ( $wc = '$value' ) ";
3017 if ($config->includeEmailInName) {
3018 $sub[] = " ( civicrm_email.email = '$value' ) ";
3019 }
3020 }
3021 elseif (strpos($name, ',') !== FALSE) {
3022 // if we have a comma in the string, search for the entire string
3023 $value = $strtolower(CRM_Core_DAO::escapeString($name));
3024 if ($wildcard) {
3025 if ($config->includeWildCardInName) {
3026 $value = "'%$value%'";
3027 }
3028 else {
3029 $value = "'$value%'";
3030 }
3031 $op = 'LIKE';
3032 }
3033 else {
3034 $value = "'$value'";
3035 }
3036 if ($newName == 'sort_name') {
3037 $wc = self::caseImportant($op) ? "LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3038 }
3039 else {
3040 $wc = self::caseImportant($op) ? "LOWER(contact_a.display_name)" : "contact_a.display_name";
3041 }
3042 $sub[] = " ( $wc $op $value )";
3043 if ($config->includeNickNameInName) {
3044 $wc = self::caseImportant($op) ? "LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3045 $sub[] = " ( $wc $op $value )";
3046 }
3047 if ($config->includeEmailInName) {
3048 $sub[] = " ( civicrm_email.email $op $value ) ";
3049 }
3050 }
3051 else {
3052 // the string should be treated as a series of keywords to be matched with match ANY OR
3053 // match ALL depending on Civi config settings (see CiviAdmin)
3054
3055 // The Civi configuration setting can be overridden if the string *starts* with the case
3056 // insenstive strings 'AND:' or 'OR:'TO THINK ABOUT: what happens when someone searches
3057 // for the following "AND: 'a string in quotes'"? - probably nothing - it would make the
3058 // AND OR variable reduntant because there is only one search string?
3059
3060 // Check to see if the $subGlue is overridden in the search text
3061 if (strtolower(substr($name, 0, 4)) == 'and:') {
3062 $name = substr($name, 4);
3063 $subGlue = ' AND ';
3064 }
3065 if (strtolower(substr($name, 0, 3)) == 'or:') {
3066 $name = substr($name, 3);
3067 $subGlue = ' OR ';
3068 }
3069
3070 $firstChar = substr($name, 0, 1);
3071 $lastChar = substr($name, -1, 1);
3072 $quotes = array("'", '"');
3073 if ((strlen($name) > 2) && in_array($firstChar, $quotes) &&
3074 in_array($lastChar, $quotes)
3075 ) {
3076 $name = substr($name, 1);
3077 $name = substr($name, 0, -1);
3078 $pieces = array($name);
3079 }
3080 else {
3081 $pieces = explode(' ', $name);
3082 }
3083 foreach ($pieces as $piece) {
3084 $value = $strtolower(CRM_Core_DAO::escapeString(trim($piece)));
3085 if (strlen($value)) {
3086 // Added If as a sanitization - without it, when you do an OR search, any string with
3087 // double spaces (i.e. " ") or that has a space after the keyword (e.g. "OR: ") will
3088 // return all contacts because it will include a condition similar to "OR contact
3089 // name LIKE '%'". It might be better to replace this with array_filter.
3090 $fieldsub = array();
3091 if ($wildcard) {
3092 if ($config->includeWildCardInName) {
3093 $value = "'%$value%'";
3094 }
3095 else {
3096 $value = "'$value%'";
3097 }
3098 $op = 'LIKE';
3099 }
3100 else {
3101 $value = "'$value'";
3102 }
3103 if ($newName == 'sort_name') {
3104 $wc = self::caseImportant($op) ? "LOWER(contact_a.sort_name)" : "contact_a.sort_name";
3105 }
3106 else {
3107 $wc = self::caseImportant($op) ? "LOWER(contact_a.display_name)" : "contact_a.display_name";
3108 }
3109 $fieldsub[] = " ( $wc $op $value )";
3110 if ($config->includeNickNameInName) {
3111 $wc = self::caseImportant($op) ? "LOWER(contact_a.nick_name)" : "contact_a.nick_name";
3112 $fieldsub[] = " ( $wc $op $value )";
3113 }
3114 if ($config->includeEmailInName) {
3115 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3116 }
3117 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3118 // I seperated the glueing in two. The first stage should always be OR because we are searching for matches in *ANY* of these fields
3119 }
3120 }
3121 }
3122
3123 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3124
3125 $this->_where[$grouping][] = $sub;
3126 if ($config->includeEmailInName) {
3127 $this->_tables['civicrm_email'] = $this->_whereTables['civicrm_email'] = 1;
3128 $this->_qill[$grouping][] = ts('Name or Email ') . "$op - '$name'";
3129 }
3130 else {
3131 $this->_qill[$grouping][] = ts('Name like') . " - '$name'";
3132 }
3133 }
3134
3135 /**
3136 * where / qill clause for email
3137 *
3138 * @return void
3139 * @access public
3140 */
3141 function email(&$values) {
3142 list($name, $op, $value, $grouping, $wildcard) = $values;
3143
3144 $n = trim($value);
3145 if ($n) {
3146 $config = CRM_Core_Config::singleton();
3147
3148 if (substr($n, 0, 1) == '"' &&
3149 substr($n, -1, 1) == '"'
3150 ) {
3151 $n = substr($n, 1, -1);
3152 $value = strtolower(CRM_Core_DAO::escapeString($n));
3153 $value = "'$value'";
3154 $op = '=';
3155 }
3156 else {
3157 $value = strtolower($n);
3158 if ($wildcard) {
3159 if (strpos($value, '%') === FALSE) {
3160 $value = "%{$value}%";
3161 }
3162 $op = 'LIKE';
3163 }
3164 }
3165 $this->_qill[$grouping][] = ts('Email') . " $op '$n'";
3166 $this->_where[$grouping][] = self::buildClause('civicrm_email.email', $op, $value, 'String');
3167 }
3168 else {
3169 $this->_qill[$grouping][] = ts('Email') . " $op ";
3170 $this->_where[$grouping][] = self::buildClause('civicrm_email.email', $op, NULL, 'String');
3171 }
3172
3173 $this->_tables['civicrm_email'] = $this->_whereTables['civicrm_email'] = 1;
3174 }
3175
3176 /**
3177 * where / qill clause for phone number
3178 *
3179 * @return void
3180 * @access public
3181 */
3182 function phone_numeric(&$values) {
3183 list($name, $op, $value, $grouping, $wildcard) = $values;
3184 // Strip non-numeric characters
3185 $number = preg_replace('/[^\d]/', '', $value);
3186 if ($number) {
3187 $this->_qill[$grouping][] = ts('Phone number contains') . " $number";
3188 $this->_where[$grouping][] = self::buildClause('civicrm_phone.phone_numeric', 'LIKE', "%$number%", 'String');
3189 $this->_tables['civicrm_phone'] = $this->_whereTables['civicrm_phone'] = 1;
3190 }
3191 }
3192
3193 /**
3194 * where / qill clause for phone type/location
3195 *
3196 * @return void
3197 * @access public
3198 */
3199 function phone_option_group($values) {
3200 list($name, $op, $value, $grouping, $wildcard) = $values;
cbf48754
AS
3201 $option = ($name == 'phone_phone_type_id' ? 'phone_type_id' : 'location_type_id');
3202 $options = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', $option);
6a488035
TO
3203 $optionName = $options[$value];
3204 $this->_qill[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ? ts('type') : ('location')) . " $op $optionName";
3205 $this->_where[$grouping][] = self::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3206 $this->_tables['civicrm_phone'] = $this->_whereTables['civicrm_phone'] = 1;
3207 }
3208
3209 /**
3210 * where / qill clause for street_address
3211 *
3212 * @return void
3213 * @access public
3214 */
3215 function street_address(&$values) {
3216 list($name, $op, $value, $grouping, $wildcard) = $values;
3217
3218 if (!$op) {
3219 $op = 'LIKE';
3220 }
3221
3222 $n = trim($value);
3223
3224 if ($n) {
3225 $value = strtolower($n);
3226 if (strpos($value, '%') === FALSE) {
3227 // only add wild card if not there
3228 $value = "%{$value}%";
3229 }
3230 $op = 'LIKE';
3231 $this->_where[$grouping][] = self::buildClause('LOWER(civicrm_address.street_address)', $op, $value, 'String');
3232 $this->_qill[$grouping][] = ts('Street') . " $op '$n'";
3233 }
3234 else {
3235 $this->_where[$grouping][] = self::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3236 $this->_qill[$grouping][] = ts('Street') . " $op ";
3237 }
3238
3239 $this->_tables['civicrm_address'] = $this->_whereTables['civicrm_address'] = 1;
3240 }
3241
3242 /**
3243 * where / qill clause for street_unit
3244 *
3245 * @return void
3246 * @access public
3247 */
3248 function street_number(&$values) {
3249 list($name, $op, $value, $grouping, $wildcard) = $values;
3250
3251 if (!$op) {
3252 $op = '=';
3253 }
3254
3255 $n = trim($value);
3256
3257 if (strtolower($n) == 'odd') {
3258 $this->_where[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3259 $this->_qill[$grouping][] = ts('Street Number is odd');
3260 }
3261 elseif (strtolower($n) == 'even') {
3262 $this->_where[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3263 $this->_qill[$grouping][] = ts('Street Number is even');
3264 }
3265 else {
3266 $value = strtolower($n);
3267
3268 $this->_where[$grouping][] = self::buildClause('LOWER(civicrm_address.street_number)', $op, $value, 'String');
3269 $this->_qill[$grouping][] = ts('Street Number') . " $op '$n'";
3270 }
3271
3272 $this->_tables['civicrm_address'] = $this->_whereTables['civicrm_address'] = 1;
3273 }
3274
3275 /**
3276 * where / qill clause for sorting by character
3277 *
3278 * @return void
3279 * @access public
3280 */
3281 function sortByCharacter(&$values) {
3282 list($name, $op, $value, $grouping, $wildcard) = $values;
3283
3284 $name = trim($value);
3285 $cond = " contact_a.sort_name LIKE '" . strtolower(CRM_Core_DAO::escapeWildCardString($name)) . "%'";
3286 $this->_where[$grouping][] = $cond;
3287 $this->_qill[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3288 }
3289
3290 /**
3291 * where / qill clause for including contact ids
3292 *
3293 * @return void
3294 * @access public
3295 */
3296 function includeContactIDs() {
3297 if (!$this->_includeContactIds || empty($this->_params)) {
3298 return;
3299 }
3300
3301 $contactIds = array();
3302 foreach ($this->_params as $id => $values) {
3303 if (substr($values[0], 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
3304 $contactIds[] = substr($values[0], CRM_Core_Form::CB_PREFIX_LEN);
3305 }
3306 }
3307 if (!empty($contactIds)) {
3308 $this->_where[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3309 }
3310 }
3311
3312 /**
3313 * where / qill clause for postal code
3314 *
3315 * @return void
3316 * @access public
3317 */
3318 function postalCode(&$values) {
3319 // skip if the fields dont have anything to do with postal_code
3320 if (!CRM_Utils_Array::value('postal_code', $this->_fields)) {
3321 return;
3322 }
3323
3324 list($name, $op, $value, $grouping, $wildcard) = $values;
3325
3326 // Handle numeric postal code range searches properly by casting the column as numeric
3327 if (is_numeric($value)) {
3328 $field = 'ROUND(civicrm_address.postal_code)';
3329 $val = CRM_Utils_Type::escape($value, 'Integer');
3330 }
3331 else {
3332 $field = 'civicrm_address.postal_code';
3333 $val = CRM_Utils_Type::escape($value, 'String');
3334 }
3335
3336 $this->_tables['civicrm_address'] = $this->_whereTables['civicrm_address'] = 1;
3337
3338 if ($name == 'postal_code') {
3339 $this->_where[$grouping][] = self::buildClause($field, $op, $val, 'String');
3340 $this->_qill[$grouping][] = ts('Postal code') . " {$op} {$value}";
3341 }
3342 elseif ($name == 'postal_code_low') {
3343 $this->_where[$grouping][] = " ( $field >= '$val' ) ";
3344 $this->_qill[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3345 }
3346 elseif ($name == 'postal_code_high') {
3347 $this->_where[$grouping][] = " ( $field <= '$val' ) ";
3348 $this->_qill[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3349 }
3350 }
3351
3352 /**
3353 * where / qill clause for location type
3354 *
3355 * @return void
3356 * @access public
3357 */
3358 function locationType(&$values, $status = NULL) {
3359 list($name, $op, $value, $grouping, $wildcard) = $values;
3360
3361 if (is_array($value)) {
3362 $this->_where[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', array_keys($value)) . ')';
3363 $this->_tables['civicrm_address'] = 1;
3364 $this->_whereTables['civicrm_address'] = 1;
3365
b2b0530a 3366 $locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
6a488035
TO
3367 $names = array();
3368 foreach (array_keys($value) as $id) {
3369 $names[] = $locationType[$id];
3370 }
3371
3372 $this->_primaryLocation = FALSE;
3373
3374 if (!$status) {
3375 $this->_qill[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3376 }
3377 else {
3378 return implode(' ' . ts('or') . ' ', $names);
3379 }
3380 }
3381 }
3382
3383 function country(&$values, $fromStateProvince = TRUE) {
3384 list($name, $op, $value, $grouping, $wildcard) = $values;
3385
3386 if (!$fromStateProvince) {
3387 $stateValues = $this->getWhereValues('state_province', $grouping);
3388 if (!empty($stateValues)) {
3389 // return back to caller if there are state province values
3390 // since that handles this case
3391 return;
3392 }
3393 }
3394
3395 $countryClause = $countryQill = NULL;
3396 if (
3397 $values &&
3398 !empty($value)
3399 ) {
d9ab802d
PJ
3400
3401 $this->_tables['civicrm_address'] = 1;
3402 $this->_whereTables['civicrm_address'] = 1;
6a488035
TO
3403
3404 $countries = CRM_Core_PseudoConstant::country();
3405 if (is_numeric($value)) {
3406 $countryClause = self::buildClause(
d9ab802d 3407 'civicrm_address.country_id',
6a488035
TO
3408 $op,
3409 $value,
3410 'Positive'
3411 );
3412 $countryName = $countries[(int ) $value];
3413 }
3414
3415 else {
3416 $intValues = self::parseSearchBuilderString($value);
3417 if ($intValues && ($op == 'IN' || $op == 'NOT IN')) {
3418 $countryClause = self::buildClause(
d9ab802d 3419 'civicrm_address.country_id',
6a488035
TO
3420 $op,
3421 $intValues,
3422 'Positive'
3423 );
3424 $countryNames = array();
3425 foreach ($intValues as $v) {
3426 $countryNames[] = $countries[$v];
3427 }
3428 $countryName = implode(',', $countryNames);
3429 }
3430 else {
d9ab802d
PJ
3431 $countries = CRM_Core_PseudoConstant::country();
3432 $intVal = CRM_Utils_Array::key($value, $countries);
6a488035 3433 $countryClause = self::buildClause(
d9ab802d 3434 'civicrm_address.country_id',
6a488035 3435 $op,
d9ab802d
PJ
3436 $intVal,
3437 'Integer'
6a488035
TO
3438 );
3439 $countryName = $value;
3440 }
3441 }
3442 $countryQill = ts('Country') . " {$op} '$countryName'";
3443
3444 if (!$fromStateProvince) {
3445 $this->_where[$grouping][] = $countryClause;
3446 $this->_qill[$grouping][] = $countryQill;
3447 }
3448 }
3449
3450 if ($fromStateProvince) {
3451 if (!empty($countryClause)) {
3452 return array(
3453 $countryClause,
3454 " ...AND... " . $countryQill,
3455 );
3456 }
3457 else {
3458 return array(NULL, NULL);
3459 }
3460 }
3461 }
3462
3463 /**
3464 * where / qill clause for county (if present)
3465 *
3466 * @return void
3467 * @access public
3468 */
3469 function county(&$values, $status = null) {
3470 list($name, $op, $value, $grouping, $wildcard) = $values;
3471
3472 if (! is_array($value)) {
3473 // force the county to be an array
3474 $value = array($value);
3475 }
3476
3477 // check if the values are ids OR names of the counties
3478 $inputFormat = 'id';
3479 foreach ($value as $v) {
3480 if (!is_numeric($v)) {
3481 $inputFormat = 'name';
3482 break;
3483 }
3484 }
3485 $names = array();
d9ab802d
PJ
3486 if ($op == '=') {
3487 $op = 'IN';
3488 }
3489 else if ($op == '!=') {
3490 $op = 'NOT IN';
3491 }
3492 else {
3493 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3494 $op = str_replace('EMPTY', 'NULL', $op);
3495 }
3496
3497 if (in_array( $op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3498 $clause = "civicrm_address.county_id $op";
3499 }
3500 elseif ($inputFormat == 'id') {
3501 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
6a488035
TO
3502
3503 $county = CRM_Core_PseudoConstant::county();
3504 foreach ($value as $id) {
3505 $names[] = CRM_Utils_Array::value($id, $county);
3506 }
3507 }
3508 else {
3509 $inputClause = array();
d9ab802d 3510 $county = CRM_Core_PseudoConstant::county();
6a488035
TO
3511 foreach ($value as $name) {
3512 $name = trim($name);
d9ab802d 3513 $inputClause[] = CRM_Utils_Array::key($name, $county);
6a488035 3514 }
d9ab802d 3515 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
6a488035
TO
3516 $names = $value;
3517 }
d9ab802d
PJ
3518 $this->_tables['civicrm_address'] = 1;
3519 $this->_whereTables['civicrm_address'] = 1;
6a488035
TO
3520
3521 $this->_where[$grouping][] = $clause;
d9ab802d 3522 if (!$status) {
6a488035
TO
3523 $this->_qill[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3524 } else {
3525 return implode(' ' . ts('or') . ' ', $names);
3526 }
3527 }
3528
3529 /**
3530 * where / qill clause for state/province AND country (if present)
3531 *
3532 * @return void
3533 * @access public
3534 */
3535 function stateProvince(&$values, $status = NULL) {
3536 list($name, $op, $value, $grouping, $wildcard) = $values;
3537
3538 // quick escape for IS NULL
3539 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
3540 $value = NULL;
3541 }
3542 else if (!is_array($value)) {
3543 // force the state to be an array
3544 // check if its in the mapper format!
3545 $values = self::parseSearchBuilderString($value);
3546 if (is_array($values)) {
3547 $value = $values;
3548 }
3549 else {
3550 $value = array($value);
3551 }
3552 }
3553
3554 // check if the values are ids OR names of the states
3555 $inputFormat = 'id';
3556 if ($value) {
3557 foreach ($value as $v) {
3558 if (!is_numeric($v)) {
3559 $inputFormat = 'name';
3560 break;
3561 }
3562 }
3563 }
3564
3565 $names = array();
3566 if ($op == '=') {
3567 $op = 'IN';
3568 }
3569 else if ($op == '!=') {
3570 $op = 'NOT IN';
3571 }
3572 else {
3573 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3574 $op = str_replace('EMPTY', 'NULL', $op);
3575 }
3576 if ( in_array( $op, array( 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY' ) ) ) {
d9ab802d 3577 $stateClause = "civicrm_address.state_province_id $op";
6a488035
TO
3578 }
3579 else if ($inputFormat == 'id') {
3580 if ($op != 'NOT IN') {
3581 $op = 'IN';
3582 }
d9ab802d 3583 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $value) . ')';
6a488035
TO
3584
3585 $stateProvince = CRM_Core_PseudoConstant::stateProvince();
3586 foreach ($value as $id) {
3587 $names[] = CRM_Utils_Array::value($id, $stateProvince);
3588 }
3589 }
3590 else {
3591 $inputClause = array();
d9ab802d 3592 $stateProvince = CRM_Core_PseudoConstant::stateProvince();
6a488035
TO
3593 foreach ($value as $name) {
3594 $name = trim($name);
d9ab802d 3595 $inputClause[] = CRM_Utils_Array::key($name, $stateProvince);
6a488035 3596 }
d9ab802d 3597 $stateClause = "civicrm_address.state_province_id $op (" . implode(',', $inputClause) . ')';
6a488035
TO
3598 $names = $value;
3599 }
d9ab802d
PJ
3600 $this->_tables['civicrm_address'] = 1;
3601 $this->_whereTables['civicrm_address'] = 1;
6a488035
TO
3602
3603 $countryValues = $this->getWhereValues('country', $grouping);
3604 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3605
3606 if ($countryClause) {
3607 $clause = "( $stateClause AND $countryClause )";
3608 }
3609 else {
3610 $clause = $stateClause;
3611 }
3612
3613 $this->_where[$grouping][] = $clause;
3614 if (!$status) {
3615 $this->_qill[$grouping][] = ts('State/Province') . " $op " . implode(' ' . ts('or') . ' ', $names) . $countryQill;
3616 }
3617 else {
9fd71915 3618 return implode(' ' . ts('or') . ' ', $names) . $countryQill;
6a488035
TO
3619 }
3620 }
3621
3622 /**
3623 * where / qill clause for change log
3624 *
3625 * @return void
3626 * @access public
3627 */
3628 function changeLog(&$values) {
3629 list($name, $op, $value, $grouping, $wildcard) = $values;
3630
3631 $targetName = $this->getWhereValues('changed_by', $grouping);
3632 if (!$targetName) {
3633 return;
3634 }
3635
3636 $name = trim($targetName[2]);
3637 $name = strtolower(CRM_Core_DAO::escapeString($name));
3638 $name = $targetName[4] ? "%$name%" : $name;
3639 $this->_where[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3640 $this->_tables['civicrm_log'] = $this->_whereTables['civicrm_log'] = 1;
3641 $this->_qill[$grouping][] = ts('Changed by') . ": $name";
3642 }
3643
3644 function modifiedDates($values) {
3645 $this->_useDistinct = TRUE;
9e9b8fdb
DL
3646
3647 // CRM-11281, default to added date if not set
228917cd 3648 $fieldTitle = ts('Added Date');
9e9b8fdb 3649
6a488035
TO
3650 foreach (array_keys($this->_params) as $id) {
3651 if ($this->_params[$id][0] == 'log_date') {
228917cd
DL
3652 if ($this->_params[$id][2] == 2) {
3653 $fieldTitle = ts('Modified Date');
6a488035
TO
3654 }
3655 }
3656 }
3657
3658 $this->dateQueryBuilder($values,
3659 'civicrm_log', 'log_date', 'modified_date', $fieldTitle
3660 );
3661 }
3662
3663 function demographics(&$values) {
3664 list($name, $op, $value, $grouping, $wildcard) = $values;
3665
3666 if (($name == 'birth_date_low') || ($name == 'birth_date_high')) {
3667
3668 $this->dateQueryBuilder($values,
3669 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3670 );
3671 }
3672 elseif (($name == 'deceased_date_low') || ($name == 'deceased_date_high')) {
3673
3674 $this->dateQueryBuilder($values,
3675 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3676 );
3677 }
3678
3679 self::$_openedPanes[ts('Demographics')] = TRUE;
3680 }
3681
3682 function privacy(&$values) {
3683 list($name, $op, $value, $grouping, $wildcard) = $values;
3684 //fixed for profile search listing CRM-4633
3685 if (strpbrk($value, "[")) {
3686 $value = "'{$value}'";
3687 $op = "!{$op}";
3688 $this->_where[$grouping][] = "contact_a.{$name} $op $value";
3689 }
3690 else {
3691 $this->_where[$grouping][] = "contact_a.{$name} $op $value";
3692 }
3693 $field = CRM_Utils_Array::value($name, $this->_fields);
3694 $title = $field ? $field['title'] : $name;
3695 $this->_qill[$grouping][] = "$title $op $value";
3696 }
3697
3698 function privacyOptions($values) {
3699 list($name, $op, $value, $grouping, $wildcard) = $values;
3700
9fd71915
CW
3701 if (empty($value) || !is_array($value)) {
3702 return;
6a488035
TO
3703 }
3704
3705 // get the operator and toggle values
3706 $opValues = $this->getWhereValues('privacy_operator', $grouping);
3707 $operator = 'OR';
3708 if ($opValues &&
3709 strtolower($opValues[2] == 'AND')
3710 ) {
3711 $operator = 'AND';
3712 }
3713
3714 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
3715 $compareOP = '!=';
3716 if ($toggleValues &&
3717 $toggleValues[2] == 2
3718 ) {
3719 $compareOP = '=';
3720 }
3721
3722 $clauses = array();
3723 $qill = array();
3724 foreach ($value as $dontCare => $pOption) {
3725 $clauses[] = " ( contact_a.{$pOption} $compareOP 1 ) ";
3726 $field = CRM_Utils_Array::value($pOption, $this->_fields);
3727 $title = $field ? $field['title'] : $pOption;
3728 $qill[] = " $title $compareOP 1 ";
3729 }
3730
3731 $this->_where[$grouping][] = '( ' . implode($operator, $clauses) . ' )';
3732 $this->_qill[$grouping][] = implode($operator, $qill);
3733 }
3734
3735 function preferredCommunication(&$values) {
3736 list($name, $op, $value, $grouping, $wildcard) = $values;
3737
3738 $pref = array();
3739 if (!is_array($value)) {
3740 $v = array();
3741 $value = trim($value, ' ()');
3742 if (strpos($value, CRM_Core_DAO::VALUE_SEPARATOR) !== FALSE) {
3743 $v = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
3744 }
3745 else {
3746 $v = explode(",", $value);
3747 }
3748
3749 foreach ($v as $item) {
3750 if ($item) {
3751 $pref[] = $item;
3752 }
3753 }
3754 }
3755 else {
3756 foreach ($value as $key => $checked) {
3757 if ($checked) {
3758 $pref[] = $key;
3759 }
3760 }
3761 }
3762
e7e657f0 3763 $commPref = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
6a488035
TO
3764
3765 $sqlValue = array();
3766 $sql = "contact_a.preferred_communication_method";
3767 foreach ($pref as $val) {
3768 $sqlValue[] = "( $sql like '%" . CRM_Core_DAO::VALUE_SEPARATOR . $val . CRM_Core_DAO::VALUE_SEPARATOR . "%' ) ";
3769 $showValue[] = $commPref[$val];
3770 }
3771 $this->_where[$grouping][] = "( " . implode(' OR ', $sqlValue) . " )";
3772 $this->_qill[$grouping][] = ts('Preferred Communication Method') . " $op " . implode(' ' . ts('or') . ' ', $showValue);
3773 }
3774
6a488035
TO
3775 /**
3776 * where / qill clause for relationship
3777 *
3778 * @return void
3779 * @access public
3780 */
3781 function relationship(&$values) {
3782 list($name, $op, $value, $grouping, $wildcard) = $values;
ad682134 3783 if($this->_relationshipValuesAdded){
3784 return;
3785 }
6a488035
TO
3786 // also get values array for relation_target_name
3787 // for relatinship search we always do wildcard
3788 $targetName = $this->getWhereValues('relation_target_name', $grouping);
3789 $relStatus = $this->getWhereValues('relation_status', $grouping);
3790 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
6a488035
TO
3791
3792 $nameClause = $name = NULL;
3793 if ($targetName) {
3794 $name = trim($targetName[2]);
3795 if (substr($name, 0, 1) == '"' &&
3796 substr($name, -1, 1) == '"'
3797 ) {
3798 $name = substr($name, 1, -1);
3799 $name = strtolower(CRM_Core_DAO::escapeString($name));
3800 $nameClause = "= '$name'";
3801 }
3802 else {
3803 $name = strtolower(CRM_Core_DAO::escapeString($name));
3804 $nameClause = "LIKE '%{$name}%'";
3805 }
3806 }
3807
3808 $rel = explode('_', $value);
3809
3810 self::$_relType = $rel[1];
ad682134 3811 $params = array('id' => $rel[0]);
3812 $rTypeValues = array();
3813 $rType = CRM_Contact_BAO_RelationshipType::retrieve($params, $rTypeValues);
3814 if ($rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) {
7c96365b 3815 // if we don't know which end of the relationship we are dealing with we'll create a temp table
3816 //@todo unless we are dealing with a target group
ad682134 3817 self::$_relType = 'reciprocal';
3818 }
7c96365b 3819 // if we are creating a temp table we build our own where for the relationship table
3820 if(self::$_relType == 'reciprocal' && empty($targetGroup)) {
3821 $where = array();
3822 self::$_relationshipTempTable = $relationshipTempTable = 'civicrm_temp_rel' . rand(0,99999);
3823 if($nameClause) {
3824 $where[$grouping][] = " sort_name $nameClause ";
3825 }
6a488035 3826 }
7c96365b 3827 else {
3828 $where = &$this->_where;
3829 if ($nameClause) {
3830 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
3831 }
3832 }
3833
04ffef8d 3834
6a488035
TO
3835 $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Individual');
3836 $relTypeOrg = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Organization');
3837 $relTypeHou = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Household');
3838 $allRelationshipType = array();
3839 $allRelationshipType = array_merge($relTypeInd, $relTypeOrg);
3840 $allRelationshipType = array_merge($allRelationshipType, $relTypeHou);
3841
3842 if ($nameClause || !$targetGroup) {
3843 $this->_qill[$grouping][] = "$allRelationshipType[$value] $name";
3844 }
3845
3846
3847 //check to see if the target contact is in specified group
3848 if ($targetGroup) {
3849 //add contacts from static groups
3850 $this->_tables['civicrm_relationship_group_contact'] =
3851 $this->_whereTables['civicrm_relationship_group_contact'] =
3852 " LEFT JOIN civicrm_group_contact civicrm_relationship_group_contact ON civicrm_relationship_group_contact.contact_id = contact_b.id";
3853 $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" . implode(",", $targetGroup[2]) . ") )";
3854
3855 //add contacts from saved searches
3856 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b");
3857
3858 //set the group where clause
3859 if ($ssWhere) {
3860 $groupWhere[] = "( " . $ssWhere . " )";
3861 }
3862 $this->_where[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
3863
3864 //Get the names of the target groups for the qill
3865 $groupNames = &CRM_Core_PseudoConstant::group();
3866 $qillNames = array();
3867 foreach ($targetGroup[2] as $groupId) {
3868 if (array_key_exists($groupId, $groupNames)) {
3869 $qillNames[] = $groupNames[$groupId];
3870 }
3871 }
3872 $this->_qill[$grouping][] = "$allRelationshipType[$value] ( " . implode(", ", $qillNames) . " )";
3873 }
3874
12ba37a0
CW
3875 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
3876 $today = date('Ymd');
6a488035
TO
3877 //check for active, inactive and all relation status
3878 if ($relStatus[2] == 0) {
7c96365b 3879 $where[$grouping][] = "(
6a488035 3880civicrm_relationship.is_active = 1 AND
12ba37a0
CW
3881( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
3882( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
6a488035
TO
3883)";
3884 $this->_qill[$grouping][] = ts('Relationship - Active and Current');
3885 }
3886 elseif ($relStatus[2] == 1) {
7c96365b 3887 $where[$grouping][] = "(
6a488035 3888civicrm_relationship.is_active = 0 OR
12ba37a0
CW
3889civicrm_relationship.end_date < {$today} OR
3890civicrm_relationship.start_date > {$today}
6a488035
TO
3891)";
3892 $this->_qill[$grouping][] = ts('Relationship - Inactive or not Current');
3893 }
3894
7c96365b 3895 $this->addRelationshipDateClauses($grouping, $where);
ad682134 3896 if(!empty($rType) && isset($rType->id)){
7c96365b 3897 $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id;
6a488035 3898 }
6a488035
TO
3899 $this->_tables['civicrm_relationship'] = $this->_whereTables['civicrm_relationship'] = 1;
3900 $this->_useDistinct = TRUE;
ad682134 3901 $this->_relationshipValuesAdded = TRUE;
7c96365b 3902 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
3903 // join on that,
3904 // @todo creating a temp table could be expanded to group filter
3905 // as even creating a temp table of all relationships is much much more efficient than
3906 // an OR in the join
3907 if($relationshipTempTable) {
3908 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
3909 $sql = "
3910 CREATE TEMPORARY TABLE {$relationshipTempTable}
3911 (SELECT contact_id_b as contact_id, civicrm_relationship.id
3912 FROM civicrm_relationship
3913 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
3914 $whereClause )
3915 UNION
3916 (SELECT contact_id_a as contact_id, civicrm_relationship.id
3917 FROM civicrm_relationship
3918 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
3919 $whereClause )
3920 ";
3921 CRM_Core_DAO::executeQuery($sql);
3922 }
3923
6a488035 3924 }
ad682134 3925/**
3926 * Add start & end date criteria in
3927 * @param string $grouping
7c96365b 3928 * @param array $where = array to add where clauses to, in case you are generating a temp table
3929 * not the main query.
ad682134 3930 */
7c96365b 3931 function addRelationshipDateClauses($grouping, &$where){
ad682134 3932 $dateValues = array();
3933 $dateTypes = array(
3934 'start_date',
3935 'end_date',
3936 );
6a488035 3937
ad682134 3938 foreach ($dateTypes as $dateField){
3939 $dateValueLow = $this->getWhereValues('relation_'. $dateField .'_low', $grouping);
3940 $dateValueHigh= $this->getWhereValues('relation_'. $dateField .'_high', $grouping);
3941 if(!empty($dateValueLow)){
3942 $date = date('Ymd', strtotime($dateValueLow[2]));
7c96365b 3943 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
ad682134 3944 $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);
3945 }
3946 if(!empty($dateValueHigh)){
3947 $date = date('Ymd', strtotime($dateValueHigh[2]));
7c96365b 3948 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
ad682134 3949 $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);
3950 }
3951 }
3952 }
6a488035
TO
3953 /**
3954 * default set of return properties
3955 *
3956 * @return void
3957 * @access public
3958 */
3959 static function &defaultReturnProperties($mode = 1) {
3960 if (!isset(self::$_defaultReturnProperties)) {
3961 self::$_defaultReturnProperties = array();
3962 }
3963
3964 if (!isset(self::$_defaultReturnProperties[$mode])) {
3965 // add activity return properties
3966 if ($mode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
3967 self::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query::defaultReturnProperties($mode, FALSE);
3968 }
3969 else {
3970 self::$_defaultReturnProperties[$mode] = CRM_Core_Component::defaultReturnProperties($mode, FALSE);
3971 }
3972
3973 if (empty(self::$_defaultReturnProperties[$mode])) {
3974 self::$_defaultReturnProperties[$mode] = array(
3975 'home_URL' => 1,
3976 'image_URL' => 1,
3977 'legal_identifier' => 1,
3978 'external_identifier' => 1,
3979 'contact_type' => 1,
3980 'contact_sub_type' => 1,
3981 'sort_name' => 1,
3982 'display_name' => 1,
3983 'preferred_mail_format' => 1,
3984 'nick_name' => 1,
3985 'first_name' => 1,
3986 'middle_name' => 1,
3987 'last_name' => 1,
04ffef8d
CW
3988 'prefix_id' => 1,
3989 'suffix_id' => 1,
6a488035 3990 'birth_date' => 1,
04ffef8d 3991 'gender_id' => 1,
6a488035
TO
3992 'street_address' => 1,
3993 'supplemental_address_1' => 1,
3994 'supplemental_address_2' => 1,
3995 'city' => 1,
3996 'postal_code' => 1,
3997 'postal_code_suffix' => 1,
3998 'state_province' => 1,
3999 'country' => 1,
4000 'world_region' => 1,
4001 'geo_code_1' => 1,
4002 'geo_code_2' => 1,
4003 'email' => 1,
4004 'on_hold' => 1,
4005 'phone' => 1,
4006 'im' => 1,
4007 'household_name' => 1,
4008 'organization_name' => 1,
4009 'deceased_date' => 1,
4010 'is_deceased' => 1,
4011 'job_title' => 1,
4012 'legal_name' => 1,
4013 'sic_code' => 1,
4014 'current_employer' => 1,
4015 // FIXME: should we use defaultHierReturnProperties() for the below?
4016 'do_not_email' => 1,
4017 'do_not_mail' => 1,
4018 'do_not_sms' => 1,
4019 'do_not_phone' => 1,
4020 'do_not_trade' => 1,
4021 'is_opt_out' => 1,
4022 'contact_is_deleted' => 1,
b725488f
CW
4023 'preferred_communication_method' => 1,
4024 'preferred_language' => 1,
6a488035
TO
4025 );
4026 }
4027 }
4028 return self::$_defaultReturnProperties[$mode];
4029 }
4030
4031 /**
4032 * get primary condition for a sql clause
4033 *
4034 * @param int $value
4035 *
4036 * @return void
4037 * @access public
4038 */
4039 static function getPrimaryCondition($value) {
4040 if (is_numeric($value)) {
4041 $value = (int ) $value;
4042 return ($value == 1) ? 'is_primary = 1' : 'is_primary = 0';
4043 }
4044 return NULL;
4045 }
4046
4047 /**
4048 * wrapper for a simple search query
4049 *
4050 * @param array $params
4051 * @param array $returnProperties
837c4660 4052 * @param \bolean|bool $count
6a488035
TO
4053 *
4054 * @return void
4055 * @access public
4056 */
4057 static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4058 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4059 list($select, $from, $where, $having) = $query->query();
4060
4061 return "$select $from $where $having";
4062 }
4063
4064 /**
4065 * These are stub comments as this function needs more explanation - particularly in terms of how it
4066 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4067 *
4068 * This function was originally written as a wrapper for the api query but is called from multiple places
4069 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4070 * but it is unclear as to whehter that is historical or there is a reason
4071 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4072 *
837c4660
E
4073 * @param array $params
4074 * @param array $returnProperties
4075 * @param null $fields
6a488035 4076 * @param string $sort
837c4660
E
4077 * @param int $offset
4078 * @param int $row_count
4079 * @param bool $smartGroupCache
6a488035
TO
4080 * @param bool $count return count obnly
4081 * @param bool $skipPermissions Should permissions be ignored or should the logged in user's permissions be applied
4082 *
837c4660
E
4083 * @params bool $smartGroupCache ?? update smart group cache?
4084 *
b725488f 4085 * @return array
6a488035
TO
4086 * @access public
4087 */
4088 static function apiQuery(
4089 $params = NULL,
4090 $returnProperties = NULL,
4091 $fields = NULL,
4092 $sort = NULL,
4093 $offset = 0,
4094 $row_count = 25,
4095 $smartGroupCache = TRUE,
4096 $count = FALSE,
d9ab802d 4097 $skipPermissions = TRUE
6a488035
TO
4098 ) {
4099
4100 $query = new CRM_Contact_BAO_Query(
4101 $params, $returnProperties,
4102 NULL, TRUE, FALSE, 1,
4103 $skipPermissions,
4104 TRUE, $smartGroupCache
4105 );
4106
4107 //this should add a check for view deleted if permissions are enabled
4108 if ($skipPermissions){
4109 $query->_skipDeleteClause = TRUE;
4110 }
4111 $query->generatePermissionClause(FALSE, $count);
d9ab802d
PJ
4112
4113 // note : this modifies _fromClause and _simpleFromClause
4114 $query->includePseudoFieldsJoin($sort);
4115
6a488035
TO
4116 list($select, $from, $where, $having) = $query->query($count);
4117
4118 $options = $query->_options;
4119 if(!empty($query->_permissionWhereClause)){
4120 if (empty($where)) {
4121 $where = "WHERE $query->_permissionWhereClause";
4122 }
4123 else {
4124 $where = "$where AND $query->_permissionWhereClause";
4125 }
4126 }
4127
4128 $sql = "$select $from $where $having";
4129
4130 // add group by
4131 if ($query->_useGroupBy) {
4132 $sql .= ' GROUP BY contact_a.id';
4133 }
4134 if (!empty($sort)) {
4135 $sql .= " ORDER BY $sort ";
4136 }
4137 if ($row_count > 0 && $offset >= 0) {
4138 $sql .= " LIMIT $offset, $row_count ";
4139 }
4140
4141 $dao = CRM_Core_DAO::executeQuery($sql);
4142
4143 $values = array();
4144 while ($dao->fetch()) {
4145 if ($count) {
4146 $noRows = $dao->rowCount;
4147 $dao->free();
4148 return array($noRows,NULL);
4149 }
d9ab802d 4150 $val = $query->store($dao);
b719f000 4151 $convertedVals = $query->convertToPseudoNames($dao, TRUE);
d9ab802d
PJ
4152
4153 if (!empty($convertedVals)) {
be3f4839 4154 $val = array_merge_recursive($val, $convertedVals);
d9ab802d
PJ
4155 }
4156 $values[$dao->contact_id] = $val;
6a488035
TO
4157 }
4158 $dao->free();
4159 return array($values, $options);
4160 }
4161
4162 /**
4163 * create and query the db for an contact search
4164 *
4165 * @param int $offset the offset for the query
4166 * @param int $rowCount the number of rows to return
4167 * @param string $sort the order by string
4168 * @param boolean $count is this a count only query ?
4169 * @param boolean $includeContactIds should we include contact ids?
4170 * @param boolean $sortByChar if true returns the distinct array of first characters for search results
4171 * @param boolean $groupContacts if true, return only the contact ids
4172 * @param boolean $returnQuery should we return the query as a string
4173 * @param string $additionalWhereClause if the caller wants to further restrict the search (used for components)
4174 * @param string $additionalFromClause should be clause with proper joins, effective to reduce where clause load.
4175 *
4176 * @return CRM_Contact_DAO_Contact
4177 * @access public
4178 */
4179 function searchQuery(
4180 $offset = 0, $rowCount = 0, $sort = NULL,
4181 $count = FALSE, $includeContactIds = FALSE,
4182 $sortByChar = FALSE, $groupContacts = FALSE,
4183 $returnQuery = FALSE,
4184 $additionalWhereClause = NULL, $sortOrder = NULL,
4185 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4186 ) {
4187
4188 if ($includeContactIds) {
4189 $this->_includeContactIds = TRUE;
4190 $this->_whereClause = $this->whereClause();
4191 }
4192
6a488035
TO
4193 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params);
4194
f4bff68a 4195 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
6a488035
TO
4196 // and that contact happens to be deleted, set $onlyDeleted to true
4197 foreach ($this->_params as $values) {
4198 $name = CRM_Utils_Array::value(0, $values);
4199 $op = CRM_Utils_Array::value(1, $values);
4200 $value = CRM_Utils_Array::value(2, $values);
4201 if ($name == 'contact_id' and $op == '=') {
4202 if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
4203 $onlyDeleted = TRUE;
4204 }
4205 break;
4206 }
4207 }
4208 $this->generatePermissionClause($onlyDeleted, $count);
4209
6a488035
TO
4210 // building the query string
4211 $groupBy = NULL;
4212 if (!$count) {
4213 if (isset($this->_groupByComponentClause)) {
4214 $groupBy = $this->_groupByComponentClause;
4215 }
4216 elseif ($this->_useGroupBy) {
4217 $groupBy = ' GROUP BY contact_a.id';
4218 }
4219 }
4220 if ($this->_mode & CRM_Contact_BAO_Query::MODE_ACTIVITY && (!$count)) {
4221 $groupBy = 'GROUP BY civicrm_activity.id ';
4222 }
4223
4224 $order = $orderBy = $limit = '';
4225 if (!$count) {
4226 $config = CRM_Core_Config::singleton();
4227 if ($config->includeOrderByClause ||
4228 isset($this->_distinctComponentClause)
4229 ) {
4230 if ($sort) {
4231 if (is_string($sort)) {
4232 $orderBy = $sort;
4233 }
4234 else {
4235 $orderBy = trim($sort->orderBy());
4236 }
4237 if (!empty($orderBy)) {
4238 // this is special case while searching for
4239 // changelog CRM-1718
4240 if (preg_match('/sort_name/i', $orderBy)) {
4241 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
4242 }
4243
4244 $order = " ORDER BY $orderBy";
4245
4246 if ($sortOrder) {
4247 $order .= " $sortOrder";
4248 }
4249
4250 // always add contact_a.id to the ORDER clause
4251 // so the order is deterministic
4252 if (strpos('contact_a.id', $order) === FALSE) {
4253 $order .= ", contact_a.id";
4254 }
4255 }
4256 }
4257 elseif ($sortByChar) {
4258 $order = " ORDER BY UPPER(LEFT(contact_a.sort_name, 1)) asc";
4259 }
4260 else {
4261 $order = " ORDER BY contact_a.sort_name asc, contact_a.id";
4262 }
4263 }
4264
6a488035
TO
4265 // hack for order clause
4266 if ($order) {
4267 $fieldStr = trim(str_replace('ORDER BY', '', $order));
4268 $fieldOrder = explode(' ', $fieldStr);
4269 $field = $fieldOrder[0];
4270
4271 if ($field) {
4272 switch ($field) {
6a488035
TO
4273 case 'city':
4274 case 'postal_code':
4275 $this->_whereTables["civicrm_address"] = 1;
4276 $order = str_replace($field, "civicrm_address.{$field}", $order);
4277 break;
4278
4279 case 'country':
4280 case 'state_province':
4281 $this->_whereTables["civicrm_{$field}"] = 1;
4282 $order = str_replace($field, "civicrm_{$field}.name", $order);
4283 break;
4284
4285 case 'email':
4286 $this->_whereTables["civicrm_email"] = 1;
4287 $order = str_replace($field, "civicrm_email.{$field}", $order);
4288 break;
6a488035 4289 }
4243847f
CW
4290 $this->_fromClause = self::fromClause($this->_tables, NULL, NULL, $this->_primaryLocation, $this->_mode);
4291 $this->_simpleFromClause = self::fromClause($this->_whereTables, NULL, NULL, $this->_primaryLocation, $this->_mode);
6a488035
TO
4292 }
4293 }
4294
6a488035
TO
4295 if ($rowCount > 0 && $offset >= 0) {
4296 $limit = " LIMIT $offset, $rowCount ";
4243847f
CW
4297 }
4298 }
6a488035 4299
b1be45a0 4300 // note : this modifies _fromClause and _simpleFromClause
d9ab802d
PJ
4301 $this->includePseudoFieldsJoin($sort);
4302
4243847f 4303 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts);
6a488035 4304
1939d296 4305 if(!empty($this->_permissionWhereClause)){
4306 if (empty($where)) {
4307 $where = "WHERE $this->_permissionWhereClause";
4308 }
4309 else {
4310 $where = "$where AND $this->_permissionWhereClause";
4311 }
4312 }
4313
4314 if ($additionalWhereClause) {
4315 $where = $where . ' AND ' . $additionalWhereClause;
4316 }
4317
4318 //additional from clause should be w/ proper joins.
4243847f
CW
4319 if ($additionalFromClause) {
4320 $from .= "\n" . $additionalFromClause;
6a488035
TO
4321 }
4322
4323 // if we are doing a transform, do it here
4324 // use the $from, $where and $having to get the contact ID
4325 if ($this->_displayRelationshipType) {
4326 $this->filterRelatedContacts($from, $where, $having);
4327 }
4328
4329 if ($skipOrderAndLimit) {
4330 $query = "$select $from $where $having $groupBy";
4331 }
4332 else {
4333 $query = "$select $from $where $having $groupBy $order $limit";
4334 }
4335
4336 if ($returnQuery) {
4337 return $query;
4338 }
4339
4340 if ($count) {
4341 return CRM_Core_DAO::singleValueQuery($query);
4342 }
4343
6a488035
TO
4344 $dao = CRM_Core_DAO::executeQuery($query);
4345 if ($groupContacts) {
4346 $ids = array();
4347 while ($dao->fetch()) {
4348 $ids[] = $dao->id;
4349 }
4350 return implode(',', $ids);
4351 }
4352
4353 return $dao;
4354 }
4355
4243847f
CW
4356 /**
4357 * Fetch a list of contacts from the prev/next cache for displaying a search results page
4358 *
4359 * @param string $cacheKey
4360 * @param int $offset
4361 * @param int $rowCount
4362 * @param bool $includeContactIds
4363 * @return CRM_Core_DAO
4364 */
4365 function getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds) {
4366 $this->_includeContactIds = $includeContactIds;
23379b49 4367 list($select, $from, $where) = $this->query();
4243847f
CW
4368 $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);
4369 $order = " ORDER BY pnc.id";
1e7a8a53 4370 $groupBy = " GROUP BY contact_a.id";
4243847f 4371 $limit = " LIMIT $offset, $rowCount";
23379b49 4372 $query = "$select $from $where $groupBy $order $limit";
4373
4243847f
CW
4374 return CRM_Core_DAO::executeQuery($query);
4375 }
4376
6a488035
TO
4377 /**
4378 * Populate $this->_permissionWhereClause with permission related clause and update other
4379 * query related properties.
4380 *
4381 * Function calls ACL permission class and hooks to filter the query appropriately
4382 *
4383 * Note that these 2 params were in the code when extracted from another function
4384 * and a second round extraction would be to make them properties of the class
4385 *
4386 * @param bool $onlyDeleted Only get deleted contacts
4387 * @param bool $count Return Count only
4388 *
4389 * @return null
4390 */
4391 function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4392 if (!$this->_skipPermission) {
4393 $this->_permissionWhereClause = CRM_ACL_API::whereClause(
4394 CRM_Core_Permission::VIEW,
4395 $this->_tables,
4396 $this->_whereTables,
4397 NULL,
4398 $onlyDeleted,
4399 $this->_skipDeleteClause
4400 );
4401
4402 // regenerate fromClause since permission might have added tables
4403 if ($this->_permissionWhereClause) {
4404 //fix for row count in qill (in contribute/membership find)
4405 if (!$count) {
4406 $this->_useDistinct = TRUE;
4407 }
4408 $this->_fromClause = self::fromClause($this->_tables, NULL, NULL, $this->_primaryLocation, $this->_mode);
4409 $this->_simpleFromClause = self::fromClause($this->_whereTables, NULL, NULL, $this->_primaryLocation, $this->_mode);
4410 }
4411 }
4412 else {
4413 // add delete clause if needed even if we are skipping permission
4414 // CRM-7639
4415 if (!$this->_skipDeleteClause) {
4416 if (CRM_Core_Permission::check('access deleted contacts') and $onlyDeleted) {
4417 $this->_permissionWhereClause = '(contact_a.is_deleted)';
4418 }
4419 else {
4420 // CRM-6181
4421 $this->_permissionWhereClause = '(contact_a.is_deleted = 0)';
4422 }
4423 }
4424 }
4425 }
4426
4427 function setSkipPermission($val) {
4428 $this->_skipPermission = $val;
4429 }
4430
4431 function &summaryContribution($context = NULL) {
4432 list($select, $from, $where, $having) = $this->query(TRUE);
4433
4434 // hack $select
4435 $select = "
4436SELECT COUNT( civicrm_contribution.total_amount ) as total_count,
4437 SUM( civicrm_contribution.total_amount ) as total_amount,
4438 AVG( civicrm_contribution.total_amount ) as total_avg,
4439 civicrm_contribution.currency as currency";
4440
4441 // make sure contribution is completed - CRM-4989
4442 $where .= " AND civicrm_contribution.contribution_status_id = 1 ";
4443 if ($context == 'search') {
4444 $where .= " AND contact_a.is_deleted = 0 ";
4445 }
4446
4447 $summary = array();
4448 $summary['total'] = array();
4449 $summary['total']['count'] = $summary['total']['amount'] = $summary['total']['avg'] = "n/a";
4450
4451 $query = "$select $from $where GROUP BY currency";
4452 $params = array();
4453
4454 $dao = CRM_Core_DAO::executeQuery($query, $params);
4455
4456 $summary['total']['count'] = 0;
4457 $summary['total']['amount'] = $summary['total']['avg'] = array();
4458 while ($dao->fetch()) {
4459 $summary['total']['count'] += $dao->total_count;
4460 $summary['total']['amount'][] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
4461 $summary['total']['avg'][] = CRM_Utils_Money::format($dao->total_avg, $dao->currency);
4462 }
4463 if (!empty($summary['total']['amount'])) {
4464 $summary['total']['amount'] = implode(',&nbsp;', $summary['total']['amount']);
4465 $summary['total']['avg'] = implode(',&nbsp;', $summary['total']['avg']);
4466 }
4467 else {
4468 $summary['total']['amount'] = $summary['total']['avg'] = 0;
4469 }
4470
4471 // hack $select
4472 $select = "
4473SELECT COUNT( civicrm_contribution.total_amount ) as cancel_count,
4474 SUM( civicrm_contribution.total_amount ) as cancel_amount,
4475 AVG( civicrm_contribution.total_amount ) as cancel_avg,
4476 civicrm_contribution.currency as currency";
4477
4478 $where .= " AND civicrm_contribution.cancel_date IS NOT NULL ";
4479 if ($context == 'search') {
4480 $where .= " AND contact_a.is_deleted = 0 ";
4481 }
4482
4483 $query = "$select $from $where GROUP BY currency";
4484 $dao = CRM_Core_DAO::executeQuery($query, $params);
4485
4486 if ($dao->N <= 1) {
4487 if ($dao->fetch()) {
4488 $summary['cancel']['count'] = $dao->cancel_count;
4489 $summary['cancel']['amount'] = $dao->cancel_amount;
4490 $summary['cancel']['avg'] = $dao->cancel_avg;
4491 }
4492 }
4493 else {
4494 $summary['cancel']['count'] = 0;
4495 $summary['cancel']['amount'] = $summary['cancel']['avg'] = array();
4496 while ($dao->fetch()) {
4497 $summary['cancel']['count'] += $dao->cancel_count;
4498 $summary['cancel']['amount'][] = CRM_Utils_Money::format($dao->cancel_amount, $dao->currency);
4499 $summary['cancel']['avg'][] = CRM_Utils_Money::format($dao->cancel_avg, $dao->currency);
4500 }
4501 $summary['cancel']['amount'] = implode(',&nbsp;', $summary['cancel']['amount']);
4502 $summary['cancel']['avg'] = implode(',&nbsp;', $summary['cancel']['avg']);
4503 }
4504
4505 return $summary;
4506 }
4507
4508 /**
4509 * getter for the qill object
4510 *
4511 * @return string
4512 * @access public
4513 */
4514 function qill() {
4515 return $this->_qill;
4516 }
4517
4518 /**
4519 * default set of return default hier return properties
4520 *
4521 * @return void
4522 * @access public
4523 */
4524 static function &defaultHierReturnProperties() {
4525 if (!isset(self::$_defaultHierReturnProperties)) {
4526 self::$_defaultHierReturnProperties = array(
4527 'home_URL' => 1,
4528 'image_URL' => 1,
4529 'legal_identifier' => 1,
4530 'external_identifier' => 1,
4531 'contact_type' => 1,
4532 'contact_sub_type' => 1,
4533 'sort_name' => 1,
4534 'display_name' => 1,
4535 'nick_name' => 1,
4536 'first_name' => 1,
4537 'middle_name' => 1,
4538 'last_name' => 1,
67744c4e
CW
4539 'prefix_id' => 1,
4540 'suffix_id' => 1,
6a488035
TO
4541 'email_greeting' => 1,
4542 'postal_greeting' => 1,
4543 'addressee' => 1,
4544 'birth_date' => 1,
67744c4e 4545 'gender_id' => 1,
6a488035
TO
4546 'preferred_communication_method' => 1,
4547 'do_not_phone' => 1,
4548 'do_not_email' => 1,
4549 'do_not_mail' => 1,
4550 'do_not_sms' => 1,
4551 'do_not_trade' => 1,
4552 'location' =>
4553 array(
4554 '1' => array('location_type' => 1,
4555 'street_address' => 1,
4556 'city' => 1,
4557 'state_province' => 1,
4558 'postal_code' => 1,
4559 'postal_code_suffix' => 1,
4560 'country' => 1,
4561 'phone-Phone' => 1,
4562 'phone-Mobile' => 1,
4563 'phone-Fax' => 1,
4564 'phone-1' => 1,
4565 'phone-2' => 1,
4566 'phone-3' => 1,
4567 'im-1' => 1,
4568 'im-2' => 1,
4569 'im-3' => 1,
4570 'email-1' => 1,
4571 'email-2' => 1,
4572 'email-3' => 1,
4573 ),
4574 '2' => array(
4575 'location_type' => 1,
4576 'street_address' => 1,
4577 'city' => 1,
4578 'state_province' => 1,
4579 'postal_code' => 1,
4580 'postal_code_suffix' => 1,
4581 'country' => 1,
4582 'phone-Phone' => 1,
4583 'phone-Mobile' => 1,
4584 'phone-1' => 1,
4585 'phone-2' => 1,
4586 'phone-3' => 1,
4587 'im-1' => 1,
4588 'im-2' => 1,
4589 'im-3' => 1,
4590 'email-1' => 1,
4591 'email-2' => 1,
4592 'email-3' => 1,
4593 ),
4594 ),
4595 );
4596 }
4597 return self::$_defaultHierReturnProperties;
4598 }
4599
4600 function dateQueryBuilder(
4601 &$values, $tableName, $fieldName,
4602 $dbFieldName, $fieldTitle,
4603 $appendTimeStamp = TRUE
4604 ) {
4605 list($name, $op, $value, $grouping, $wildcard) = $values;
4606
4607 if (!$value) {
4608 return;
4609 }
4610
4611 if ($name == "{$fieldName}_low" ||
4612 $name == "{$fieldName}_high"
4613 ) {
4614 if (isset($this->_rangeCache[$fieldName])) {
4615 return;
4616 }
4617 $this->_rangeCache[$fieldName] = 1;
4618
4619 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
4620
4621 if ($name == $fieldName . '_low') {
4622 $firstOP = '>=';
228917cd 4623 $firstPhrase = ts('greater than or equal to');
6a488035
TO
4624 $firstDate = CRM_Utils_Date::processDate($value);
4625
4626 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
228917cd 4627 if (!empty($secondValues) && $secondValues[2]) {
6a488035 4628 $secondOP = '<=';
228917cd 4629 $secondPhrase = ts('less than or equal to');
6a488035
TO
4630 $secondValue = $secondValues[2];
4631
228917cd 4632 if ($appendTimeStamp && strlen($secondValue) == 10) {
6a488035
TO
4633 $secondValue .= ' 23:59:59';
4634 }
4635 $secondDate = CRM_Utils_Date::processDate($secondValue);
4636 }
4637 }
4638 elseif ($name == $fieldName . '_high') {
4639 $firstOP = '<=';
228917cd 4640 $firstPhrase = ts('less than or equal to');
6a488035 4641
228917cd 4642 if ($appendTimeStamp && strlen($value) == 10) {
6a488035
TO
4643 $value .= ' 23:59:59';
4644 }
4645 $firstDate = CRM_Utils_Date::processDate($value);
4646
4647 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
228917cd 4648 if (!empty($secondValues) && $secondValues[2]) {
6a488035 4649 $secondOP = '>=';
228917cd 4650 $secondPhrase = ts('greater than or equal to');
6a488035
TO
4651 $secondValue = $secondValues[2];
4652 $secondDate = CRM_Utils_Date::processDate($secondValue);
4653 }
4654 }
4655
4656 if (!$appendTimeStamp) {
4657 $firstDate = substr($firstDate, 0, 8);
4658 }
4659 $firstDateFormat = CRM_Utils_Date::customFormat($firstDate);
4660
4661 if ($secondDate) {
4662 if (!$appendTimeStamp) {
4663 $secondDate = substr($secondDate, 0, 8);
4664 }
4665 $secondDateFormat = CRM_Utils_Date::customFormat($secondDate);
4666 }
4667
4668 $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
4669 if ($secondDate) {
4670 $this->_where[$grouping][] = "
4671( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
4672( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
4673";
4674 $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
4675 }
4676 else {
4677 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
4678 $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
4679 }
4680 }
4681
4682 if ($name == $fieldName) {
4683 // $op = '=';
4684 $phrase = $op;
4685
4686 $date = CRM_Utils_Date::processDate($value);
4687
4688 if (!$appendTimeStamp) {
4689 $date = substr($date, 0, 8);
4690 }
4691
4692 $format = CRM_Utils_Date::customFormat($date);
4693
4694 if ($date) {
4695 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $op '$date'";
4696 }
4697 else {
4698 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $op";
4699 }
4700 $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
4701 $this->_qill[$grouping][] = "$fieldTitle - $phrase \"$format\"";
4702 }
4703
4704 if (
4705 $tableName == 'civicrm_log' &&
228917cd 4706 $fieldTitle == ts('Added Date')
6a488035
TO
4707 ) {
4708 //CRM-6903 --hack to check modified date of first record.
4709 //as added date means first modified date of object.
4710 $addedDateQuery = 'select id from civicrm_log group by entity_id order by id';
4711 $this->_where[$grouping][] = "civicrm_log.id IN ( {$addedDateQuery} )";
4712 }
4713 }
4714
4715 function numberRangeBuilder(&$values,
4716 $tableName, $fieldName,
4717 $dbFieldName, $fieldTitle,
4718 $options = NULL
4719 ) {
4720 list($name, $op, $value, $grouping, $wildcard) = $values;
4721
4722 if ($name == "{$fieldName}_low" ||
4723 $name == "{$fieldName}_high"
4724 ) {
4725 if (isset($this->_rangeCache[$fieldName])) {
4726 return;
4727 }
4728 $this->_rangeCache[$fieldName] = 1;
4729
4730 $secondOP = $secondPhrase = $secondValue = NULL;
4731
4732 if ($name == "{$fieldName}_low") {
4733 $firstOP = '>=';
228917cd 4734 $firstPhrase = ts('greater than');
6a488035
TO
4735
4736 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
4737 if (!empty($secondValues)) {
4738 $secondOP = '<=';
228917cd 4739 $secondPhrase = ts('less than');
6a488035
TO
4740 $secondValue = $secondValues[2];
4741 }
4742 }
4743 else {
4744 $firstOP = '<=';
228917cd 4745 $firstPhrase = ts('less than');
6a488035
TO
4746
4747 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
4748 if (!empty($secondValues)) {
4749 $secondOP = '>=';
228917cd 4750 $secondPhrase = ts('greater than');
6a488035
TO
4751 $secondValue = $secondValues[2];
4752 }
4753 }
4754
4755 if ($secondOP) {
4756 $this->_where[$grouping][] = "
4757( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
4758( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
4759";
4760 $displayValue = $options ? $options[$value] : $value;
4761 $secondDisplayValue = $options ? $options[$secondValue] : $secondValue;
4762
228917cd
DL
4763 $this->_qill[$grouping][] =
4764 "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
6a488035
TO
4765 }
4766 else {
4767 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
4768 $displayValue = $options ? $options[$value] : $value;
4769 $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
4770 }
4771 $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
4772
4773 return;
4774 }
4775
4776 if ($name == $fieldName) {
4777 $op = '=';
4778 $phrase = '=';
4779
4780 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
4781
4782 $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
4783 $displayValue = $options ? $options[$value] : $value;
4784 $this->_qill[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
4785 }
4786
4787 return;
4788 }
4789
4790 /**
4791 * Given the field name, operator, value & its data type
4792 * builds the where Clause for the query
4793 * used for handling 'IS NULL'/'IS NOT NULL' operators
4794 *
4795 * @param string $field fieldname
4796 * @param string $op operator
4797 * @param string $value value
4798 * @param string $dataType data type of the field
4799 *
4800 * @return where clause for the query
4801 * @access public
4802 */
4803 static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
4804 $op = trim($op);
4805 $clause = "$field $op";
4806
4807 switch ($op) {
4808 case 'IS NULL':
4809 case 'IS NOT NULL':
4810 return $clause;
4811
4812 case 'IS EMPTY':
4813 $clause = " ( $field IS NULL OR $field = '' ) ";
4814 return $clause;
4815
4816 case 'IS NOT EMPTY':
4817 $clause = " ( $field IS NOT NULL AND $field <> '' ) ";
4818 return $clause;
4819
4820 case 'IN':
4821 case 'NOT IN':
4822 if (isset($dataType)) {
4823 if (is_array($value)) {
4824 $values = $value;
4825 }
4826 else {
4827 $value = CRM_Utils_Type::escape($value, "String");
4828 $values = explode(',', CRM_Utils_Array::value(0, explode(')', CRM_Utils_Array::value(1, explode('(', $value)))));
4829 }
4830 // supporting multiple values in IN clause
4831 $val = array();
4832 foreach ($values as $v) {
4833 $v = trim($v);
4834 $val[] = "'" . CRM_Utils_Type::escape($v, $dataType) . "'";
4835 }
4836 $value = "(" . implode($val, ",") . ")";
4837 }
4838 return "$clause $value";
4839
4840 default:
4841 if (empty($dataType)) {
4842 $dataType = 'String';
4843 }
4844
4845 $value = CRM_Utils_Type::escape($value, $dataType);
4846
4847 // if we dont have a dataType we should assume
85bdc94e 4848 if ($dataType == 'String' || $dataType == 'Text') {
6a488035
TO
4849 $value = "'" . strtolower($value) . "'";
4850 }
4851 return "$clause $value";
4852 }
4853 }
4854
4855 function openedSearchPanes($reset = FALSE) {
4856 if (!$reset || empty($this->_whereTables)) {
4857 return self::$_openedPanes;
4858 }
4859
4860 // pane name to table mapper
4861 $panesMapper = array(
4862 ts('Contributions') => 'civicrm_contribution',
4863 ts('Memberships') => 'civicrm_membership',
4864 ts('Events') => 'civicrm_participant',
4865 ts('Relationships') => 'civicrm_relationship',
4866 ts('Activities') => 'civicrm_activity',
4867 ts('Pledges') => 'civicrm_pledge',
4868 ts('Cases') => 'civicrm_case',
4869 ts('Grants') => 'civicrm_grant',
4870 ts('Address Fields') => 'civicrm_address',
4871 ts('Notes') => 'civicrm_note',
4872 ts('Change Log') => 'civicrm_log',
4873 ts('Mailings') => 'civicrm_mailing_event_queue',
4874 );
4875
4876 foreach (array_keys($this->_whereTables) as $table) {
4877 if ($panName = array_search($table, $panesMapper)) {
4878 self::$_openedPanes[$panName] = TRUE;
4879 }
4880 }
4881
4882 return self::$_openedPanes;
4883 }
4884
4885 function setOperator($operator) {
4886 $validOperators = array('AND', 'OR');
4887 if (!in_array($operator, $validOperators)) {
4888 $operator = 'AND';
4889 }
4890 $this->_operator = $operator;
4891 }
4892
4893 function getOperator() {
4894 return $this->_operator;
4895 }
4896
4897 function filterRelatedContacts(&$from, &$where, &$having) {
4898 static $_rTypeProcessed = NULL;
4899 static $_rTypeFrom = NULL;
4900 static $_rTypeWhere = NULL;
4901
4902 if (!$_rTypeProcessed) {
4903 $_rTypeProcessed = TRUE;
4904
4905 // create temp table with contact ids
4906 $tableName = CRM_Core_DAO::createTempTableName('civicrm_transform', TRUE);
4907 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
4908 CRM_Core_DAO::executeQuery($sql);
4909
4910 $sql = "
4911REPLACE INTO $tableName ( contact_id )
4912SELECT contact_a.id
4913 $from
4914 $where
4915 $having
4916";
4917 CRM_Core_DAO::executeQuery($sql);
4918
4919 $qillMessage = ts('Contacts with a Relationship Type of: ');
4920 $rTypes = CRM_Core_PseudoConstant::relationshipType();
4921
4922 if (is_numeric($this->_displayRelationshipType)) {
4923 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType]['label_a_b'];
4924 $_rTypeFrom = "
4925INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
4926INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
4927";
4928 $_rTypeWhere = "
4929WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
4930AND displayRelType.is_active = 1
4931";
4932 }
4933 else {
4934 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType);
4935 if ($dirOne == 'a') {
4936 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
4937 $_rTypeFrom .= "
4938INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
4939INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
4940";
4941 }
4942 else {
4943 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
4944 $_rTypeFrom .= "
4945INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
4946INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
4947";
4948 }
4949 $_rTypeWhere = "
4950WHERE displayRelType.relationship_type_id = $relType
4951AND displayRelType.is_active = 1
4952";
4953 }
6a488035
TO
4954 $this->_qill[0][] = $qillMessage . "'" . $relationshipTypeLabel . "'";
4955 }
4956
4957 if (strpos($from, $_rTypeFrom) === FALSE) {
4958 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
4959 // this happens when we have an event_type in the quert (CRM-7969)
4960 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
4961 $from .= $_rTypeFrom;
4962 $where = $_rTypeWhere;
4963 }
4964
4965 $having = NULL;
4966 }
4967
4968 static function caseImportant( $op ) {
4969 return
4970 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ? FALSE : TRUE;
4971 }
4972
4973 static function componentPresent( &$returnProperties, $prefix ) {
4974 foreach ($returnProperties as $name => $dontCare ) {
4975 if (substr($name, 0, strlen($prefix)) == $prefix) {
4976 return TRUE;
4977 }
4978 }
4979 return FALSE;
4980 }
4981
4982 /**
4983 * Builds the necessary structures for all fields that are similar to option value lookups
4984 *
4985 * @param $name string the name of the field
4986 * @param $op string the sql operator, this function should handle ALL SQL operators
4987 * @param $value any string / integer / array depends on the operator and whos calling the query builder
4988 * @param $grouping int the index where to place the where clause
837c4660 4989 * @param $selectValues
6a488035
TO
4990 * @param $field array an array that contains various properties of the field identified by $name
4991 * @param $label string The label for this field element
4992 * @param $dataType string The data type for this element
4993 *
837c4660
E
4994 * @param bool $useIDsOnly
4995 *
4996 * @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
4997 * @return void adds the where clause and qill to the query object
4998 */
4999 function optionValueQuery(
5000 $name,
5001 $op,
5002 $value,
5003 $grouping,
5004 $selectValues,
5005 $field,
5006 $label,
a30e57e0
DL
5007 $dataType = 'String',
5008 $useIDsOnly = FALSE
6a488035 5009 ) {
bd3728fb 5010
5011 if (!empty($selectValues)) {
5012 $qill = $selectValues[$value];
5013 }
5014 else {
5015 $qill = $value;
5016 }
5017
04ffef8d 5018 $pseudoFields = array('email_greeting', 'postal_greeting', 'addressee', 'gender_id', 'prefix_id', 'suffix_id');
d9ab802d 5019
6a488035 5020 if (is_numeric($value)) {
a30e57e0 5021 $qill = $selectValues[(int ) $value];
6a488035
TO
5022 }
5023 elseif ($op == 'IN' || $op == 'NOT IN') {
5024 $values = self::parseSearchBuilderString($value);
5025 if (is_array($values)) {
d9ab802d 5026 $intVals = array();
6a488035
TO
5027 $newValues = array();
5028 foreach ($values as $v) {
d9ab802d 5029 $intVals[] = (int) $v;
6a488035
TO
5030 $newValues[] = $selectValues[(int ) $v];
5031 }
d9ab802d
PJ
5032
5033 $value = (in_array($name, $pseudoFields)) ? $intVals : $newValues;
5034 $qill = implode(', ', $newValues);
6a488035
TO
5035 }
5036 }
9131c564 5037 elseif (!array_key_exists($value, $selectValues)) {
a30e57e0
DL
5038 // its a string, lets get the int value
5039 $value = array_search($value, $selectValues);
5040 }
9df8a11d
DL
5041 if ($useIDsOnly) {
5042 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5043 if ($tableName == 'civicrm_contact') {
5044 $wc = "contact_a.$fieldName";
5045 }
5046 }
5047 else {
5048 $wc = self::caseImportant($op) ? "LOWER({$field['where']})" : "{$field['where']}";
5049 }
d9ab802d
PJ
5050
5051 if (in_array($name, $pseudoFields)) {
04ffef8d 5052 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id'))) {
d9ab802d
PJ
5053 $wc = "contact_a.{$name}_id";
5054 }
5055 $dataType = 'Positive';
5056 $value = (!$value) ? 0 : $value;
5057 }
5058
6a488035 5059 $this->_qill[$grouping][] = $label . " $op '$qill'";
d9ab802d
PJ
5060 $op = (in_array($name, $pseudoFields) && ($op == 'LIKE' || $op == 'RLIKE')) ? '=' : $op;
5061 $this->_where[$grouping][] = self::buildClause($wc, $op, $value, $dataType);
6a488035
TO
5062 }
5063
a30e57e0
DL
5064 /**
5065 * function to check and explode a user defined numeric string into an array
6a488035
TO
5066 * this was the protocol used by search builder in the old old days before we had
5067 * super nice js widgets to do the hard work
5068 *
837c4660
E
5069 * @param the $string
5070 * @param string $dataType the dataType we should check for the values, default integer
6a488035
TO
5071 *
5072 * @return FALSE if string does not match the patter
5073 * array of numeric values if string does match the pattern
5074 * @static
5075 */
5076 static function parseSearchBuilderString($string, $dataType = 'Integer') {
5077 $string = trim($string);
5078 if (substr($string, 0, 1) != '(' || substr($string, -1, 1) != ')') {
5079 Return FALSE;
5080 }
5081
5082 $string = substr($string, 1, -1);
5083 $values = explode(',', $string);
5084 if (empty($values)) {
5085 return FALSE;
5086 }
5087
5088 $returnValues = array();
5089 foreach ($values as $v) {
5090 if ($dataType == 'Integer' && ! is_numeric($v)) {
5091 return FALSE;
5092 }
5093 else if ($dataType == 'String' && ! is_string($v)) {
5094 return FALSE;
5095 }
5096 $returnValues[] = trim($v);
5097 }
5098
5099 if (empty($returnValues)) {
5100 return FALSE;
5101 }
5102
5103 return $returnValues;
5104 }
6a488035 5105
d9ab802d
PJ
5106 /**
5107 * convert the pseudo constants id's to their names
837c4660 5108 *
d9ab802d 5109 * @param reference parameter $dao
837c4660
E
5110 * @param bool $return
5111 *
5112 * @return array
d9ab802d 5113 */
b719f000 5114 function convertToPseudoNames(&$dao, $return = FALSE) {
d9ab802d
PJ
5115 if (empty($this->_pseudoConstantsSelect)) {
5116 return;
5117 }
d9ab802d
PJ
5118 $values = array();
5119 foreach ($this->_pseudoConstantsSelect as $key => $value) {
5120 if (CRM_Utils_Array::value('sorting', $this->_pseudoConstantsSelect[$key])) {
5121 continue;
5122 }
5123
5124 if (property_exists($dao, $value['idCol'])) {
5125 $val = $dao->$value['idCol'];
5126
5127 if (CRM_Utils_System::isNull($val)) {
5128 $dao->$key = NULL;
d9ab802d 5129 }
b719f000 5130 elseif ($baoName = CRM_Utils_Array::value('bao', $value, NULL)) {
827659b2 5131 //preserve id value
5132 $idColumn = "{$key}_id";
5133 $dao->$idColumn = $val;
09aefef4 5134 $dao->$key = CRM_Core_PseudoConstant::getLabel($baoName, $value['pseudoField'], $val);
d9ab802d
PJ
5135 }
5136 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5137 $dao->$key = CRM_Core_PseudoConstant::stateProvinceAbbreviation($val);
5138 }
d9ab802d
PJ
5139 else {
5140 $labels = CRM_Core_OptionGroup::values($value['pseudoField']);
5141 $dao->$key = $labels[$val];
5142 }
b719f000
PJ
5143
5144 // return converted values in array format
5145 if ($return) {
5146 if (strpos($key, '-') !== FALSE) {
5147 $keyVal = explode('-', $key);
5148 $current = &$values;
5149 $lastElement = array_pop($keyVal);
5150 foreach ($keyVal as $v) {
5151 if (!array_key_exists($v, $current)) {
5152 $current[$v] = array();
5153 }
5154 $current = &$current[$v];
5155 }
5156 $current[$lastElement] = $dao->$key;
5157 }
5158 else {
5159 $values[$key] = $dao->$key;
5160 }
5161 }
d9ab802d
PJ
5162 }
5163 }
5164 return $values;
5165 }
5166
837c4660 5167 /**
d9ab802d
PJ
5168 * include pseudo fields LEFT JOIN
5169 * @param $sort can be a object or string
5170 *
837c4660 5171 * @return array
d9ab802d
PJ
5172 */
5173 function includePseudoFieldsJoin($sort) {
5174 if (!$sort || empty($this->_pseudoConstantsSelect)) {
5175 return;
5176 }
5177 $sort = is_string($sort) ? $sort : $sort->orderBy();
5178 $present = array();
5179
5180 foreach ($this->_pseudoConstantsSelect as $name => $value) {
5181 if (CRM_Utils_Array::value('table', $value)) {
5182 $regex = "/({$value['table']}\.|{$name})/";
5183 if (preg_match($regex, $sort)) {
5184 $this->_elemnt[$value['element']] = 1;
5185 $this->_select[$value['element']] = $value['select'];
5186 $this->_pseudoConstantsSelect[$name]['sorting'] = 1;
5187 $present[$value['table']] = $value['join'];
5188 }
5189 }
5190 }
5191 $presentSimpleFrom = $present;
5192
5193 if (array_key_exists('civicrm_worldregion', $this->_whereTables) &&
5194 array_key_exists('civicrm_country', $presentSimpleFrom)) {
5195 unset($presentSimpleFrom['civicrm_country']);
5196 }
5197 if (array_key_exists('civicrm_worldregion', $this->_tables) &&
5198 array_key_exists('civicrm_country', $present)) {
5199 unset($present['civicrm_country']);
5200 }
5201
5202 $presentClause = $presentSimpleFromClause = NULL;
5203 if (!empty($present)) {
5204 $presentClause = implode(' ', $present);
5205 }
5206 if (!empty($presentSimpleFrom)) {
5207 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
5208 }
5209
5210 $this->_fromClause = $this->_fromClause . $presentClause;
5211 $this->_simpleFromClause = $this->_simpleFromClause . $presentSimpleFromClause;
5212
5213 return array($presentClause, $presentSimpleFromClause);
5214 }
e7830dbe 5215}