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