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