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