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