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