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