Merge pull request #15638 from eileenmcnaughton/vangelis
[civicrm-core.git] / CRM / Contact / BAO / Query.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
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
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
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 41 *
746aa919
CB
42 * As of February 2017, entries not present for 4, 32, 64, 1024.
43 *
44 * MODE_ALL seems to be out of sync with the available constants;
45 * if this is intentionally excluding MODE_MAILING then that may
46 * bear documenting?
47 *
48 * Likewise if there's reason for the missing modes (4, 32, 64 etc).
49 *
6a488035
TO
50 * @var int
51 */
7da04cde 52 const
33092c89 53 NO_RETURN_PROPERTIES = 'CRM_Contact_BAO_Query::NO_RETURN_PROPERTIES',
6a488035
TO
54 MODE_CONTACTS = 1,
55 MODE_CONTRIBUTE = 2,
746aa919 56 // There is no 4,
6a488035
TO
57 MODE_MEMBER = 8,
58 MODE_EVENT = 16,
eda34f9b
MW
59 MODE_CONTACTSRELATED = 32,
60 // no 64.
6a488035
TO
61 MODE_GRANT = 128,
62 MODE_PLEDGEBANK = 256,
63 MODE_PLEDGE = 512,
746aa919 64 // There is no 1024,
6a488035 65 MODE_CASE = 2048,
6a488035
TO
66 MODE_ACTIVITY = 4096,
67 MODE_CAMPAIGN = 8192,
746aa919
CB
68 MODE_MAILING = 16384,
69 MODE_ALL = 17407;
6a488035 70
eda34f9b
MW
71 /**
72 * Constants for search operators
73 */
74 const
75 SEARCH_OPERATOR_AND = 'AND',
76 SEARCH_OPERATOR_OR = 'OR';
77
6a488035 78 /**
fe482240 79 * The default set of return properties.
6a488035
TO
80 *
81 * @var array
6a488035 82 */
69078420 83 public static $_defaultReturnProperties = NULL;
6a488035
TO
84
85 /**
fe482240 86 * The default set of hier return properties.
6a488035
TO
87 *
88 * @var array
6a488035 89 */
69078420 90 public static $_defaultHierReturnProperties;
6a488035
TO
91
92 /**
fe482240 93 * The set of input params.
6a488035
TO
94 *
95 * @var array
96 */
97 public $_params;
98
99 public $_cfIDs;
100
101 public $_paramLookup;
102
ac4985d5 103 public $_sort;
746aa919 104
6a488035 105 /**
100fef9d 106 * The set of output params
6a488035
TO
107 *
108 * @var array
109 */
110 public $_returnProperties;
111
112 /**
100fef9d 113 * The select clause
6a488035
TO
114 *
115 * @var array
116 */
117 public $_select;
118
119 /**
100fef9d 120 * The name of the elements that are in the select clause
746aa919 121 * used to extract the values.
6a488035
TO
122 *
123 * @var array
124 */
125 public $_element;
126
127 /**
746aa919 128 * The tables involved in the query.
6a488035
TO
129 *
130 * @var array
131 */
132 public $_tables;
133
134 /**
746aa919 135 * The table involved in the where clause.
6a488035
TO
136 *
137 * @var array
138 */
139 public $_whereTables;
140
141 /**
746aa919 142 * Array of WHERE clause components.
6a488035
TO
143 *
144 * @var array
145 */
146 public $_where;
147
148 /**
746aa919 149 * The WHERE clause as a string.
6a488035
TO
150 *
151 * @var string
6a488035
TO
152 */
153 public $_whereClause;
154
155 /**
746aa919 156 * Additional WHERE clause for permissions.
6a488035
TO
157 *
158 * @var string
6a488035
TO
159 */
160 public $_permissionWhereClause;
a30e57e0 161
6a488035 162 /**
100fef9d 163 * The from string
6a488035
TO
164 *
165 * @var string
6a488035
TO
166 */
167 public $_fromClause;
168
169 /**
100fef9d 170 * Additional permission from clause
6a488035
TO
171 *
172 * @var string
6a488035
TO
173 */
174 public $_permissionFromClause;
175
176 /**
100fef9d 177 * The from clause for the simple select and alphabetical
6a488035
TO
178 * select
179 *
180 * @var string
181 */
182 public $_simpleFromClause;
183
184 /**
100fef9d 185 * The having values
6a488035
TO
186 *
187 * @var string
6a488035
TO
188 */
189 public $_having;
190
191 /**
192 * The english language version of the query
193 *
194 * @var array
195 */
196 public $_qill;
197
198 /**
199 * All the fields that could potentially be involved in
200 * this query
201 *
202 * @var array
203 */
204 public $_fields;
205
714ab070 206 /**
207 * Fields hacked for legacy reasons.
208 *
209 * Generally where a field has a option group defining it's options we add them to
210 * the fields array as pseudofields - eg for gender we would add the key 'gender' to fields
211 * using CRM_Core_DAO::appendPseudoConstantsToFields($fields);
212 *
213 * The rendered results would hold an id in the gender_id field and the label in the pseudo 'Gender'
214 * field. The heading for the pseudofield would come form the the option group name & for the id field
215 * from the xml.
216 *
217 * These fields are handled in a more legacy way - ie overwriting 'gender_id' with the label on output
218 * via the convertToPseudoNames function. Ideally we would convert them but they would then need to be fixed
219 * in some other places & there are also some issues around the name (ie. Gender currently has the label in the
220 * schema 'Gender' so adding a second 'Gender' field to search builder & export would be confusing and the standard is
221 * not fully agreed here.
222 *
223 * @var array
224 */
225 protected $legacyHackedFields = [
226 'gender_id' => 'gender',
227 'prefix_id' => 'individual_prefix',
228 'suffix_id' => 'individual_suffix',
229 'communication_style_id' => 'communication_style',
230 ];
231
6a488035 232 /**
fe482240 233 * The cache to translate the option values into labels.
6a488035
TO
234 *
235 * @var array
236 */
237 public $_options;
238
239 /**
fe482240 240 * Are we in search mode.
6a488035 241 *
b67daa72 242 * @var bool
6a488035
TO
243 */
244 public $_search = TRUE;
245
246 /**
fe482240 247 * Should we skip permission checking.
6a488035 248 *
b67daa72 249 * @var bool
6a488035
TO
250 */
251 public $_skipPermission = FALSE;
252
253 /**
fe482240 254 * Should we skip adding of delete clause.
6a488035 255 *
b67daa72 256 * @var bool
6a488035
TO
257 */
258 public $_skipDeleteClause = FALSE;
259
260 /**
100fef9d 261 * Are we in strict mode (use equality over LIKE)
6a488035 262 *
b67daa72 263 * @var bool
6a488035
TO
264 */
265 public $_strict = FALSE;
266
267 /**
fe482240 268 * What operator to use to group the clauses.
6a488035
TO
269 *
270 * @var string
271 */
272 public $_operator = 'AND';
273
274 public $_mode = 1;
275
276 /**
fe482240 277 * Should we only search on primary location.
6a488035 278 *
b67daa72 279 * @var bool
6a488035
TO
280 */
281 public $_primaryLocation = TRUE;
282
283 /**
fe482240 284 * Are contact ids part of the query.
6a488035 285 *
b67daa72 286 * @var bool
6a488035
TO
287 */
288 public $_includeContactIds = FALSE;
289
290 /**
fe482240 291 * Should we use the smart group cache.
6a488035 292 *
b67daa72 293 * @var bool
6a488035
TO
294 */
295 public $_smartGroupCache = TRUE;
296
297 /**
fe482240 298 * Should we display contacts with a specific relationship type.
6a488035
TO
299 *
300 * @var string
301 */
302 public $_displayRelationshipType = NULL;
303
304 /**
fe482240 305 * Reference to the query object for custom values.
6a488035
TO
306 *
307 * @var Object
308 */
309 public $_customQuery;
310
311 /**
100fef9d 312 * Should we enable the distinct clause, used if we are including
6a488035
TO
313 * more than one group
314 *
b67daa72 315 * @var bool
6a488035
TO
316 */
317 public $_useDistinct = FALSE;
318
319 /**
320 * Should we just display one contact record
69078420 321 * @var bool
6a488035
TO
322 */
323 public $_useGroupBy = FALSE;
324
325 /**
100fef9d 326 * The relationship type direction
6a488035
TO
327 *
328 * @var array
6a488035 329 */
69078420 330 public static $_relType;
6a488035
TO
331
332 /**
100fef9d 333 * The activity role
6a488035
TO
334 *
335 * @var array
6a488035 336 */
69078420 337 public static $_activityRole;
6a488035
TO
338
339 /**
340 * Consider the component activity type
341 * during activity search.
342 *
343 * @var array
6a488035 344 */
69078420 345 public static $_considerCompActivities;
6a488035
TO
346
347 /**
348 * Consider with contact activities only,
349 * during activity search.
350 *
351 * @var array
6a488035 352 */
69078420 353 public static $_withContactActivitiesOnly;
6a488035
TO
354
355 /**
100fef9d 356 * Use distinct component clause for component searches
6a488035
TO
357 *
358 * @var string
359 */
360 public $_distinctComponentClause;
361
3dbf477c
DS
362 public $_rowCountClause;
363
6a488035 364 /**
100fef9d 365 * Use groupBy component clause for component searches
6a488035
TO
366 *
367 * @var string
368 */
369 public $_groupByComponentClause;
370
371 /**
372 * Track open panes, useful in advance search
373 *
374 * @var array
6a488035 375 */
be2fb01f 376 public static $_openedPanes = [];
6a488035 377
442df34b
CW
378 /**
379 * For search builder - which custom fields are location-dependent
380 * @var array
381 */
be2fb01f 382 public $_locationSpecificCustomFields = [];
442df34b 383
6a488035
TO
384 /**
385 * The tables which have a dependency on location and/or address
386 *
387 * @var array
6a488035 388 */
69078420 389 public static $_dependencies = [
6a488035
TO
390 'civicrm_state_province' => 1,
391 'civicrm_country' => 1,
392 'civicrm_county' => 1,
393 'civicrm_address' => 1,
394 'civicrm_location_type' => 1,
be2fb01f 395 ];
6a488035
TO
396
397 /**
fe482240 398 * List of location specific fields.
69078420 399 * @var array
6a488035 400 */
69078420 401 public static $_locationSpecificFields = [
6a488035
TO
402 'street_address',
403 'street_number',
404 'street_name',
405 'street_unit',
406 'supplemental_address_1',
407 'supplemental_address_2',
207f62c6 408 'supplemental_address_3',
6a488035
TO
409 'city',
410 'postal_code',
411 'postal_code_suffix',
412 'geo_code_1',
413 'geo_code_2',
414 'state_province',
415 'country',
416 'county',
417 'phone',
418 'email',
419 'im',
420 'address_name',
994a070c 421 'master_id',
be2fb01f 422 ];
6a488035
TO
423
424 /**
4e6072d5 425 * Remember if we handle either end of a number or date range
6a488035 426 * so we can skip the other
69078420 427 * @var array
6a488035 428 */
be2fb01f 429 protected $_rangeCache = [];
d9ab802d 430 /**
b67daa72 431 * Set to true when $this->relationship is run to avoid adding twice.
432 *
433 * @var bool
d9ab802d 434 */
ad682134 435 protected $_relationshipValuesAdded = FALSE;
d9ab802d 436
7c96365b 437 /**
9f266042 438 * Set to the name of the temp table if one has been created.
439 *
440 * @var string
7c96365b 441 */
69078420 442 public static $_relationshipTempTable = NULL;
d9ab802d 443
be2fb01f 444 public $_pseudoConstantsSelect = [];
9131c564 445
ed17b5e2 446 public $_groupUniqueKey = NULL;
e24f9388 447 public $_groupKeys = [];
ed17b5e2 448
6a488035 449 /**
fe482240 450 * Class constructor which also does all the work.
6a488035 451 *
2a6da8d7
EM
452 * @param array $params
453 * @param array $returnProperties
454 * @param array $fields
77c5b619
TO
455 * @param bool $includeContactIds
456 * @param bool $strict
2a6da8d7 457 * @param bool|int $mode - mode the search is operating on
6a488035 458 *
2a6da8d7
EM
459 * @param bool $skipPermission
460 * @param bool $searchDescendentGroups
461 * @param bool $smartGroupCache
462 * @param null $displayRelationshipType
463 * @param string $operator
66670e4d 464 * @param string $apiEntity
041ecc95 465 * @param bool|null $primaryLocationOnly
6a488035 466 */
59f4c9ee 467 public function __construct(
6a488035
TO
468 $params = NULL, $returnProperties = NULL, $fields = NULL,
469 $includeContactIds = FALSE, $strict = FALSE, $mode = 1,
470 $skipPermission = FALSE, $searchDescendentGroups = TRUE,
471 $smartGroupCache = TRUE, $displayRelationshipType = NULL,
66670e4d 472 $operator = 'AND',
0606198b 473 $apiEntity = NULL,
474 $primaryLocationOnly = NULL
6a488035 475 ) {
0606198b 476 if ($primaryLocationOnly === NULL) {
477 $primaryLocationOnly = Civi::settings()->get('searchPrimaryDetailsOnly');
478 }
479 $this->_primaryLocation = $primaryLocationOnly;
6a488035
TO
480 $this->_params = &$params;
481 if ($this->_params == NULL) {
be2fb01f 482 $this->_params = [];
6a488035
TO
483 }
484
33092c89 485 if ($returnProperties === self::NO_RETURN_PROPERTIES) {
be2fb01f 486 $this->_returnProperties = [];
33092c89
SB
487 }
488 elseif (empty($returnProperties)) {
6a488035
TO
489 $this->_returnProperties = self::defaultReturnProperties($mode);
490 }
491 else {
492 $this->_returnProperties = &$returnProperties;
493 }
494
495 $this->_includeContactIds = $includeContactIds;
496 $this->_strict = $strict;
497 $this->_mode = $mode;
498 $this->_skipPermission = $skipPermission;
499 $this->_smartGroupCache = $smartGroupCache;
500 $this->_displayRelationshipType = $displayRelationshipType;
501 $this->setOperator($operator);
502
503 if ($fields) {
504 $this->_fields = &$fields;
505 $this->_search = FALSE;
506 $this->_skipPermission = TRUE;
507 }
508 else {
5837835b 509 $this->_fields = CRM_Contact_BAO_Contact::exportableFields('All', FALSE, TRUE, TRUE, FALSE, !$skipPermission);
714ab070 510 // The legacy hacked fields will output as a string rather than their underlying type.
511 foreach (array_keys($this->legacyHackedFields) as $fieldName) {
512 $this->_fields[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
513 }
41b8dd1d 514 $relationMetadata = CRM_Contact_BAO_Relationship::fields();
515 $relationFields = array_intersect_key($relationMetadata, array_fill_keys(['relationship_start_date', 'relationship_end_date'], 1));
7d8f464a 516 // No good option other than hard-coding metadata for this 'special' field in.
517 $relationFields['relation_active_period_date'] = [
518 'name' => 'relation_active_period_date',
519 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
520 'title' => ts('Active Period'),
521 'table_name' => 'civicrm_relationship',
522 'where' => 'civicrm_relationship.start_date',
523 'where_end' => 'civicrm_relationship.end_date',
524 'html' => ['type' => 'SelectDate', 'formatType' => 'activityDateTime'],
525 ];
41b8dd1d 526 $this->_fields = array_merge($relationFields, $this->_fields);
6a488035 527
5837835b 528 $fields = CRM_Core_Component::getQueryFields(!$this->_skipPermission);
6a488035
TO
529 unset($fields['note']);
530 $this->_fields = array_merge($this->_fields, $fields);
531
532 // add activity fields
533 $fields = CRM_Activity_BAO_Activity::exportableFields();
534 $this->_fields = array_merge($this->_fields, $fields);
f2a9b25c 535
99e9587a
DS
536 // add any fields provided by hook implementers
537 $extFields = CRM_Contact_BAO_Query_Hook::singleton()->getFields();
f2a9b25c 538 $this->_fields = array_merge($this->_fields, $extFields);
6a488035
TO
539 }
540
541 // basically do all the work once, and then reuse it
66670e4d 542 $this->initialize($apiEntity);
6a488035
TO
543 }
544
545 /**
fe482240 546 * Function which actually does all the work for the constructor.
8f165fa5 547 *
548 * @param string $apiEntity
549 * The api entity being called.
550 * This sort-of duplicates $mode in a confusing way. Probably not by design.
6a488035 551 */
66670e4d 552 public function initialize($apiEntity = NULL) {
be2fb01f
CW
553 $this->_select = [];
554 $this->_element = [];
555 $this->_tables = [];
556 $this->_whereTables = [];
557 $this->_where = [];
558 $this->_qill = [];
559 $this->_options = [];
560 $this->_cfIDs = [];
561 $this->_paramLookup = [];
562 $this->_having = [];
6a488035
TO
563
564 $this->_customQuery = NULL;
565
566 // reset cached static variables - CRM-5803
567 self::$_activityRole = NULL;
568 self::$_considerCompActivities = NULL;
569 self::$_withContactActivitiesOnly = NULL;
570
571 $this->_select['contact_id'] = 'contact_a.id as contact_id';
572 $this->_element['contact_id'] = 1;
573 $this->_tables['civicrm_contact'] = 1;
574
575 if (!empty($this->_params)) {
576 $this->buildParamsLookup();
577 }
578
579 $this->_whereTables = $this->_tables;
580
66670e4d 581 $this->selectClause($apiEntity);
9178793e 582 $isForcePrimaryOnly = !empty($apiEntity);
583 $this->_whereClause = $this->whereClause($isForcePrimaryOnly);
be274d8a
E
584 if (array_key_exists('civicrm_contribution', $this->_whereTables)) {
585 $component = 'contribution';
586 }
587 if (array_key_exists('civicrm_membership', $this->_whereTables)) {
588 $component = 'membership';
589 }
40ae908c 590 if (isset($component) && !$this->_skipPermission) {
591 // Unit test coverage in api_v3_FinancialTypeACLTest::testGetACLContribution.
ecb39dfd
E
592 CRM_Financial_BAO_FinancialType::buildPermissionedClause($this->_whereClause, $component);
593 }
6a488035 594
b3e1c09d 595 $this->_fromClause = self::fromClause($this->_tables, NULL, NULL, $this->_primaryLocation, $this->_mode, $apiEntity);
6a488035
TO
596 $this->_simpleFromClause = self::fromClause($this->_whereTables, NULL, NULL, $this->_primaryLocation, $this->_mode);
597
598 $this->openedSearchPanes(TRUE);
599 }
600
67d19299 601 /**
bb05da0c 602 * Function for same purpose as convertFormValues.
603 *
604 * Like convert form values this function exists to pre-Process parameters from the form.
605 *
606 * It is unclear why they are different functions & likely relates to advances search
607 * versus search builder.
608 *
609 * The direction we are going is having the form convert values to a standardised format &
8f165fa5 610 * moving away from weird & wonderful where clause switches.
bb05da0c 611 *
67d19299 612 * Fix and handle contact deletion nicely.
613 *
614 * this code is primarily for search builder use case where different clauses can specify if they want deleted.
615 *
616 * CRM-11971
617 */
00be9182 618 public function buildParamsLookup() {
6a488035 619 $trashParamExists = FALSE;
be2fb01f 620 $paramByGroup = [];
5c7dad85
TO
621 foreach ($this->_params as $k => $param) {
622 if (!empty($param[0]) && $param[0] == 'contact_is_deleted') {
6a488035
TO
623 $trashParamExists = TRUE;
624 }
e6f3f602 625 if (!empty($param[3])) {
626 $paramByGroup[$param[3]][$k] = $param;
627 }
6a488035
TO
628 }
629
5c7dad85 630 if ($trashParamExists) {
6a488035
TO
631 $this->_skipDeleteClause = TRUE;
632
633 //cycle through group sets and explicitly add trash param if not set
5c7dad85 634 foreach ($paramByGroup as $setID => $set) {
6a488035 635 if (
be2fb01f
CW
636 !in_array(['contact_is_deleted', '=', '1', $setID, '0'], $this->_params) &&
637 !in_array(['contact_is_deleted', '=', '0', $setID, '0'], $this->_params)
5c7dad85 638 ) {
be2fb01f 639 $this->_params[] = [
6a488035
TO
640 'contact_is_deleted',
641 '=',
642 '0',
643 $setID,
644 '0',
be2fb01f 645 ];
6a488035
TO
646 }
647 }
648 }
649
650 foreach ($this->_params as $value) {
a7488080 651 if (empty($value[0])) {
6a488035
TO
652 continue;
653 }
7f175707 654 $cfID = CRM_Core_BAO_CustomField::getKeyID(str_replace('_relative', '', $value[0]));
6a488035
TO
655 if ($cfID) {
656 if (!array_key_exists($cfID, $this->_cfIDs)) {
be2fb01f 657 $this->_cfIDs[$cfID] = [];
6a488035 658 }
3130209f
CW
659 // Set wildcard value based on "and/or" selection
660 foreach ($this->_params as $key => $param) {
661 if ($param[0] == $value[0] . '_operator') {
662 $value[4] = $param[2] == 'or';
663 break;
664 }
665 }
6a488035
TO
666 $this->_cfIDs[$cfID][] = $value;
667 }
668
669 if (!array_key_exists($value[0], $this->_paramLookup)) {
be2fb01f 670 $this->_paramLookup[$value[0]] = [];
6a488035 671 }
485a3a1f 672 if ($value[0] !== 'group') {
8f165fa5 673 // Just trying to unravel how group interacts here! This whole function is weird.
485a3a1f 674 $this->_paramLookup[$value[0]][] = $value;
675 }
6a488035
TO
676 }
677 }
678
679 /**
67d19299 680 * Some composite fields do not appear in the fields array hack to make them part of the query.
8f165fa5 681 *
682 * @param $apiEntity
683 * The api entity being called.
684 * This sort-of duplicates $mode in a confusing way. Probably not by design.
6a488035 685 */
66670e4d 686 public function addSpecialFields($apiEntity) {
be2fb01f 687 static $special = ['contact_type', 'contact_sub_type', 'sort_name', 'display_name'];
66670e4d 688 // if get called via Contact.get API having address_id as return parameter
689 if ($apiEntity == 'Contact') {
690 $special[] = 'address_id';
691 }
6a488035 692 foreach ($special as $name) {
a7488080 693 if (!empty($this->_returnProperties[$name])) {
66670e4d 694 if ($name == 'address_id') {
695 $this->_tables['civicrm_address'] = 1;
696 $this->_select['address_id'] = 'civicrm_address.id as address_id';
697 $this->_element['address_id'] = 1;
698 }
699 else {
700 $this->_select[$name] = "contact_a.{$name} as $name";
701 $this->_element[$name] = 1;
702 }
6a488035
TO
703 }
704 }
705 }
706
707 /**
708 * Given a list of conditions in params and a list of desired
709 * return Properties generate the required select and from
710 * clauses. Note that since the where clause introduces new
711 * tables, the initial attempt also retrieves all variables used
712 * in the params list
8f165fa5 713 *
714 * @param string $apiEntity
715 * The api entity being called.
716 * This sort-of duplicates $mode in a confusing way. Probably not by design.
6a488035 717 */
66670e4d 718 public function selectClause($apiEntity = NULL) {
6a488035 719
3af96592 720 // @todo Tidy up this. This arises because 1) we are ignoring the $mode & adding a new
721 // param ($apiEntity) instead - presumably an oversight & 2 because
722 // contact is not implemented as a component.
66670e4d 723 $this->addSpecialFields($apiEntity);
6a488035
TO
724
725 foreach ($this->_fields as $name => $field) {
6a488035
TO
726 // skip component fields
727 // there are done by the alter query below
728 // and need not be done on every field
3af96592 729 // @todo remove these & handle using metadata - only obscure fields
730 // that are hack-added should need to be excluded from the main loop.
1071730c
DL
731 if (
732 (substr($name, 0, 12) == 'participant_') ||
6a488035 733 (substr($name, 0, 7) == 'pledge_') ||
9d5c7f14 734 (substr($name, 0, 5) == 'case_')
6a488035
TO
735 ) {
736 continue;
737 }
738
739 // redirect to activity select clause
4c24c842 740 if (
86538308 741 (substr($name, 0, 9) == 'activity_') ||
4c24c842
PN
742 ($name == 'parent_id')
743 ) {
6a488035 744 CRM_Activity_BAO_Query::select($this);
6a488035
TO
745 }
746
747 // if this is a hierarchical name, we ignore it
748 $names = explode('-', $name);
0742f843 749 if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) {
6a488035
TO
750 continue;
751 }
752
c6ff5b0d 753 // make an exception for special cases, to add the field in select clause
fd18baa6 754 $makeException = FALSE;
c6ff5b0d
KJ
755
756 //special handling for groups/tags
be2fb01f 757 if (in_array($name, ['groups', 'tags', 'notes'])
fd18baa6
KJ
758 && isset($this->_returnProperties[substr($name, 0, -1)])
759 ) {
8f165fa5 760 // @todo instead of setting make exception to get us into
761 // an if clause that has handling for these fields buried with in it
762 // move the handling to here.
fd18baa6
KJ
763 $makeException = TRUE;
764 }
765
c6ff5b0d
KJ
766 // since note has 3 different options we need special handling
767 // note / note_subject / note_body
768 if ($name == 'notes') {
be2fb01f 769 foreach (['note', 'note_subject', 'note_body'] as $noteField) {
c6ff5b0d
KJ
770 if (isset($this->_returnProperties[$noteField])) {
771 $makeException = TRUE;
772 break;
773 }
774 }
775 }
a87ba7c0 776
6a488035 777 $cfID = CRM_Core_BAO_CustomField::getKeyID($name);
86ab13b7 778 if (
779 !empty($this->_paramLookup[$name])
780 || !empty($this->_returnProperties[$name])
124f3c1b 781 || $this->pseudoConstantNameIsInReturnProperties($field, $name)
86ab13b7 782 || $makeException
6a488035 783 ) {
6a488035
TO
784 if ($cfID) {
785 // add to cfIDs array if not present
786 if (!array_key_exists($cfID, $this->_cfIDs)) {
be2fb01f 787 $this->_cfIDs[$cfID] = [];
6a488035
TO
788 }
789 }
790 elseif (isset($field['where'])) {
791 list($tableName, $fieldName) = explode('.', $field['where'], 2);
792 if (isset($tableName)) {
6a488035
TO
793 if (CRM_Utils_Array::value($tableName, self::$_dependencies)) {
794 $this->_tables['civicrm_address'] = 1;
795 $this->_select['address_id'] = 'civicrm_address.id as address_id';
796 $this->_element['address_id'] = 1;
797 }
798
d9ab802d
PJ
799 if ($tableName == 'im_provider' || $tableName == 'email_greeting' ||
800 $tableName == 'postal_greeting' || $tableName == 'addressee'
6a488035 801 ) {
d9ab802d
PJ
802 if ($tableName == 'im_provider') {
803 CRM_Core_OptionValue::select($this);
804 }
805
806 if (in_array($tableName,
be2fb01f 807 ['email_greeting', 'postal_greeting', 'addressee'])) {
d9ab802d
PJ
808 $this->_element["{$name}_id"] = 1;
809 $this->_select["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
be2fb01f 810 $this->_pseudoConstantsSelect[$name] = ['pseudoField' => $tableName, 'idCol' => "{$name}_id"];
d9ab802d
PJ
811 $this->_pseudoConstantsSelect[$name]['select'] = "{$name}.{$fieldName} as $name";
812 $this->_pseudoConstantsSelect[$name]['element'] = $name;
813
814 if ($tableName == 'email_greeting') {
3af96592 815 // @todo bad join.
59f4c9ee
TO
816 $this->_pseudoConstantsSelect[$name]['join']
817 = " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
d9ab802d
PJ
818 $this->_pseudoConstantsSelect[$name]['join'] .=
819 " 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 ) ";
820 }
821 elseif ($tableName == 'postal_greeting') {
3af96592 822 // @todo bad join.
59f4c9ee
TO
823 $this->_pseudoConstantsSelect[$name]['join']
824 = " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
d9ab802d
PJ
825 $this->_pseudoConstantsSelect[$name]['join'] .=
826 " 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 ) ";
827 }
828 elseif ($tableName == 'addressee') {
3af96592 829 // @todo bad join.
59f4c9ee
TO
830 $this->_pseudoConstantsSelect[$name]['join']
831 = " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
d9ab802d
PJ
832 $this->_pseudoConstantsSelect[$name]['join'] .=
833 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
834 }
835 $this->_pseudoConstantsSelect[$name]['table'] = $tableName;
836
6a488035
TO
837 //get display
838 $greetField = "{$name}_display";
839 $this->_select[$greetField] = "contact_a.{$greetField} as {$greetField}";
840 $this->_element[$greetField] = 1;
841 //get custom
842 $greetField = "{$name}_custom";
843 $this->_select[$greetField] = "contact_a.{$greetField} as {$greetField}";
844 $this->_element[$greetField] = 1;
845 }
846 }
847 else {
be2fb01f 848 if (!in_array($tableName, ['civicrm_state_province', 'civicrm_country', 'civicrm_county'])) {
d9ab802d
PJ
849 $this->_tables[$tableName] = 1;
850 }
6a488035
TO
851
852 // also get the id of the tableName
853 $tName = substr($tableName, 8);
be2fb01f 854 if (in_array($tName, ['country', 'state_province', 'county'])) {
d9ab802d 855 if ($tName == 'state_province') {
be2fb01f 856 $this->_pseudoConstantsSelect['state_province_name'] = [
59f4c9ee
TO
857 'pseudoField' => "{$tName}",
858 'idCol' => "{$tName}_id",
859 'bao' => 'CRM_Core_BAO_Address',
860 'table' => "civicrm_{$tName}",
861 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
be2fb01f 862 ];
59f4c9ee 863
be2fb01f 864 $this->_pseudoConstantsSelect[$tName] = [
59f4c9ee
TO
865 'pseudoField' => 'state_province_abbreviation',
866 'idCol' => "{$tName}_id",
867 'table' => "civicrm_{$tName}",
868 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
be2fb01f 869 ];
d9ab802d 870 }
7f84f734 871 else {
be2fb01f 872 $this->_pseudoConstantsSelect[$name] = [
59f4c9ee
TO
873 'pseudoField' => "{$tName}_id",
874 'idCol' => "{$tName}_id",
875 'bao' => 'CRM_Core_BAO_Address',
876 'table' => "civicrm_{$tName}",
877 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
be2fb01f 878 ];
7f84f734 879 }
6a488035 880
d9ab802d
PJ
881 $this->_select["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
882 $this->_element["{$tName}_id"] = 1;
883 }
884 elseif ($tName != 'contact') {
6a488035
TO
885 $this->_select["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
886 $this->_element["{$tName}_id"] = 1;
887 }
888
889 //special case for phone
890 if ($name == 'phone') {
891 $this->_select['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
892 $this->_element['phone_type_id'] = 1;
893 }
894
895 // if IM then select provider_id also
896 // to get "IM Service Provider" in a file to be exported, CRM-3140
897 if ($name == 'im') {
898 $this->_select['provider_id'] = "civicrm_im.provider_id as provider_id";
899 $this->_element['provider_id'] = 1;
900 }
901
86ab13b7 902 if ($tName == 'contact' && $fieldName == 'organization_name') {
6a488035 903 // special case, when current employer is set for Individual contact
86ab13b7 904 $this->_select[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
905 }
906 elseif ($tName == 'contact' && $fieldName === 'id') {
907 // Handled elsewhere, explicitly ignore. Possibly for all tables...
6a488035 908 }
be2fb01f 909 elseif (in_array($tName, ['country', 'county'])) {
4e6490d4
E
910 $this->_pseudoConstantsSelect[$name]['select'] = "{$field['where']} as `$name`";
911 $this->_pseudoConstantsSelect[$name]['element'] = $name;
912 }
913 elseif ($tName == 'state_province') {
914 $this->_pseudoConstantsSelect[$tName]['select'] = "{$field['where']} as `$name`";
915 $this->_pseudoConstantsSelect[$tName]['element'] = $name;
d9ab802d 916 }
e4ce3252 917 elseif (strpos($name, 'contribution_soft_credit') !== FALSE) {
2d94ea54 918 if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled($this->_params)) {
919 $this->_select[$name] = "{$field['where']} as `$name`";
920 }
921 }
124f3c1b 922 elseif ($this->pseudoConstantNameIsInReturnProperties($field, $name)) {
923 $this->addPseudoconstantFieldToSelect($name);
924 }
6a488035 925 else {
86ab13b7 926 $this->_select[$name] = str_replace('civicrm_contact.', 'contact_a.', "{$field['where']} as `$name`");
6a488035 927 }
be2fb01f 928 if (!in_array($tName, ['state_province', 'country', 'county'])) {
d9ab802d
PJ
929 $this->_element[$name] = 1;
930 }
6a488035
TO
931 }
932 }
933 }
934 elseif ($name === 'tags') {
8f165fa5 935 //@todo move this handling outside the big IF & ditch $makeException
6a488035
TO
936 $this->_useGroupBy = TRUE;
937 $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
938 $this->_element[$name] = 1;
939 $this->_tables['civicrm_tag'] = 1;
940 $this->_tables['civicrm_entity_tag'] = 1;
941 }
942 elseif ($name === 'groups') {
8f165fa5 943 //@todo move this handling outside the big IF & ditch $makeException
6a488035 944 $this->_useGroupBy = TRUE;
3875e6b6 945 // Duplicates will be created here but better to sort them out in php land.
946 $this->_select[$name] = "
947 CONCAT_WS(',',
948 GROUP_CONCAT(DISTINCT IF(civicrm_group_contact.status = 'Added', civicrm_group_contact.group_id, '')),
949 GROUP_CONCAT(DISTINCT civicrm_group_contact_cache.group_id)
950 )
951 as groups";
6a488035 952 $this->_element[$name] = 1;
3875e6b6 953 $this->_tables['civicrm_group_contact'] = 1;
954 $this->_tables['civicrm_group_contact_cache'] = 1;
be2fb01f 955 $this->_pseudoConstantsSelect["{$name}"] = [
3875e6b6 956 'pseudoField' => "groups",
957 'idCol' => "groups",
be2fb01f 958 ];
6a488035
TO
959 }
960 elseif ($name === 'notes') {
8f165fa5 961 //@todo move this handling outside the big IF & ditch $makeException
e3199114 962 // if note field is subject then return subject else body of the note
963 $noteColumn = 'note';
964 if (isset($noteField) && $noteField == 'note_subject') {
965 $noteColumn = 'subject';
966 }
967
6a488035 968 $this->_useGroupBy = TRUE;
e3199114 969 $this->_select[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
6a488035
TO
970 $this->_element[$name] = 1;
971 $this->_tables['civicrm_note'] = 1;
972 }
973 elseif ($name === 'current_employer') {
974 $this->_select[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
975 $this->_element[$name] = 1;
976 }
977 }
978
8cc574cf 979 if ($cfID && !empty($field['is_search_range'])) {
6a488035 980 // this is a custom field with range search enabled, so we better check for two/from values
a7488080 981 if (!empty($this->_paramLookup[$name . '_from'])) {
6a488035 982 if (!array_key_exists($cfID, $this->_cfIDs)) {
be2fb01f 983 $this->_cfIDs[$cfID] = [];
6a488035
TO
984 }
985 foreach ($this->_paramLookup[$name . '_from'] as $pID => $p) {
986 // search in the cdID array for the same grouping
987 $fnd = FALSE;
988 foreach ($this->_cfIDs[$cfID] as $cID => $c) {
989 if ($c[3] == $p[3]) {
990 $this->_cfIDs[$cfID][$cID][2]['from'] = $p[2];
991 $fnd = TRUE;
992 }
993 }
994 if (!$fnd) {
be2fb01f 995 $p[2] = ['from' => $p[2]];
6a488035
TO
996 $this->_cfIDs[$cfID][] = $p;
997 }
998 }
999 }
a7488080 1000 if (!empty($this->_paramLookup[$name . '_to'])) {
6a488035 1001 if (!array_key_exists($cfID, $this->_cfIDs)) {
be2fb01f 1002 $this->_cfIDs[$cfID] = [];
6a488035
TO
1003 }
1004 foreach ($this->_paramLookup[$name . '_to'] as $pID => $p) {
1005 // search in the cdID array for the same grouping
1006 $fnd = FALSE;
1007 foreach ($this->_cfIDs[$cfID] as $cID => $c) {
1008 if ($c[4] == $p[4]) {
1009 $this->_cfIDs[$cfID][$cID][2]['to'] = $p[2];
1010 $fnd = TRUE;
1011 }
1012 }
1013 if (!$fnd) {
be2fb01f 1014 $p[2] = ['to' => $p[2]];
6a488035
TO
1015 $this->_cfIDs[$cfID][] = $p;
1016 }
1017 }
1018 }
1019 }
1020 }
1021
1022 // add location as hierarchical elements
1023 $this->addHierarchicalElements();
1024
1025 // add multiple field like website
1026 $this->addMultipleElements();
1027
1028 //fix for CRM-951
1029 CRM_Core_Component::alterQuery($this, 'select');
1030
99e9587a 1031 CRM_Contact_BAO_Query_Hook::singleton()->alterSearchQuery($this, 'select');
f2a9b25c 1032
6a488035 1033 if (!empty($this->_cfIDs)) {
bb05da0c 1034 // @todo This function is the select function but instead of running 'select' it
1035 // is running the whole query.
442df34b 1036 $this->_customQuery = new CRM_Core_BAO_CustomQuery($this->_cfIDs, TRUE, $this->_locationSpecificCustomFields);
6a488035
TO
1037 $this->_customQuery->query();
1038 $this->_select = array_merge($this->_select, $this->_customQuery->_select);
1039 $this->_element = array_merge($this->_element, $this->_customQuery->_element);
1040 $this->_tables = array_merge($this->_tables, $this->_customQuery->_tables);
1041 $this->_whereTables = array_merge($this->_whereTables, $this->_customQuery->_whereTables);
1042 $this->_options = $this->_customQuery->_options;
1043 }
1044 }
1045
1046 /**
c037736a 1047 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
6a488035 1048 */
00be9182 1049 public function addHierarchicalElements() {
a7488080 1050 if (empty($this->_returnProperties['location'])) {
6a488035
TO
1051 return;
1052 }
1053 if (!is_array($this->_returnProperties['location'])) {
1054 return;
1055 }
1056
f9ba4d01 1057 $locationTypes = CRM_Core_DAO_Address::buildOptions('location_type_id', 'validate');
be2fb01f 1058 $processed = [];
6a488035
TO
1059 $index = 0;
1060
1061 $addressCustomFields = CRM_Core_BAO_CustomField::getFieldsForImport('Address');
be2fb01f 1062 $addressCustomFieldIds = [];
6a488035
TO
1063
1064 foreach ($this->_returnProperties['location'] as $name => $elements) {
1065 $lCond = self::getPrimaryCondition($name);
708ce91f 1066 $locationTypeId = is_numeric($name) ? NULL : array_search($name, $locationTypes);
6a488035
TO
1067
1068 if (!$lCond) {
6a488035
TO
1069 if ($locationTypeId === FALSE) {
1070 continue;
1071 }
1072 $lCond = "location_type_id = $locationTypeId";
1073 $this->_useDistinct = TRUE;
1074
1075 //commented for CRM-3256
1076 $this->_useGroupBy = TRUE;
1077 }
1078
1079 $name = str_replace(' ', '_', $name);
6a488035
TO
1080 $tName = "$name-location_type";
1081 $ltName = "`$name-location_type`";
1082 $this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1083 $this->_select["{$tName}"] = "`$tName`.name as `{$tName}`";
1084 $this->_element["{$tName}_id"] = 1;
1085 $this->_element["{$tName}"] = 1;
1086
1087 $locationTypeName = $tName;
be2fb01f 1088 $locationTypeJoin = [];
6a488035 1089
6a488035
TO
1090 $addWhereCount = 0;
1091 foreach ($elements as $elementFullName => $dontCare) {
1092 $index++;
1093 $elementName = $elementCmpName = $elementFullName;
1094
1095 if (substr($elementCmpName, 0, 5) == 'phone') {
1096 $elementCmpName = 'phone';
1097 }
1098
1099 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
1100 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($elementCmpName)) {
1101 $addressCustomFieldIds[$cfID][$name] = 1;
1102 }
1103 }
708ce91f 1104 // add address table - doesn't matter if we do it mutliple times - it's the same data
1105 // @todo ditch the double processing of addressJoin
6a488035 1106 if ((in_array($elementCmpName, self::$_locationSpecificFields) || !empty($addressCustomFieldIds))
be2fb01f 1107 && !in_array($elementCmpName, ['email', 'phone', 'im', 'openid'])
6a488035 1108 ) {
708ce91f 1109 list($aName, $addressJoin) = $this->addAddressTable($name, $lCond);
6a488035
TO
1110 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
1111 $processed[$aName] = 1;
6a488035
TO
1112 }
1113
1114 $cond = $elementType = '';
1115 if (strpos($elementName, '-') !== FALSE) {
1116 // this is either phone, email or IM
1117 list($elementName, $elementType) = explode('-', $elementName);
1118
6a488035
TO
1119 if (($elementName != 'phone') && ($elementName != 'im')) {
1120 $cond = self::getPrimaryCondition($elementType);
1121 }
6e7e6dc0
PJ
1122 // CRM-13011 : If location type is primary, do not restrict search to the phone
1123 // type id - we want the primary phone, regardless of what type it is.
1124 // Otherwise, restrict to the specified phone type for the given field.
9457ac35 1125 if ((!$cond) && ($elementName == 'phone')) {
6a488035
TO
1126 $cond = "phone_type_id = '$elementType'";
1127 }
1128 elseif ((!$cond) && ($elementName == 'im')) {
1129 // IM service provider id, CRM-3140
1130 $cond = "provider_id = '$elementType'";
1131 }
1132 $elementType = '-' . $elementType;
1133 }
1134
1135 $field = CRM_Utils_Array::value($elementName, $this->_fields);
1136
1137 // hack for profile, add location id
1138 if (!$field) {
1139 if ($elementType &&
1140 // fix for CRM-882( to handle phone types )
1141 !is_numeric($elementType)
1142 ) {
1143 if (is_numeric($name)) {
1144 $field = CRM_Utils_Array::value($elementName . "-Primary$elementType", $this->_fields);
1145 }
1146 else {
1147 $field = CRM_Utils_Array::value($elementName . "-$locationTypeId$elementType", $this->_fields);
1148 }
1149 }
1150 elseif (is_numeric($name)) {
1151 //this for phone type to work
be2fb01f 1152 if (in_array($elementName, ['phone', 'phone_ext'])) {
6a488035
TO
1153 $field = CRM_Utils_Array::value($elementName . "-Primary" . $elementType, $this->_fields);
1154 }
1155 else {
1156 $field = CRM_Utils_Array::value($elementName . "-Primary", $this->_fields);
1157 }
1158 }
1159 else {
1160 //this is for phone type to work for profile edit
be2fb01f 1161 if (in_array($elementName, ['phone', 'phone_ext'])) {
6a488035
TO
1162 $field = CRM_Utils_Array::value($elementName . "-$locationTypeId$elementType", $this->_fields);
1163 }
1164 else {
1165 $field = CRM_Utils_Array::value($elementName . "-$locationTypeId", $this->_fields);
1166 }
1167 }
1168 }
1169
314dbef8 1170 // Check if there is a value, if so also add to where Clause
6a488035
TO
1171 $addWhere = FALSE;
1172 if ($this->_params) {
1173 $nm = $elementName;
1174 if (isset($locationTypeId)) {
1175 $nm .= "-$locationTypeId";
1176 }
1177 if (!is_numeric($elementType)) {
1178 $nm .= "$elementType";
1179 }
1180
1181 foreach ($this->_params as $id => $values) {
8af73472 1182 if ((is_array($values) && $values[0] == $nm) ||
be2fb01f 1183 (in_array($elementName, ['phone', 'im'])
6a488035
TO
1184 && (strpos($values[0], $nm) !== FALSE)
1185 )
1186 ) {
1187 $addWhere = TRUE;
1188 $addWhereCount++;
1189 break;
1190 }
1191 }
1192 }
1193
1194 if ($field && isset($field['where'])) {
1195 list($tableName, $fieldName) = explode('.', $field['where'], 2);
d9ab802d
PJ
1196 $pf = substr($tableName, 8);
1197 $tName = $name . '-' . $pf . $elementType;
6a488035 1198 if (isset($tableName)) {
d9ab802d
PJ
1199 if ($tableName == 'civicrm_state_province' || $tableName == 'civicrm_country' || $tableName == 'civicrm_county') {
1200 $this->_select["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1201 }
1202 else {
1203 $this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1204 }
1205
6a488035
TO
1206 $this->_element["{$tName}_id"] = 1;
1207 if (substr($tName, -15) == '-state_province') {
1208 // FIXME: hack to fix CRM-1900
aaffa79f 1209 $a = Civi::settings()->get('address_format');
6a488035
TO
1210
1211 if (substr_count($a, 'state_province_name') > 0) {
be2fb01f 1212 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"] = [
59f4c9ee
TO
1213 'pseudoField' => "{$pf}_id",
1214 'idCol' => "{$tName}_id",
1215 'bao' => 'CRM_Core_BAO_Address',
be2fb01f 1216 ];
d9ab802d 1217 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
6a488035
TO
1218 }
1219 else {
be2fb01f 1220 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"] = [
59f4c9ee
TO
1221 'pseudoField' => 'state_province_abbreviation',
1222 'idCol' => "{$tName}_id",
be2fb01f 1223 ];
d9ab802d 1224 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
6a488035
TO
1225 }
1226 }
1227 else {
1228 if (substr($elementFullName, 0, 2) == 'im') {
1229 $provider = "{$name}-{$elementFullName}-provider_id";
1230 $this->_select[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1231 $this->_element[$provider] = 1;
1232 }
d9ab802d 1233 if ($pf == 'country' || $pf == 'county') {
be2fb01f 1234 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"] = [
5c7dad85
TO
1235 'pseudoField' => "{$pf}_id",
1236 'idCol' => "{$tName}_id",
21dfd5f5 1237 'bao' => 'CRM_Core_BAO_Address',
be2fb01f 1238 ];
d9ab802d
PJ
1239 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1240 }
1241 else {
1242 $this->_select["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1243 }
1244 }
6a488035 1245
be2fb01f 1246 if (in_array($pf, ['state_province', 'country', 'county'])) {
d9ab802d
PJ
1247 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1248 }
1249 else {
1250 $this->_element["{$name}-{$elementFullName}"] = 1;
6a488035
TO
1251 }
1252
a7488080 1253 if (empty($processed["`$tName`"])) {
6a488035
TO
1254 $processed["`$tName`"] = 1;
1255 $newName = $tableName . '_' . $index;
1256 switch ($tableName) {
1257 case 'civicrm_phone':
1258 case 'civicrm_email':
1259 case 'civicrm_im':
1260 case 'civicrm_openid':
1261
9457ac35 1262 $this->_tables[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id";
1263 if ($tableName != 'civicrm_phone') {
1264 $this->_tables[$tName] .= " AND `$tName`.$lCond";
1265 }
1266 elseif (is_numeric($name)) {
1267 $this->_select[$tName] = "IF (`$tName`.is_primary = $name, `$tName`.phone, NULL) as `$tName`";
1268 }
1269
6a488035
TO
1270 // this special case to add phone type
1271 if ($cond) {
1272 $phoneTypeCondition = " AND `$tName`.$cond ";
1273 //gross hack to pickup corrupted data also, CRM-7603
1274 if (strpos($cond, 'phone_type_id') !== FALSE) {
1275 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
8b3d5966
J
1276 if (!empty($lCond)) {
1277 $phoneTypeCondition .= " AND ( `$tName`.$lCond ) ";
1278 }
6a488035
TO
1279 }
1280 $this->_tables[$tName] .= $phoneTypeCondition;
1281 }
1282
1283 //build locationType join
1284 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1285
1286 if ($addWhere) {
1287 $this->_whereTables[$tName] = $this->_tables[$tName];
1288 }
1289 break;
1290
1291 case 'civicrm_state_province':
d9ab802d 1292 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['table'] = $tName;
59f4c9ee
TO
1293 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['join']
1294 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
6a488035
TO
1295 if ($addWhere) {
1296 $this->_whereTables["{$name}-address"] = $addressJoin;
6a488035
TO
1297 }
1298 break;
1299
1300 case 'civicrm_country':
d9ab802d 1301 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['table'] = $newName;
59f4c9ee
TO
1302 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['join']
1303 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
6a488035
TO
1304 if ($addWhere) {
1305 $this->_whereTables["{$name}-address"] = $addressJoin;
6a488035
TO
1306 }
1307 break;
1308
1309 case 'civicrm_county':
d9ab802d 1310 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['table'] = $newName;
59f4c9ee
TO
1311 $this->_pseudoConstantsSelect["{$name}-{$elementFullName}"]['join']
1312 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
6a488035
TO
1313 if ($addWhere) {
1314 $this->_whereTables["{$name}-address"] = $addressJoin;
6a488035
TO
1315 }
1316 break;
1317
1318 default:
4ad408ae
VP
1319 if (isset($addressCustomFields[$elementName]['custom_field_id']) && !empty($addressCustomFields[$elementName]['custom_field_id'])) {
1320 $this->_tables[$tName] = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.id";
1321 }
6a488035
TO
1322 if ($addWhere) {
1323 $this->_whereTables["{$name}-address"] = $addressJoin;
1324 }
1325 break;
1326 }
1327 }
1328 }
1329 }
1330 }
1331
1332 // add location type join
1333 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1334 $this->_tables[$locationTypeName] = $ltypeJoin;
1335
1336 // table should be present in $this->_whereTables,
1337 // to add its condition in location type join, CRM-3939.
1338 if ($addWhereCount) {
be2fb01f 1339 $locClause = [];
6a488035 1340 foreach ($this->_whereTables as $tableName => $clause) {
a7488080 1341 if (!empty($locationTypeJoin[$tableName])) {
6a488035
TO
1342 $locClause[] = $locationTypeJoin[$tableName];
1343 }
1344 }
1345
1346 if (!empty($locClause)) {
1347 $this->_whereTables[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1348 }
1349 }
1350 }
1351
1352 if (!empty($addressCustomFieldIds)) {
442df34b 1353 $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
6a488035
TO
1354 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1355 foreach ($locTypeName as $name => $dnc) {
be2fb01f 1356 $this->_locationSpecificCustomFields[$cfID] = [$name, array_search($name, $locationTypes)];
6a488035
TO
1357 $fieldName = "$name-custom_{$cfID}";
1358 $tName = "$name-address-custom-{$cfID}";
1359 $aName = "`$name-address-custom-{$cfID}`";
1360 $this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1361 $this->_element["{$tName}_id"] = 1;
1362 $this->_select[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1363 $this->_element[$fieldName] = 1;
1364 $this->_tables[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1365 }
1366 }
1367 }
1368 }
1369
1370 /**
c037736a 1371 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
6a488035 1372 */
00be9182 1373 public function addMultipleElements() {
a7488080 1374 if (empty($this->_returnProperties['website'])) {
6a488035
TO
1375 return;
1376 }
1377 if (!is_array($this->_returnProperties['website'])) {
1378 return;
1379 }
1380
1381 foreach ($this->_returnProperties['website'] as $key => $elements) {
1382 foreach ($elements as $elementFullName => $dontCare) {
1383 $tName = "website-{$key}-{$elementFullName}";
1384 $this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1385 $this->_select["{$tName}"] = "`$tName`.url as `{$tName}`";
1386 $this->_element["{$tName}_id"] = 1;
1387 $this->_element["{$tName}"] = 1;
1388
1389 $type = "website-{$key}-website_type_id";
1390 $this->_select[$type] = "`$tName`.website_type_id as `{$type}`";
1391 $this->_element[$type] = 1;
887e764d 1392 $this->_tables[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id AND `$tName`.website_type_id = $key )";
6a488035
TO
1393 }
1394 }
1395 }
1396
1397 /**
fe482240 1398 * Generate the query based on what type of query we need.
6a488035 1399 *
77c5b619
TO
1400 * @param bool $count
1401 * @param bool $sortByChar
1402 * @param bool $groupContacts
1403 * @param bool $onlyDeleted
6a488035 1404 *
a6c01b45
CW
1405 * @return array
1406 * sql query parts as an array
6a488035 1407 */
00be9182 1408 public function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE, $onlyDeleted = FALSE) {
2c3ad4b7 1409 // build permission clause
1410 $this->generatePermissionClause($onlyDeleted, $count);
1411
6a488035 1412 if ($count) {
3dbf477c
DS
1413 if (isset($this->_rowCountClause)) {
1414 $select = "SELECT {$this->_rowCountClause}";
5c7dad85 1415 }
4c9b6178 1416 elseif (isset($this->_distinctComponentClause)) {
6a488035
TO
1417 // we add distinct to get the right count for components
1418 // for the more complex result set, we use GROUP BY the same id
1419 // CRM-9630
9ae25b56 1420 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} ) as rowCount";
6a488035
TO
1421 }
1422 else {
1423 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1424 }
1425 $from = $this->_simpleFromClause;
1426 if ($this->_useDistinct) {
1427 $this->_useGroupBy = TRUE;
1428 }
1429 }
1430 elseif ($sortByChar) {
caefed7d
MWMC
1431 // @fixme add the deprecated warning back in (it breaks CRM_Contact_SelectorTest::testSelectorQuery)
1432 // CRM_Core_Error::deprecatedFunctionWarning('sort by char is deprecated - use alphabetQuery method');
52cda5dc 1433 $select = 'SELECT DISTINCT LEFT(contact_a.sort_name, 1) as sort_name';
6a488035
TO
1434 $from = $this->_simpleFromClause;
1435 }
1436 elseif ($groupContacts) {
1437 $select = 'SELECT contact_a.id as id';
1438 if ($this->_useDistinct) {
1439 $this->_useGroupBy = TRUE;
1440 }
1441 $from = $this->_simpleFromClause;
1442 }
1443 else {
a7488080 1444 if (!empty($this->_paramLookup['group'])) {
ca91bd7f 1445
1446 list($name, $op, $value, $grouping, $wildcard) = $this->_paramLookup['group'][0];
1447
1448 if (is_array($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
1449 $this->_paramLookup['group'][0][1] = key($value);
1450 }
1451
3875e6b6 1452 // Presumably the lines below come into manage groups screen.
6a488035
TO
1453 // make sure there is only one element
1454 // this is used when we are running under smog and need to know
1455 // how the contact was added (CRM-1203)
db135a44 1456 $groups = (array) CRM_Utils_Array::value($this->_paramLookup['group'][0][1], $this->_paramLookup['group'][0][2], $this->_paramLookup['group'][0][2]);
6a488035 1457 if ((count($this->_paramLookup['group']) == 1) &&
7cc09daf 1458 (count($groups) == 1)
6a488035 1459 ) {
6a488035
TO
1460 $groupId = $groups[0];
1461
1462 //check if group is saved search
1463 $group = new CRM_Contact_BAO_Group();
1464 $group->id = $groupId;
1465 $group->find(TRUE);
1466
1467 if (!isset($group->saved_search_id)) {
f30aa754 1468 $tbName = "civicrm_group_contact";
82ae55f4 1469 // CRM-17254 don't retrieve extra fields if contact_id is specifically requested
1470 // as this will add load to an intentionally light query.
1471 // ideally this code would be removed as it appears to be to support CRM-1203
1472 // and passing in the required returnProperties from the url would
1473 // make more sense that globally applying the requirements of one form.
be2fb01f 1474 if (($this->_returnProperties != ['contact_id'])) {
82ae55f4 1475 $this->_select['group_contact_id'] = "$tbName.id as group_contact_id";
1476 $this->_element['group_contact_id'] = 1;
1477 $this->_select['status'] = "$tbName.status as status";
1478 $this->_element['status'] = 1;
1479 }
6a488035
TO
1480 }
1481 }
1482 $this->_useGroupBy = TRUE;
1483 }
1484 if ($this->_useDistinct && !isset($this->_distinctComponentClause)) {
1485 if (!($this->_mode & CRM_Contact_BAO_Query::MODE_ACTIVITY)) {
1486 // CRM-5954
1487 $this->_select['contact_id'] = 'contact_a.id as contact_id';
1488 $this->_useDistinct = FALSE;
1489 $this->_useGroupBy = TRUE;
1490 }
1491 }
1492
f946d152 1493 $select = $this->getSelect();
6a488035
TO
1494 $from = $this->_fromClause;
1495 }
1496
1497 $where = '';
1498 if (!empty($this->_whereClause)) {
1499 $where = "WHERE {$this->_whereClause}";
1500 }
1501
0619ff2f 1502 if (!empty($this->_permissionWhereClause) && empty($this->_displayRelationshipType)) {
2c3ad4b7 1503 if (empty($where)) {
1504 $where = "WHERE $this->_permissionWhereClause";
1505 }
1506 else {
1507 $where = "$where AND $this->_permissionWhereClause";
1508 }
1509 }
1510
6a488035
TO
1511 $having = '';
1512 if (!empty($this->_having)) {
2ef90ca7
EM
1513 foreach ($this->_having as $havingSets) {
1514 foreach ($havingSets as $havingSet) {
1515 $havingValue[] = $havingSet;
6a488035
TO
1516 }
1517 }
2ef90ca7 1518 $having = ' HAVING ' . implode(' AND ', $havingValue);
6a488035
TO
1519 }
1520
1521 // if we are doing a transform, do it here
1522 // use the $from, $where and $having to get the contact ID
1523 if ($this->_displayRelationshipType) {
1524 $this->filterRelatedContacts($from, $where, $having);
1525 }
1526
be2fb01f 1527 return [$select, $from, $where, $having];
6a488035
TO
1528 }
1529
86538308 1530 /**
c037736a 1531 * Get where values from the parameters.
1532 *
100fef9d 1533 * @param string $name
c037736a 1534 * @param mixed $grouping
86538308 1535 *
c037736a 1536 * @return mixed
86538308 1537 */
c037736a 1538 public function getWhereValues($name, $grouping) {
6a488035 1539 $result = NULL;
f4bff68a 1540 foreach ($this->_params as $values) {
6a488035
TO
1541 if ($values[0] == $name && $values[3] == $grouping) {
1542 return $values;
1543 }
1544 }
1545
1546 return $result;
1547 }
1548
86538308 1549 /**
c037736a 1550 * Fix date values.
1551 *
1552 * @param bool $relative
1553 * @param string $from
1554 * @param string $to
86538308 1555 */
00be9182 1556 public static function fixDateValues($relative, &$from, &$to) {
6a488035
TO
1557 if ($relative) {
1558 list($from, $to) = CRM_Utils_Date::getFromTo($relative, $from, $to);
1559 }
1560 }
1561
86538308 1562 /**
bb05da0c 1563 * Convert values from form-appropriate to query-object appropriate.
1564 *
1565 * The query object is increasingly supporting the sql-filter syntax which is the most flexible syntax.
1566 * So, ideally we would convert all fields to look like
1567 * array(
1568 * 0 => $fieldName
1569 * // Set the operator for legacy reasons, but it is ignored
1570 * 1 => '='
1571 * // array in sql filter syntax
1572 * 2 => array('BETWEEN' => array(1,60),
1573 * 3 => null
1574 * 4 => null
1575 * );
1576 *
1577 * There are some examples of the syntax in
1578 * https://github.com/civicrm/civicrm-core/tree/master/api/v3/examples/Relationship
1579 *
1580 * More notes at CRM_Core_DAO::createSQLFilter
1581 *
1582 * and a list of supported operators in CRM_Core_DAO
c037736a 1583 *
1584 * @param array $formValues
86538308
EM
1585 * @param int $wildcard
1586 * @param bool $useEquals
1587 *
0e2e76cf
EM
1588 * @param string $apiEntity
1589 *
df60621b 1590 * @param array $entityReferenceFields
1591 * Field names of any entity reference fields (which will need reformatting to IN syntax).
1592 *
86538308
EM
1593 * @return array
1594 */
df60621b 1595 public static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL,
be2fb01f
CW
1596 $entityReferenceFields = []) {
1597 $params = [];
6a488035
TO
1598 if (empty($formValues)) {
1599 return $params;
1600 }
1601
20306bb8 1602 self::filterCountryFromValuesIfStateExists($formValues);
8a6fde27 1603 // We shouldn't have to whitelist fields to not hack but here we are, for now.
c4853004
SL
1604 $nonLegacyDateFields = [
1605 'participant_register_date_relative',
1606 'receive_date_relative',
1607 'pledge_end_date_relative',
1608 'pledge_create_date_relative',
1609 'pledge_start_date_relative',
1610 'pledge_payment_scheduled_date_relative',
41b8dd1d 1611 'relationship_start_date_relative',
1612 'relationship_end_date_relative',
5f97e97f
SL
1613 'membership_join_date_relative',
1614 'membership_start_date_relative',
1615 'membership_end_date_relative',
7d832c0c
SL
1616 'case_start_date_relative',
1617 'case_end_date_relative',
0058ef3f 1618 'mailing_job_start_date_relative',
bca2ad39 1619 'birth_date_relative',
1620 'deceased_date_relative',
7d8f464a 1621 'relation_active_period_date_relative',
c4853004 1622 ];
be588106
AS
1623 // Handle relative dates first
1624 foreach (array_keys($formValues) as $id) {
8a6fde27 1625 if (
1626 !in_array($id, $nonLegacyDateFields) && (
936ededf 1627 preg_match('/_date_relative$/', $id))
be588106 1628 ) {
936ededf 1629 $dateComponent = explode('_date_relative', $id);
1630 $fromRange = "{$dateComponent[0]}_date_low";
1631 $toRange = "{$dateComponent[0]}_date_high";
be588106
AS
1632
1633 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1634 CRM_Contact_BAO_Query::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1635 }
1636 }
1637 }
e34642c9 1638
5840d253 1639 foreach ($formValues as $id => $values) {
df60621b 1640 if (self::isAlreadyProcessedForQueryFormat($values)) {
1641 $params[] = $values;
1642 continue;
1643 }
06d67d53 1644
1645 self::legacyConvertFormValues($id, $values);
1646
46b3417a
CW
1647 // The form uses 1 field to represent two db fields
1648 if ($id == 'contact_type' && $values && (!is_array($values) || !array_intersect(array_keys($values), CRM_Core_DAO::acceptedSQLOperators()))) {
be2fb01f
CW
1649 $contactType = [];
1650 $subType = [];
46b3417a 1651 foreach ((array) $values as $key => $type) {
f12a86ad 1652 $types = explode('__', is_numeric($type) ? $key : $type, 2);
46b3417a
CW
1653 $contactType[$types[0]] = $types[0];
1654 // Add sub-type if specified
1655 if (!empty($types[1])) {
1656 $subType[$types[1]] = $types[1];
1657 }
1658 }
be2fb01f 1659 $params[] = ['contact_type', 'IN', $contactType, 0, 0];
46b3417a 1660 if ($subType) {
be2fb01f 1661 $params[] = ['contact_sub_type', 'IN', $subType, 0, 0];
46b3417a
CW
1662 }
1663 }
1664 elseif ($id == 'privacy') {
6a488035 1665 if (is_array($formValues['privacy'])) {
0d8afee2 1666 $op = !empty($formValues['privacy']['do_not_toggle']) ? '=' : '!=';
6a488035
TO
1667 foreach ($formValues['privacy'] as $key => $value) {
1668 if ($value) {
be2fb01f 1669 $params[] = [$key, $op, $value, 0, 0];
6a488035
TO
1670 }
1671 }
1672 }
1673 }
1674 elseif ($id == 'email_on_hold') {
38056b36 1675 if ($onHoldValue = CRM_Utils_Array::value('email_on_hold', $formValues)) {
1d94ee08 1676 // onHoldValue should be 0 or 1 or an array. Some legacy groups may hold ''
1677 // so in 5.11 we have an extra if that should become redundant over time.
1678 // https://lab.civicrm.org/dev/core/issues/745
1679 // @todo this renaming of email_on_hold to on_hold needs revisiting
1680 // it preceeds recent changes but causes the default not to reload.
828c2392 1681 $onHoldValue = array_filter((array) $onHoldValue, 'is_numeric');
1682 if (!empty($onHoldValue)) {
1d94ee08 1683 $params[] = ['on_hold', 'IN', $onHoldValue, 0, 0];
1684 }
6a488035
TO
1685 }
1686 }
bb05da0c 1687 elseif (substr($id, 0, 7) == 'custom_'
4c2fe77b 1688 && (
7f175707 1689 substr($id, -5, 5) == '_from'
4c2fe77b 1690 || substr($id, -3, 3) == '_to'
1691 )
bb05da0c 1692 ) {
4c2fe77b 1693 self::convertCustomRelativeFields($formValues, $params, $values, $id);
bb05da0c 1694 }
8a6fde27 1695 elseif (
1696 !in_array($id, $nonLegacyDateFields) && (
936ededf 1697 preg_match('/_date_relative$/', $id))
5c7dad85 1698 ) {
be588106
AS
1699 // Already handled in previous loop
1700 continue;
6a488035 1701 }
df60621b 1702 elseif (in_array($id, $entityReferenceFields) && !empty($values) && is_string($values) && (strpos($values, ',') !=
1703 FALSE)) {
be2fb01f 1704 $params[] = [$id, 'IN', explode(',', $values), 0, 0];
df60621b 1705 }
6a488035 1706 else {
3c151c70 1707 $values = CRM_Contact_BAO_Query::fixWhereValues($id, $values, $wildcard, $useEquals, $apiEntity);
6a488035
TO
1708
1709 if (!$values) {
1710 continue;
1711 }
1712 $params[] = $values;
1713 }
1714 }
1715 return $params;
1716 }
1717
e34642c9 1718 /**
1719 * Function to support legacy format for groups and tags.
1720 *
1721 * @param string $id
1722 * @param array|int $values
1723 *
1724 */
5450bf88 1725 public static function legacyConvertFormValues($id, &$values) {
be2fb01f 1726 $legacyElements = [
06d67d53 1727 'group',
1728 'tag',
1729 'contact_tags',
1730 'contact_type',
1731 'membership_type_id',
1732 'membership_status_id',
be2fb01f 1733 ];
06d67d53 1734 if (in_array($id, $legacyElements) && is_array($values)) {
5450bf88 1735 // prior to 4.7, formValues for some attributes (e.g. group, tag) are stored in array(id1 => 1, id2 => 1),
1736 // as per the recent Search fixes $values need to be in standard array(id1, id2) format
e5ad0335 1737 $values = CRM_Utils_Array::convertCheckboxFormatToArray($values);
5450bf88 1738 }
e34642c9 1739 }
1740
86538308 1741 /**
c037736a 1742 * Fix values from query from/to something no-one cared enough to document.
1743 *
100fef9d 1744 * @param int $id
c037736a 1745 * @param array $values
86538308
EM
1746 * @param int $wildcard
1747 * @param bool $useEquals
1748 *
0e2e76cf
EM
1749 * @param string $apiEntity
1750 *
86538308
EM
1751 * @return array|null
1752 */
c037736a 1753 public static function fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL) {
6a488035
TO
1754 // skip a few search variables
1755 static $skipWhere = NULL;
6a488035
TO
1756 static $likeNames = NULL;
1757 $result = NULL;
57f8e7f0 1758
244bbdd8
CW
1759 // Change camelCase EntityName to lowercase with underscores
1760 $apiEntity = _civicrm_api_get_entity_name_from_camel($apiEntity);
6a488035 1761
57f8e7f0 1762 // check if $value is in OK (Operator as Key) format as used by Get API
6a488035
TO
1763 if (CRM_Utils_System::isNull($values)) {
1764 return $result;
1765 }
1766
1767 if (!$skipWhere) {
be2fb01f 1768 $skipWhere = [
5c7dad85
TO
1769 'task',
1770 'radio_ts',
1771 'uf_group_id',
1772 'component_mode',
1773 'qfKey',
1774 'operator',
6a488035 1775 'display_relationship_type',
be2fb01f 1776 ];
6a488035
TO
1777 }
1778
1779 if (in_array($id, $skipWhere) ||
1780 substr($id, 0, 4) == '_qf_' ||
1781 substr($id, 0, 7) == 'hidden_'
1782 ) {
1783 return $result;
1784 }
1785
afa0b07c 1786 if ($apiEntity &&
1787 (substr($id, 0, strlen($apiEntity)) != $apiEntity) &&
1a3e22cc
MM
1788 (substr($id, 0, 10) != 'financial_' && substr($id, 0, 8) != 'payment_') &&
1789 (substr($id, 0, 7) != 'custom_')
afa0b07c 1790 ) {
3c151c70 1791 $id = $apiEntity . '_' . $id;
1792 }
1793
6a488035 1794 if (!$likeNames) {
be2fb01f 1795 $likeNames = ['sort_name', 'email', 'note', 'display_name'];
6a488035
TO
1796 }
1797
1798 // email comes in via advanced search
1799 // so use wildcard always
1800 if ($id == 'email') {
1801 $wildcard = 1;
1802 }
1803
5c7dad85 1804 if (!$useEquals && in_array($id, $likeNames)) {
be2fb01f 1805 $result = [$id, 'LIKE', $values, 0, 1];
6a488035
TO
1806 }
1807 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
be2fb01f 1808 $result = [$id, 'LIKE', $values, 0, 0];
6a488035 1809 }
a0cbe4fa 1810 elseif ($id == 'contact_type' ||
1811 (!empty($values) && is_array($values) && !in_array(key($values), CRM_Core_DAO::acceptedSQLOperators(), TRUE))
1812 ) {
be2fb01f 1813 $result = [$id, 'IN', $values, 0, $wildcard];
c33e01a5 1814 }
6a488035 1815 else {
be2fb01f 1816 $result = [$id, '=', $values, 0, $wildcard];
6a488035
TO
1817 }
1818
1819 return $result;
1820 }
1821
86538308 1822 /**
c037736a 1823 * Get the where clause for a single field.
1824 *
1825 * @param array $values
9178793e 1826 * @param bool $isForcePrimaryOnly
1827 *
1828 * @throws \CRM_Core_Exception
86538308 1829 */
9178793e 1830 public function whereClauseSingle(&$values, $isForcePrimaryOnly = FALSE) {
8fc9f99a 1831 if ($this->isARelativeDateField($values[0])) {
1832 $this->buildRelativeDateQuery($values);
1833 return;
1834 }
33a17d7e 1835 // @todo also handle _low, _high generically here with if ($query->buildDateRangeQuery($values)) {return}
8fc9f99a 1836
6a488035
TO
1837 // do not process custom fields or prefixed contact ids or component params
1838 if (CRM_Core_BAO_CustomField::getKeyID($values[0]) ||
1839 (substr($values[0], 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) ||
1840 (substr($values[0], 0, 13) == 'contribution_') ||
1841 (substr($values[0], 0, 6) == 'event_') ||
1842 (substr($values[0], 0, 12) == 'participant_') ||
1843 (substr($values[0], 0, 7) == 'member_') ||
1844 (substr($values[0], 0, 6) == 'grant_') ||
1845 (substr($values[0], 0, 7) == 'pledge_') ||
289c8051 1846 (substr($values[0], 0, 5) == 'case_') ||
3c53f77e 1847 (substr($values[0], 0, 10) == 'financial_') ||
afa0b07c 1848 (substr($values[0], 0, 8) == 'payment_') ||
3c53f77e 1849 (substr($values[0], 0, 11) == 'membership_')
6a488035
TO
1850 ) {
1851 return;
1852 }
1853
efa3a566
DS
1854 // skip for hook injected fields / params
1855 $extFields = CRM_Contact_BAO_Query_Hook::singleton()->getFields();
1856 if (array_key_exists($values[0], $extFields)) {
1857 return;
1858 }
1859
6a488035
TO
1860 switch ($values[0]) {
1861 case 'deleted_contacts':
1862 $this->deletedContacts($values);
1863 return;
1864
6a488035
TO
1865 case 'contact_sub_type':
1866 $this->contactSubType($values);
1867 return;
1868
1869 case 'group':
6a488035 1870 case 'group_type':
6a488035
TO
1871 $this->group($values);
1872 return;
6a488035 1873
c905b59f 1874 // case tag comes from find contacts
6a488035
TO
1875 case 'tag_search':
1876 $this->tagSearch($values);
1877 return;
1878
1879 case 'tag':
1880 case 'contact_tags':
1881 $this->tag($values);
1882 return;
1883
1884 case 'note':
1885 case 'note_body':
1886 case 'note_subject':
1887 $this->notes($values);
1888 return;
1889
1890 case 'uf_user':
1891 $this->ufUser($values);
1892 return;
1893
1894 case 'sort_name':
1895 case 'display_name':
1896 $this->sortName($values);
6a488035
TO
1897 return;
1898
02adf2f9
BS
1899 case 'addressee':
1900 case 'postal_greeting':
1901 case 'email_greeting':
1902 $this->greetings($values);
1903 return;
1904
6a488035 1905 case 'email':
57f8e7f0 1906 case 'email_id':
9178793e 1907 $this->email($values, $isForcePrimaryOnly);
6a488035
TO
1908 return;
1909
1910 case 'phone_numeric':
1911 $this->phone_numeric($values);
1912 return;
1913
1914 case 'phone_phone_type_id':
1915 case 'phone_location_type_id':
1916 $this->phone_option_group($values);
1917 return;
1918
1919 case 'street_address':
1920 $this->street_address($values);
1921 return;
1922
1923 case 'street_number':
1924 $this->street_number($values);
1925 return;
1926
1927 case 'sortByCharacter':
1928 $this->sortByCharacter($values);
1929 return;
1930
1931 case 'location_type':
1932 $this->locationType($values);
1933 return;
1934
1935 case 'county':
1936 $this->county($values);
1937 return;
1938
1939 case 'state_province':
3493947a 1940 case 'state_province_id':
1941 case 'state_province_name':
6a488035
TO
1942 $this->stateProvince($values);
1943 return;
1944
1945 case 'country':
3493947a 1946 case 'country_id':
6a488035
TO
1947 $this->country($values, FALSE);
1948 return;
1949
1950 case 'postal_code':
1951 case 'postal_code_low':
1952 case 'postal_code_high':
1953 $this->postalCode($values);
1954 return;
1955
1956 case 'activity_date':
1957 case 'activity_date_low':
1958 case 'activity_date_high':
27cedb98 1959 case 'activity_date_time_low':
1960 case 'activity_date_time_high':
6a488035 1961 case 'activity_role':
9ab34172 1962 case 'activity_status_id':
6a488035 1963 case 'activity_status':
da236f9a 1964 case 'activity_priority':
1965 case 'activity_priority_id':
4c24c842
PN
1966 case 'followup_parent_id':
1967 case 'parent_id':
9ab34172 1968 case 'source_contact_id':
92e9c781 1969 case 'activity_text':
c9c5c58d 1970 case 'activity_option':
6a488035
TO
1971 case 'test_activities':
1972 case 'activity_type_id':
3e4a4597 1973 case 'activity_type':
6a488035
TO
1974 case 'activity_survey_id':
1975 case 'activity_tags':
1976 case 'activity_taglist':
1977 case 'activity_test':
6a488035
TO
1978 case 'activity_campaign_id':
1979 case 'activity_engagement_level':
1980 case 'activity_id':
4041c9b6 1981 case 'activity_result':
6a488035
TO
1982 case 'source_contact':
1983 CRM_Activity_BAO_Query::whereClauseSingle($values, $this);
1984 return;
1985
c4a7c967 1986 case 'age_low':
1987 case 'age_high':
6a488035
TO
1988 case 'birth_date_low':
1989 case 'birth_date_high':
1990 case 'deceased_date_low':
1991 case 'deceased_date_high':
1992 $this->demographics($values);
1993 return;
1994
c4a7c967 1995 case 'age_asof_date':
1996 // handled by demographics
1997 return;
1998
6a488035
TO
1999 case 'log_date_low':
2000 case 'log_date_high':
2001 $this->modifiedDates($values);
2002 return;
2003
2004 case 'changed_by':
2005 $this->changeLog($values);
2006 return;
2007
2008 case 'do_not_phone':
2009 case 'do_not_email':
2010 case 'do_not_mail':
2011 case 'do_not_sms':
2012 case 'do_not_trade':
2013 case 'is_opt_out':
2014 $this->privacy($values);
2015 return;
2016
2017 case 'privacy_options':
2018 $this->privacyOptions($values);
2019 return;
2020
2021 case 'privacy_operator':
2022 case 'privacy_toggle':
2023 // these are handled by privacy options
2024 return;
2025
2026 case 'preferred_communication_method':
2027 $this->preferredCommunication($values);
2028 return;
2029
2030 case 'relation_type_id':
41b8dd1d 2031 case 'relationship_start_date_high':
2032 case 'relationship_start_date_low':
2033 case 'relationship_end_date_high':
2034 case 'relationship_end_date_low':
eea5db81 2035 case 'relation_active_period_date_high':
2036 case 'relation_active_period_date_low':
6a488035
TO
2037 case 'relation_target_name':
2038 case 'relation_status':
6e83b317 2039 case 'relation_description':
6a488035
TO
2040 case 'relation_date_low':
2041 case 'relation_date_high':
7c96365b 2042 $this->relationship($values);
2043 $this->_relationshipValuesAdded = TRUE;
6a488035
TO
2044 return;
2045
2046 case 'task_status_id':
2047 $this->task($values);
2048 return;
2049
2050 case 'task_id':
2051 // since this case is handled with the above
2052 return;
2053
2054 case 'prox_distance':
2055 CRM_Contact_BAO_ProximityQuery::process($this, $values);
2056 return;
2057
2058 case 'prox_street_address':
2059 case 'prox_city':
2060 case 'prox_postal_code':
2061 case 'prox_state_province_id':
2062 case 'prox_country_id':
4b2d36d7 2063 case 'prox_geo_code_1':
2064 case 'prox_geo_code_2':
6a488035
TO
2065 // handled by the proximity_distance clause
2066 return;
2067
2068 default:
2069 $this->restWhere($values);
2070 return;
2071 }
2072 }
2073
2074 /**
c037736a 2075 * Given a list of conditions in params generate the required where clause.
6a488035 2076 *
9178793e 2077 * @param bool $isForcePrimaryEmailOnly
57f8e7f0 2078 *
fffe9ee1 2079 * @return string
9178793e 2080 * @throws \CRM_Core_Exception
6a488035 2081 */
9178793e 2082 public function whereClause($isForcePrimaryEmailOnly = NULL) {
be2fb01f
CW
2083 $this->_where[0] = [];
2084 $this->_qill[0] = [];
6a488035 2085
6a488035
TO
2086 $this->includeContactIds();
2087 if (!empty($this->_params)) {
6a488035 2088 foreach (array_keys($this->_params) as $id) {
a7488080 2089 if (empty($this->_params[$id][0])) {
6a488035
TO
2090 continue;
2091 }
2092 // check for both id and contact_id
2093 if ($this->_params[$id][0] == 'id' || $this->_params[$id][0] == 'contact_id') {
f819588f 2094 $this->_where[0][] = self::buildClause("contact_a.id", $this->_params[$id][1], $this->_params[$id][2]);
9ea799a3
PN
2095 $field = CRM_Utils_Array::value('id', $this->_fields);
2096 list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(
2097 'CRM_Contact_BAO_Contact',
2098 "contact_a.id",
2099 $this->_params[$id][2],
2100 $this->_params[$id][1]
2101 );
2102 $this->_qill[0][] = ts("%1 %2 %3", [
2103 1 => $field['title'],
2104 2 => $qillop,
69078420 2105 3 => $qillVal,
9ea799a3 2106 ]);
6a488035
TO
2107 }
2108 else {
9178793e 2109 $this->whereClauseSingle($this->_params[$id], $isForcePrimaryEmailOnly);
6a488035
TO
2110 }
2111 }
2112
2113 CRM_Core_Component::alterQuery($this, 'where');
f2a9b25c 2114
99e9587a 2115 CRM_Contact_BAO_Query_Hook::singleton()->alterSearchQuery($this, 'where');
6a488035
TO
2116 }
2117
2118 if ($this->_customQuery) {
c037736a 2119 // Added following if condition to avoid the wrong value display for 'my account' / any UF info.
6a488035
TO
2120 // Hope it wont affect the other part of civicrm.. if it does please remove it.
2121 if (!empty($this->_customQuery->_where)) {
2122 $this->_where = CRM_Utils_Array::crmArrayMerge($this->_where, $this->_customQuery->_where);
2123 }
2124
2125 $this->_qill = CRM_Utils_Array::crmArrayMerge($this->_qill, $this->_customQuery->_qill);
2126 }
2127
be2fb01f
CW
2128 $clauses = [];
2129 $andClauses = [];
6a488035
TO
2130
2131 $validClauses = 0;
2132 if (!empty($this->_where)) {
2133 foreach ($this->_where as $grouping => $values) {
2134 if ($grouping > 0 && !empty($values)) {
2135 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
2136 $validClauses++;
2137 }
2138 }
2139
2140 if (!empty($this->_where[0])) {
2141 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where[0]) . ' ) ';
2142 }
2143 if (!empty($clauses)) {
2144 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
2145 }
2146
2147 if ($validClauses > 1) {
2148 $this->_useDistinct = TRUE;
2149 }
2150 }
2151
2152 return implode(' AND ', $andClauses);
2153 }
2154
86538308 2155 /**
c037736a 2156 * Generate where clause for any parameters not already handled.
2157 *
2158 * @param array $values
86538308
EM
2159 *
2160 * @throws Exception
2161 */
00be9182 2162 public function restWhere(&$values) {
6a488035
TO
2163 $name = CRM_Utils_Array::value(0, $values);
2164 $op = CRM_Utils_Array::value(1, $values);
2165 $value = CRM_Utils_Array::value(2, $values);
2166 $grouping = CRM_Utils_Array::value(3, $values);
2167 $wildcard = CRM_Utils_Array::value(4, $values);
2168
8cc574cf 2169 if (isset($grouping) && empty($this->_where[$grouping])) {
be2fb01f 2170 $this->_where[$grouping] = [];
6a488035
TO
2171 }
2172
be2fb01f 2173 $multipleFields = ['url'];
6a488035 2174
3493947a 2175 //check if the location type exists for fields
6a488035
TO
2176 $lType = '';
2177 $locType = explode('-', $name);
2178
2179 if (!in_array($locType[0], $multipleFields)) {
2180 //add phone type if exists
2181 if (isset($locType[2]) && $locType[2]) {
2182 $locType[2] = CRM_Core_DAO::escapeString($locType[2]);
2183 }
2184 }
2185
2186 $field = CRM_Utils_Array::value($name, $this->_fields);
2187
2188 if (!$field) {
2189 $field = CRM_Utils_Array::value($locType[0], $this->_fields);
2190
2191 if (!$field) {
5b5ea9b6 2192 // Strip any trailing _high & _low that might be appended.
2193 $realFieldName = str_replace(['_high', '_low'], '', $name);
2194 if (isset($this->_fields[$realFieldName])) {
2195 $field = $this->_fields[str_replace(['_high', '_low'], '', $realFieldName)];
2b750181 2196 $this->dateQueryBuilder($values, $field['table_name'], $realFieldName, $field['name'], $field['title']);
5b5ea9b6 2197 }
6a488035
TO
2198 return;
2199 }
2200 }
2201
2202 $setTables = TRUE;
2203
db1a73f5 2204 $locationType = CRM_Core_DAO_Address::buildOptions('location_type_id', 'validate');
fdfca3e9
VG
2205 if (isset($locType[1]) && is_numeric($locType[1])) {
2206 $lType = $locationType[$locType[1]];
2207 }
2208 if ($lType) {
2209 $field['title'] .= " ($lType)";
2210 }
6a488035
TO
2211
2212 if (substr($name, 0, 14) === 'state_province') {
2213 if (isset($locType[1]) && is_numeric($locType[1])) {
2e155dbd 2214 $setTables = FALSE;
fdfca3e9 2215 $aName = "{$lType}-address";
d9ab802d 2216 $where = "`$aName`.state_province_id";
6a488035
TO
2217 }
2218 else {
d9ab802d 2219 $where = "civicrm_address.state_province_id";
6a488035
TO
2220 }
2221
8ab09481 2222 $this->_where[$grouping][] = self::buildClause($where, $op, $value);
8f0fd14c 2223 $this->_tables[$aName] = $this->_whereTables[$aName] = 1;
7cc09daf 2224 list($qillop, $qillVal) = self::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
be2fb01f 2225 $this->_qill[$grouping][] = ts("%1 %2 %3", [1 => $field['title'], 2 => $qillop, 3 => $qillVal]);
6a488035 2226 }
1c1a84a2 2227 elseif (!empty($field['pseudoconstant'])) {
1071730c
DL
2228 $this->optionValueQuery(
2229 $name, $op, $value, $grouping,
9b183452 2230 'CRM_Contact_DAO_Contact',
1071730c 2231 $field,
a30e57e0
DL
2232 $field['title'],
2233 'String',
2234 TRUE
1071730c 2235 );
9df8a11d 2236 if ($name == 'gender_id') {
1071730c
DL
2237 self::$_openedPanes[ts('Demographics')] = TRUE;
2238 }
2239 }
9b183452 2240 elseif (substr($name, 0, 7) === 'country' || substr($name, 0, 6) === 'county') {
2241 $name = (substr($name, 0, 7) === 'country') ? "country_id" : "county_id";
6a488035 2242 if (isset($locType[1]) && is_numeric($locType[1])) {
2e155dbd 2243 $setTables = FALSE;
fdfca3e9 2244 $aName = "{$lType}-address";
9b183452 2245 $where = "`$aName`.$name";
6a488035
TO
2246 }
2247 else {
9b183452 2248 $where = "civicrm_address.$name";
6a488035 2249 }
d9ab802d 2250
9b183452 2251 $this->_where[$grouping][] = self::buildClause($where, $op, $value, 'Positive');
8f0fd14c 2252 $this->_tables[$aName] = $this->_whereTables[$aName] = 1;
6a488035 2253
9d9cfb9f 2254 list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(NULL, $name, $value, $op);
be2fb01f 2255 $this->_qill[$grouping][] = ts("%1 %2 %3", [1 => $field['title'], 2 => $qillop, 3 => $qillVal]);
6a488035
TO
2256 }
2257 elseif ($name === 'world_region') {
2258 $this->optionValueQuery(
2259 $name, $op, $value, $grouping,
728eefa0 2260 NULL,
6a488035 2261 $field,
8b695e91
CW
2262 ts('World Region'),
2263 'Positive',
2264 TRUE
6a488035
TO
2265 );
2266 }
6a488035 2267 elseif ($name === 'is_deceased') {
962f4484 2268 $this->setQillAndWhere($name, $op, $value, $grouping, $field);
6a488035
TO
2269 self::$_openedPanes[ts('Demographics')] = TRUE;
2270 }
d820f4e8 2271 elseif ($name === 'created_date' || $name === 'modified_date' || $name === 'deceased_date' || $name === 'birth_date') {
ee657a1c 2272 $appendDateTime = TRUE;
d820f4e8 2273 if ($name === 'deceased_date' || $name === 'birth_date') {
ee657a1c 2274 $appendDateTime = FALSE;
d820f4e8 2275 self::$_openedPanes[ts('Demographics')] = TRUE;
2276 }
0b83b6c2 2277 $this->dateQueryBuilder($values, 'contact_a', $name, $name, $field['title'], $appendDateTime);
d820f4e8 2278 }
6a488035
TO
2279 elseif ($name === 'contact_id') {
2280 if (is_int($value)) {
2281 $this->_where[$grouping][] = self::buildClause($field['where'], $op, $value);
2282 $this->_qill[$grouping][] = "$field[title] $op $value";
2283 }
2284 }
2285 elseif ($name === 'name') {
2bde57c6 2286 $value = CRM_Core_DAO::escapeString($value);
6a488035 2287 if ($wildcard) {
6a488035 2288 $op = 'LIKE';
0b38e8f1 2289 $value = self::getWildCardedValue($wildcard, $op, $value);
6a488035 2290 }
2bde57c6 2291 CRM_Core_Error::deprecatedFunctionWarning('Untested code path');
2292 // @todo it's likely this code path is obsolete / never called. It is definitely not
2293 // passed through in our test suite.
2294 $this->_where[$grouping][] = self::buildClause($field['where'], $op, "'$value'");
6a488035
TO
2295 $this->_qill[$grouping][] = "$field[title] $op \"$value\"";
2296 }
2297 elseif ($name === 'current_employer') {
6a488035 2298 if ($wildcard) {
6a488035 2299 $op = 'LIKE';
0b38e8f1 2300 $value = self::getWildCardedValue($wildcard, $op, $value);
6a488035 2301 }
30415e03 2302 $ceWhereClause = self::buildClause("contact_a.organization_name", $op,
0d77b56a 2303 $value
6a488035 2304 );
0d77b56a
PJ
2305 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2306 $this->_where[$grouping][] = $ceWhereClause;
6a488035
TO
2307 $this->_qill[$grouping][] = "$field[title] $op \"$value\"";
2308 }
2309 elseif ($name === 'email_greeting') {
b7aa36b6 2310 CRM_Core_Error::deprecatedFunctionWarning('pass in email_greeting_id or email_greeting_display');
be2fb01f 2311 $filterCondition = ['greeting_type' => 'email_greeting'];
6a488035
TO
2312 $this->optionValueQuery(
2313 $name, $op, $value, $grouping,
2314 CRM_Core_PseudoConstant::greeting($filterCondition),
2315 $field,
2316 ts('Email Greeting')
2317 );
2318 }
2319 elseif ($name === 'postal_greeting') {
b7aa36b6 2320 CRM_Core_Error::deprecatedFunctionWarning('pass in postal_greeting_id or postal_greeting_display');
be2fb01f 2321 $filterCondition = ['greeting_type' => 'postal_greeting'];
6a488035
TO
2322 $this->optionValueQuery(
2323 $name, $op, $value, $grouping,
2324 CRM_Core_PseudoConstant::greeting($filterCondition),
2325 $field,
2326 ts('Postal Greeting')
2327 );
2328 }
2329 elseif ($name === 'addressee') {
b7aa36b6 2330 CRM_Core_Error::deprecatedFunctionWarning('pass in addressee_id or addressee_display');
be2fb01f 2331 $filterCondition = ['greeting_type' => 'addressee'];
6a488035
TO
2332 $this->optionValueQuery(
2333 $name, $op, $value, $grouping,
2334 CRM_Core_PseudoConstant::greeting($filterCondition),
2335 $field,
2336 ts('Addressee')
2337 );
2338 }
2339 elseif (substr($name, 0, 4) === 'url-') {
2340 $tName = 'civicrm_website';
2341 $this->_whereTables[$tName] = $this->_tables[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2fc64082 2342 $value = CRM_Core_DAO::escapeString($value);
6a488035 2343 if ($wildcard) {
6a488035 2344 $op = 'LIKE';
0b38e8f1 2345 $value = self::getWildCardedValue($wildcard, $op, $value);
6a488035
TO
2346 }
2347
962f4484 2348 $this->_where[$grouping][] = $d = self::buildClause('civicrm_website.url', $op, $value);
6a488035
TO
2349 $this->_qill[$grouping][] = "$field[title] $op \"$value\"";
2350 }
2351 elseif ($name === 'contact_is_deleted') {
962f4484 2352 $this->setQillAndWhere('is_deleted', $op, $value, $grouping, $field);
6a488035 2353 }
efb88612 2354 elseif (!empty($field['where'])) {
2355 $type = NULL;
2356 if (!empty($field['type'])) {
2357 $type = CRM_Utils_Type::typeToString($field['type']);
2358 }
2359
2360 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2361
2362 if (isset($locType[1]) &&
2363 is_numeric($locType[1])
2364 ) {
2365 $setTables = FALSE;
2366
2367 //get the location name
2368 list($tName, $fldName) = self::getLocationTableName($field['where'], $locType);
54e02ce8 2369 $fieldName = "`$tName`.$fldName";
efb88612 2370
2371 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2372 $this->_tables[$tName] = $this->_whereTables[$tName] = 1;
2373
2374 }
2375 else {
2376 if ($tableName == 'civicrm_contact') {
1809f3cf 2377 $fieldName = "contact_a.{$fieldName}";
efb88612 2378 }
2379 else {
7fde0061 2380 $fieldName = $field['where'];
efb88612 2381 }
2382 }
2383
2384 list($qillop, $qillVal) = self::buildQillForFieldValue(NULL, $field['title'], $value, $op);
be2fb01f 2385 $this->_qill[$grouping][] = ts("%1 %2 %3", [
9b183452 2386 1 => $field['title'],
2387 2 => $qillop,
69078420
SL
2388 3 => (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) ? $qillVal : "'$qillVal'",
2389 ]);
efb88612 2390
6a488035 2391 if (is_array($value)) {
a75c13cc
EM
2392 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2393 // for api style operators for functions that hit this point without worrying about regression
2394 // (the previous comments indicated the condition for hitting this point were unknown
2395 // per CRM-14743 we are adding modified_date & created_date operator support
2396 $operations = array_keys($value);
2397 foreach ($operations as $operator) {
11a5aa5d 2398 if (!in_array($operator, CRM_Core_DAO::acceptedSQLOperators())) {
efb88612 2399 //Via Contact get api value is not in array(operator => array(values)) format ONLY for IN/NOT IN operators
2400 //so this condition will satisfy the search for now
0a74debb 2401 if (strpos($op, 'IN') !== FALSE) {
be2fb01f 2402 $value = [$op => $value];
efb88612 2403 }
a75c13cc 2404 // we don't know when this might happen
efb88612 2405 else {
be2fb01f 2406 CRM_Core_Error::fatal(ts("%1 is not a valid operator", [1 => $operator]));
efb88612 2407 }
a75c13cc
EM
2408 }
2409 }
efb88612 2410 $this->_where[$grouping][] = CRM_Core_DAO::createSQLFilter($fieldName, $value, $type);
6a488035 2411 }
efb88612 2412 else {
6a488035 2413 if ($wildcard) {
6a488035 2414 $op = 'LIKE';
0b38e8f1 2415 $value = self::getWildCardedValue($wildcard, $op, $value);
6a488035
TO
2416 }
2417
efb88612 2418 $this->_where[$grouping][] = self::buildClause($fieldName, $op, $value, $type);
6a488035
TO
2419 }
2420 }
2421
2422 if ($setTables && isset($field['where'])) {
2423 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2424 if (isset($tableName)) {
2425 $this->_tables[$tableName] = 1;
2426 $this->_whereTables[$tableName] = 1;
2427 }
2428 }
2429 }
2430
86538308
EM
2431 /**
2432 * @param $where
2433 * @param $locType
2434 *
2435 * @return array
2436 * @throws Exception
2437 */
00be9182 2438 public static function getLocationTableName(&$where, &$locType) {
6a488035
TO
2439 if (isset($locType[1]) && is_numeric($locType[1])) {
2440 list($tbName, $fldName) = explode(".", $where);
2441
2442 //get the location name
f9ba4d01 2443 $locationType = CRM_Core_DAO_Address::buildOptions('location_type_id', 'validate');
be2fb01f 2444 $specialFields = ['email', 'im', 'phone', 'openid', 'phone_ext'];
6a488035
TO
2445 if (in_array($locType[0], $specialFields)) {
2446 //hack to fix / special handing for phone_ext
2447 if ($locType[0] == 'phone_ext') {
2448 $locType[0] = 'phone';
2449 }
2450 if (isset($locType[2]) && $locType[2]) {
2451 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2452 }
2453 else {
2454 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2455 }
2456 }
2457 elseif (in_array($locType[0],
be2fb01f 2458 [
5c7dad85
TO
2459 'address_name',
2460 'street_address',
7cc09daf 2461 'street_name',
2462 'street_number_suffix',
2463 'street_unit',
5c7dad85
TO
2464 'supplemental_address_1',
2465 'supplemental_address_2',
207f62c6 2466 'supplemental_address_3',
5c7dad85
TO
2467 'city',
2468 'postal_code',
2469 'postal_code_suffix',
2470 'geo_code_1',
2471 'geo_code_2',
7cc09daf 2472 'master_id',
be2fb01f 2473 ]
5c7dad85 2474 )) {
6a488035 2475 //fix for search by profile with address fields.
a822d3d8 2476 $tName = "{$locationType[$locType[1]]}-address";
6a488035 2477 }
7cc09daf 2478 elseif (in_array($locType[0],
be2fb01f 2479 [
7cc09daf 2480 'on_hold',
2481 'signature_html',
2482 'signature_text',
2483 'is_bulkmail',
be2fb01f 2484 ]
7cc09daf 2485 )) {
6a488035
TO
2486 $tName = "{$locationType[$locType[1]]}-email";
2487 }
7cc09daf 2488 elseif ($locType[0] == 'provider_id') {
2489 $tName = "{$locationType[$locType[1]]}-im";
2490 }
2491 elseif ($locType[0] == 'openid') {
2492 $tName = "{$locationType[$locType[1]]}-openid";
2493 }
6a488035
TO
2494 else {
2495 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2496 }
2497 $tName = str_replace(' ', '_', $tName);
be2fb01f 2498 return [$tName, $fldName];
6a488035
TO
2499 }
2500 CRM_Core_Error::fatal();
2501 }
2502
2503 /**
2504 * Given a result dao, extract the values and return that array
2505 *
c490a46a 2506 * @param CRM_Core_DAO $dao
6a488035 2507 *
a6c01b45
CW
2508 * @return array
2509 * values for this query
6a488035 2510 */
00be9182 2511 public function store($dao) {
be2fb01f 2512 $value = [];
6a488035
TO
2513
2514 foreach ($this->_element as $key => $dontCare) {
2515 if (property_exists($dao, $key)) {
2516 if (strpos($key, '-') !== FALSE) {
2517 $values = explode('-', $key);
2518 $lastElement = array_pop($values);
2519 $current = &$value;
2520 $cnt = count($values);
2521 $count = 1;
2522 foreach ($values as $v) {
2523 if (!array_key_exists($v, $current)) {
be2fb01f 2524 $current[$v] = [];
6a488035
TO
2525 }
2526 //bad hack for im_provider
2527 if ($lastElement == 'provider_id') {
2528 if ($count < $cnt) {
2529 $current = &$current[$v];
2530 }
2531 else {
2532 $lastElement = "{$v}_{$lastElement}";
2533 }
2534 }
2535 else {
2536 $current = &$current[$v];
2537 }
2538 $count++;
2539 }
2540
2541 $current[$lastElement] = $dao->$key;
2542 }
2543 else {
2544 $value[$key] = $dao->$key;
2545 }
2546 }
2547 }
2548 return $value;
2549 }
2550
2551 /**
fe482240 2552 * Getter for tables array.
6a488035
TO
2553 *
2554 * @return array
6a488035 2555 */
00be9182 2556 public function tables() {
6a488035
TO
2557 return $this->_tables;
2558 }
2559
86538308 2560 /**
746aa919
CB
2561 * Sometimes used to create the from clause, but, not reliably, set
2562 * this AND set tables.
2563 *
2564 * It's unclear the intent - there is a 'simpleFrom' clause which
2565 * takes whereTables into account & a fromClause which doesn't.
2566 *
2567 * logic may have eroded?
2568 *
86538308
EM
2569 * @return array
2570 */
00be9182 2571 public function whereTables() {
6a488035
TO
2572 return $this->_whereTables;
2573 }
2574
2575 /**
100fef9d 2576 * Generate the where clause (used in match contacts and permissions)
6a488035
TO
2577 *
2578 * @param array $params
2579 * @param array $fields
2580 * @param array $tables
77b97be7 2581 * @param $whereTables
77c5b619 2582 * @param bool $strict
6a488035
TO
2583 *
2584 * @return string
6a488035 2585 */
00be9182 2586 public static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
6a488035
TO
2587 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2588 FALSE, $strict
2589 );
2590
2591 $tables = array_merge($query->tables(), $tables);
2592 $whereTables = array_merge($query->whereTables(), $whereTables);
2593
2594 return $query->_whereClause;
2595 }
2596
2597 /**
fe482240 2598 * Create the from clause.
6a488035 2599 *
77c5b619 2600 * @param array $tables
84193f76
CB
2601 * Tables that need to be included in this from clause. If null,
2602 * return mimimal from clause (i.e. civicrm_contact).
77c5b619
TO
2603 * @param array $inner
2604 * Tables that should be inner-joined.
2605 * @param array $right
2606 * Tables that should be right-joined.
77b97be7 2607 * @param bool $primaryLocation
84193f76 2608 * Search on primary location. See note below.
77b97be7 2609 * @param int $mode
84193f76 2610 * Determines search mode based on bitwise MODE_* constants.
b3e1c09d 2611 * @param string|NULL $apiEntity
84193f76
CB
2612 * Determines search mode based on entity by string.
2613 *
2614 * The $primaryLocation flag only seems to be used when
2615 * locationType() has been called. This may be a search option
2616 * exposed, or perhaps it's a "search all details" approach which
2617 * predates decoupling of location types and primary fields?
6a488035 2618 *
6c58f897
CB
2619 * @see https://issues.civicrm.org/jira/browse/CRM-19967
2620 *
a6c01b45
CW
2621 * @return string
2622 * the from clause
6a488035 2623 */
b3e1c09d 2624 public static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1, $apiEntity = NULL) {
6a488035
TO
2625
2626 $from = ' FROM civicrm_contact contact_a';
2627 if (empty($tables)) {
2628 return $from;
2629 }
2630
a7488080 2631 if (!empty($tables['civicrm_worldregion'])) {
be2fb01f 2632 $tables = array_merge(['civicrm_country' => 1], $tables);
6a488035
TO
2633 }
2634
8cc574cf 2635 if ((!empty($tables['civicrm_state_province']) || !empty($tables['civicrm_country']) ||
69078420 2636 CRM_Utils_Array::value('civicrm_county', $tables)) && empty($tables['civicrm_address'])) {
be2fb01f 2637 $tables = array_merge(['civicrm_address' => 1],
6a488035
TO
2638 $tables
2639 );
2640 }
2641
6a488035 2642 // add group_contact and group table is subscription history is present
8cc574cf 2643 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
be2fb01f 2644 $tables = array_merge([
69078420
SL
2645 'civicrm_group' => 1,
2646 'civicrm_group_contact' => 1,
2647 ],
6a488035
TO
2648 $tables
2649 );
2650 }
2651
2652 // to handle table dependencies of components
2653 CRM_Core_Component::tableNames($tables);
efa3a566
DS
2654 // to handle table dependencies of hook injected tables
2655 CRM_Contact_BAO_Query_Hook::singleton()->setTableDependency($tables);
6a488035
TO
2656
2657 //format the table list according to the weight
2658 $info = CRM_Core_TableHierarchy::info();
2659
2660 foreach ($tables as $key => $value) {
2661 $k = 99;
2662 if (strpos($key, '-') !== FALSE) {
2663 $keyArray = explode('-', $key);
2664 $k = CRM_Utils_Array::value('civicrm_' . $keyArray[1], $info, 99);
2665 }
2666 elseif (strpos($key, '_') !== FALSE) {
2667 $keyArray = explode('_', $key);
2668 if (is_numeric(array_pop($keyArray))) {
2669 $k = CRM_Utils_Array::value(implode('_', $keyArray), $info, 99);
2670 }
2671 else {
2672 $k = CRM_Utils_Array::value($key, $info, 99);
2673 }
2674 }
2675 else {
2676 $k = CRM_Utils_Array::value($key, $info, 99);
2677 }
2678 $tempTable[$k . ".$key"] = $key;
2679 }
2680 ksort($tempTable);
be2fb01f 2681 $newTables = [];
6a488035
TO
2682 foreach ($tempTable as $key) {
2683 $newTables[$key] = $tables[$key];
2684 }
2685
2686 $tables = $newTables;
2687
2688 foreach ($tables as $name => $value) {
2689 if (!$value) {
2690 continue;
2691 }
2692
a7488080 2693 if (!empty($inner[$name])) {
6a488035
TO
2694 $side = 'INNER';
2695 }
a7488080 2696 elseif (!empty($right[$name])) {
6a488035
TO
2697 $side = 'RIGHT';
2698 }
2699 else {
2700 $side = 'LEFT';
2701 }
2702
2703 if ($value != 1) {
2704 // if there is already a join statement in value, use value itself
2705 if (strpos($value, 'JOIN')) {
2706 $from .= " $value ";
2707 }
2708 else {
2709 $from .= " $side JOIN $name ON ( $value ) ";
2710 }
2711 continue;
2712 }
0606198b 2713
ccd8e56f 2714 $from .= ' ' . trim(self::getEntitySpecificJoins($name, $mode, $side, $primaryLocation)) . ' ';
af023bf8
EE
2715 }
2716 return $from;
2717 }
6a488035 2718
af023bf8
EE
2719 /**
2720 * Get join statements for the from clause depending on entity type
2721 *
2722 * @param string $name
2723 * @param int $mode
2724 * @param string $side
2725 * @param string $primaryLocation
2726 * @return string
2727 */
2728 protected static function getEntitySpecificJoins($name, $mode, $side, $primaryLocation) {
2729 $limitToPrimaryClause = $primaryLocation ? "AND {$name}.is_primary = 1" : '';
2730 switch ($name) {
2731 case 'civicrm_address':
2732 //CRM-14263 further handling of address joins further down...
2733 return " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id {$limitToPrimaryClause} )";
6a488035 2734
7f594311 2735 case 'civicrm_state_province':
2736 // This is encountered when doing an export after having applied a 'sort' - it pretty much implies primary
2737 // but that will have been implied-in by the calling function.
2738 // test cover in testContactIDQuery
2739 return " $side JOIN civicrm_state_province ON ( civicrm_address.state_province_id = civicrm_state_province.id )";
2740
2741 case 'civicrm_country':
2742 // This is encountered when doing an export after having applied a 'sort' - it pretty much implies primary
2743 // but that will have been implied-in by the calling function.
2744 // test cover in testContactIDQuery
2745 return " $side JOIN civicrm_country ON ( civicrm_address.country_id = civicrm_country.id )";
2746
af023bf8
EE
2747 case 'civicrm_phone':
2748 return " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id {$limitToPrimaryClause}) ";
6a488035 2749
af023bf8
EE
2750 case 'civicrm_email':
2751 return " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id {$limitToPrimaryClause})";
6a488035 2752
af023bf8
EE
2753 case 'civicrm_im':
2754 return " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id {$limitToPrimaryClause}) ";
6a488035 2755
af023bf8
EE
2756 case 'im_provider':
2757 $from = " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2758 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2759 $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)";
2760 return $from;
6a488035 2761
af023bf8
EE
2762 case 'civicrm_openid':
2763 return " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id {$limitToPrimaryClause} )";
6a488035 2764
af023bf8 2765 case 'civicrm_worldregion':
7f594311 2766 // We can be sure from the calling function that country will already be joined in.
2767 // we really don't need world_region - we could use a pseudoconstant for it.
c156762a 2768 return " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
0cd50623 2769
af023bf8
EE
2770 case 'civicrm_location_type':
2771 return " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
6a488035 2772
af023bf8
EE
2773 case 'civicrm_group':
2774 return " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
6a488035 2775
af023bf8
EE
2776 case 'civicrm_group_contact':
2777 return " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
6a488035 2778
af023bf8
EE
2779 case 'civicrm_group_contact_cache':
2780 return " $side JOIN civicrm_group_contact_cache ON contact_a.id = civicrm_group_contact_cache.contact_id ";
6a488035 2781
af023bf8
EE
2782 case 'civicrm_activity':
2783 case 'civicrm_activity_tag':
2784 case 'activity_type':
2785 case 'activity_status':
2786 case 'parent_id':
2787 case 'civicrm_activity_contact':
2788 case 'source_contact':
2789 case 'activity_priority':
2790 return CRM_Activity_BAO_Query::from($name, $mode, $side);
2791
2792 case 'civicrm_entity_tag':
2793 $from = " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact'";
2794 return "$from AND civicrm_entity_tag.entity_id = contact_a.id ) ";
2795
2796 case 'civicrm_note':
2797 $from = " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact'";
2798 return "$from AND contact_a.id = civicrm_note.entity_id ) ";
2799
2800 case 'civicrm_subscription_history':
2801 $from = " $side JOIN civicrm_subscription_history";
2802 $from .= " ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id";
2803 return "$from AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2804
2805 case 'civicrm_relationship':
2806 if (self::$_relType == 'reciprocal') {
2807 if (self::$_relationshipTempTable) {
2808 // we have a temptable to join on
2809 $tbl = self::$_relationshipTempTable;
2810 return " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
6a488035
TO
2811 }
2812 else {
af023bf8
EE
2813 $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2814 $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)";
2815 return $from;
6a488035 2816 }
af023bf8
EE
2817 }
2818 elseif (self::$_relType == 'b') {
2819 $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2820 return "$from $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2821 }
2822 else {
2823 $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2824 return "$from $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2825 }
6a488035 2826
af023bf8
EE
2827 case 'civicrm_log':
2828 $from = " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2829 return "$from INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
6a488035 2830
af023bf8
EE
2831 case 'civicrm_tag':
2832 return " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
6a488035 2833
af023bf8
EE
2834 case 'civicrm_grant':
2835 return CRM_Grant_BAO_Query::from($name, $mode, $side);
6a488035 2836
af023bf8
EE
2837 case 'civicrm_website':
2838 return " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
7851dc81 2839
af023bf8
EE
2840 case 'civicrm_campaign':
2841 //Move to default case if not in either mode.
2842 if ($mode & CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
2843 return CRM_Contribute_BAO_Query::from($name, $mode, $side);
2844 }
2845 elseif ($mode & CRM_Contact_BAO_Query::MODE_MAILING) {
2846 return CRM_Mailing_BAO_Query::from($name, $mode, $side);
2847 }
2848 elseif ($mode & CRM_Contact_BAO_Query::MODE_CAMPAIGN) {
2849 return CRM_Campaign_BAO_Query::from($name, $mode, $side);
2850 }
6a488035 2851
af023bf8
EE
2852 default:
2853 $locationTypeName = '';
2854 if (strpos($name, '-address') != 0) {
2855 $locationTypeName = 'address';
2856 }
2857 elseif (strpos($name, '-phone') != 0) {
2858 $locationTypeName = 'phone';
2859 }
2860 elseif (strpos($name, '-email') != 0) {
2861 $locationTypeName = 'email';
2862 }
2863 elseif (strpos($name, '-im') != 0) {
2864 $locationTypeName = 'im';
2865 }
2866 elseif (strpos($name, '-openid') != 0) {
2867 $locationTypeName = 'openid';
2868 }
7cc09daf 2869
af023bf8
EE
2870 if ($locationTypeName) {
2871 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2872 $parts = explode('-', $name);
2873 $locationTypes = CRM_Core_DAO_Address::buildOptions('location_type_id', 'validate');
2874 foreach ($locationTypes as $locationTypeID => $locationType) {
2875 if ($parts[0] == str_replace(' ', '_', $locationType)) {
2876 $locationID = $locationTypeID;
140e25ee 2877 }
e5fccefb 2878 }
af023bf8
EE
2879 $from = " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2880 }
2881 else {
2882 $from = CRM_Core_Component::from($name, $mode, $side);
2883 }
2884 $from .= CRM_Contact_BAO_Query_Hook::singleton()->buildSearchfrom($name, $mode, $side);
99e9587a 2885
af023bf8 2886 return $from;
6a488035 2887 }
6a488035
TO
2888 }
2889
2890 /**
2891 * WHERE / QILL clause for deleted_contacts
2892 *
c037736a 2893 * @param array $values
6a488035 2894 */
00be9182 2895 public function deletedContacts($values) {
6a488035
TO
2896 list($_, $_, $value, $grouping, $_) = $values;
2897 if ($value) {
2898 // *prepend* to the relevant grouping as this is quite an important factor
2899 array_unshift($this->_qill[$grouping], ts('Search in Trash'));
2900 }
2901 }
2902
2903 /**
100fef9d 2904 * Where / qill clause for contact_type
6a488035 2905 *
77b97be7 2906 * @param $values
6a488035 2907 */
00be9182 2908 public function contactType(&$values) {
6a488035
TO
2909 list($name, $op, $value, $grouping, $wildcard) = $values;
2910
be2fb01f
CW
2911 $subTypes = [];
2912 $clause = [];
6a488035
TO
2913
2914 // account for search builder mapping multiple values
2915 if (!is_array($value)) {
2916 $values = self::parseSearchBuilderString($value, 'String');
2917 if (is_array($values)) {
2918 $value = array_flip($values);
2919 }
2920 }
2921
2922 if (is_array($value)) {
2923 foreach ($value as $k => $v) {
2924 // fix for CRM-771
2925 if ($k) {
2926 $subType = NULL;
2927 $contactType = $k;
2928 if (strpos($k, CRM_Core_DAO::VALUE_SEPARATOR)) {
2929 list($contactType, $subType) = explode(CRM_Core_DAO::VALUE_SEPARATOR, $k, 2);
2930 }
2931
2932 if (!empty($subType)) {
2933 $subTypes[$subType] = 1;
2934 }
2935 $clause[$contactType] = "'" . CRM_Utils_Type::escape($contactType, 'String') . "'";
2936 }
2937 }
2938 }
2939 else {
2940 $contactTypeANDSubType = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value, 2);
2941 $contactType = $contactTypeANDSubType[0];
2942 $subType = CRM_Utils_Array::value(1, $contactTypeANDSubType);
2943 if (!empty($subType)) {
2944 $subTypes[$subType] = 1;
2945 }
2946 $clause[$contactType] = "'" . CRM_Utils_Type::escape($contactType, 'String') . "'";
2947 }
2948
2949 // fix for CRM-771
2950 if (!empty($clause)) {
c33e01a5 2951 $quill = $clause;
3b3bc827
CW
2952 if ($op == 'IN' || $op == 'NOT IN') {
2953 $this->_where[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2954 }
2955 else {
2956 $type = array_pop($clause);
dbc6f6d6 2957 $this->_where[$grouping][] = self::buildClause("contact_a.contact_type", $op, $contactType);
3b3bc827 2958 }
d4b81b9a 2959
aa3c3360 2960 $this->_qill[$grouping][] = ts('Contact Type') . " $op " . implode(' ' . ts('or') . ' ', $quill);
6a488035
TO
2961
2962 if (!empty($subTypes)) {
2963 $this->includeContactSubTypes($subTypes, $grouping);
2964 }
2965 }
2966 }
2967
2968 /**
8f165fa5 2969 * Where / qill clause for contact_sub_type.
6a488035 2970 *
8f165fa5 2971 * @param array $values
6a488035 2972 */
00be9182 2973 public function contactSubType(&$values) {
6a488035 2974 list($name, $op, $value, $grouping, $wildcard) = $values;
1d2bcc81 2975 $this->includeContactSubTypes($value, $grouping, $op);
6a488035
TO
2976 }
2977
86538308
EM
2978 /**
2979 * @param $value
2980 * @param $grouping
0e2e76cf 2981 * @param string $op
86538308 2982 */
00be9182 2983 public function includeContactSubTypes($value, $grouping, $op = 'LIKE') {
6a488035 2984
e9fd1f48 2985 if (is_array($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
2986 $op = key($value);
2987 $value = $value[$op];
2988 }
2989
be2fb01f 2990 $clause = [];
6a488035 2991 $alias = "contact_a.contact_sub_type";
46b3417a 2992 $qillOperators = CRM_Core_SelectValues::getSearchBuilderOperators();
6a488035 2993
1d2bcc81 2994 $op = str_replace('IN', 'LIKE', $op);
ccc79dfc 2995 $op = str_replace('=', 'LIKE', $op);
2996 $op = str_replace('!', 'NOT ', $op);
1d2bcc81 2997
2998 if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) {
2999 $this->_where[$grouping][] = self::buildClause($alias, $op, $value, 'String');
3000 }
4c9b6178 3001 elseif (is_array($value)) {
6a488035 3002 foreach ($value as $k => $v) {
35fbf8a2 3003 $clause[$k] = "($alias $op '%" . CRM_Core_DAO::VALUE_SEPARATOR . CRM_Utils_Type::escape($v, 'String') . CRM_Core_DAO::VALUE_SEPARATOR . "%')";
6a488035
TO
3004 }
3005 }
3006 else {
1d2bcc81 3007 $clause[$value] = "($alias $op '%" . CRM_Core_DAO::VALUE_SEPARATOR . CRM_Utils_Type::escape($value, 'String') . CRM_Core_DAO::VALUE_SEPARATOR . "%')";
6a488035
TO
3008 }
3009
3010 if (!empty($clause)) {
3011 $this->_where[$grouping][] = "( " . implode(' OR ', $clause) . " )";
6a488035 3012 }
be2fb01f 3013 $this->_qill[$grouping][] = ts('Contact Subtype %1 ', [1 => $qillOperators[$op]]) . implode(' ' . ts('or') . ' ', array_keys($clause));
6a488035
TO
3014 }
3015
3016 /**
c3137c08 3017 * Where / qill clause for groups.
6a488035 3018 *
77b97be7 3019 * @param $values
0d38cb6d 3020 *
3021 * @throws \CRM_Core_Exception
6a488035 3022 */
c3137c08 3023 public function group($values) {
6a488035
TO
3024 list($name, $op, $value, $grouping, $wildcard) = $values;
3025
ca91bd7f 3026 // If the $value is in OK (operator as key) array format we need to extract the key as operator and value first
3027 if (is_array($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
3028 $op = key($value);
3029 $value = $value[$op];
3030 }
673fae6c 3031 // Translate EMPTY to NULL as EMPTY is cannot be used in it's intended meaning here
3032 // so has to be 'squashed into' NULL. (ie. group membership cannot be '').
3033 // even one group might equate to multiple when looking at children so IN is simpler.
3034 // @todo - also look at != casting but there are rows below to review.
3035 $opReplacements = [
3036 'EMPTY' => 'NULL',
3037 'NOT EMPTY' => 'NOT NULL',
3038 '=' => 'IN',
3039 ];
3040 if (isset($opReplacements[$op])) {
3041 $op = $opReplacements[$op];
3042 }
e8401ae2 3043
ca91bd7f 3044 if (strpos($op, 'NULL')) {
3045 $value = NULL;
3046 }
3047
0d71d885 3048 if (is_array($value) && count($value) > 1) {
e8401ae2 3049 if (strpos($op, 'IN') === FALSE && strpos($op, 'NULL') === FALSE) {
be2fb01f 3050 CRM_Core_Error::fatal(ts("%1 is not a valid operator", [1 => $op]));
e8401ae2 3051 }
6a488035
TO
3052 $this->_useDistinct = TRUE;
3053 }
3054
7cc09daf 3055 if (isset($value)) {
3056 $value = CRM_Utils_Array::value($op, $value, $value);
3057 }
3058
d412bcca 3059 if ($name == 'group_type') {
3060 $value = array_keys($this->getGroupsFromTypeCriteria($value));
3061 }
3062
be2fb01f 3063 $regularGroupIDs = $smartGroupIDs = [];
181962cf 3064 foreach ((array) $value as $id) {
3065 if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
6c5056ec 3066 $smartGroupIDs[] = (int) $id;
181962cf 3067 }
3068 else {
6c5056ec 3069 $regularGroupIDs[] = (int) trim($id);
181962cf 3070 }
3071 }
d7570a7f 3072 $hasNonSmartGroups = count($regularGroupIDs);
c3137c08 3073
e8401ae2 3074 $isNotOp = ($op == 'NOT IN' || $op == '!=');
d79d2a59 3075
d7570a7f 3076 $statusJoinClause = $this->getGroupStatusClause($grouping);
0d38cb6d 3077 // If we are searching for 'Removed' contacts then despite it being a smart group we only care about the group_contact table.
3078 $isGroupStatusSearch = (!empty($this->getSelectedGroupStatuses($grouping)) && $this->getSelectedGroupStatuses($grouping) !== ["'Added'"]);
be2fb01f 3079 $groupClause = [];
0d38cb6d 3080 if ($hasNonSmartGroups || empty($value) || $isGroupStatusSearch) {
783144b0 3081 // include child groups IDs if any
3082 $childGroupIds = (array) CRM_Contact_BAO_Group::getChildGroupIds($regularGroupIDs);
3083 foreach ($childGroupIds as $key => $id) {
3084 if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
3085 $smartGroupIDs[] = $id;
3086 unset($childGroupIds[$key]);
3087 }
3088 }
3089 if (count($childGroupIds)) {
3090 $regularGroupIDs = array_merge($regularGroupIDs, $childGroupIds);
3091 }
3092
9ca472a1 3093 if (empty($regularGroupIDs)) {
0d38cb6d 3094 if ($isGroupStatusSearch) {
3095 $regularGroupIDs = $smartGroupIDs;
3096 }
3097 // If it is still empty we want a filter that blocks all results.
3098 if (empty($regularGroupIDs)) {
3099 $regularGroupIDs = [0];
3100 }
9ca472a1
PN
3101 }
3102
f30aa754 3103 $gcTable = "`civicrm_group_contact-" . uniqid() . "`";
be2fb01f 3104 $joinClause = ["contact_a.id = {$gcTable}.contact_id"];
783144b0 3105
6c5056ec
PN
3106 // @todo consider just casting != to NOT IN & handling both together.
3107 if ($op == '!=') {
3108 $groupIds = '';
3109 if (!empty($regularGroupIDs)) {
3110 $groupIds = CRM_Utils_Type::validate(
3111 implode(',', (array) $regularGroupIDs),
3112 'CommaSeparatedIntegers'
3113 );
3114 }
783144b0 3115 $clause = "{$gcTable}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact cgc WHERE cgc.group_id = $groupIds )";
c112a6f9 3116 }
3117 else {
673fae6c 3118 $clause = self::buildClause("{$gcTable}.group_id", $op, $regularGroupIDs);
c112a6f9 3119 }
783144b0 3120 $groupClause[] = "( {$clause} )";
6a488035 3121
d7570a7f 3122 if ($statusJoinClause) {
3123 $joinClause[] = "{$gcTable}.$statusJoinClause";
6a488035 3124 }
783144b0 3125 $this->_tables[$gcTable] = $this->_whereTables[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
6a488035
TO
3126 }
3127
181962cf 3128 //CRM-19589: contact(s) removed from a Smart Group, resides in civicrm_group_contact table
0d38cb6d 3129 // If we are only searching for Removed or Pending contacts we don't need to resolve the smart group
3130 // as that info is in the group_contact table.
3131 if ((count($smartGroupIDs) || empty($value)) && !$isGroupStatusSearch) {
ed17b5e2 3132 $this->_groupUniqueKey = uniqid();
e24f9388 3133 $this->_groupKeys[] = $this->_groupUniqueKey;
ed17b5e2 3134 $gccTableAlias = "civicrm_group_contact_cache_{$this->_groupUniqueKey}";
9f6a1556 3135 $groupContactCacheClause = $this->addGroupContactCache($smartGroupIDs, $gccTableAlias, "contact_a", $op);
6451118c 3136 if (!empty($groupContactCacheClause)) {
9f6a1556
JP
3137 if ($isNotOp) {
3138 $groupIds = implode(',', (array) $smartGroupIDs);
ed17b5e2 3139 $gcTable = "civicrm_group_contact_{$this->_groupUniqueKey}";
be2fb01f 3140 $joinClause = ["contact_a.id = {$gcTable}.contact_id"];
9f6a1556
JP
3141 $this->_tables[$gcTable] = $this->_whereTables[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
3142 if (strpos($op, 'IN') !== FALSE) {
3143 $groupClause[] = "{$gcTable}.group_id $op ( $groupIds ) AND {$gccTableAlias}.group_id IS NULL";
3144 }
3145 else {
3146 $groupClause[] = "{$gcTable}.group_id $op $groupIds AND {$gccTableAlias}.group_id IS NULL";
3147 }
3148 }
6451118c
JP
3149 $groupClause[] = " ( {$groupContactCacheClause} ) ";
3150 }
6a488035
TO
3151 }
3152
883e1e76 3153 $and = ($op == 'IS NULL') ? ' AND ' : ' OR ';
6451118c
JP
3154 if (!empty($groupClause)) {
3155 $this->_where[$grouping][] = ' ( ' . implode($and, $groupClause) . ' ) ';
3156 }
181962cf 3157
e8401ae2 3158 list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contact_DAO_Group', 'id', $value, $op);
be2fb01f 3159 $this->_qill[$grouping][] = ts("Group(s) %1 %2", [1 => $qillop, 2 => $qillVal]);
0cd50623 3160 if (strpos($op, 'NULL') === FALSE) {
d7570a7f 3161 $this->_qill[$grouping][] = ts("Group Status %1", [1 => implode(' ' . ts('or') . ' ', $this->getSelectedGroupStatuses($grouping))]);
0cd50623 3162 }
6a488035 3163 }
d424ffde 3164
e24f9388
SL
3165 public function getGroupCacheTableKeys() {
3166 return $this->_groupKeys;
ed17b5e2
SL
3167 }
3168
86538308 3169 /**
fe482240 3170 * Function translates selection of group type into a list of groups.
86538308
EM
3171 * @param $value
3172 *
3173 * @return array
3174 */
5c7dad85 3175 public function getGroupsFromTypeCriteria($value) {
be2fb01f 3176 $groupIds = [];
d79d2a59 3177 foreach ((array) $value as $groupTypeValue) {
6a488035
TO
3178 $groupList = CRM_Core_PseudoConstant::group($groupTypeValue);
3179 $groupIds = ($groupIds + $groupList);
3180 }
3181 return $groupIds;
3182 }
3183
e6b676a0 3184 /**
72a2eeab
AS
3185 * Prime smart group cache for smart groups in the search, and join
3186 * civicrm_group_contact_cache table into the query.
3187 *
3188 * @param array $groups IDs of groups specified in search criteria.
3189 * @param string $tableAlias Alias to use for civicrm_group_contact_cache table.
3190 * @param string $joinTable Table on which to join civicrm_group_contact_cache
3191 * @param string $op SQL comparison operator (NULL, IN, !=, IS NULL, etc.)
3192 * @param string $joinColumn Column in $joinTable on which to join civicrm_group_contact_cache.contact_id
e6b676a0 3193 *
72a2eeab 3194 * @return string WHERE clause component for smart group criteria.
e6b676a0 3195 */
f30aa754 3196 public function addGroupContactCache($groups, $tableAlias, $joinTable = "contact_a", $op, $joinColumn = 'id') {
e8401ae2 3197 $isNullOp = (strpos($op, 'NULL') !== FALSE);
3198 $groupsIds = $groups;
6451118c
JP
3199
3200 $operator = ['=' => 'IN', '!=' => 'NOT IN'];
3201 if (!empty($operator[$op]) && is_array($groups)) {
3202 $op = $operator[$op];
3203 }
e8401ae2 3204 if (!$isNullOp && !$groups) {
6a488035
TO
3205 return NULL;
3206 }
e8401ae2 3207 elseif (strpos($op, 'IN') !== FALSE) {
be2fb01f 3208 $groups = [$op => $groups];
e8401ae2 3209 }
d4ed6fbd 3210 elseif (is_array($groups) && count($groups)) {
be2fb01f 3211 $groups = ['IN' => $groups];
d4ed6fbd 3212 }
6a488035 3213
e8401ae2 3214 // Find all the groups that are part of a saved search.
3215 $smartGroupClause = self::buildClause("id", $op, $groups, 'Int');
6a488035
TO
3216 $sql = "
3217SELECT id, cache_date, saved_search_id, children
3218FROM civicrm_group
e8401ae2 3219WHERE $smartGroupClause
6a488035
TO
3220 AND ( saved_search_id != 0
3221 OR saved_search_id IS NOT NULL
3222 OR children IS NOT NULL )
3223";
e6b676a0 3224
5c7dad85 3225 $group = CRM_Core_DAO::executeQuery($sql);
e6b676a0 3226
6a488035 3227 while ($group->fetch()) {
6a488035 3228 $this->_useDistinct = TRUE;
6a488035
TO
3229 if (!$this->_smartGroupCache || $group->cache_date == NULL) {
3230 CRM_Contact_BAO_GroupContactCache::load($group);
3231 }
6a488035 3232 }
9f6a1556 3233 if ($group->N == 0 && $op != 'NOT IN') {
485a3a1f 3234 return NULL;
3235 }
6a488035 3236
72a2eeab 3237 $this->_tables[$tableAlias] = $this->_whereTables[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache {$tableAlias} ON {$joinTable}.{$joinColumn} = {$tableAlias}.contact_id ";
9f6a1556
JP
3238
3239 if ($op == 'NOT IN') {
3240 return "{$tableAlias}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact_cache cgcc WHERE cgcc.group_id IN ( " . implode(',', (array) $groupsIds) . " ) )";
3241 }
e8401ae2 3242 return self::buildClause("{$tableAlias}.group_id", $op, $groups, 'Int');
6a488035
TO
3243 }
3244
3245 /**
100fef9d 3246 * Where / qill clause for cms users
6a488035 3247 *
77b97be7 3248 * @param $values
6a488035 3249 */
00be9182 3250 public function ufUser(&$values) {
6a488035
TO
3251 list($name, $op, $value, $grouping, $wildcard) = $values;
3252
3253 if ($value == 1) {
3254 $this->_tables['civicrm_uf_match'] = $this->_whereTables['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3255
3256 $this->_qill[$grouping][] = ts('CMS User');
3257 }
3258 elseif ($value == 0) {
3259 $this->_tables['civicrm_uf_match'] = $this->_whereTables['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3260
3261 $this->_where[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
3262 $this->_qill[$grouping][] = ts('Not a CMS User');
3263 }
3264 }
3265
3266 /**
fe482240 3267 * All tag search specific.
6a488035 3268 *
c037736a 3269 * @param array $values
6a488035 3270 */
00be9182 3271 public function tagSearch(&$values) {
6a488035
TO
3272 list($name, $op, $value, $grouping, $wildcard) = $values;
3273
3274 $op = "LIKE";
3275 $value = "%{$value}%";
0cf0a3f3 3276 $escapedValue = CRM_Utils_Type::escape("%{$value}%", 'String');
6a488035 3277
6a488035
TO
3278 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3279 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3280
394643b9
PF
3281 $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
3282 $tTable = "`civicrm_tag-" . uniqid() . "`";
6a488035
TO
3283
3284 if ($useAllTagTypes[2]) {
59f4c9ee
TO
3285 $this->_tables[$etTable] = $this->_whereTables[$etTable]
3286 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
3287 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
6a488035
TO
3288
3289 // search tag in cases
394643b9
PF
3290 $etCaseTable = "`civicrm_entity_case_tag-" . uniqid() . "`";
3291 $tCaseTable = "`civicrm_case_tag-" . uniqid() . "`";
59f4c9ee
TO
3292 $this->_tables[$etCaseTable] = $this->_whereTables[$etCaseTable]
3293 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3294 LEFT JOIN civicrm_case
6a488035
TO
3295 ON (civicrm_case_contact.case_id = civicrm_case.id
3296 AND civicrm_case.is_deleted = 0 )
59f4c9ee
TO
3297 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
3298 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
6a488035 3299 // search tag in activities
394643b9
PF
3300 $etActTable = "`civicrm_entity_act_tag-" . uniqid() . "`";
3301 $tActTable = "`civicrm_act_tag-" . uniqid() . "`";
44f817d4 3302 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
9e74e3ce 3303 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1071730c 3304
59f4c9ee
TO
3305 $this->_tables[$etActTable] = $this->_whereTables[$etActTable]
3306 = " LEFT JOIN civicrm_activity_contact
9e74e3ce 3307 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
59f4c9ee 3308 LEFT JOIN civicrm_activity
91da6cd5 3309 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
6a488035 3310 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
59f4c9ee
TO
3311 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
3312 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
6a488035 3313
0cf0a3f3 3314 $this->_where[$grouping][] = "({$tTable}.name $op '" . $escapedValue . "' OR {$tCaseTable}.name $op '" . $escapedValue . "' OR {$tActTable}.name $op '" . $escapedValue . "')";
be2fb01f 3315 $this->_qill[$grouping][] = ts('Tag %1 %2', [1 => $tagTypesText[2], 2 => $op]) . ' ' . $value;
5c7dad85
TO
3316 }
3317 else {
394643b9
PF
3318 $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
3319 $tTable = "`civicrm_tag-" . uniqid() . "`";
6a488035
TO
3320 $this->_tables[$etTable] = $this->_whereTables[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
3321 {$etTable}.entity_table = 'civicrm_contact' )
3322 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
3323
3324 $this->_where[$grouping][] = self::buildClause("{$tTable}.name", $op, $value, 'String');
be2fb01f 3325 $this->_qill[$grouping][] = ts('Tagged %1', [1 => $op]) . ' ' . $value;
6a488035
TO
3326 }
3327 }
3328
3329 /**
8f165fa5 3330 * Where / qill clause for tag.
6a488035 3331 *
c037736a 3332 * @param array $values
6a488035 3333 */
00be9182 3334 public function tag(&$values) {
6a488035
TO
3335 list($name, $op, $value, $grouping, $wildcard) = $values;
3336
be2fb01f 3337 list($qillop, $qillVal) = self::buildQillForFieldValue('CRM_Core_DAO_EntityTag', "tag_id", $value, $op, ['onlyActive' => FALSE]);
7cc09daf 3338 // API/Search Builder format array(operator => array(values))
6a488035 3339 if (is_array($value)) {
7cc09daf 3340 if (in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
3341 $op = key($value);
3342 $value = $value[$op];
3343 }
6a488035
TO
3344 if (count($value) > 1) {
3345 $this->_useDistinct = TRUE;
3346 }
6a488035
TO
3347 }
3348
f2ec9ca7
PF
3349 // implode array, then remove all spaces
3350 $value = str_replace(' ', '', implode(',', (array) $value));
3351 if (!empty($value)) {
3352 $value = CRM_Utils_Type::validate(
3353 $value,
3354 'CommaSeparatedIntegers'
3355 );
3356 }
0cf0a3f3 3357
6a488035
TO
3358 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3359 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3360
394643b9 3361 $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
6a488035
TO
3362
3363 if ($useAllTagTypes[2]) {
59f4c9ee
TO
3364 $this->_tables[$etTable] = $this->_whereTables[$etTable]
3365 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
6a488035
TO
3366
3367 // search tag in cases
394643b9 3368 $etCaseTable = "`civicrm_entity_case_tag-" . uniqid() . "`";
44f817d4 3369 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
9e74e3ce 3370 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
3371
59f4c9ee
TO
3372 $this->_tables[$etCaseTable] = $this->_whereTables[$etCaseTable]
3373 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3374 LEFT JOIN civicrm_case
6a488035
TO
3375 ON (civicrm_case_contact.case_id = civicrm_case.id
3376 AND civicrm_case.is_deleted = 0 )
59f4c9ee 3377 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
6a488035 3378 // search tag in activities
394643b9 3379 $etActTable = "`civicrm_entity_act_tag-" . uniqid() . "`";
59f4c9ee
TO
3380 $this->_tables[$etActTable] = $this->_whereTables[$etActTable]
3381 = " LEFT JOIN civicrm_activity_contact
9e74e3ce 3382 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
59f4c9ee 3383 LEFT JOIN civicrm_activity
91da6cd5 3384 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
6a488035 3385 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
59f4c9ee 3386 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
6a488035
TO
3387
3388 // CRM-10338
be2fb01f 3389 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
6a488035
TO
3390 $this->_where[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3391 }
3392 else {
5c7dad85 3393 $this->_where[$grouping][] = "({$etTable}.tag_id $op (" . $value . ") OR {$etCaseTable}.tag_id $op (" . $value . ") OR {$etActTable}.tag_id $op (" . $value . "))";
6a488035 3394 }
5c7dad85
TO
3395 }
3396 else {
59f4c9ee
TO
3397 $this->_tables[$etTable] = $this->_whereTables[$etTable]
3398 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
6a488035
TO
3399
3400 // CRM-10338
be2fb01f 3401 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
6a488035
TO
3402 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3403 $op = str_replace('EMPTY', 'NULL', $op);
3404 $this->_where[$grouping][] = "{$etTable}.tag_id $op";
3405 }
c112a6f9 3406 // CRM-16941: for tag tried with != operator we don't show contact who don't have given $value AND also in other tag
3407 elseif ($op == '!=') {
3408 $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') . ")";
3409 }
3410 elseif ($op == '=' || strstr($op, 'IN')) {
3411 $op = ($op == '=') ? 'IN' : $op;
3412 $this->_where[$grouping][] = "{$etTable}.tag_id $op ( $value )";
6a488035 3413 }
6a488035 3414 }
be2fb01f 3415 $this->_qill[$grouping][] = ts('Tagged %1 %2', [1 => $qillop, 2 => $qillVal]);
6a488035
TO
3416 }
3417
3418 /**
100fef9d 3419 * Where/qill clause for notes
6a488035 3420 *
c037736a 3421 * @param array $values
6a488035 3422 */
00be9182 3423 public function notes(&$values) {
6a488035
TO
3424 list($name, $op, $value, $grouping, $wildcard) = $values;
3425
3426 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3427 $noteOption = CRM_Utils_Array::value('2', $noteOptionValues, '6');
3428 $noteOption = ($name == 'note_body') ? 2 : (($name == 'note_subject') ? 3 : $noteOption);
3429
3430 $this->_useDistinct = TRUE;
3431
59f4c9ee
TO
3432 $this->_tables['civicrm_note'] = $this->_whereTables['civicrm_note']
3433 = " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
6a488035 3434
6a488035 3435 $n = trim($value);
2fc64082 3436 $value = CRM_Core_DAO::escapeString($n);
05d214de 3437 if ($wildcard) {
6a488035
TO
3438 if (strpos($value, '%') === FALSE) {
3439 $value = "%$value%";
3440 }
3441 $op = 'LIKE';
3442 }
3443 elseif ($op == 'IS NULL' || $op == 'IS NOT NULL') {
3444 $value = NULL;
3445 }
3446
3447 $label = NULL;
be2fb01f 3448 $clauses = [];
5c7dad85 3449 if ($noteOption % 2 == 0) {
6a488035
TO
3450 $clauses[] = self::buildClause('civicrm_note.note', $op, $value, 'String');
3451 $label = ts('Note: Body Only');
3452 }
5c7dad85 3453 if ($noteOption % 3 == 0) {
6a488035
TO
3454 $clauses[] = self::buildClause('civicrm_note.subject', $op, $value, 'String');
3455 $label = $label ? ts('Note: Body and Subject') : ts('Note: Subject Only');
3456 }
3457 $this->_where[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
05d214de 3458 list($qillOp, $qillVal) = self::buildQillForFieldValue(NULL, $name, $n, $op);
be2fb01f 3459 $this->_qill[$grouping][] = ts("%1 %2 %3", [1 => $label, 2 => $qillOp, 3 => $qillVal]);
6a488035
TO
3460 }
3461
86538308 3462 /**
100fef9d 3463 * @param string $name
86538308
EM
3464 * @param $op
3465 * @param $grouping
3466 *
3467 * @return bool
3468 */
00be9182 3469 public function nameNullOrEmptyOp($name, $op, $grouping) {
5c7dad85 3470 switch ($op) {
6a488035
TO
3471 case 'IS NULL':
3472 case 'IS NOT NULL':
3473 $this->_where[$grouping][] = "contact_a.$name $op";
3474 $this->_qill[$grouping][] = ts('Name') . ' ' . $op;
5c7dad85 3475 return TRUE;
6a488035
TO
3476
3477 case 'IS EMPTY':
3478 $this->_where[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3479 $this->_qill[$grouping][] = ts('Name') . ' ' . $op;
5c7dad85 3480 return TRUE;
6a488035
TO
3481
3482 case 'IS NOT EMPTY':
3483 $this->_where[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3484 $this->_qill[$grouping][] = ts('Name') . ' ' . $op;
5c7dad85 3485 return TRUE;
6a488035
TO
3486
3487 default:
5c7dad85 3488 return FALSE;
6a488035
TO
3489 }
3490 }
3491
3492 /**
100fef9d 3493 * Where / qill clause for sort_name
6a488035 3494 *
c037736a 3495 * @param array $values
6a488035 3496 */
00be9182 3497 public function sortName(&$values) {
fd816db5 3498 list($fieldName, $op, $value, $grouping, $wildcard) = $values;
6a488035
TO
3499
3500 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
fd816db5 3501 if ($this->nameNullOrEmptyOp($fieldName, $op, $grouping)) {
6a488035
TO
3502 return;
3503 }
3504
359fdb6f 3505 $input = $value = is_array($value) ? trim($value['LIKE']) : trim($value);
6a488035 3506
fd816db5 3507 if (!strlen($value)) {
6a488035
TO
3508 return;
3509 }
3510
3511 $config = CRM_Core_Config::singleton();
3512
be2fb01f 3513 $sub = [];
6a488035
TO
3514
3515 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3516 $subGlue = ' OR ';
3517
fd816db5
CW
3518 $firstChar = substr($value, 0, 1);
3519 $lastChar = substr($value, -1, 1);
be2fb01f 3520 $quotes = ["'", '"'];
fd816db5
CW
3521 // If string is quoted, strip quotes and otherwise don't alter it
3522 if ((strlen($value) > 2) && in_array($firstChar, $quotes) && in_array($lastChar, $quotes)) {
3523 $value = trim($value, implode('', $quotes));
3524 }
3525 // Replace spaces with wildcards for a LIKE operation
3526 // UNLESS string contains a comma (this exception is a tiny bit questionable)
3527 elseif ($op == 'LIKE' && strpos($value, ',') === FALSE) {
3528 $value = str_replace(' ', '%', $value);
3529 }
9436d5d5 3530 $value = CRM_Core_DAO::escapeString(trim($value));
fd816db5 3531 if (strlen($value)) {
be2fb01f 3532 $fieldsub = [];
0b38e8f1 3533 $value = "'" . self::getWildCardedValue($wildcard, $op, $value) . "'";
fd816db5 3534 if ($fieldName == 'sort_name') {
9436d5d5 3535 $wc = "contact_a.sort_name";
6a488035
TO
3536 }
3537 else {
9436d5d5 3538 $wc = "contact_a.display_name";
6a488035 3539 }
fd816db5 3540 $fieldsub[] = " ( $wc $op $value )";
6a488035 3541 if ($config->includeNickNameInName) {
9436d5d5 3542 $wc = "contact_a.nick_name";
fd816db5 3543 $fieldsub[] = " ( $wc $op $value )";
6a488035
TO
3544 }
3545 if ($config->includeEmailInName) {
fd816db5 3546 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
6a488035 3547 }
fd816db5 3548 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
6a488035
TO
3549 }
3550
3551 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3552
3553 $this->_where[$grouping][] = $sub;
3554 if ($config->includeEmailInName) {
3555 $this->_tables['civicrm_email'] = $this->_whereTables['civicrm_email'] = 1;
fd816db5 3556 $this->_qill[$grouping][] = ts('Name or Email') . " $op - '$input'";
6a488035
TO
3557 }
3558 else {
fd816db5 3559 $this->_qill[$grouping][] = ts('Name') . " $op - '$input'";
6a488035
TO
3560 }
3561 }
3562
0e2e76cf 3563 /**
cde2037d 3564 * Where/qill clause for greeting fields.
02adf2f9 3565 *
cd2dfbd7 3566 * @param array $values
02adf2f9 3567 */
0e2e76cf 3568 public function greetings(&$values) {
02adf2f9
BS
3569 list($name, $op, $value, $grouping, $wildcard) = $values;
3570 $name .= '_display';
3571
9b183452 3572 list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(NULL, $name, $value, $op);
be2fb01f 3573 $this->_qill[$grouping][] = ts('Greeting %1 %2', [1 => $qillop, 2 => $qillVal]);
9b183452 3574 $this->_where[$grouping][] = self::buildClause("contact_a.{$name}", $op, $value, 'String');
02adf2f9
BS
3575 }
3576
6a488035 3577 /**
100fef9d 3578 * Where / qill clause for email
6a488035 3579 *
c037736a 3580 * @param array $values
9178793e 3581 * @param string $isForcePrimaryOnly
3582 *
3583 * @throws \CRM_Core_Exception
6a488035 3584 */
9178793e 3585 protected function email(&$values, $isForcePrimaryOnly) {
6a488035 3586 list($name, $op, $value, $grouping, $wildcard) = $values;
11f8e194 3587 $this->_tables['civicrm_email'] = $this->_whereTables['civicrm_email'] = 1;
6a488035 3588
57f8e7f0 3589 // CRM-18147: for Contact's GET API, email fieldname got appended with its entity as in {$apiEntiy}_{$name}
3590 // so following code is use build whereClause for contact's primart email id
9178793e 3591 if (!empty($isForcePrimaryOnly)) {
57f8e7f0 3592 $this->_where[$grouping][] = self::buildClause('civicrm_email.is_primary', '=', 1, 'Integer');
9178793e 3593 }
3594 // @todo - this should come from the $this->_fields array
3595 $dbName = $name === 'email_id' ? 'id' : $name;
3596
3597 if (is_array($value) || $name === 'email_id') {
3598 $this->_qill[$grouping][] = $this->getQillForField($name, $value, $op);
3599 $this->_where[$grouping][] = self::buildClause('civicrm_email.' . $dbName, $op, $value, 'String');
57f8e7f0 3600 return;
3601 }
3602
9178793e 3603 // Is this ever hit now? Ideally ensure always an array & handle above.
c245fd99 3604 $n = trim($value);
6a488035 3605 if ($n) {
6a488035
TO
3606 if (substr($n, 0, 1) == '"' &&
3607 substr($n, -1, 1) == '"'
3608 ) {
3609 $n = substr($n, 1, -1);
836eb043 3610 $value = CRM_Core_DAO::escapeString($n);
6a488035
TO
3611 $op = '=';
3612 }
3613 else {
0b38e8f1 3614 $value = self::getWildCardedValue($wildcard, $op, $n);
6a488035
TO
3615 }
3616 $this->_qill[$grouping][] = ts('Email') . " $op '$n'";
3617 $this->_where[$grouping][] = self::buildClause('civicrm_email.email', $op, $value, 'String');
3618 }
3619 else {
3620 $this->_qill[$grouping][] = ts('Email') . " $op ";
3621 $this->_where[$grouping][] = self::buildClause('civicrm_email.email', $op, NULL, 'String');
3622 }
6a488035
TO
3623 }
3624
3625 /**
100fef9d 3626 * Where / qill clause for phone number
6a488035 3627 *
c037736a 3628 * @param array $values
6a488035 3629 */
00be9182 3630 public function phone_numeric(&$values) {
6a488035 3631 list($name, $op, $value, $grouping, $wildcard) = $values;
a195fab2
BS
3632 // Strip non-numeric characters; allow wildcards
3633 $number = preg_replace('/[^\d%]/', '', $value);
6a488035 3634 if ($number) {
5c7dad85 3635 if (strpos($number, '%') === FALSE) {
a195fab2
BS
3636 $number = "%$number%";
3637 }
3638
6a488035 3639 $this->_qill[$grouping][] = ts('Phone number contains') . " $number";
a195fab2 3640 $this->_where[$grouping][] = self::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
6a488035
TO
3641 $this->_tables['civicrm_phone'] = $this->_whereTables['civicrm_phone'] = 1;
3642 }
3643 }
3644
3645 /**
100fef9d 3646 * Where / qill clause for phone type/location
6a488035 3647 *
c037736a 3648 * @param array $values
6a488035 3649 */
00be9182 3650 public function phone_option_group($values) {
6a488035 3651 list($name, $op, $value, $grouping, $wildcard) = $values;
cbf48754
AS
3652 $option = ($name == 'phone_phone_type_id' ? 'phone_type_id' : 'location_type_id');
3653 $options = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', $option);
6a488035
TO
3654 $optionName = $options[$value];
3655 $this->_qill[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ? ts('type') : ('location')) . " $op $optionName";
3656 $this->_where[$grouping][] = self::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3657 $this->_tables['civicrm_phone'] = $this->_whereTables['civicrm_phone'] = 1;
3658 }
3659
3660 /**
c037736a 3661 * Where / qill clause for street_address.
6a488035 3662 *
c037736a 3663 * @param array $values
6a488035 3664 */
00be9182 3665 public function street_address(&$values) {
6d52bfe5 3666 list($name, $op, $value, $grouping) = $values;
6a488035
TO
3667
3668 if (!$op) {
3669 $op = 'LIKE';
3670 }
3671
3672 $n = trim($value);
3673
3674 if ($n) {
6a488035
TO
3675 if (strpos($value, '%') === FALSE) {
3676 // only add wild card if not there
3677 $value = "%{$value}%";
3678 }
3679 $op = 'LIKE';
fea8ae41 3680 $this->_where[$grouping][] = self::buildClause('civicrm_address.street_address', $op, $value, 'String');
6a488035
TO
3681 $this->_qill[$grouping][] = ts('Street') . " $op '$n'";
3682 }
3683 else {
3684 $this->_where[$grouping][] = self::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3685 $this->_qill[$grouping][] = ts('Street') . " $op ";
3686 }
3687
3688 $this->_tables['civicrm_address'] = $this->_whereTables['civicrm_address'] = 1;
3689 }
3690
3691 /**
c037736a 3692 * Where / qill clause for street_unit.
77b97be7 3693 *
c037736a 3694 * @param array $values
6a488035 3695 */
00be9182 3696 public function street_number(&$values) {
6a488035
TO
3697 list($name, $op, $value, $grouping, $wildcard) = $values;
3698
3699 if (!$op) {
3700 $op = '=';
3701 }
3702
3703 $n = trim($value);
3704
3705 if (strtolower($n) == 'odd') {
3706 $this->_where[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3707 $this->_qill[$grouping][] = ts('Street Number is odd');
3708 }
3709 elseif (strtolower($n) == 'even') {
3710 $this->_where[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3711 $this->_qill[$grouping][] = ts('Street Number is even');
3712 }
3713 else {
2fc64082 3714 $value = $n;
3715 $this->_where[$grouping][] = self::buildClause('civicrm_address.street_number', $op, $value, 'String');
6a488035
TO
3716 $this->_qill[$grouping][] = ts('Street Number') . " $op '$n'";
3717 }
3718
3719 $this->_tables['civicrm_address'] = $this->_whereTables['civicrm_address'] = 1;
3720 }
3721
3722 /**
c037736a 3723 * Where / qill clause for sorting by character.
77b97be7 3724 *
c037736a 3725 * @param array $values
6a488035 3726 */
00be9182 3727 public function sortByCharacter(&$values) {
6a488035
TO
3728 list($name, $op, $value, $grouping, $wildcard) = $values;
3729
3730 $name = trim($value);
2fc64082 3731 $cond = " contact_a.sort_name LIKE '" . CRM_Core_DAO::escapeWildCardString($name) . "%'";
6a488035 3732 $this->_where[$grouping][] = $cond;
be2fb01f 3733 $this->_qill[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', [1 => $name]);
6a488035
TO
3734 }
3735
3736 /**
c037736a 3737 * Where / qill clause for including contact ids.
6a488035 3738 */
00be9182 3739 public function includeContactIDs() {
6a488035
TO
3740 if (!$this->_includeContactIds || empty($this->_params)) {
3741 return;
3742 }
3743
be2fb01f 3744 $contactIds = [];
6a488035
TO
3745 foreach ($this->_params as $id => $values) {
3746 if (substr($values[0], 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
3747 $contactIds[] = substr($values[0], CRM_Core_Form::CB_PREFIX_LEN);
3748 }
3749 }
b1128d0b 3750 CRM_Utils_Type::validateAll($contactIds, 'Positive');
6a488035
TO
3751 if (!empty($contactIds)) {
3752 $this->_where[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3753 }
3754 }
3755
3756 /**
c037736a 3757 * Where / qill clause for postal code.
77b97be7 3758 *
c037736a 3759 * @param array $values
6a488035 3760 */
00be9182 3761 public function postalCode(&$values) {
6a488035 3762 // skip if the fields dont have anything to do with postal_code
a7488080 3763 if (empty($this->_fields['postal_code'])) {
6a488035
TO
3764 return;
3765 }
3766
3767 list($name, $op, $value, $grouping, $wildcard) = $values;
3768
3769 // Handle numeric postal code range searches properly by casting the column as numeric
3770 if (is_numeric($value)) {
abc78dd4 3771 $field = "IF (civicrm_address.postal_code REGEXP '^[0-9]{1,10}$', CAST(civicrm_address.postal_code AS UNSIGNED), 0)";
6a488035
TO
3772 $val = CRM_Utils_Type::escape($value, 'Integer');
3773 }
3774 else {
3775 $field = 'civicrm_address.postal_code';
715277e7 3776 // Per CRM-17060 we might be looking at an 'IN' syntax so don't case arrays to string.
3777 if (!is_array($value)) {
3778 $val = CRM_Utils_Type::escape($value, 'String');
3779 }
3780 else {
3781 // Do we need to escape values here? I would expect buildClause does.
3782 $val = $value;
3783 }
6a488035
TO
3784 }
3785
3786 $this->_tables['civicrm_address'] = $this->_whereTables['civicrm_address'] = 1;
3787
3788 if ($name == 'postal_code') {
3789 $this->_where[$grouping][] = self::buildClause($field, $op, $val, 'String');
3790 $this->_qill[$grouping][] = ts('Postal code') . " {$op} {$value}";
3791 }
3792 elseif ($name == 'postal_code_low') {
3793 $this->_where[$grouping][] = " ( $field >= '$val' ) ";
be2fb01f 3794 $this->_qill[$grouping][] = ts('Postal code greater than or equal to \'%1\'', [1 => $value]);
6a488035
TO
3795 }
3796 elseif ($name == 'postal_code_high') {
3797 $this->_where[$grouping][] = " ( $field <= '$val' ) ";
be2fb01f 3798 $this->_qill[$grouping][] = ts('Postal code less than or equal to \'%1\'', [1 => $value]);
6a488035
TO
3799 }
3800 }
3801
3802 /**
c037736a 3803 * Where / qill clause for location type.
6a488035 3804 *
c037736a 3805 * @param array $values
77b97be7
EM
3806 * @param null $status
3807 *
c037736a 3808 * @return string
6a488035 3809 */
00be9182 3810 public function locationType(&$values, $status = NULL) {
6a488035
TO
3811 list($name, $op, $value, $grouping, $wildcard) = $values;
3812
3813 if (is_array($value)) {
d8a8bb0b 3814 $this->_where[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')';
6a488035
TO
3815 $this->_tables['civicrm_address'] = 1;
3816 $this->_whereTables['civicrm_address'] = 1;
3817
b2b0530a 3818 $locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
be2fb01f 3819 $names = [];
d8a8bb0b 3820 foreach ($value as $id) {
6a488035
TO
3821 $names[] = $locationType[$id];
3822 }
3823
3824 $this->_primaryLocation = FALSE;
3825
3826 if (!$status) {
3827 $this->_qill[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3828 }
3829 else {
3830 return implode(' ' . ts('or') . ' ', $names);
3831 }
3832 }
3833 }
3834
86538308
EM
3835 /**
3836 * @param $values
3837 * @param bool $fromStateProvince
3838 *
59f4c9ee 3839 * @return array|NULL
86538308 3840 */
00be9182 3841 public function country(&$values, $fromStateProvince = TRUE) {
6a488035
TO
3842 list($name, $op, $value, $grouping, $wildcard) = $values;
3843
3844 if (!$fromStateProvince) {
3845 $stateValues = $this->getWhereValues('state_province', $grouping);
3846 if (!empty($stateValues)) {
3847 // return back to caller if there are state province values
3848 // since that handles this case
59f4c9ee 3849 return NULL;
6a488035
TO
3850 }
3851 }
3852
3853 $countryClause = $countryQill = NULL;
be2fb01f 3854 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY']) || ($values && !empty($value))) {
d9ab802d
PJ
3855 $this->_tables['civicrm_address'] = 1;
3856 $this->_whereTables['civicrm_address'] = 1;
6a488035 3857
836f1f3f 3858 $countryClause = self::buildClause('civicrm_address.country_id', $op, $value, 'Positive');
3859 list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(NULL, 'country_id', $value, $op);
be2fb01f 3860 $countryQill = ts("%1 %2 %3", [1 => 'Country', 2 => $qillop, 3 => $qillVal]);
6a488035
TO
3861
3862 if (!$fromStateProvince) {
3863 $this->_where[$grouping][] = $countryClause;
3864 $this->_qill[$grouping][] = $countryQill;
3865 }
3866 }
3867
3868 if ($fromStateProvince) {
3869 if (!empty($countryClause)) {
be2fb01f 3870 return [
6a488035
TO
3871 $countryClause,
3872 " ...AND... " . $countryQill,
be2fb01f 3873 ];
6a488035
TO
3874 }
3875 else {
be2fb01f 3876 return [NULL, NULL];
6a488035
TO
3877 }
3878 }
3879 }
3880
3881 /**
c037736a 3882 * Where / qill clause for county (if present).
6a488035 3883 *
c037736a 3884 * @param array $values
77b97be7
EM
3885 * @param null $status
3886 *
c037736a 3887 * @return string
6a488035 3888 */
5c7dad85 3889 public function county(&$values, $status = NULL) {
6a488035
TO
3890 list($name, $op, $value, $grouping, $wildcard) = $values;
3891
5c7dad85 3892 if (!is_array($value)) {
6a488035 3893 // force the county to be an array
be2fb01f 3894 $value = [$value];
6a488035
TO
3895 }
3896
3897 // check if the values are ids OR names of the counties
3898 $inputFormat = 'id';
3899 foreach ($value as $v) {
3900 if (!is_numeric($v)) {
3901 $inputFormat = 'name';
3902 break;
3903 }
3904 }
be2fb01f 3905 $names = [];
d9ab802d
PJ
3906 if ($op == '=') {
3907 $op = 'IN';
3908 }
4c9b6178 3909 elseif ($op == '!=') {
d9ab802d
PJ
3910 $op = 'NOT IN';
3911 }
3912 else {
3913 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3914 $op = str_replace('EMPTY', 'NULL', $op);
3915 }
3916
be2fb01f 3917 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
d9ab802d
PJ
3918 $clause = "civicrm_address.county_id $op";
3919 }
3920 elseif ($inputFormat == 'id') {
3921 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
6a488035
TO
3922
3923 $county = CRM_Core_PseudoConstant::county();
3924 foreach ($value as $id) {
3925 $names[] = CRM_Utils_Array::value($id, $county);
3926 }
3927 }
3928 else {
be2fb01f 3929 $inputClause = [];
d9ab802d 3930 $county = CRM_Core_PseudoConstant::county();
6a488035
TO
3931 foreach ($value as $name) {
3932 $name = trim($name);
d9ab802d 3933 $inputClause[] = CRM_Utils_Array::key($name, $county);
6a488035 3934 }
d9ab802d 3935 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
6a488035
TO
3936 $names = $value;
3937 }
d9ab802d
PJ
3938 $this->_tables['civicrm_address'] = 1;
3939 $this->_whereTables['civicrm_address'] = 1;
6a488035
TO
3940
3941 $this->_where[$grouping][] = $clause;
d9ab802d 3942 if (!$status) {
6a488035 3943 $this->_qill[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
5c7dad85
TO
3944 }
3945 else {
6a488035
TO
3946 return implode(' ' . ts('or') . ' ', $names);
3947 }
3948 }
3949
3950 /**
c037736a 3951 * Where / qill clause for state/province AND country (if present).
6a488035 3952 *
c037736a 3953 * @param array $values
77b97be7
EM
3954 * @param null $status
3955 *
c037736a 3956 * @return string
6a488035 3957 */
00be9182 3958 public function stateProvince(&$values, $status = NULL) {
6a488035
TO
3959 list($name, $op, $value, $grouping, $wildcard) = $values;
3960
6bd09f41 3961 $stateClause = self::buildClause('civicrm_address.state_province_id', $op, $value, 'Positive');
d9ab802d
PJ
3962 $this->_tables['civicrm_address'] = 1;
3963 $this->_whereTables['civicrm_address'] = 1;
6a488035
TO
3964
3965 $countryValues = $this->getWhereValues('country', $grouping);
3966 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
6a488035
TO
3967 if ($countryClause) {
3968 $clause = "( $stateClause AND $countryClause )";
3969 }
3970 else {
3971 $clause = $stateClause;
3972 }
3973
3974 $this->_where[$grouping][] = $clause;
6bd09f41 3975 list($qillop, $qillVal) = self::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
6a488035 3976 if (!$status) {
be2fb01f 3977 $this->_qill[$grouping][] = ts("State/Province %1 %2 %3", [1 => $qillop, 2 => $qillVal, 3 => $countryQill]);
6a488035
TO
3978 }
3979 else {
6bd09f41 3980 return implode(' ' . ts('or') . ' ', $qillVal) . $countryQill;
6a488035
TO
3981 }
3982 }
3983
3984 /**
c037736a 3985 * Where / qill clause for change log.
77b97be7 3986 *
c037736a 3987 * @param array $values
6a488035 3988 */
00be9182 3989 public function changeLog(&$values) {
6a488035
TO
3990 list($name, $op, $value, $grouping, $wildcard) = $values;
3991
3992 $targetName = $this->getWhereValues('changed_by', $grouping);
3993 if (!$targetName) {
3994 return;
3995 }
3996
3997 $name = trim($targetName[2]);
2fc64082 3998 $name = CRM_Core_DAO::escapeString($name);
6a488035
TO
3999 $name = $targetName[4] ? "%$name%" : $name;
4000 $this->_where[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
4001 $this->_tables['civicrm_log'] = $this->_whereTables['civicrm_log'] = 1;
96b84142
PN
4002 $fieldTitle = ts('Added By');
4003 foreach ($this->_params as $params) {
4004 if ($params[0] == 'log_date') {
4005 if ($params[2] == 2) {
4006 $fieldTitle = ts('Modified By');
4007 }
4008 break;
4009 }
4010 }
4011 list($qillop, $qillVal) = self::buildQillForFieldValue(NULL, 'changed_by', $name, 'LIKE');
b478616b 4012 $this->_qill[$grouping][] = ts("%1 %2 '%3'", [
96b84142
PN
4013 1 => $fieldTitle,
4014 2 => $qillop,
4015 3 => $qillVal,
4016 ]);
6a488035
TO
4017 }
4018
86538308
EM
4019 /**
4020 * @param $values
4021 */
00be9182 4022 public function modifiedDates($values) {
6a488035 4023 $this->_useDistinct = TRUE;
9e9b8fdb
DL
4024
4025 // CRM-11281, default to added date if not set
228917cd 4026 $fieldTitle = ts('Added Date');
06103b23 4027 $fieldName = 'created_date';
6a488035
TO
4028 foreach (array_keys($this->_params) as $id) {
4029 if ($this->_params[$id][0] == 'log_date') {
228917cd
DL
4030 if ($this->_params[$id][2] == 2) {
4031 $fieldTitle = ts('Modified Date');
06103b23 4032 $fieldName = 'modified_date';
6a488035
TO
4033 }
4034 }
4035 }
4036
06103b23 4037 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
4038
4039 self::$_openedPanes[ts('Change Log')] = TRUE;
6a488035
TO
4040 }
4041
86538308
EM
4042 /**
4043 * @param $values
4044 */
00be9182 4045 public function demographics(&$values) {
6a488035
TO
4046 list($name, $op, $value, $grouping, $wildcard) = $values;
4047
c4a7c967 4048 if (($name == 'age_low') || ($name == 'age_high')) {
4049 $this->ageRangeQueryBuilder($values,
4050 'contact_a', 'age', 'birth_date', ts('Age')
4051 );
4052 }
4053 elseif (($name == 'birth_date_low') || ($name == 'birth_date_high')) {
6a488035
TO
4054
4055 $this->dateQueryBuilder($values,
4056 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
4057 );
4058 }
4059 elseif (($name == 'deceased_date_low') || ($name == 'deceased_date_high')) {
4060
4061 $this->dateQueryBuilder($values,
4062 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
4063 );
4064 }
4065
4066 self::$_openedPanes[ts('Demographics')] = TRUE;
4067 }
4068
86538308
EM
4069 /**
4070 * @param $values
4071 */
00be9182 4072 public function privacy(&$values) {
6d52bfe5 4073 list($name, $op, $value, $grouping) = $values;
6a488035
TO
4074 //fixed for profile search listing CRM-4633
4075 if (strpbrk($value, "[")) {
4076 $value = "'{$value}'";
4077 $op = "!{$op}";
4078 $this->_where[$grouping][] = "contact_a.{$name} $op $value";
4079 }
4080 else {
4081 $this->_where[$grouping][] = "contact_a.{$name} $op $value";
4082 }
4083 $field = CRM_Utils_Array::value($name, $this->_fields);
9b183452 4084 $op = CRM_Utils_Array::value($op, CRM_Core_SelectValues::getSearchBuilderOperators(), $op);
6a488035
TO
4085 $title = $field ? $field['title'] : $name;
4086 $this->_qill[$grouping][] = "$title $op $value";
4087 }
4088
86538308
EM
4089 /**
4090 * @param $values
4091 */
00be9182 4092 public function privacyOptions($values) {
6a488035
TO
4093 list($name, $op, $value, $grouping, $wildcard) = $values;
4094
9fd71915
CW
4095 if (empty($value) || !is_array($value)) {
4096 return;
6a488035
TO
4097 }
4098
4099 // get the operator and toggle values
4100 $opValues = $this->getWhereValues('privacy_operator', $grouping);
4101 $operator = 'OR';
4102 if ($opValues &&
4103 strtolower($opValues[2] == 'AND')
4104 ) {
2fc64082 4105 // @todo this line is logially unreachable
6a488035
TO
4106 $operator = 'AND';
4107 }
4108
4109 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
e10c7983 4110 $compareOP = '!';
6a488035
TO
4111 if ($toggleValues &&
4112 $toggleValues[2] == 2
4113 ) {
e10c7983 4114 $compareOP = '';
6a488035
TO
4115 }
4116
be2fb01f
CW
4117 $clauses = [];
4118 $qill = [];
6a488035 4119 foreach ($value as $dontCare => $pOption) {
e10c7983 4120 $clauses[] = " ( contact_a.{$pOption} = 1 ) ";
6a488035
TO
4121 $field = CRM_Utils_Array::value($pOption, $this->_fields);
4122 $title = $field ? $field['title'] : $pOption;
e10c7983 4123 $qill[] = " $title = 1 ";
6a488035
TO
4124 }
4125
e10c7983
JL
4126 $this->_where[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )';
4127 $this->_qill[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )';
6a488035
TO
4128 }
4129
86538308
EM
4130 /**
4131 * @param $values
4132 */
00be9182 4133 public function preferredCommunication(&$values) {
6a488035
TO
4134 list($name, $op, $value, $grouping, $wildcard) = $values;
4135
c112a6f9 4136 if (!is_array($value)) {
be2fb01f 4137 $value = str_replace(['(', ')'], '', explode(",", $value));
6a488035 4138 }
7cc09daf 4139 elseif (in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
4140 $op = key($value);
4141 $value = $value[$op];
6a488035 4142 }
05d214de 4143 list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Contact_DAO_Contact', $name, $value, $op);
6a488035 4144
05d214de 4145 if (self::caseImportant($op)) {
4146 $value = implode("[[:cntrl:]]|[[:cntrl:]]", (array) $value);
4147 $op = (strstr($op, '!') || strstr($op, 'NOT')) ? 'NOT RLIKE' : 'RLIKE';
4148 $value = "[[:cntrl:]]" . $value . "[[:cntrl:]]";
4b20f7df 4149 }
6a488035 4150
05d214de 4151 $this->_where[$grouping][] = self::buildClause("contact_a.preferred_communication_method", $op, $value);
be2fb01f 4152 $this->_qill[$grouping][] = ts('Preferred Communication Method %1 %2', [1 => $qillop, 2 => $qillVal]);
6a488035
TO
4153 }
4154
6a488035 4155 /**
c037736a 4156 * Where / qill clause for relationship.
77b97be7 4157 *
c037736a 4158 * @param array $values
6a488035 4159 */
00be9182 4160 public function relationship(&$values) {
6a488035 4161 list($name, $op, $value, $grouping, $wildcard) = $values;
5c7dad85
TO
4162 if ($this->_relationshipValuesAdded) {
4163 return;
ad682134 4164 }
6a488035 4165 // also get values array for relation_target_name
2fef460a 4166 // for relationship search we always do wildcard
b3342109 4167 $relationType = $this->getWhereValues('relation_type_id', $grouping);
6e83b317 4168 $description = $this->getWhereValues('relation_description', $grouping);
6a488035
TO
4169 $targetName = $this->getWhereValues('relation_target_name', $grouping);
4170 $relStatus = $this->getWhereValues('relation_status', $grouping);
4171 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
b9cb427a 4172
6a488035
TO
4173 $nameClause = $name = NULL;
4174 if ($targetName) {
4175 $name = trim($targetName[2]);
4176 if (substr($name, 0, 1) == '"' &&
4177 substr($name, -1, 1) == '"'
4178 ) {
4179 $name = substr($name, 1, -1);
dd2db5e5 4180 $name = CRM_Core_DAO::escapeString($name);
6a488035
TO
4181 $nameClause = "= '$name'";
4182 }
4183 else {
dd2db5e5 4184 $name = CRM_Core_DAO::escapeString($name);
6a488035
TO
4185 $nameClause = "LIKE '%{$name}%'";
4186 }
4187 }
4188
be2fb01f 4189 $relTypes = $relTypesIds = [];
5c7dad85 4190 if (!empty($relationType)) {
026242fc
SL
4191 $relationType[2] = (array) $relationType[2];
4192 foreach ($relationType[2] as $relType) {
4193 $rel = explode('_', $relType);
c0184a48 4194 self::$_relType = $rel[1];
be2fb01f
CW
4195 $params = ['id' => $rel[0]];
4196 $typeValues = [];
5ad36be5
SL
4197 $rTypeValue = CRM_Contact_BAO_RelationshipType::retrieve($params, $typeValues);
4198 if (!empty($rTypeValue)) {
dd2db5e5 4199 if ($rTypeValue->name_a_b == $rTypeValue->name_b_a) {
4200 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4201 self::$_relType = 'reciprocal';
4202 }
5ad36be5
SL
4203 $relTypesIds[] = $rel[0];
4204 $relTypes[] = $relType;
4205 }
026242fc
SL
4206 }
4207 }
dd2db5e5 4208
7c96365b 4209 // if we are creating a temp table we build our own where for the relationship table
085e6226 4210 $relationshipTempTable = NULL;
72a2eeab 4211 if (self::$_relType == 'reciprocal') {
be2fb01f 4212 $where = [];
59f4c9ee 4213 self::$_relationshipTempTable = $relationshipTempTable = CRM_Core_DAO::createTempTableName('civicrm_rel');
11a5aa5d 4214 if ($nameClause) {
7c96365b 4215 $where[$grouping][] = " sort_name $nameClause ";
4216 }
72a2eeab
AS
4217 $groupJoinTable = "civicrm_relationship";
4218 $groupJoinColumn = "contact_id_alt";
6a488035 4219 }
7c96365b 4220 else {
4221 $where = &$this->_where;
4222 if ($nameClause) {
4223 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4224 }
72a2eeab
AS
4225 $groupJoinTable = "contact_b";
4226 $groupJoinColumn = "id";
7c96365b 4227 }
1de4945d 4228 $allRelationshipType = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, NULL, TRUE);
6a488035 4229 if ($nameClause || !$targetGroup) {
5c7dad85 4230 if (!empty($relationType)) {
026242fc 4231 $relQill = '';
5ad36be5 4232 foreach ($relTypes as $rel) {
026242fc
SL
4233 if (!empty($relQill)) {
4234 $relQill .= ' OR ';
4235 }
4236 $relQill .= $allRelationshipType[$rel];
4237 }
4238 $this->_qill[$grouping][] = 'Relationship Type(s) ' . $relQill . " $name";
5c7dad85
TO
4239 }
4240 else {
2b0c31bc
DG
4241 $this->_qill[$grouping][] = $name;
4242 }
6a488035
TO
4243 }
4244
6a488035
TO
4245 //check to see if the target contact is in specified group
4246 if ($targetGroup) {
4247 //add contacts from static groups
59f4c9ee 4248 $this->_tables['civicrm_relationship_group_contact'] = $this->_whereTables['civicrm_relationship_group_contact']
72a2eeab 4249 = " LEFT JOIN civicrm_group_contact civicrm_relationship_group_contact ON civicrm_relationship_group_contact.contact_id = {$groupJoinTable}.{$groupJoinColumn} AND civicrm_relationship_group_contact.status = 'Added'";
59f4c9ee 4250 $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" .
5c7dad85 4251 implode(",", $targetGroup[2]) . ") ) ";
6a488035
TO
4252
4253 //add contacts from saved searches
72a2eeab 4254 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", $groupJoinTable, $op, $groupJoinColumn);
6a488035
TO
4255
4256 //set the group where clause
4257 if ($ssWhere) {
4258 $groupWhere[] = "( " . $ssWhere . " )";
4259 }
4260 $this->_where[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4261
4262 //Get the names of the target groups for the qill
085e6226 4263 $groupNames = CRM_Core_PseudoConstant::group();
be2fb01f 4264 $qillNames = [];
6a488035
TO
4265 foreach ($targetGroup[2] as $groupId) {
4266 if (array_key_exists($groupId, $groupNames)) {
4267 $qillNames[] = $groupNames[$groupId];
4268 }
4269 }
5c7dad85 4270 if (!empty($relationType)) {
026242fc 4271 $relQill = '';
5ad36be5 4272 foreach ($relTypes as $rel) {
026242fc
SL
4273 if (!empty($relQill)) {
4274 $relQill .= ' OR ';
4275 }
72a2eeab 4276 $relQill .= CRM_Utils_Array::value($rel, $allRelationshipType);
026242fc
SL
4277 }
4278 $this->_qill[$grouping][] = 'Relationship Type(s) ' . $relQill . " ( " . implode(", ", $qillNames) . " )";
5c7dad85
TO
4279 }
4280 else {
2b0c31bc
DG
4281 $this->_qill[$grouping][] = implode(", ", $qillNames);
4282 }
6a488035
TO
4283 }
4284
6e83b317
CW
4285 // Description
4286 if (!empty($description[2]) && trim($description[2])) {
4287 $this->_qill[$grouping][] = ts('Relationship description - ' . $description[2]);
4288 $description = CRM_Core_DAO::escapeString(trim($description[2]));
4289 $where[$grouping][] = "civicrm_relationship.description LIKE '%{$description}%'";
4290 }
4291
12ba37a0
CW
4292 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4293 $today = date('Ymd');
6a488035
TO
4294 //check for active, inactive and all relation status
4295 if ($relStatus[2] == 0) {
7c96365b 4296 $where[$grouping][] = "(
6a488035 4297civicrm_relationship.is_active = 1 AND
12ba37a0
CW
4298( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4299( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
6a488035
TO
4300)";
4301 $this->_qill[$grouping][] = ts('Relationship - Active and Current');
4302 }
4303 elseif ($relStatus[2] == 1) {
7c96365b 4304 $where[$grouping][] = "(
6a488035 4305civicrm_relationship.is_active = 0 OR
12ba37a0
CW
4306civicrm_relationship.end_date < {$today} OR
4307civicrm_relationship.start_date > {$today}
6a488035
TO
4308)";
4309 $this->_qill[$grouping][] = ts('Relationship - Inactive or not Current');
4310 }
4311
d64e31ab 4312 $onlyDeleted = 0;
be2fb01f 4313 if (in_array(['deleted_contacts', '=', '1', '0', '0'], $this->_params)) {
d64e31ab 4314 $onlyDeleted = 1;
4315 }
4316 $where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})";
4317
f871c3a9 4318 $this->addRelationshipPermissionClauses($grouping, $where);
7c96365b 4319 $this->addRelationshipDateClauses($grouping, $where);
eea5db81 4320 $this->addRelationshipActivePeriodClauses($grouping, $where);
026242fc 4321 if (!empty($relTypes)) {
5ad36be5 4322 $where[$grouping][] = 'civicrm_relationship.relationship_type_id IN (' . implode(',', $relTypesIds) . ')';
6a488035 4323 }
6a488035
TO
4324 $this->_tables['civicrm_relationship'] = $this->_whereTables['civicrm_relationship'] = 1;
4325 $this->_useDistinct = TRUE;
ad682134 4326 $this->_relationshipValuesAdded = TRUE;
7c96365b 4327 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4328 // join on that,
2b0c31bc
DG
4329 if ($relationshipTempTable) {
4330 $whereClause = '';
5c7dad85 4331 if (!empty($where[$grouping])) {
2b0c31bc 4332 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
792750a5 4333 $whereClause = str_replace('contact_b', 'c', $whereClause);
2b0c31bc 4334 }
7c96365b 4335 $sql = "
4336 CREATE TEMPORARY TABLE {$relationshipTempTable}
08fa90dc
AS
4337 (
4338 `contact_id` int(10) unsigned NOT NULL DEFAULT '0',
4339 `contact_id_alt` int(10) unsigned NOT NULL DEFAULT '0',
4340 KEY `contact_id` (`contact_id`),
4341 KEY `contact_id_alt` (`contact_id_alt`)
4342 )
72a2eeab 4343 (SELECT contact_id_b as contact_id, contact_id_a as contact_id_alt, civicrm_relationship.id
7c96365b 4344 FROM civicrm_relationship
4345 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4346 $whereClause )
4347 UNION
72a2eeab 4348 (SELECT contact_id_a as contact_id, contact_id_b as contact_id_alt, civicrm_relationship.id
7c96365b 4349 FROM civicrm_relationship
4350 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4351 $whereClause )
4352 ";
4353 CRM_Core_DAO::executeQuery($sql);
4354 }
6a488035 4355 }
5c7dad85 4356
9c9908e9 4357 /**
4358 * Add relationship permission criteria to where clause.
4359 *
4360 * @param string $grouping
4361 * @param array $where Array to add "where" criteria to, in case you are generating a temp table.
4362 * Not the main query.
4363 */
f871c3a9
AS
4364 public function addRelationshipPermissionClauses($grouping, &$where) {
4365 $relPermission = $this->getWhereValues('relation_permission', $grouping);
4366 if ($relPermission) {
f85f95ba
NM
4367 if (!is_array($relPermission[2])) {
4368 // this form value was scalar in previous versions of Civi
be2fb01f 4369 $relPermission[2] = [$relPermission[2]];
f85f95ba 4370 }
f871c3a9
AS
4371 $where[$grouping][] = "(civicrm_relationship.is_permission_a_b IN (" . implode(",", $relPermission[2]) . "))";
4372
4373 $allRelationshipPermissions = CRM_Contact_BAO_Relationship::buildOptions('is_permission_a_b');
9c9908e9 4374
4375 $relPermNames = array_intersect_key($allRelationshipPermissions, array_flip($relPermission[2]));
4376 $this->_qill[$grouping][] = ts('Permissioned Relationships') . ' - ' . implode(' OR ', $relPermNames);
f871c3a9
AS
4377 }
4378 }
4379
5c7dad85
TO
4380 /**
4381 * Add start & end date criteria in
4382 * @param string $grouping
4383 * @param array $where
4384 * = array to add where clauses to, in case you are generating a temp table.
4385 * not the main query.
4386 */
4387 public function addRelationshipDateClauses($grouping, &$where) {
41b8dd1d 4388 foreach (['start_date', 'end_date'] as $dateField) {
4389 $dateValueLow = $this->getWhereValues('relationship_' . $dateField . '_low', $grouping);
4390 $dateValueHigh = $this->getWhereValues('relationship_' . $dateField . '_high', $grouping);
5c7dad85 4391 if (!empty($dateValueLow)) {
ad682134 4392 $date = date('Ymd', strtotime($dateValueLow[2]));
7c96365b 4393 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
c8e625fc 4394 $this->_qill[$grouping][] = ($dateField == 'end_date' ? ts('Relationship Ended on or After') : ts('Relationship Recorded Start Date On or After')) . " " . CRM_Utils_Date::customFormat($date);
ad682134 4395 }
5c7dad85 4396 if (!empty($dateValueHigh)) {
ad682134 4397 $date = date('Ymd', strtotime($dateValueHigh[2]));
7c96365b 4398 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
c8e625fc 4399 $this->_qill[$grouping][] = ($dateField == 'end_date' ? ts('Relationship Ended on or Before') : ts('Relationship Recorded Start Date On or Before')) . " " . CRM_Utils_Date::customFormat($date);
ad682134 4400 }
4401 }
4402 }
77b97be7 4403
eea5db81 4404 /**
4405 * Add start & end active period criteria in
4406 * @param string $grouping
4407 * @param array $where
4408 * = array to add where clauses to, in case you are generating a temp table.
4409 * not the main query.
4410 */
4411 public function addRelationshipActivePeriodClauses($grouping, &$where) {
be2fb01f 4412 $dateValues = [];
eea5db81 4413 $dateField = 'active_period_date';
4414
4415 $dateValueLow = $this->getWhereValues('relation_active_period_date_low', $grouping);
4416 $dateValueHigh = $this->getWhereValues('relation_active_period_date_high', $grouping);
02633eb0 4417 $dateValueLowFormated = $dateValueHighFormated = NULL;
eea5db81 4418 if (!empty($dateValueLow) && !empty($dateValueHigh)) {
4419 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4420 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
eea5db81 4421 $this->_qill[$grouping][] = (ts('Relationship was active between')) . " " . CRM_Utils_Date::customFormat($dateValueLowFormated) . " and " . CRM_Utils_Date::customFormat($dateValueHighFormated);
4422 }
4423 elseif (!empty($dateValueLow)) {
4424 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
eea5db81 4425 $this->_qill[$grouping][] = (ts('Relationship was active after')) . " " . CRM_Utils_Date::customFormat($dateValueLowFormated);
4426 }
4427 elseif (!empty($dateValueHigh)) {
4428 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
eea5db81 4429 $this->_qill[$grouping][] = (ts('Relationship was active before')) . " " . CRM_Utils_Date::customFormat($dateValueHighFormated);
4430 }
02633eb0
FBB
4431
4432 if ($activePeriodClauses = self::getRelationshipActivePeriodClauses($dateValueLowFormated, $dateValueHighFormated, TRUE)) {
4433 $where[$grouping][] = $activePeriodClauses;
4434 }
eea5db81 4435 }
4436
4437 /**
4438 * Get start & end active period criteria
4439 */
4440 public static function getRelationshipActivePeriodClauses($from, $to, $forceTableName) {
4441 $tableName = $forceTableName ? 'civicrm_relationship.' : '';
4442 if (!is_null($from) && !is_null($to)) {
4443 return '(((' . $tableName . 'start_date >= ' . $from . ' AND ' . $tableName . 'start_date <= ' . $to . ') OR
4444 (' . $tableName . 'end_date >= ' . $from . ' AND ' . $tableName . 'end_date <= ' . $to . ') OR
4445 (' . $tableName . 'start_date <= ' . $from . ' AND ' . $tableName . 'end_date >= ' . $to . ' )) OR
4446 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4447 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . ') OR
4448 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4449 }
4450 elseif (!is_null($from)) {
4451 return '((' . $tableName . 'start_date >= ' . $from . ') OR
4452 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4453 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . '))';
4454 }
4455 elseif (!is_null($to)) {
4456 return '((' . $tableName . 'start_date <= ' . $to . ') OR
4457 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4458 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4459 }
4460 }
4461
6a488035 4462 /**
fe482240 4463 * Default set of return properties.
6a488035 4464 *
77b97be7
EM
4465 * @param int $mode
4466 *
a6c01b45
CW
4467 * @return array
4468 * derault return properties
6a488035 4469 */
00be9182 4470 public static function &defaultReturnProperties($mode = 1) {
6a488035 4471 if (!isset(self::$_defaultReturnProperties)) {
be2fb01f 4472 self::$_defaultReturnProperties = [];
6a488035
TO
4473 }
4474
4475 if (!isset(self::$_defaultReturnProperties[$mode])) {
4476 // add activity return properties
4477 if ($mode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
4478 self::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query::defaultReturnProperties($mode, FALSE);
4479 }
4480 else {
4481 self::$_defaultReturnProperties[$mode] = CRM_Core_Component::defaultReturnProperties($mode, FALSE);
4482 }
4483
4484 if (empty(self::$_defaultReturnProperties[$mode])) {
be2fb01f 4485 self::$_defaultReturnProperties[$mode] = [
6a488035
TO
4486 'home_URL' => 1,
4487 'image_URL' => 1,
4488 'legal_identifier' => 1,
4489 'external_identifier' => 1,
4490 'contact_type' => 1,
4491 'contact_sub_type' => 1,
4492 'sort_name' => 1,
4493 'display_name' => 1,
4494 'preferred_mail_format' => 1,
4495 'nick_name' => 1,
4496 'first_name' => 1,
4497 'middle_name' => 1,
4498 'last_name' => 1,
04ffef8d
CW
4499 'prefix_id' => 1,
4500 'suffix_id' => 1,
e171748b 4501 'formal_title' => 1,
aa62b355 4502 'communication_style_id' => 1,
6a488035 4503 'birth_date' => 1,
04ffef8d 4504 'gender_id' => 1,
6a488035
TO
4505 'street_address' => 1,
4506 'supplemental_address_1' => 1,
4507 'supplemental_address_2' => 1,
207f62c6 4508 'supplemental_address_3' => 1,
6a488035
TO
4509 'city' => 1,
4510 'postal_code' => 1,
4511 'postal_code_suffix' => 1,
4512 'state_province' => 1,
4513 'country' => 1,
4514 'world_region' => 1,
4515 'geo_code_1' => 1,
4516 'geo_code_2' => 1,
4517 'email' => 1,
4518 'on_hold' => 1,
4519 'phone' => 1,
4520 'im' => 1,
4521 'household_name' => 1,
4522 'organization_name' => 1,
4523 'deceased_date' => 1,
4524 'is_deceased' => 1,
4525 'job_title' => 1,
4526 'legal_name' => 1,
4527 'sic_code' => 1,
4528 'current_employer' => 1,
4529 // FIXME: should we use defaultHierReturnProperties() for the below?
4530 'do_not_email' => 1,
4531 'do_not_mail' => 1,
4532 'do_not_sms' => 1,
4533 'do_not_phone' => 1,
4534 'do_not_trade' => 1,
4535 'is_opt_out' => 1,
4536 'contact_is_deleted' => 1,
b725488f
CW
4537 'preferred_communication_method' => 1,
4538 'preferred_language' => 1,
be2fb01f 4539 ];
6a488035
TO
4540 }
4541 }
4542 return self::$_defaultReturnProperties[$mode];
4543 }
4544
4545 /**
fe482240 4546 * Get primary condition for a sql clause.
6a488035
TO
4547 *
4548 * @param int $value
4549 *
fffe9ee1 4550 * @return string|NULL
6a488035 4551 */
00be9182 4552 public static function getPrimaryCondition($value) {
6a488035
TO
4553 if (is_numeric($value)) {
4554 $value = (int ) $value;
4555 return ($value == 1) ? 'is_primary = 1' : 'is_primary = 0';
4556 }
4557 return NULL;
4558 }
4559
4560 /**
fe482240 4561 * Wrapper for a simple search query.
6a488035
TO
4562 *
4563 * @param array $params
4564 * @param array $returnProperties
4e6072d5 4565 * @param bool $count
6a488035 4566 *
4e6072d5 4567 * @return string
6a488035 4568 */
00be9182 4569 public static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
6a488035
TO
4570 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4571 list($select, $from, $where, $having) = $query->query();
3875e6b6 4572 $groupBy = ($query->_useGroupBy) ? 'GROUP BY contact_a.id' : '';
6a488035 4573
c9c5c58d
AS
4574 $query = "$select $from $where $groupBy $having";
4575 return $query;
6a488035
TO
4576 }
4577
4578 /**
4579 * These are stub comments as this function needs more explanation - particularly in terms of how it
4580 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4581 *
4582 * This function was originally written as a wrapper for the api query but is called from multiple places
4583 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4584 * but it is unclear as to whehter that is historical or there is a reason
4585 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4586 *
837c4660
E
4587 * @param array $params
4588 * @param array $returnProperties
4589 * @param null $fields
6a488035 4590 * @param string $sort
837c4660
E
4591 * @param int $offset
4592 * @param int $row_count
77c5b619
TO
4593 * @param bool $smartGroupCache
4594 * ?? update smart group cache?.
4595 * @param bool $count
4596 * Return count obnly.
4597 * @param bool $skipPermissions
4598 * Should permissions be ignored or should the logged in user's permissions be applied.
9ae25b56 4599 * @param int $mode
4600 * This basically correlates to the component.
8f165fa5 4601 * @param string $apiEntity
4602 * The api entity being called.
4603 * This sort-of duplicates $mode in a confusing way. Probably not by design.
837c4660 4604 *
0606198b 4605 * @param bool|null $primaryLocationOnly
b725488f 4606 * @return array
6a488035 4607 */
59f4c9ee 4608 public static function apiQuery(
6a488035
TO
4609 $params = NULL,
4610 $returnProperties = NULL,
4611 $fields = NULL,
4612 $sort = NULL,
4613 $offset = 0,
4614 $row_count = 25,
4615 $smartGroupCache = TRUE,
4616 $count = FALSE,
9ae25b56 4617 $skipPermissions = TRUE,
3123273f 4618 $mode = CRM_Contact_BAO_Query::MODE_CONTACTS,
0606198b 4619 $apiEntity = NULL,
4620 $primaryLocationOnly = NULL
6a488035
TO
4621 ) {
4622
4623 $query = new CRM_Contact_BAO_Query(
4624 $params, $returnProperties,
9ae25b56 4625 NULL, TRUE, FALSE, $mode,
6a488035 4626 $skipPermissions,
66670e4d 4627 TRUE, $smartGroupCache,
4628 NULL, 'AND',
0606198b 4629 $apiEntity, $primaryLocationOnly
6a488035
TO
4630 );
4631
5c7dad85
TO
4632 //this should add a check for view deleted if permissions are enabled
4633 if ($skipPermissions) {
4634 $query->_skipDeleteClause = TRUE;
4635 }
6a488035 4636 $query->generatePermissionClause(FALSE, $count);
d9ab802d
PJ
4637
4638 // note : this modifies _fromClause and _simpleFromClause
4639 $query->includePseudoFieldsJoin($sort);
4640
6a488035
TO
4641 list($select, $from, $where, $having) = $query->query($count);
4642
4643 $options = $query->_options;
5c7dad85 4644 if (!empty($query->_permissionWhereClause)) {
6a488035
TO
4645 if (empty($where)) {
4646 $where = "WHERE $query->_permissionWhereClause";
4647 }
4648 else {
4649 $where = "$where AND $query->_permissionWhereClause";
4650 }
4651 }
4652
4653 $sql = "$select $from $where $having";
4654
783144b0 4655 // add group by only when API action is not getcount
4656 // otherwise query fetches incorrect count
4657 if ($query->_useGroupBy && !$count) {
e5cceea5 4658 $sql .= self::getGroupByFromSelectColumns($query->_select, 'contact_a.id');
6a488035
TO
4659 }
4660 if (!empty($sort)) {
bd9a3dd5 4661 $sort = CRM_Utils_Type::escape($sort, 'String');
6a488035
TO
4662 $sql .= " ORDER BY $sort ";
4663 }
4664 if ($row_count > 0 && $offset >= 0) {
bf00d1b6 4665 $offset = CRM_Utils_Type::escape($offset, 'Int');
9ae25b56 4666 $row_count = CRM_Utils_Type::escape($row_count, 'Int');
6a488035
TO
4667 $sql .= " LIMIT $offset, $row_count ";
4668 }
4669
4670 $dao = CRM_Core_DAO::executeQuery($sql);
4671
9ae25b56 4672 // @todo derive this from the component class rather than hard-code two options.
4673 $entityIDField = ($mode == CRM_Contact_BAO_Query::MODE_CONTRIBUTE) ? 'contribution_id' : 'contact_id';
4674
be2fb01f 4675 $values = [];
6a488035
TO
4676 while ($dao->fetch()) {
4677 if ($count) {
4678 $noRows = $dao->rowCount;
be2fb01f 4679 return [$noRows, NULL];
6a488035 4680 }
d9ab802d 4681 $val = $query->store($dao);
86ab13b7 4682 $convertedVals = $query->convertToPseudoNames($dao, TRUE, TRUE);
d9ab802d
PJ
4683
4684 if (!empty($convertedVals)) {
e3571aca 4685 $val = array_replace_recursive($val, $convertedVals);
d9ab802d 4686 }
9ae25b56 4687 $values[$dao->$entityIDField] = $val;
6a488035 4688 }
be2fb01f 4689 return [$values, $options];
6a488035
TO
4690 }
4691
bb05da0c 4692 /**
4693 * Get the actual custom field name by stripping off the appended string.
4694 *
4695 * The string could be _relative, _from, or _to
4696 *
4697 * @todo use metadata rather than convention to do this.
4698 *
4699 * @param string $parameterName
4700 * The name of the parameter submitted to the form.
4701 * e.g
4702 * custom_3_relative
4703 * custom_3_from
4704 *
4705 * @return string
4706 */
4707 public static function getCustomFieldName($parameterName) {
4708 if (substr($parameterName, -5, 5) == '_from') {
4709 return substr($parameterName, 0, strpos($parameterName, '_from'));
4710 }
4711 if (substr($parameterName, -9, 9) == '_relative') {
4712 return substr($parameterName, 0, strpos($parameterName, '_relative'));
4713 }
4714 if (substr($parameterName, -3, 3) == '_to') {
4715 return substr($parameterName, 0, strpos($parameterName, '_to'));
4716 }
4717 }
4718
4719 /**
4c2fe77b 4720 * Convert submitted values for relative custom fields to query object format.
bb05da0c 4721 *
4722 * The query will support the sqlOperator format so convert to that format.
4723 *
4724 * @param array $formValues
4725 * Submitted values.
4726 * @param array $params
4727 * Converted parameters for the query object.
4728 * @param string $values
4729 * Submitted value.
4730 * @param string $fieldName
4731 * Submitted field name. (Matches form field not DB field.)
4732 */
4c2fe77b 4733 protected static function convertCustomRelativeFields(&$formValues, &$params, $values, $fieldName) {
bb05da0c 4734 if (empty($values)) {
4735 // e.g we might have relative set & from & to empty. The form flow is a bit funky &
4736 // this function gets called again after they fields have been converted which can get ugly.
4737 return;
4738 }
4739 $customFieldName = self::getCustomFieldName($fieldName);
4740
4741 if (substr($fieldName, -9, 9) == '_relative') {
4742 list($from, $to) = CRM_Utils_Date::getFromTo($values, NULL, NULL);
4743 }
4744 else {
4745 if ($fieldName == $customFieldName . '_to' && CRM_Utils_Array::value($customFieldName . '_from', $formValues)) {
4746 // Both to & from are set. We only need to acton one, choosing from.
4747 return;
4748 }
4749
4c2fe77b 4750 $from = CRM_Utils_Array::value($customFieldName . '_from', $formValues, NULL);
4751 $to = CRM_Utils_Array::value($customFieldName . '_to', $formValues, NULL);
4752
2fe91f9d 4753 if (self::isCustomDateField($customFieldName)) {
4c2fe77b 4754 list($from, $to) = CRM_Utils_Date::getFromTo(NULL, $from, $to);
4755 }
bb05da0c 4756 }
4757
4758 if ($from) {
4759 if ($to) {
be2fb01f 4760 $relativeFunction = ['BETWEEN' => [$from, $to]];
bb05da0c 4761 }
4762 else {
be2fb01f 4763 $relativeFunction = ['>=' => $from];
bb05da0c 4764 }
4765 }
4766 else {
be2fb01f 4767 $relativeFunction = ['<=' => $to];
bb05da0c 4768 }
be2fb01f 4769 $params[] = [
bb05da0c 4770 $customFieldName,
4771 '=',
4772 $relativeFunction,
4773 0,
4774 0,
be2fb01f 4775 ];
bb05da0c 4776 }
4777
2fe91f9d 4778 /**
4779 * Are we dealing with custom field of type date.
4780 *
4781 * @param $fieldName
4782 *
4783 * @return bool
4784 */
4785 public static function isCustomDateField($fieldName) {
4786 if (($customFieldID = CRM_Core_BAO_CustomField::getKeyID($fieldName)) == FALSE) {
4787 return FALSE;
4788 }
be2fb01f 4789 if ('Date' == civicrm_api3('CustomField', 'getvalue', ['id' => $customFieldID, 'return' => 'data_type'])) {
2fe91f9d 4790 return TRUE;
4791 }
4792 return FALSE;
4793 }
4794
df60621b 4795 /**
4796 * Has this field already been reformatting to Query object syntax.
4797 *
4798 * The form layer passed formValues to this function in preProcess & postProcess. Reason unknown. This seems
4799 * to come with associated double queries & is possibly damaging performance.
4800 *
4801 * However, here we add a tested function to ensure convertFormValues identifies pre-processed fields & returns
4802 * them as they are.
4803 *
4804 * @param mixed $values
4805 * Value in formValues for the field.
4806 *
4807 * @return bool;
4808 */
06d67d53 4809 public static function isAlreadyProcessedForQueryFormat($values) {
df60621b 4810 if (!is_array($values)) {
4811 return FALSE;
4812 }
4813 if (($operator = CRM_Utils_Array::value(1, $values)) == FALSE) {
4814 return FALSE;
4815 }
4816 return in_array($operator, CRM_Core_DAO::acceptedSQLOperators());
4817 }
4818
20306bb8 4819 /**
4820 * If the state and country are passed remove state.
4821 *
4822 * Country is implicit from the state, but including both results in
4823 * a poor query as there is no combined index on state AND country.
4824 *
4825 * CRM-18125
4826 *
4827 * @param array $formValues
4828 */
4829 public static function filterCountryFromValuesIfStateExists(&$formValues) {
e4001cf0 4830 if (!empty($formValues['country']) && !empty($formValues['state_province'])) {
4831 // The use of array map sanitises the data by ensuring we are dealing with integers.
4832 $states = implode(', ', array_map('intval', $formValues['state_province']));
4833 $countryList = CRM_Core_DAO::singleValueQuery(
4834 "SELECT GROUP_CONCAT(country_id) FROM civicrm_state_province WHERE id IN ($states)"
4835 );
4836 if ($countryList == $formValues['country']) {
4837 unset($formValues['country']);
20306bb8 4838 }
4839 }
4840 }
4841
36d2f4d5 4842 /**
4843 * For some special cases, grouping by subset of select fields becomes mandatory.
4844 * Hence, full_group_by mode is handled by appending any_value
4845 * keyword to select fields not present in groupBy
4846 *
4847 * @param array $selectClauses
4848 * @param array $groupBy - Columns already included in GROUP By clause.
0ad26017 4849 * @param string $aggregateFunction
36d2f4d5 4850 *
4851 * @return string
4852 */
0ad26017 4853 public static function appendAnyValueToSelect($selectClauses, $groupBy, $aggregateFunction = 'ANY_VALUE') {
b07c960a 4854 if (!CRM_Utils_SQL::disableFullGroupByMode()) {
36d2f4d5 4855 $groupBy = array_map('trim', (array) $groupBy);
f8a02ee1 4856 $aggregateFunctions = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN|IF)[[:blank:]]*\(/i';
36d2f4d5 4857 foreach ($selectClauses as $key => &$val) {
4858 list($selectColumn, $alias) = array_pad(preg_split('/ as /i', $val), 2, NULL);
4859 // append ANY_VALUE() keyword
4860 if (!in_array($selectColumn, $groupBy) && preg_match($aggregateFunctions, trim($selectColumn)) !== 1) {
0ad26017 4861 $val = ($aggregateFunction == 'GROUP_CONCAT') ?
4862 str_replace($selectColumn, "$aggregateFunction(DISTINCT {$selectColumn})", $val) :
4863 str_replace($selectColumn, "$aggregateFunction({$selectColumn})", $val);
36d2f4d5 4864 }
4865 }
4866 }
4867
4868 return "SELECT " . implode(', ', $selectClauses) . " ";
4869 }
4870
b07c960a 4871 /**
4872 * For some special cases, where if non-aggregate ORDER BY columns are not present in GROUP BY
4873 * on full_group_by mode, then append the those missing columns to GROUP BY clause
4874 * keyword to select fields not present in groupBy
4875 *
e5167553 4876 * @param string $groupBy - GROUP BY clause where missing ORDER BY columns will be appended if not present
b07c960a 4877 * @param array $orderBys - ORDER BY sub-clauses
4878 *
4879 */
4880 public static function getGroupByFromOrderBy(&$groupBy, $orderBys) {
0ad26017 4881 if (!CRM_Utils_SQL::disableFullGroupByMode()) {
b07c960a 4882 foreach ($orderBys as $orderBy) {
69078420
SL
4883 // remove sort syntax from ORDER BY clauses if present
4884 $orderBy = str_ireplace([' DESC', ' ASC', '`'], '', $orderBy);
b07c960a 4885 // if ORDER BY column is not present in GROUP BY then append it to end
e5167553 4886 if (preg_match('/(MAX|MIN)\(/i', trim($orderBy)) !== 1 && !strstr($groupBy, $orderBy)) {
4887 $groupBy .= ", {$orderBy}";
b07c960a 4888 }
4889 }
4890 }
4891 }
4892
e5cceea5 4893 /**
4894 * Include Select columns in groupBy clause.
4895 *
dc852c7b 4896 * @param array $selectClauses
e5cceea5 4897 * @param array $groupBy - Columns already included in GROUP By clause.
4898 *
4899 * @return string
4900 */
4901 public static function getGroupByFromSelectColumns($selectClauses, $groupBy = NULL) {
b708c08d 4902 $groupBy = (array) $groupBy;
3636b520 4903 $mysqlVersion = CRM_Core_DAO::singleValueQuery('SELECT VERSION()');
bad98dd5 4904 $sqlMode = CRM_Core_DAO::singleValueQuery('SELECT @@sql_mode');
b708c08d 4905
4906 //return if ONLY_FULL_GROUP_BY is not enabled.
712e729f 4907 if (CRM_Utils_SQL::supportsFullGroupBy() && !empty($sqlMode) && in_array('ONLY_FULL_GROUP_BY', explode(',', $sqlMode))) {
f8a02ee1 4908 $regexToExclude = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN|IF)[[:blank:]]*\(/i';
dc852c7b 4909 foreach ($selectClauses as $key => $val) {
4910 $aliasArray = preg_split('/ as /i', $val);
4911 // if more than 1 alias we need to split by ','.
4912 if (count($aliasArray) > 2) {
4913 $aliasArray = preg_split('/,/', $val);
4914 foreach ($aliasArray as $key => $value) {
4915 $alias = current(preg_split('/ as /i', $value));
4916 if (!in_array($alias, $groupBy) && preg_match($regexToExclude, trim($alias)) !== 1) {
4917 $groupBy[] = $alias;
4918 }
e5cceea5 4919 }
4920 }
dc852c7b 4921 else {
4922 list($selectColumn, $alias) = array_pad($aliasArray, 2, NULL);
4923 $dateRegex = '/^(DATE_FORMAT|DATE_ADD|CASE)/i';
4924 $tableName = current(explode('.', $selectColumn));
4925 $primaryKey = "{$tableName}.id";
4926 // exclude columns which are already included in groupBy and aggregate functions from select
4927 // CRM-18439 - Also exclude the columns which are functionally dependent on columns in $groupBy (MySQL 5.7+)
4928 if (!in_array($selectColumn, $groupBy) && !in_array($primaryKey, $groupBy) && preg_match($regexToExclude, trim($selectColumn)) !== 1) {
4929 if (!empty($alias) && preg_match($dateRegex, trim($selectColumn))) {
4930 $groupBy[] = $alias;
4931 }
4932 else {
4933 $groupBy[] = $selectColumn;
4934 }
e5cceea5 4935 }
4936 }
4937 }
4938 }
4939
b708c08d 4940 if (!empty($groupBy)) {
4941 return " GROUP BY " . implode(', ', $groupBy);
e5cceea5 4942 }
4943 return '';
4944 }
4945
6a488035 4946 /**
fe482240 4947 * Create and query the db for an contact search.
6a488035 4948 *
77c5b619
TO
4949 * @param int $offset
4950 * The offset for the query.
4951 * @param int $rowCount
4952 * The number of rows to return.
db54ba06 4953 * @param string|CRM_Utils_Sort $sort
77c5b619
TO
4954 * The order by string.
4955 * @param bool $count
4956 * Is this a count only query ?.
4957 * @param bool $includeContactIds
4958 * Should we include contact ids?.
4959 * @param bool $sortByChar
4960 * If true returns the distinct array of first characters for search results.
4961 * @param bool $groupContacts
4962 * If true, return only the contact ids.
4963 * @param bool $returnQuery
4964 * Should we return the query as a string.
4965 * @param string $additionalWhereClause
4966 * If the caller wants to further restrict the search (used for components).
77b97be7 4967 * @param null $sortOrder
77c5b619
TO
4968 * @param string $additionalFromClause
4969 * Should be clause with proper joins, effective to reduce where clause load.
77b97be7
EM
4970 *
4971 * @param bool $skipOrderAndLimit
6a488035 4972 *
55eb4e22 4973 * @return CRM_Core_DAO
6a488035 4974 */
59f4c9ee 4975 public function searchQuery(
6a488035
TO
4976 $offset = 0, $rowCount = 0, $sort = NULL,
4977 $count = FALSE, $includeContactIds = FALSE,
4978 $sortByChar = FALSE, $groupContacts = FALSE,
4979 $returnQuery = FALSE,
4980 $additionalWhereClause = NULL, $sortOrder = NULL,
4981 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4982 ) {
4983
89d7bb76 4984 $query = $this->getSearchSQL($offset, $rowCount, $sort, $count, $includeContactIds, $sortByChar, $groupContacts, $additionalWhereClause, $sortOrder, $additionalFromClause, $skipOrderAndLimit);
6a488035
TO
4985
4986 if ($returnQuery) {
4987 return $query;
4988 }
6a488035
TO
4989 if ($count) {
4990 return CRM_Core_DAO::singleValueQuery($query);
4991 }
4992
6a488035 4993 $dao = CRM_Core_DAO::executeQuery($query);
d567ed10 4994
89d7bb76 4995 // We can always call this - it will only re-enable if it was originally enabled.
4996 CRM_Core_DAO::reenableFullGroupByMode();
d567ed10 4997
6a488035 4998 if ($groupContacts) {
be2fb01f 4999 $ids = [];
6a488035
TO
5000 while ($dao->fetch()) {
5001 $ids[] = $dao->id;
5002 }
5003 return implode(',', $ids);
5004 }
5005
5006 return $dao;
5007 }
5008
52cda5dc 5009 /**
caefed7d 5010 * Create and query the db for the list of all first letters used by contacts
52cda5dc
MWMC
5011 *
5012 * @return CRM_Core_DAO
5013 */
5014 public function alphabetQuery() {
caefed7d
MWMC
5015 $sqlParts = $this->getSearchSQLParts(NULL, NULL, NULL, FALSE, FALSE, TRUE);
5016 $query = "SELECT DISTINCT LEFT(contact_a.sort_name, 1) as sort_name
def88c52 5017 {$sqlParts['from']}
caefed7d
MWMC
5018 {$sqlParts['where']}
5019 {$sqlParts['having']}
5020 GROUP BY sort_name
5021 ORDER BY sort_name asc";
52cda5dc 5022 $dao = CRM_Core_DAO::executeQuery($query);
52cda5dc
MWMC
5023 return $dao;
5024 }
5025
4243847f 5026 /**
2ca46d4d 5027 * Fetch a list of contacts for displaying a search results page
4243847f 5028 *
2ca46d4d
TO
5029 * @param array $cids
5030 * List of contact IDs
77c5b619 5031 * @param bool $includeContactIds
4243847f
CW
5032 * @return CRM_Core_DAO
5033 */
2ca46d4d 5034 public function getCachedContacts($cids, $includeContactIds) {
00a03110 5035 CRM_Core_DAO::disableFullGroupByMode();
2ca46d4d 5036 CRM_Utils_Type::validateAll($cids, 'Positive');
4243847f 5037 $this->_includeContactIds = $includeContactIds;
be2fb01f 5038 $onlyDeleted = in_array(['deleted_contacts', '=', '1', '0', '0'], $this->_params);
f6364403 5039 list($select, $from, $where) = $this->query(FALSE, FALSE, FALSE, $onlyDeleted);
2ca46d4d
TO
5040 $select .= sprintf(", (%s) AS _wgt", $this->createSqlCase('contact_a.id', $cids));
5041 $where .= sprintf(' AND contact_a.id IN (%s)', implode(',', $cids));
5042 $order = 'ORDER BY _wgt';
1d8fcdc5 5043 $groupBy = $this->_useGroupBy ? ' GROUP BY contact_a.id' : '';
2ca46d4d 5044 $limit = '';
9b5914f2 5045 $query = "$select $from $where $groupBy $order $limit";
23379b49 5046
00a03110 5047 $result = CRM_Core_DAO::executeQuery($query);
5048 CRM_Core_DAO::reenableFullGroupByMode();
5049 return $result;
4243847f
CW
5050 }
5051
2ca46d4d
TO
5052 /**
5053 * Construct a SQL CASE expression.
5054 *
5055 * @param string $idCol
5056 * The name of a column with ID's (eg 'contact_a.id').
5057 * @param array $cids
5058 * Array(int $weight => int $id).
5059 * @return string
5060 * CASE WHEN id=123 THEN 1 WHEN id=456 THEN 2 END
5061 */
5062 private function createSqlCase($idCol, $cids) {
5063 $buf = "CASE\n";
5064 foreach ($cids as $weight => $cid) {
5065 $buf .= " WHEN $idCol = $cid THEN $weight \n";
5066 }
5067 $buf .= "END\n";
5068 return $buf;
5069 }
5070
6a488035
TO
5071 /**
5072 * Populate $this->_permissionWhereClause with permission related clause and update other
5073 * query related properties.
5074 *
5075 * Function calls ACL permission class and hooks to filter the query appropriately
5076 *
5077 * Note that these 2 params were in the code when extracted from another function
5078 * and a second round extraction would be to make them properties of the class
5079 *
77c5b619
TO
5080 * @param bool $onlyDeleted
5081 * Only get deleted contacts.
5082 * @param bool $count
5083 * Return Count only.
6a488035 5084 */
00be9182 5085 public function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
6a488035
TO
5086 if (!$this->_skipPermission) {
5087 $this->_permissionWhereClause = CRM_ACL_API::whereClause(
5088 CRM_Core_Permission::VIEW,
5089 $this->_tables,
5090 $this->_whereTables,
5091 NULL,
5092 $onlyDeleted,
5093 $this->_skipDeleteClause
5094 );
5095
5096 // regenerate fromClause since permission might have added tables
5097 if ($this->_permissionWhereClause) {
5098 //fix for row count in qill (in contribute/membership find)
5099 if (!$count) {
5100 $this->_useDistinct = TRUE;
5101 }
94cb2350 5102 //CRM-15231
5103 $this->_fromClause = self::fromClause($this->_tables, NULL, NULL, $this->_primaryLocation, $this->_mode);
5104 $this->_simpleFromClause = self::fromClause($this->_whereTables, NULL, NULL, $this->_primaryLocation, $this->_mode);
47cd307b 5105 // note : this modifies _fromClause and _simpleFromClause
ac4985d5 5106 $this->includePseudoFieldsJoin($this->_sort);
6a488035
TO
5107 }
5108 }
5109 else {
5110 // add delete clause if needed even if we are skipping permission
5111 // CRM-7639
5112 if (!$this->_skipDeleteClause) {
5113 if (CRM_Core_Permission::check('access deleted contacts') and $onlyDeleted) {
5114 $this->_permissionWhereClause = '(contact_a.is_deleted)';
5115 }
5116 else {
5117 // CRM-6181
5118 $this->_permissionWhereClause = '(contact_a.is_deleted = 0)';
5119 }
5120 }
5121 }
5122 }
5123
86538308
EM
5124 /**
5125 * @param $val
5126 */
00be9182 5127 public function setSkipPermission($val) {
6a488035
TO
5128 $this->_skipPermission = $val;
5129 }
5130
86538308
EM
5131 /**
5132 * @param null $context
5133 *
5134 * @return array
5135 */
faba82fc 5136 public function summaryContribution($context = NULL) {
d7803ec1 5137 list($innerselect, $from, $where, $having) = $this->query(TRUE);
8ef6eb78 5138 if ($this->_permissionWhereClause) {
5139 $where .= " AND " . $this->_permissionWhereClause;
5140 }
5141 if ($context == 'search') {
5142 $where .= " AND contact_a.is_deleted = 0 ";
5143 }
6a488035 5144
8ef6eb78 5145 $this->appendFinancialTypeWhereAndFromToQueryStrings($where, $from);
dbaa9d7d 5146
8ef6eb78 5147 $summary = ['total' => []];
5148 $this->addBasicStatsToSummary($summary, $where, $from);
d03881d3 5149
6d68fd76 5150 if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled()) {
5151 $this->addBasicSoftCreditStatsToStats($summary, $where, $from);
5152 }
5153
386fce20 5154 $this->addBasicCancelStatsToSummary($summary, $where, $from);
6a488035
TO
5155
5156 return $summary;
5157 }
5158
5384a978 5159 /**
dbaa9d7d 5160 * Append financial ACL limits to the query from & where clauses, if applicable.
5384a978 5161 *
dbaa9d7d 5162 * @param string $where
5163 * @param string $from
5384a978 5164 */
dbaa9d7d 5165 public function appendFinancialTypeWhereAndFromToQueryStrings(&$where, &$from) {
5166 if (!CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
5167 return;
5384a978
VR
5168 }
5169 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
5170 if (!empty($financialTypes)) {
5171 $where .= " AND civicrm_contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND li.id IS NULL";
5172 $from .= " LEFT JOIN civicrm_line_item li
5173 ON civicrm_contribution.id = li.contribution_id AND
5174 li.entity_table = 'civicrm_contribution' AND li.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ") ";
5175 }
5176 else {
5177 $where .= " AND civicrm_contribution.financial_type_id IN (0)";
5178 }
5384a978
VR
5179 }
5180
6a488035 5181 /**
fe482240 5182 * Getter for the qill object.
6a488035
TO
5183 *
5184 * @return string
6a488035 5185 */
00be9182 5186 public function qill() {
6a488035
TO
5187 return $this->_qill;
5188 }
5189
5190 /**
fe482240 5191 * Default set of return default hier return properties.
6a488035 5192 *
fffe9ee1 5193 * @return array
6a488035 5194 */
00be9182 5195 public static function &defaultHierReturnProperties() {
6a488035 5196 if (!isset(self::$_defaultHierReturnProperties)) {
be2fb01f 5197 self::$_defaultHierReturnProperties = [
6a488035
TO
5198 'home_URL' => 1,
5199 'image_URL' => 1,
5200 'legal_identifier' => 1,
5201 'external_identifier' => 1,
5202 'contact_type' => 1,
5203 'contact_sub_type' => 1,
5204 'sort_name' => 1,
5205 'display_name' => 1,
5206 'nick_name' => 1,
5207 'first_name' => 1,
5208 'middle_name' => 1,
5209 'last_name' => 1,
67744c4e
CW
5210 'prefix_id' => 1,
5211 'suffix_id' => 1,
e171748b 5212 'formal_title' => 1,
aa62b355 5213 'communication_style_id' => 1,
6a488035
TO
5214 'email_greeting' => 1,
5215 'postal_greeting' => 1,
5216 'addressee' => 1,
5217 'birth_date' => 1,
67744c4e 5218 'gender_id' => 1,
6a488035
TO
5219 'preferred_communication_method' => 1,
5220 'do_not_phone' => 1,
5221 'do_not_email' => 1,
5222 'do_not_mail' => 1,
5223 'do_not_sms' => 1,
5224 'do_not_trade' => 1,
be2fb01f
CW
5225 'location' => [
5226 '1' => [
59f4c9ee
TO
5227 'location_type' => 1,
5228 'street_address' => 1,
5229 'city' => 1,
5230 'state_province' => 1,
5231 'postal_code' => 1,
5232 'postal_code_suffix' => 1,
5233 'country' => 1,
5234 'phone-Phone' => 1,
5235 'phone-Mobile' => 1,
5236 'phone-Fax' => 1,
5237 'phone-1' => 1,
5238 'phone-2' => 1,
5239 'phone-3' => 1,
5240 'im-1' => 1,
5241 'im-2' => 1,
5242 'im-3' => 1,
5243 'email-1' => 1,
5244 'email-2' => 1,
5245 'email-3' => 1,
be2fb01f
CW
5246 ],
5247 '2' => [
59f4c9ee
TO
5248 'location_type' => 1,
5249 'street_address' => 1,
5250 'city' => 1,
5251 'state_province' => 1,
5252 'postal_code' => 1,
5253 'postal_code_suffix' => 1,
5254 'country' => 1,
5255 'phone-Phone' => 1,
5256 'phone-Mobile' => 1,
5257 'phone-1' => 1,
5258 'phone-2' => 1,
5259 'phone-3' => 1,
5260 'im-1' => 1,
5261 'im-2' => 1,
5262 'im-3' => 1,
5263 'email-1' => 1,
5264 'email-2' => 1,
5265 'email-3' => 1,
be2fb01f
CW
5266 ],
5267 ],
5268 ];
6a488035
TO
5269 }
5270 return self::$_defaultHierReturnProperties;
5271 }
5272
86538308 5273 /**
c037736a 5274 * Build query for a date field.
5275 *
5276 * @param array $values
100fef9d
CW
5277 * @param string $tableName
5278 * @param string $fieldName
5279 * @param string $dbFieldName
c037736a 5280 * @param string $fieldTitle
86538308 5281 * @param bool $appendTimeStamp
d51e2817 5282 * @param string $dateFormat
936ededf 5283 * @param string|null $highDBFieldName
5284 * Optional field name for when the 'high' part of the calculation uses a different field than the 'low' part.
5285 * This is an obscure situation & one we don't want to do more of but supporting them here is the only way for now.
5286 * Examples are event date & relationship active date -in both cases we are looking for things greater than the start
5287 * date & less than the end date.
5288 *
5289 * @throws \CRM_Core_Exception
86538308 5290 */
59f4c9ee 5291 public function dateQueryBuilder(
33a17d7e 5292 $values, $tableName, $fieldName,
6a488035 5293 $dbFieldName, $fieldTitle,
d51e2817 5294 $appendTimeStamp = TRUE,
936ededf 5295 $dateFormat = 'YmdHis',
5296 $highDBFieldName = NULL
6a488035 5297 ) {
5b5ea9b6 5298 // @todo - remove dateFormat - pretty sure it's never passed in...
6a488035
TO
5299 list($name, $op, $value, $grouping, $wildcard) = $values;
5300
6a488035
TO
5301 if ($name == "{$fieldName}_low" ||
5302 $name == "{$fieldName}_high"
5303 ) {
efb88612 5304 if (isset($this->_rangeCache[$fieldName]) || !$value) {
6a488035
TO
5305 return;
5306 }
5307 $this->_rangeCache[$fieldName] = 1;
5308
5309 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
5310
5311 if ($name == $fieldName . '_low') {
5312 $firstOP = '>=';
228917cd 5313 $firstPhrase = ts('greater than or equal to');
d51e2817 5314 $firstDate = CRM_Utils_Date::processDate($value, NULL, FALSE, $dateFormat);
6a488035
TO
5315
5316 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
228917cd 5317 if (!empty($secondValues) && $secondValues[2]) {
6a488035 5318 $secondOP = '<=';
228917cd 5319 $secondPhrase = ts('less than or equal to');
6a488035
TO
5320 $secondValue = $secondValues[2];
5321
228917cd 5322 if ($appendTimeStamp && strlen($secondValue) == 10) {
6a488035
TO
5323 $secondValue .= ' 23:59:59';
5324 }
d51e2817 5325 $secondDate = CRM_Utils_Date::processDate($secondValue, NULL, FALSE, $dateFormat);
6a488035
TO
5326 }
5327 }
5328 elseif ($name == $fieldName . '_high') {
5329 $firstOP = '<=';
228917cd 5330 $firstPhrase = ts('less than or equal to');
6a488035 5331
228917cd 5332 if ($appendTimeStamp && strlen($value) == 10) {
6a488035
TO
5333 $value .= ' 23:59:59';
5334 }
d51e2817 5335 $firstDate = CRM_Utils_Date::processDate($value, NULL, FALSE, $dateFormat);
6a488035
TO
5336
5337 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
228917cd 5338 if (!empty($secondValues) && $secondValues[2]) {
6a488035 5339 $secondOP = '>=';
228917cd 5340 $secondPhrase = ts('greater than or equal to');
6a488035 5341 $secondValue = $secondValues[2];
d51e2817 5342 $secondDate = CRM_Utils_Date::processDate($secondValue, NULL, FALSE, $dateFormat);
6a488035
TO
5343 }
5344 }
5345
5346 if (!$appendTimeStamp) {
5347 $firstDate = substr($firstDate, 0, 8);
5348 }
5349 $firstDateFormat = CRM_Utils_Date::customFormat($firstDate);
5350
5351 if ($secondDate) {
5352 if (!$appendTimeStamp) {
5353 $secondDate = substr($secondDate, 0, 8);
5354 }
5355 $secondDateFormat = CRM_Utils_Date::customFormat($secondDate);
5356 }
5357
5358 $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
5359 if ($secondDate) {
936ededf 5360 $highDBFieldName = $highDBFieldName ?? $dbFieldName;
6a488035
TO
5361 $this->_where[$grouping][] = "
5362( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
936ededf 5363( {$tableName}.{$highDBFieldName} $secondOP '$secondDate' )
6a488035
TO
5364";
5365 $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
5366 }
5367 else {
5368 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5369 $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5370 }
5371 }
5372
5373 if ($name == $fieldName) {
d820f4e8 5374 //In Get API, for operators other then '=' the $value is in array(op => value) format
5375 if (is_array($value) && !empty($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
5376 $op = key($value);
5377 $value = $value[$op];
5378 }
6a488035 5379
efb88612 5380 $date = $format = NULL;
fbc6a4d4 5381 if (strstr($op, 'IN')) {
be2fb01f 5382 $format = [];
ee657a1c 5383 foreach ($value as &$date) {
d51e2817 5384 $date = CRM_Utils_Date::processDate($date, NULL, FALSE, $dateFormat);
ee657a1c 5385 if (!$appendTimeStamp) {
5386 $date = substr($date, 0, 8);
5387 }
fbc6a4d4 5388 $format[] = CRM_Utils_Date::customFormat($date);
ee657a1c 5389 }
5390 $date = "('" . implode("','", $value) . "')";
fbc6a4d4 5391 $format = implode(', ', $format);
ee657a1c 5392 }
0a74debb 5393 elseif ($value && (!strstr($op, 'NULL') && !strstr($op, 'EMPTY'))) {
d51e2817 5394 $date = CRM_Utils_Date::processDate($value, NULL, FALSE, $dateFormat);
ee657a1c 5395 if (!$appendTimeStamp) {
5396 $date = substr($date, 0, 8);
5397 }
fbc6a4d4 5398 $format = CRM_Utils_Date::customFormat($date);
efb88612 5399 $date = "'$date'";
6a488035 5400 }
6a488035
TO
5401
5402 if ($date) {
f1339cf2 5403 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $op $date";
6a488035
TO
5404 }
5405 else {
515293b2 5406 $this->_where[$grouping][] = self::buildClause("{$tableName}.{$dbFieldName}", $op);
6a488035 5407 }
efb88612 5408
6a488035 5409 $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
d820f4e8 5410
5411 $op = CRM_Utils_Array::value($op, CRM_Core_SelectValues::getSearchBuilderOperators(), $op);
efb88612 5412 $this->_qill[$grouping][] = "$fieldTitle $op $format";
6a488035 5413 }
6a488035
TO
5414 }
5415
86538308
EM
5416 /**
5417 * @param $values
100fef9d
CW
5418 * @param string $tableName
5419 * @param string $fieldName
5420 * @param string $dbFieldName
86538308
EM
5421 * @param $fieldTitle
5422 * @param null $options
5423 */
59f4c9ee 5424 public function numberRangeBuilder(
51ccfbbe
TO
5425 &$values,
5426 $tableName, $fieldName,
5427 $dbFieldName, $fieldTitle,
5428 $options = NULL
6a488035
TO
5429 ) {
5430 list($name, $op, $value, $grouping, $wildcard) = $values;
5431
5432 if ($name == "{$fieldName}_low" ||
5433 $name == "{$fieldName}_high"
5434 ) {
5435 if (isset($this->_rangeCache[$fieldName])) {
5436 return;
5437 }
5438 $this->_rangeCache[$fieldName] = 1;
5439
5440 $secondOP = $secondPhrase = $secondValue = NULL;
5441
5442 if ($name == "{$fieldName}_low") {
5443 $firstOP = '>=';
228917cd 5444 $firstPhrase = ts('greater than');
6a488035
TO
5445
5446 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5447 if (!empty($secondValues)) {
5448 $secondOP = '<=';
228917cd 5449 $secondPhrase = ts('less than');
6a488035
TO
5450 $secondValue = $secondValues[2];
5451 }
5452 }
5453 else {
5454 $firstOP = '<=';
228917cd 5455 $firstPhrase = ts('less than');
6a488035
TO
5456
5457 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5458 if (!empty($secondValues)) {
5459 $secondOP = '>=';
228917cd 5460 $secondPhrase = ts('greater than');
6a488035
TO
5461 $secondValue = $secondValues[2];
5462 }
5463 }
5464
5465 if ($secondOP) {
5466 $this->_where[$grouping][] = "
5467( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5468( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5469";
5470 $displayValue = $options ? $options[$value] : $value;
5471 $secondDisplayValue = $options ? $options[$secondValue] : $secondValue;
5472
59f4c9ee
TO
5473 $this->_qill[$grouping][]
5474 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
6a488035
TO
5475 }
5476 else {
5477 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5478 $displayValue = $options ? $options[$value] : $value;
5479 $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5480 }
5481 $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
5482
5483 return;
5484 }
5485
5486 if ($name == $fieldName) {
5487 $op = '=';
5488 $phrase = '=';
5489
5490 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5491
5492 $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
5493 $displayValue = $options ? $options[$value] : $value;
5494 $this->_qill[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5495 }
6a488035
TO
5496 }
5497
c4a7c967 5498 /**
5499 * @param $values
5500 * @param string $tableName
5501 * @param string $fieldName
5502 * @param string $dbFieldName
5503 * @param $fieldTitle
5504 * @param null $options
5505 */
5506 public function ageRangeQueryBuilder(
5507 &$values,
5508 $tableName, $fieldName,
5509 $dbFieldName, $fieldTitle,
5510 $options = NULL
5511 ) {
5512 list($name, $op, $value, $grouping, $wildcard) = $values;
5513
5514 $asofDateValues = $this->getWhereValues("{$fieldName}_asof_date", $grouping);
69078420
SL
5515 // will be treated as current day
5516 $asofDate = NULL;
c4a7c967 5517 if ($asofDateValues) {
5518 $asofDate = CRM_Utils_Date::processDate($asofDateValues[2]);
5519 $asofDateFormat = CRM_Utils_Date::customFormat(substr($asofDate, 0, 8));
5520 $fieldTitle .= ' ' . ts('as of') . ' ' . $asofDateFormat;
5521 }
5522
5523 if ($name == "{$fieldName}_low" ||
5524 $name == "{$fieldName}_high"
5525 ) {
5526 if (isset($this->_rangeCache[$fieldName])) {
5527 return;
5528 }
5529 $this->_rangeCache[$fieldName] = 1;
5530
5531 $secondOP = $secondPhrase = $secondValue = NULL;
5532
5533 if ($name == "{$fieldName}_low") {
5534 $firstPhrase = ts('greater than or equal to');
5535 // NB: age > X means date of birth < Y
5536 $firstOP = '<=';
5537 $firstDate = self::calcDateFromAge($asofDate, $value, 'min');
5538
5539 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5540 if (!empty($secondValues)) {
5541 $secondOP = '>=';
5542 $secondPhrase = ts('less than or equal to');
5543 $secondValue = $secondValues[2];
5544 $secondDate = self::calcDateFromAge($asofDate, $secondValue, 'max');
5545 }
5546 }
5547 else {
5548 $firstOP = '>=';
5549 $firstPhrase = ts('less than or equal to');
5550 $firstDate = self::calcDateFromAge($asofDate, $value, 'max');
5551
5552 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5553 if (!empty($secondValues)) {
5554 $secondOP = '<=';
5555 $secondPhrase = ts('greater than or equal to');
5556 $secondValue = $secondValues[2];
5557 $secondDate = self::calcDateFromAge($asofDate, $secondValue, 'min');
5558 }
5559 }
5560
c4a7c967 5561 if ($secondOP) {
5562 $this->_where[$grouping][] = "
5563( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5564( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5565";
5566 $displayValue = $options ? $options[$value] : $value;
5567 $secondDisplayValue = $options ? $options[$secondValue] : $secondValue;
5568
5569 $this->_qill[$grouping][]
5570 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5571 }
5572 else {
5573 $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5574 $displayValue = $options ? $options[$value] : $value;
5575 $this->_qill[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5576 }
5577 $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
5578 return;
5579 }
5580 }
5581
70599df6 5582 /**
5583 * Calculate date from age.
5584 *
5585 * @param string $asofDate
5586 * @param int $age
5587 * @param string $type
5588 *
5589 * @return string
5590 */
c4a7c967 5591 public static function calcDateFromAge($asofDate, $age, $type) {
5592 $date = new DateTime($asofDate);
5593 if ($type == "min") {
5594 // minimum age is $age: dob <= date - age "235959"
5595 $date->sub(new DateInterval("P" . $age . "Y"));
5596 return $date->format('Ymd') . "235959";
69c53a43 5597 }
5598 else {
c4a7c967 5599 // max age is $age: dob >= date - (age + 1y) + 1d "000000"
5600 $date->sub(new DateInterval("P" . ($age + 1) . "Y"))->add(new DateInterval("P1D"));
5601 return $date->format('Ymd') . "000000";
5602 }
5603 }
5604
6a488035
TO
5605 /**
5606 * Given the field name, operator, value & its data type
5607 * builds the where Clause for the query
5608 * used for handling 'IS NULL'/'IS NOT NULL' operators
5609 *
77c5b619
TO
5610 * @param string $field
5611 * Fieldname.
5612 * @param string $op
5613 * Operator.
5614 * @param string $value
5615 * Value.
5616 * @param string $dataType
5617 * Data type of the field.
6a488035 5618 *
a6c01b45 5619 * @return string
59f4c9ee 5620 * Where clause for the query.
6a488035 5621 */
00be9182 5622 public static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
6a488035
TO
5623 $op = trim($op);
5624 $clause = "$field $op";
5625
5626 switch ($op) {
5627 case 'IS NULL':
5628 case 'IS NOT NULL':
5629 return $clause;
5630
5631 case 'IS EMPTY':
89d4a22f 5632 $clause = ($dataType == 'Date') ? " $field IS NULL " : " (NULLIF($field, '') IS NULL) ";
6a488035
TO
5633 return $clause;
5634
5635 case 'IS NOT EMPTY':
89d4a22f 5636 $clause = ($dataType == 'Date') ? " $field IS NOT NULL " : " (NULLIF($field, '') IS NOT NULL) ";
6a488035
TO
5637 return $clause;
5638
a0475688 5639 case 'RLIKE':
5640 return " {$clause} BINARY '{$value}' ";
5641
e2b0fbec 5642 case 'IN':
5643 case 'NOT IN':
715277e7 5644 // I feel like this would be escaped properly if passed through $queryString = CRM_Core_DAO::createSqlFilter.
46b3417a 5645 if (!empty($value) && (!is_array($value) || !array_key_exists($op, $value))) {
be2fb01f 5646 $value = [$op => (array) $value];
e2b0fbec 5647 }
5648
6a488035 5649 default:
89d4a22f 5650 if (empty($dataType) || $dataType == 'Date') {
6a488035
TO
5651 $dataType = 'String';
5652 }
461c9a60
EM
5653 if (is_array($value)) {
5654 //this could have come from the api - as in the restWhere section we potentially use the api operator syntax which is becoming more
5655 // widely used and consistent across the codebase
5656 // adding this here won't accept the search functions which don't submit an array
5657 if (($queryString = CRM_Core_DAO::createSqlFilter($field, $value, $dataType)) != FALSE) {
6e23130a 5658
461c9a60
EM
5659 return $queryString;
5660 }
ccabbc44 5661 if (!empty($value[0]) && $op === 'BETWEEN') {
5662 CRM_Core_Error::deprecatedFunctionWarning('Fix search input params');
be2fb01f 5663 if (($queryString = CRM_Core_DAO::createSqlFilter($field, [$op => $value], $dataType)) != FALSE) {
6e23130a
EM
5664 return $queryString;
5665 }
5666 }
ccabbc44 5667 throw new CRM_Core_Exception(ts('Failed to interpret input for search'));
461c9a60 5668 }
c0b154eb 5669
6a488035 5670 $value = CRM_Utils_Type::escape($value, $dataType);
a75c13cc 5671 // if we don't have a dataType we should assume
85bdc94e 5672 if ($dataType == 'String' || $dataType == 'Text') {
2fc64082 5673 $value = "'" . $value . "'";
6a488035
TO
5674 }
5675 return "$clause $value";
5676 }
5677 }
5678
86538308
EM
5679 /**
5680 * @param bool $reset
5681 *
5682 * @return array
5683 */
00be9182 5684 public function openedSearchPanes($reset = FALSE) {
6a488035
TO
5685 if (!$reset || empty($this->_whereTables)) {
5686 return self::$_openedPanes;
5687 }
5688
5689 // pane name to table mapper
be2fb01f 5690 $panesMapper = [
6a488035
TO
5691 ts('Contributions') => 'civicrm_contribution',
5692 ts('Memberships') => 'civicrm_membership',
5693 ts('Events') => 'civicrm_participant',
5694 ts('Relationships') => 'civicrm_relationship',
5695 ts('Activities') => 'civicrm_activity',
5696 ts('Pledges') => 'civicrm_pledge',
5697 ts('Cases') => 'civicrm_case',
5698 ts('Grants') => 'civicrm_grant',
5699 ts('Address Fields') => 'civicrm_address',
5700 ts('Notes') => 'civicrm_note',
5701 ts('Change Log') => 'civicrm_log',
974ae237 5702 ts('Mailings') => 'civicrm_mailing',
be2fb01f 5703 ];
066b4d4a 5704 CRM_Contact_BAO_Query_Hook::singleton()->getPanesMapper($panesMapper);
6a488035
TO
5705
5706 foreach (array_keys($this->_whereTables) as $table) {
5707 if ($panName = array_search($table, $panesMapper)) {
5708 self::$_openedPanes[$panName] = TRUE;
5709 }
5710 }
5711
5712 return self::$_openedPanes;
5713 }
5714
86538308
EM
5715 /**
5716 * @param $operator
5717 */
00be9182 5718 public function setOperator($operator) {
be2fb01f 5719 $validOperators = ['AND', 'OR'];
6a488035
TO
5720 if (!in_array($operator, $validOperators)) {
5721 $operator = 'AND';
5722 }
5723 $this->_operator = $operator;
5724 }
5725
86538308
EM
5726 /**
5727 * @return string
5728 */
00be9182 5729 public function getOperator() {
6a488035
TO
5730 return $this->_operator;
5731 }
5732
86538308
EM
5733 /**
5734 * @param $from
5735 * @param $where
5736 * @param $having
5737 */
00be9182 5738 public function filterRelatedContacts(&$from, &$where, &$having) {
2bedfb3f 5739 if (!isset(Civi::$statics[__CLASS__]['related_contacts_filter'])) {
be2fb01f 5740 Civi::$statics[__CLASS__]['related_contacts_filter'] = [];
2bedfb3f
HA
5741 }
5742 $_rTempCache =& Civi::$statics[__CLASS__]['related_contacts_filter'];
68f8975b 5743 // since there only can be one instance of this filter in every query
2bedfb3f
HA
5744 // skip if filter has already applied
5745 foreach ($_rTempCache as $acache) {
68f8975b
HA
5746 foreach ($acache['queries'] as $aqcache) {
5747 if (strpos($from, $aqcache['from']) !== FALSE) {
5748 $having = NULL;
5749 return;
5750 }
2bedfb3f
HA
5751 }
5752 }
5753 $arg_sig = sha1("$from $where $having");
5754 if (isset($_rTempCache[$arg_sig])) {
5755 $cache = $_rTempCache[$arg_sig];
5756 }
5757 else {
6a488035 5758 // create temp table with contact ids
68f8975b 5759
def88c52 5760 $tableName = CRM_Utils_SQL_TempTable::build()->createWithColumns('contact_id int primary key')->setMemory(TRUE)->getName();
6a488035
TO
5761
5762 $sql = "
5763REPLACE INTO $tableName ( contact_id )
5764SELECT contact_a.id
5765 $from
5766 $where
5767 $having
5768";
5769 CRM_Core_DAO::executeQuery($sql);
5770
be2fb01f 5771 $cache = ['tableName' => $tableName, 'queries' => []];
68f8975b
HA
5772 $_rTempCache[$arg_sig] = $cache;
5773 }
5774 // upsert the query depending on relationship type
5775 if (isset($cache['queries'][$this->_displayRelationshipType])) {
5776 $qcache = $cache['queries'][$this->_displayRelationshipType];
5777 }
5778 else {
5779 $tableName = $cache['tableName'];
be2fb01f 5780 $qcache = [
68f8975b
HA
5781 "from" => "",
5782 "where" => "",
be2fb01f 5783 ];
6a488035 5784 $rTypes = CRM_Core_PseudoConstant::relationshipType();
6a488035
TO
5785 if (is_numeric($this->_displayRelationshipType)) {
5786 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType]['label_a_b'];
68f8975b 5787 $qcache['from'] = "
6a488035
TO
5788INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5789INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5790";
68f8975b 5791 $qcache['where'] = "
6a488035
TO
5792WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5793AND displayRelType.is_active = 1
5794";
5795 }
5796 else {
5797 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType);
5798 if ($dirOne == 'a') {
5799 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
68f8975b 5800 $qcache['from'] .= "
6a488035
TO
5801INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5802INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5803";
5804 }
5805 else {
5806 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
68f8975b 5807 $qcache['from'] .= "
6a488035
TO
5808INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5809INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5810";
5811 }
68f8975b 5812 $qcache['where'] = "
6a488035
TO
5813WHERE displayRelType.relationship_type_id = $relType
5814AND displayRelType.is_active = 1
5815";
5816 }
68f8975b
HA
5817 $qcache['relTypeLabel'] = $relationshipTypeLabel;
5818 $_rTempCache[$arg_sig]['queries'][$this->_displayRelationshipType] = $qcache;
6a488035 5819 }
68f8975b
HA
5820 $qillMessage = ts('Contacts with a Relationship Type of: ');
5821 $iqill = $qillMessage . "'" . $qcache['relTypeLabel'] . "'";
5822 if (!is_array($this->_qill[0]) || !in_array($iqill, $this->_qill[0])) {
5823 $this->_qill[0][] = $iqill;
5824 }
5825 if (strpos($from, $qcache['from']) === FALSE) {
6a488035
TO
5826 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5827 // this happens when we have an event_type in the quert (CRM-7969)
5828 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
68f8975b
HA
5829 $from .= $qcache['from'];
5830 $where = $qcache['where'];
2bedfb3f
HA
5831 if (!empty($this->_permissionWhereClause)) {
5832 $where .= "AND $this->_permissionWhereClause";
5833 }
6a488035
TO
5834 }
5835
5836 $having = NULL;
5837 }
5838
86538308 5839 /**
30415e03 5840 * See CRM-19811 for why this is database hurty without apparent benefit.
5841 *
86538308
EM
5842 * @param $op
5843 *
5844 * @return bool
5845 */
5c7dad85 5846 public static function caseImportant($op) {
69078420 5847 return in_array($op, ['LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY']) ? FALSE : TRUE;
6a488035
TO
5848 }
5849
86538308
EM
5850 /**
5851 * @param $returnProperties
5852 * @param $prefix
5853 *
5854 * @return bool
5855 */
5c7dad85
TO
5856 public static function componentPresent(&$returnProperties, $prefix) {
5857 foreach ($returnProperties as $name => $dontCare) {
6a488035
TO
5858 if (substr($name, 0, strlen($prefix)) == $prefix) {
5859 return TRUE;
5860 }
5861 }
5862 return FALSE;
5863 }
5864
5865 /**
c037736a 5866 * Builds the necessary structures for all fields that are similar to option value look-ups.
6a488035 5867 *
5a4f6742
CW
5868 * @param string $name
5869 * the name of the field.
5870 * @param string $op
5871 * the sql operator, this function should handle ALL SQL operators.
5872 * @param string $value
5873 * depends on the operator and who's calling the query builder.
5874 * @param int $grouping
5875 * the index where to place the where clause.
3bdf1f3a 5876 * @param string $daoName
5877 * DAO Name.
5a4f6742
CW
5878 * @param array $field
5879 * an array that contains various properties of the field identified by $name.
5880 * @param string $label
5881 * The label for this field element.
5882 * @param string $dataType
5883 * The data type for this element.
837c4660 5884 * @param bool $useIDsOnly
6a488035 5885 */
59f4c9ee 5886 public function optionValueQuery(
6a488035
TO
5887 $name,
5888 $op,
5889 $value,
5890 $grouping,
9b183452 5891 $daoName = NULL,
6a488035
TO
5892 $field,
5893 $label,
a30e57e0
DL
5894 $dataType = 'String',
5895 $useIDsOnly = FALSE
6a488035 5896 ) {
bd3728fb 5897
be2fb01f 5898 $pseudoFields = [
5c7dad85
TO
5899 'email_greeting',
5900 'postal_greeting',
5901 'addressee',
5902 'gender_id',
5903 'prefix_id',
5904 'suffix_id',
21dfd5f5 5905 'communication_style_id',
be2fb01f 5906 ];
d9ab802d 5907
9df8a11d
DL
5908 if ($useIDsOnly) {
5909 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5910 if ($tableName == 'civicrm_contact') {
5911 $wc = "contact_a.$fieldName";
5912 }
8b695e91 5913 else {
f61d1b83
AS
5914 // Special handling for on_hold, so that we actually use the 'where'
5915 // property in order to limit the query by the on_hold status of the email,
5916 // instead of using email.id which would be nonsensical.
5917 if ($field['name'] == 'on_hold') {
5918 $wc = "{$field['where']}";
5919 }
5920 else {
5921 $wc = "$tableName.id";
5922 }
8b695e91 5923 }
9df8a11d
DL
5924 }
5925 else {
b7aa36b6 5926 CRM_Core_Error::deprecatedFunctionWarning('pass $ids to this method');
5927 $wc = "{$field['where']}";
9df8a11d 5928 }
d9ab802d 5929 if (in_array($name, $pseudoFields)) {
be2fb01f 5930 if (!in_array($name, ['gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'])) {
d9ab802d
PJ
5931 $wc = "contact_a.{$name}_id";
5932 }
5933 $dataType = 'Positive';
5934 $value = (!$value) ? 0 : $value;
5935 }
728eefa0 5936 if ($name == "world_region") {
5937 $field['name'] = $name;
5938 }
d9ab802d 5939
9b183452 5940 list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue($daoName, $field['name'], $value, $op);
be2fb01f 5941 $this->_qill[$grouping][] = ts("%1 %2 %3", [1 => $label, 2 => $qillop, 3 => $qillVal]);
d9ab802d 5942 $this->_where[$grouping][] = self::buildClause($wc, $op, $value, $dataType);
6a488035
TO
5943 }
5944
a30e57e0 5945 /**
100fef9d 5946 * Check and explode a user defined numeric string into an array
6a488035
TO
5947 * this was the protocol used by search builder in the old old days before we had
5948 * super nice js widgets to do the hard work
5949 *
4e6072d5 5950 * @param string $string
77c5b619
TO
5951 * @param string $dataType
5952 * The dataType we should check for the values, default integer.
6a488035 5953 *
72b3a70c
CW
5954 * @return bool|array
5955 * false if string does not match the pattern
5956 * array of numeric values if string does match the pattern
6a488035 5957 */
00be9182 5958 public static function parseSearchBuilderString($string, $dataType = 'Integer') {
6a488035
TO
5959 $string = trim($string);
5960 if (substr($string, 0, 1) != '(' || substr($string, -1, 1) != ')') {
69078420 5961 return FALSE;
6a488035
TO
5962 }
5963
5964 $string = substr($string, 1, -1);
5965 $values = explode(',', $string);
5966 if (empty($values)) {
5967 return FALSE;
5968 }
5969
be2fb01f 5970 $returnValues = [];
6a488035 5971 foreach ($values as $v) {
5c7dad85 5972 if ($dataType == 'Integer' && !is_numeric($v)) {
6a488035
TO
5973 return FALSE;
5974 }
4c9b6178 5975 elseif ($dataType == 'String' && !is_string($v)) {
6a488035
TO
5976 return FALSE;
5977 }
5978 $returnValues[] = trim($v);
5979 }
5980
5981 if (empty($returnValues)) {
5982 return FALSE;
5983 }
5984
5985 return $returnValues;
5986 }
6a488035 5987
d9ab802d 5988 /**
100fef9d 5989 * Convert the pseudo constants id's to their names
837c4660 5990 *
59f4c9ee 5991 * @param CRM_Core_DAO $dao
837c4660 5992 * @param bool $return
a5e77b37 5993 * @param bool $usedForAPI
837c4660 5994 *
59f4c9ee 5995 * @return array|NULL
d9ab802d 5996 */
a5e77b37 5997 public function convertToPseudoNames(&$dao, $return = FALSE, $usedForAPI = FALSE) {
d9ab802d 5998 if (empty($this->_pseudoConstantsSelect)) {
59f4c9ee 5999 return NULL;
d9ab802d 6000 }
be2fb01f 6001 $values = [];
d9ab802d 6002 foreach ($this->_pseudoConstantsSelect as $key => $value) {
a7488080 6003 if (!empty($this->_pseudoConstantsSelect[$key]['sorting'])) {
d9ab802d
PJ
6004 continue;
6005 }
6006
9db71ff2 6007 if (is_object($dao) && property_exists($dao, $value['idCol'])) {
6ef04c72 6008 $val = $dao->{$value['idCol']};
3875e6b6 6009 if ($key == 'groups') {
6010 $dao->groups = $this->convertGroupIDStringToLabelString($dao, $val);
86ab13b7 6011 continue;
3875e6b6 6012 }
d9ab802d
PJ
6013
6014 if (CRM_Utils_System::isNull($val)) {
6015 $dao->$key = NULL;
d9ab802d 6016 }
86ab13b7 6017 elseif (!empty($value['pseudoconstant'])) {
6018 // If pseudoconstant is set that is kind of defacto for 'we have a bit more info about this'
6019 // and we can use the metadata to figure it out.
6020 // ideally this bit of IF will absorb & replace all the rest in time as we move to
6021 // more metadata based choices.
6022 if (strpos($val, CRM_Core_DAO::VALUE_SEPARATOR) !== FALSE) {
6023 $dbValues = explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($val, CRM_Core_DAO::VALUE_SEPARATOR));
6024 foreach ($dbValues as $pseudoValue) {
6025 $convertedValues[] = CRM_Core_PseudoConstant::getLabel($value['bao'], $value['idCol'], $pseudoValue);
6026 }
6027
6028 $dao->$key = ($usedForAPI) ? $convertedValues : implode(', ', $convertedValues);
6029 $realFieldName = CRM_Utils_Array::value('field_name', $this->_pseudoConstantsSelect[$key]);
6030 if ($usedForAPI && $realFieldName) {
6031 // normally we would see 2 fields returned for pseudoConstants. An exception is
6032 // preferred_communication_method where there is no id-variant.
6033 // For the api we prioritise getting the real data returned.
6034 // over the resolved version
6035 $dao->$realFieldName = $dbValues;
6036 }
6037
6038 }
6039 else {
6040 // This is basically the same as the default but since we have the bao we can use
6041 // a cached function.
6042 $dao->$key = CRM_Core_PseudoConstant::getLabel($value['bao'], $value['idCol'], $val);
6043 }
6044 }
b719f000 6045 elseif ($baoName = CRM_Utils_Array::value('bao', $value, NULL)) {
827659b2 6046 //preserve id value
6047 $idColumn = "{$key}_id";
6048 $dao->$idColumn = $val;
b105067c 6049
6050 if ($key == 'state_province_name') {
144d0efe 6051 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant::stateProvince($val);
b105067c 6052 }
6053 else {
6ef04c72 6054 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant::getLabel($baoName, $value['pseudoField'], $val);
b105067c 6055 }
d9ab802d
PJ
6056 }
6057 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
6058 $dao->$key = CRM_Core_PseudoConstant::stateProvinceAbbreviation($val);
6059 }
86ab13b7 6060 // @todo handle this in the section above for pseudoconstants.
be2fb01f 6061 elseif (in_array($value['pseudoField'], ['participant_role_id', 'participant_role'])) {
3af96592 6062 // @todo define bao on this & merge into the above condition.
348b1fda 6063 $viewValues = explode(CRM_Core_DAO::VALUE_SEPARATOR, $val);
6064
6065 if ($value['pseudoField'] == 'participant_role') {
6066 $pseudoOptions = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', 'role_id');
6067 foreach ($viewValues as $k => $v) {
6068 $viewValues[$k] = $pseudoOptions[$v];
6069 }
62fd7fe8 6070 }
a5e77b37 6071 $dao->$key = ($usedForAPI && count($viewValues) > 1) ? $viewValues : implode(', ', $viewValues);
62fd7fe8 6072 }
d9ab802d
PJ
6073 else {
6074 $labels = CRM_Core_OptionGroup::values($value['pseudoField']);
6075 $dao->$key = $labels[$val];
6076 }
b719f000
PJ
6077
6078 // return converted values in array format
6079 if ($return) {
6080 if (strpos($key, '-') !== FALSE) {
6081 $keyVal = explode('-', $key);
6082 $current = &$values;
6083 $lastElement = array_pop($keyVal);
6084 foreach ($keyVal as $v) {
6085 if (!array_key_exists($v, $current)) {
be2fb01f 6086 $current[$v] = [];
b719f000
PJ
6087 }
6088 $current = &$current[$v];
6089 }
6090 $current[$lastElement] = $dao->$key;
6091 }
6092 else {
6093 $values[$key] = $dao->$key;
6094 }
6095 }
d9ab802d
PJ
6096 }
6097 }
86ab13b7 6098 if (!$usedForAPI) {
714ab070 6099 foreach ($this->legacyHackedFields as $realField => $labelField) {
86ab13b7 6100 // This is a temporary routine for handling these fields while
6101 // we figure out how to handled them based on metadata in
6102 /// export and search builder. CRM-19815, CRM-19830.
f02f3e59 6103 if (isset($dao->$realField) && is_numeric($dao->$realField) && isset($dao->$labelField)) {
86ab13b7 6104 $dao->$realField = $dao->$labelField;
6105 }
6106 }
6107 }
d9ab802d
PJ
6108 return $values;
6109 }
6110
837c4660 6111 /**
fe482240 6112 * Include pseudo fields LEFT JOIN.
77c5b619 6113 * @param string|array $sort can be a object or string
d9ab802d 6114 *
59f4c9ee 6115 * @return array|NULL
d9ab802d 6116 */
00be9182 6117 public function includePseudoFieldsJoin($sort) {
d9ab802d 6118 if (!$sort || empty($this->_pseudoConstantsSelect)) {
59f4c9ee 6119 return NULL;
d9ab802d
PJ
6120 }
6121 $sort = is_string($sort) ? $sort : $sort->orderBy();
be2fb01f 6122 $present = [];
d9ab802d
PJ
6123
6124 foreach ($this->_pseudoConstantsSelect as $name => $value) {
a7488080 6125 if (!empty($value['table'])) {
d9ab802d
PJ
6126 $regex = "/({$value['table']}\.|{$name})/";
6127 if (preg_match($regex, $sort)) {
6128 $this->_elemnt[$value['element']] = 1;
6129 $this->_select[$value['element']] = $value['select'];
6130 $this->_pseudoConstantsSelect[$name]['sorting'] = 1;
6131 $present[$value['table']] = $value['join'];
6132 }
6133 }
6134 }
6135 $presentSimpleFrom = $present;
6136
6137 if (array_key_exists('civicrm_worldregion', $this->_whereTables) &&
5c7dad85
TO
6138 array_key_exists('civicrm_country', $presentSimpleFrom)
6139 ) {
d9ab802d
PJ
6140 unset($presentSimpleFrom['civicrm_country']);
6141 }
6142 if (array_key_exists('civicrm_worldregion', $this->_tables) &&
5c7dad85
TO
6143 array_key_exists('civicrm_country', $present)
6144 ) {
d9ab802d
PJ
6145 unset($present['civicrm_country']);
6146 }
6147
6148 $presentClause = $presentSimpleFromClause = NULL;
6149 if (!empty($present)) {
6150 $presentClause = implode(' ', $present);
6151 }
6152 if (!empty($presentSimpleFrom)) {
6153 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
6154 }
6155
6156 $this->_fromClause = $this->_fromClause . $presentClause;
6157 $this->_simpleFromClause = $this->_simpleFromClause . $presentSimpleFromClause;
6158
be2fb01f 6159 return [$presentClause, $presentSimpleFromClause];
d9ab802d 6160 }
9ab34172 6161
0e2e76cf
EM
6162 /**
6163 * Build qill for field.
6164 *
6165 * Qill refers to the query detail visible on the UI.
6166 *
bb05da0c 6167 * @param string $daoName
6168 * @param string $fieldName
6169 * @param mixed $fieldValue
6170 * @param string $op
6171 * @param array $pseudoExtraParam
6172 * @param int $type
6173 * Type of the field per CRM_Utils_Type
0e2e76cf
EM
6174 *
6175 * @return array
6176 */
bb05da0c 6177 public static function buildQillForFieldValue(
6178 $daoName,
6179 $fieldName,
6180 $fieldValue,
6181 $op,
be2fb01f 6182 $pseudoExtraParam = [],
bb05da0c 6183 $type = CRM_Utils_Type::T_STRING
6184 ) {
afa0b07c 6185 $qillOperators = CRM_Core_SelectValues::getSearchBuilderOperators();
97c1cf60 6186
3086e282 6187 //API usually have fieldValue format as array(operator => array(values)),
6188 //so we need to separate operator out of fieldValue param
6189 if (is_array($fieldValue) && in_array(key($fieldValue), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
6190 $op = key($fieldValue);
6191 $fieldValue = $fieldValue[$op];
6192 }
6193
9b183452 6194 // if Operator chosen is NULL/EMPTY then
6195 if (strpos($op, 'NULL') !== FALSE || strpos($op, 'EMPTY') !== FALSE) {
be2fb01f 6196 return [CRM_Utils_Array::value($op, $qillOperators, $op), ''];
9b183452 6197 }
6198
9ab34172 6199 if ($fieldName == 'activity_type_id') {
bb05da0c 6200 $pseudoOptions = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE);
9ab34172 6201 }
9b183452 6202 elseif ($fieldName == 'country_id') {
e4001cf0 6203 $pseudoOptions = CRM_Core_PseudoConstant::country();
9b183452 6204 }
6205 elseif ($fieldName == 'county_id') {
e4001cf0 6206 $pseudoOptions = CRM_Core_PseudoConstant::county();
9b183452 6207 }
728eefa0 6208 elseif ($fieldName == 'world_region') {
e4001cf0 6209 $pseudoOptions = CRM_Core_PseudoConstant::worldRegion();
728eefa0 6210 }
97c1cf60 6211 elseif ($daoName == 'CRM_Event_DAO_Event' && $fieldName == 'id') {
450fcddb
JP
6212 $checkPermission = CRM_Utils_Array::value('check_permission', $pseudoExtraParam, TRUE);
6213 $pseudoOptions = CRM_Event_BAO_Event::getEvents(0, $fieldValue, TRUE, $checkPermission, TRUE);
97c1cf60 6214 }
6ffab5b7 6215 elseif ($fieldName == 'contribution_product_id') {
bb05da0c 6216 $pseudoOptions = CRM_Contribute_PseudoConstant::products();
6ffab5b7 6217 }
e8401ae2 6218 elseif ($daoName == 'CRM_Contact_DAO_Group' && $fieldName == 'id') {
bb05da0c 6219 $pseudoOptions = CRM_Core_PseudoConstant::group();
e8401ae2 6220 }
3086e282 6221 elseif ($daoName == 'CRM_Batch_BAO_EntityBatch' && $fieldName == 'batch_id') {
6222 $pseudoOptions = CRM_Contribute_PseudoConstant::batch();
6223 }
efb88612 6224 elseif ($daoName) {
bb05da0c 6225 $pseudoOptions = CRM_Core_PseudoConstant::get($daoName, $fieldName, $pseudoExtraParam);
97c1cf60 6226 }
9ab34172 6227
efb88612 6228 if (is_array($fieldValue)) {
be2fb01f 6229 $qillString = [];
bb05da0c 6230 if (!empty($pseudoOptions)) {
efb88612 6231 foreach ((array) $fieldValue as $val) {
bb05da0c 6232 $qillString[] = CRM_Utils_Array::value($val, $pseudoOptions, $val);
efb88612 6233 }
6234 $fieldValue = implode(', ', $qillString);
9ab34172 6235 }
efb88612 6236 else {
bb05da0c 6237 if ($type == CRM_Utils_Type::T_DATE) {
6238 foreach ($fieldValue as $index => $value) {
6239 $fieldValue[$index] = CRM_Utils_Date::customFormat($value);
6240 }
6241 }
6242 $separator = ', ';
6243 // @todo - this is a bit specific (one operator).
6244 // However it is covered by a unit test so can be altered later with
6245 // some confidence.
6246 if ($op == 'BETWEEN') {
6247 $separator = ' AND ';
6248 }
6249 $fieldValue = implode($separator, $fieldValue);
9ab34172 6250 }
9ab34172 6251 }
bb05da0c 6252 elseif (!empty($pseudoOptions) && array_key_exists($fieldValue, $pseudoOptions)) {
6253 $fieldValue = $pseudoOptions[$fieldValue];
6254 }
6255 elseif ($type === CRM_Utils_Type::T_DATE) {
6256 $fieldValue = CRM_Utils_Date::customFormat($fieldValue);
9ab34172 6257 }
afa0b07c 6258
be2fb01f 6259 return [CRM_Utils_Array::value($op, $qillOperators, $op), $fieldValue];
9ab34172 6260 }
96025800 6261
1a7029b8
MD
6262 /**
6263 * Get the qill (search description for field) for the specified field.
6264 *
6265 * @param string $daoName
6266 * @param string $name
6267 * @param string $value
6268 * @param string|array $op
6269 * @param string $label
6270 *
6271 * @return string
6272 */
6273 public static function getQillValue($daoName, string $name, $value, $op, string $label) {
6274 list($op, $value) = self::buildQillForFieldValue($daoName, $name, $value, $op);
6275 return ts('%1 %2 %3', [1 => $label, 2 => $op, 3 => $value]);
6276 }
6277
836eb043 6278 /**
6279 * Alter value to reflect wildcard settings.
6280 *
6281 * The form will have tried to guess whether this is a good field to wildcard but there is
6282 * also a site-wide setting that specifies whether it is OK to append the wild card to the beginning
6283 * or only the end of the string
6284 *
6285 * @param bool $wildcard
6286 * This is a bool made on an assessment 'elsewhere' on whether this is a good field to wildcard.
6287 * @param string $op
6288 * Generally '=' or 'LIKE'.
6289 * @param string $value
6290 * The search string.
6291 *
6292 * @return string
6293 */
0b38e8f1 6294 public static function getWildCardedValue($wildcard, $op, $value) {
836eb043 6295 if ($wildcard && $op == 'LIKE') {
6296 if (CRM_Core_Config::singleton()->includeWildCardInName && (substr($value, 0, 1) != '%')) {
6297 return "%$value%";
6298 }
6299 else {
6300 return "$value%";
6301 }
6302 }
6303 else {
6304 return "$value";
6305 }
6306 }
6307
0b38e8f1 6308 /**
6309 * Process special fields of Search Form in OK (Operator in Key) format
6310 *
6311 * @param array $formValues
6312 * @param array $specialFields
6313 * Special params to be processed
6314 * @param array $changeNames
6315 * Array of fields whose name should be changed
6316 */
be2fb01f 6317 public static function processSpecialFormValue(&$formValues, $specialFields, $changeNames = []) {
3086e282 6318 // Array of special fields whose value are considered only for NULL or EMPTY operators
be2fb01f 6319 $nullableFields = ['contribution_batch_id'];
3086e282 6320
0b38e8f1 6321 foreach ($specialFields as $element) {
6322 $value = CRM_Utils_Array::value($element, $formValues);
6323 if ($value) {
6324 if (is_array($value)) {
a8d8984f 6325 if (in_array($element, array_keys($changeNames))) {
0b38e8f1 6326 unset($formValues[$element]);
6327 $element = $changeNames[$element];
6328 }
be2fb01f 6329 $formValues[$element] = ['IN' => $value];
0b38e8f1 6330 }
be2fb01f
CW
6331 elseif (in_array($value, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
6332 $formValues[$element] = [$value => 1];
3086e282 6333 }
6334 elseif (!in_array($element, $nullableFields)) {
0b38e8f1 6335 // if wildcard is already present return searchString as it is OR append and/or prepend with wildcard
6336 $isWilcard = strstr($value, '%') ? FALSE : CRM_Core_Config::singleton()->includeWildCardInName;
be2fb01f 6337 $formValues[$element] = ['LIKE' => self::getWildCardedValue($isWilcard, 'LIKE', $value)];
0b38e8f1 6338 }
6339 }
6340 }
6341 }
6342
db54ba06
TO
6343 /**
6344 * Parse and assimilate the various sort options.
6345 *
6346 * Side-effect: if sorting on a common column from a related table (`city`, `postal_code`,
6347 * `email`), the related table may be joined automatically.
6348 *
6349 * At time of writing, this code is deeply flawed and should be rewritten. For the moment,
6350 * it's been extracted to a standalone function.
6351 *
6352 * @param string|CRM_Utils_Sort $sort
6353 * The order by string.
db54ba06
TO
6354 * @param null $sortOrder
6355 * Who knows? Hu knows. He who knows Hu knows who.
59733b26 6356 *
db54ba06
TO
6357 * @return array
6358 * list(string $orderByClause, string $additionalFromClause).
6359 */
59733b26 6360 protected function prepareOrderBy($sort, $sortOrder) {
fbf68a81 6361 $orderByArray = [];
6362 $orderBy = '';
6363
6364 if (CRM_Core_Config::singleton()->includeOrderByClause ||
db54ba06
TO
6365 isset($this->_distinctComponentClause)
6366 ) {
6367 if ($sort) {
6368 if (is_string($sort)) {
6369 $orderBy = $sort;
6370 }
6371 else {
6372 $orderBy = trim($sort->orderBy());
6373 }
6374 // Deliberately remove the backticks again, as they mess up the evil
6375 // string munging below. This balanced by re-escaping before use.
6376 $orderBy = str_replace('`', '', $orderBy);
6377
6378 if (!empty($orderBy)) {
6379 // this is special case while searching for
6380 // change log CRM-1718
6381 if (preg_match('/sort_name/i', $orderBy)) {
6382 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
6383 }
6384
db54ba06 6385 if ($sortOrder) {
fbf68a81 6386 $orderBy .= " $sortOrder";
db54ba06
TO
6387 }
6388
6389 // always add contact_a.id to the ORDER clause
6390 // so the order is deterministic
fbf68a81 6391 if (strpos('contact_a.id', $orderBy) === FALSE) {
6392 $orderBy .= ", contact_a.id";
db54ba06
TO
6393 }
6394 }
6395 }
db54ba06 6396 else {
fbf68a81 6397 $orderBy = " contact_a.sort_name ASC, contact_a.id";
db54ba06
TO
6398 }
6399 }
52cda5dc 6400 if (!$orderBy) {
59733b26 6401 return NULL;
252f0858 6402 }
6403 // Remove this here & add it at the end for simplicity.
fbf68a81 6404 $order = trim($orderBy);
52cda5dc 6405 $orderByArray = explode(',', $order);
db54ba06 6406
9d5c7f14 6407 foreach ($orderByArray as $orderByClause) {
6408 $orderByClauseParts = explode(' ', trim($orderByClause));
6409 $field = $orderByClauseParts[0];
6410 $direction = isset($orderByClauseParts[1]) ? $orderByClauseParts[1] : 'asc';
7f594311 6411 $fieldSpec = $this->getMetadataForRealField($field);
252f0858 6412
708ce91f 6413 // This is a hacky add-in for primary address joins. Feel free to iterate as it is unit tested.
6414 // @todo much more cleanup on location handling in addHierarchical elements. Potentially
6415 // add keys to $this->fields to represent the actual keys for locations.
6416 if (empty($fieldSpec) && substr($field, 0, 2) === '1-') {
6417 $fieldSpec = $this->getMetadataForField(substr($field, 2));
6418 $this->addAddressTable('1-' . str_replace('civicrm_', '', $fieldSpec['table_name']), 'is_primary = 1');
6419 }
6420
7f594311 6421 if ($this->_returnProperties === []) {
6422 if (!empty($fieldSpec['table_name']) && !isset($this->_tables[$fieldSpec['table_name']])) {
6423 $this->_tables[$fieldSpec['table_name']] = 1;
6424 $order = $fieldSpec['where'] . ' ' . $direction;
6425 }
252f0858 6426
7f594311 6427 }
1ddfb09e 6428 $cfID = CRM_Core_BAO_CustomField::getKeyID($field);
6429 // add to cfIDs array if not present
6430 if (!empty($cfID) && !array_key_exists($cfID, $this->_cfIDs)) {
be2fb01f 6431 $this->_cfIDs[$cfID] = [];
1ddfb09e 6432 $this->_customQuery = new CRM_Core_BAO_CustomQuery($this->_cfIDs, TRUE, $this->_locationSpecificCustomFields);
6433 $this->_customQuery->query();
6434 $this->_select = array_merge($this->_select, $this->_customQuery->_select);
6435 $this->_tables = array_merge($this->_tables, $this->_customQuery->_tables);
6436 }
6437
6438 // By replacing the join to the option value table with the mysql construct
6439 // ORDER BY field('contribution_status_id', 2,1,4)
6440 // we can remove a join. In the case of the option value join it is
6441 /// a join known to cause slow queries.
6442 // @todo cover other pseudoconstant types. Limited to option group ones & Foreign keys
6443 // matching an id+name parrern in the
6444 // first instance for scope reasons. They require slightly different handling as the column (label)
6445 // is not declared for them.
6446 // @todo so far only integer fields are being handled. If we add string fields we need to look at
6447 // escaping.
6448 $pseudoConstantMetadata = CRM_Utils_Array::value('pseudoconstant', $fieldSpec, FALSE);
6449 if (!empty($pseudoConstantMetadata)
6450 ) {
6451 if (!empty($pseudoConstantMetadata['optionGroupName'])
6452 || $this->isPseudoFieldAnFK($fieldSpec)
6453 ) {
1dd6ae65
D
6454 // dev/core#1305 @todo this is not the right thing to do but for now avoid fatal error
6455 if (empty($fieldSpec['bao'])) {
6456 continue;
6457 }
1ddfb09e 6458 $sortedOptions = $fieldSpec['bao']::buildOptions($fieldSpec['name'], NULL, [
6459 'orderColumn' => CRM_Utils_Array::value('labelColumn', $pseudoConstantMetadata, 'label'),
6460 ]);
6461 $fieldIDsInOrder = implode(',', array_keys($sortedOptions));
6462 // Pretty sure this validation ALSO happens in the order clause & this can't be reached but...
6463 // this might give some early warning.
6464 CRM_Utils_Type::validate($fieldIDsInOrder, 'CommaSeparatedIntegers');
6465 $order = str_replace("$field", "field({$fieldSpec['name']},$fieldIDsInOrder)", $order);
6466 }
6467 //CRM-12565 add "`" around $field if it is a pseudo constant
6468 // This appears to be for 'special' fields like locations with appended numbers or hyphens .. maybe.
6469 if (!empty($pseudoConstantMetadata['element']) && $pseudoConstantMetadata['element'] == $field) {
6470 $order = str_replace($field, "`{$field}`", $order);
6471 }
db54ba06
TO
6472 }
6473 }
6474
9d5c7f14 6475 $this->_fromClause = self::fromClause($this->_tables, NULL, NULL, $this->_primaryLocation, $this->_mode);
6476 $this->_simpleFromClause = self::fromClause($this->_whereTables, NULL, NULL, $this->_primaryLocation, $this->_mode);
6477
db54ba06
TO
6478 // The above code relies on crazy brittle string manipulation of a peculiarly-encoded ORDER BY
6479 // clause. But this magic helper which forgivingly reescapes ORDER BY.
9d5c7f14 6480 if ($order) {
252f0858 6481 $order = CRM_Utils_Type::escape($order, 'MysqlOrderBy');
59733b26 6482 return ' ORDER BY ' . $order;
db54ba06 6483 }
db54ba06
TO
6484 }
6485
3875e6b6 6486 /**
6487 * Convert a string of group IDs to a string of group labels.
6488 *
6489 * The original string may include duplicates and groups the user does not have
6490 * permission to see.
6491 *
6492 * @param CRM_Core_DAO $dao
6493 * @param string $val
6494 *
6495 * @return string
6496 */
6497 public function convertGroupIDStringToLabelString(&$dao, $val) {
6498 $groupIDs = explode(',', $val);
3875e6b6 6499 // Note that groups that the user does not have permission to will be excluded (good).
6d054a8e 6500 $groups = array_intersect_key(CRM_Core_PseudoConstant::group(), array_flip($groupIDs));
3875e6b6 6501 return implode(', ', $groups);
962f4484 6502
6503 }
6504
6505 /**
6506 * Set the qill and where properties for a field.
6507 *
6508 * This function is intended as a short-term function to encourage refactoring
6509 * & re-use - but really we should just have less special-casing.
6510 *
6511 * @param string $name
6512 * @param string $op
6513 * @param string|array $value
6514 * @param string $grouping
6515 * @param string $field
6516 */
6517 public function setQillAndWhere($name, $op, $value, $grouping, $field) {
6518 $this->_where[$grouping][] = self::buildClause("contact_a.{$name}", $op, $value);
6519 list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(NULL, $name, $value, $op);
be2fb01f 6520 $this->_qill[$grouping][] = ts("%1 %2 %3", [
962f4484 6521 1 => $field['title'],
6522 2 => $qillop,
6523 3 => $qillVal,
be2fb01f 6524 ]);
3875e6b6 6525 }
6526
86ab13b7 6527 /**
6528 * Has the pseudoconstant of the field been requested.
6529 *
6530 * For example if the field is payment_instrument_id then it
6531 * has been requested if either payment_instrument_id or payment_instrument
6532 * have been requested. Payment_instrument is the option groun name field value.
6533 *
6534 * @param array $field
7bd16b05 6535 * @param string $fieldName
6536 * The unique name of the field - ie. the one it will be aliased to in the query.
86ab13b7 6537 *
6538 * @return bool
6539 */
7bd16b05 6540 private function pseudoConstantNameIsInReturnProperties($field, $fieldName = NULL) {
124f3c1b 6541 $realField = $this->getMetadataForRealField($fieldName);
6542 if (!isset($realField['pseudoconstant'])) {
6543 return FALSE;
6544 }
6545 $pseudoConstant = $realField['pseudoconstant'];
6546 if (empty($pseudoConstant['optionGroupName']) &&
6547 CRM_Utils_Array::value('labelColumn', $pseudoConstant) !== 'name') {
6548 // We are increasing our pseudoconstant handling - but still very cautiously,
6549 // hence the check for labelColumn === name
86ab13b7 6550 return FALSE;
6551 }
86ab13b7 6552
124f3c1b 6553 if (!empty($pseudoConstant['optionGroupName']) && CRM_Utils_Array::value($pseudoConstant['optionGroupName'], $this->_returnProperties)) {
86ab13b7 6554 return TRUE;
6555 }
7bd16b05 6556 if (CRM_Utils_Array::value($fieldName, $this->_returnProperties)) {
6557 return TRUE;
6558 }
6559 // Is this still required - the above goes off the unique name. Test with things like
5c9e101f 6560 // communication_preferences & prefix_id.
86ab13b7 6561 if (CRM_Utils_Array::value($field['name'], $this->_returnProperties)) {
6562 return TRUE;
6563 }
6564 return FALSE;
6565 }
6566
f946d152 6567 /**
6568 * Get Select Clause.
6569 *
6570 * @return string
6571 */
6572 public function getSelect() {
6573 $select = "SELECT ";
6574 if (isset($this->_distinctComponentClause)) {
6575 $select .= "{$this->_distinctComponentClause}, ";
6576 }
6577 $select .= implode(', ', $this->_select);
6578 return $select;
6579 }
6580
8ef6eb78 6581 /**
6582 * Add basic statistics to the summary.
6583 *
6584 * @param array $summary
6585 * @param string $where
6586 * @param string $from
6587 *
041ecc95 6588 *
8ef6eb78 6589 * @return array
041ecc95 6590 * @throws \CRM_Core_Exception
8ef6eb78 6591 */
6592 protected function addBasicStatsToSummary(&$summary, $where, $from) {
fb75fcb0 6593 $summary['total']['count'] = 0;
6594 $summary['total']['amount'] = $summary['total']['avg'] = [];
8ef6eb78 6595
6596 $query = "
6597 SELECT COUNT( conts.total_amount ) as total_count,
6598 SUM( conts.total_amount ) as total_amount,
6599 AVG( conts.total_amount ) as total_avg,
6600 conts.currency as currency
6601 FROM (
6602 SELECT civicrm_contribution.total_amount, COUNT(civicrm_contribution.total_amount) as civicrm_contribution_total_amount_count,
6603 civicrm_contribution.currency
6604 $from
6605 $where AND civicrm_contribution.contribution_status_id = 1
6606 GROUP BY civicrm_contribution.id
6607 ) as conts
6608 GROUP BY currency";
6609
6610 $dao = CRM_Core_DAO::executeQuery($query);
6611
8ef6eb78 6612 while ($dao->fetch()) {
6613 $summary['total']['count'] += $dao->total_count;
6614 $summary['total']['amount'][] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
6615 $summary['total']['avg'][] = CRM_Utils_Money::format($dao->total_avg, $dao->currency);
6616 }
bfac1665 6617
261b72cf 6618 if (!empty($summary['total']['amount'])) {
6619 $summary['total']['amount'] = implode(',&nbsp;', $summary['total']['amount']);
6620 $summary['total']['avg'] = implode(',&nbsp;', $summary['total']['avg']);
6621 }
6622 else {
b64b7a9e 6623 $summary['total']['amount'] = $summary['total']['avg'] = 0;
261b72cf 6624 }
8ef6eb78 6625 return $summary;
6626 }
6627
6d68fd76 6628 /**
6629 * Add basic soft credit statistics to summary array.
6630 *
6631 * @param array $summary
6632 * @param string $where
6633 * @param string $from
6634 */
6635 protected function addBasicSoftCreditStatsToStats(&$summary, $where, $from) {
6636 $query = "
6637 SELECT COUNT( conts.total_amount ) as total_count,
6638 SUM( conts.total_amount ) as total_amount,
6639 AVG( conts.total_amount ) as total_avg,
6640 conts.currency as currency
6641 FROM (
6642 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency
6643 $from
6644 $where AND civicrm_contribution.contribution_status_id = 1 AND civicrm_contribution_soft.id IS NOT NULL
6645 GROUP BY civicrm_contribution_soft.id
6646 ) as conts
6647 GROUP BY currency";
6648
6649 $dao = CRM_Core_DAO::executeQuery($query);
6650 $summary['soft_credit']['count'] = 0;
6651 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = [];
6652 while ($dao->fetch()) {
6653 $summary['soft_credit']['count'] += $dao->total_count;
6654 $summary['soft_credit']['amount'][] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
6655 $summary['soft_credit']['avg'][] = CRM_Utils_Money::format($dao->total_avg, $dao->currency);
6656 }
6657 if (!empty($summary['soft_credit']['amount'])) {
6658 $summary['soft_credit']['amount'] = implode(',&nbsp;', $summary['soft_credit']['amount']);
6659 $summary['soft_credit']['avg'] = implode(',&nbsp;', $summary['soft_credit']['avg']);
6660 }
6661 else {
6662 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
6663 }
6664 }
6665
386fce20 6666 /**
6667 * Add basic stats about cancelled contributions to the summary.
6668 *
6669 * @param array $summary
6670 * @param string $where
6671 * @param string $from
6672 */
6673 protected function addBasicCancelStatsToSummary(&$summary, $where, $from) {
6674 $query = "
6675 SELECT COUNT( conts.total_amount ) as cancel_count,
6676 SUM( conts.total_amount ) as cancel_amount,
6677 AVG( conts.total_amount ) as cancel_avg,
6678 conts.currency as currency
6679 FROM (
6680 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency
6681 $from
1a7029b8 6682 $where AND civicrm_contribution.cancel_date IS NOT NULL
386fce20 6683 GROUP BY civicrm_contribution.id
6684 ) as conts
6685 GROUP BY currency";
6686
6687 $dao = CRM_Core_DAO::executeQuery($query);
6688
6689 if ($dao->N <= 1) {
6690 if ($dao->fetch()) {
6691 $summary['cancel']['count'] = $dao->cancel_count;
6692 $summary['cancel']['amount'] = CRM_Utils_Money::format($dao->cancel_amount, $dao->currency);
6693 $summary['cancel']['avg'] = CRM_Utils_Money::format($dao->cancel_avg, $dao->currency);
6694 }
6695 }
6696 else {
6697 $summary['cancel']['count'] = 0;
6698 $summary['cancel']['amount'] = $summary['cancel']['avg'] = [];
6699 while ($dao->fetch()) {
6700 $summary['cancel']['count'] += $dao->cancel_count;
6701 $summary['cancel']['amount'][] = CRM_Utils_Money::format($dao->cancel_amount, $dao->currency);
6702 $summary['cancel']['avg'][] = CRM_Utils_Money::format($dao->cancel_avg, $dao->currency);
6703 }
6704 $summary['cancel']['amount'] = implode(',&nbsp;', $summary['cancel']['amount']);
6705 $summary['cancel']['avg'] = implode(',&nbsp;', $summary['cancel']['avg']);
6706 }
6707 }
6708
89d7bb76 6709 /**
89d7bb76 6710 * Create the sql query for an contact search.
6711 *
6712 * @param int $offset
6713 * The offset for the query.
6714 * @param int $rowCount
6715 * The number of rows to return.
6716 * @param string|CRM_Utils_Sort $sort
6717 * The order by string.
6718 * @param bool $count
6719 * Is this a count only query ?.
6720 * @param bool $includeContactIds
6721 * Should we include contact ids?.
6722 * @param bool $sortByChar
6723 * If true returns the distinct array of first characters for search results.
6724 * @param bool $groupContacts
6725 * If true, return only the contact ids.
6726 * @param string $additionalWhereClause
6727 * If the caller wants to further restrict the search (used for components).
6728 * @param null $sortOrder
6729 * @param string $additionalFromClause
6730 * Should be clause with proper joins, effective to reduce where clause load.
6731 *
6732 * @param bool $skipOrderAndLimit
6733 * @return string
6734 */
6735 public function getSearchSQL(
6736 $offset = 0, $rowCount = 0, $sort = NULL,
6737 $count = FALSE, $includeContactIds = FALSE,
6738 $sortByChar = FALSE, $groupContacts = FALSE,
6739 $additionalWhereClause = NULL, $sortOrder = NULL,
6740 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE) {
fe3416bf 6741
6742 $sqlParts = $this->getSearchSQLParts($offset, $rowCount, $sort, $count, $includeContactIds, $sortByChar, $groupContacts, $additionalWhereClause, $sortOrder, $additionalFromClause);
6743
caefed7d
MWMC
6744 if ($sortByChar) {
6745 CRM_Core_Error::deprecatedFunctionWarning('sort by char is deprecated - use alphabetQuery method');
6746 $sqlParts['order_by'] = 'ORDER BY sort_name asc';
6747 }
6748
fe3416bf 6749 if ($skipOrderAndLimit) {
6750 CRM_Core_Error::deprecatedFunctionWarning('skipOrderAndLimit is deprected - call getSearchSQLParts & construct it in the calling function');
6751 $query = "{$sqlParts['select']} {$sqlParts['from']} {$sqlParts['where']} {$sqlParts['having']} {$sqlParts['group_by']}";
6752 }
6753 else {
6754 $query = "{$sqlParts['select']} {$sqlParts['from']} {$sqlParts['where']} {$sqlParts['having']} {$sqlParts['group_by']} {$sqlParts['order_by']} {$sqlParts['limit']}";
6755 }
6756 return $query;
6757 }
6758
6759 /**
6760 * Get the component parts of the search query as an array.
6761 *
6762 * @param int $offset
6763 * The offset for the query.
6764 * @param int $rowCount
6765 * The number of rows to return.
6766 * @param string|CRM_Utils_Sort $sort
6767 * The order by string.
6768 * @param bool $count
6769 * Is this a count only query ?.
6770 * @param bool $includeContactIds
6771 * Should we include contact ids?.
6772 * @param bool $sortByChar
6773 * If true returns the distinct array of first characters for search results.
6774 * @param bool $groupContacts
6775 * If true, return only the contact ids.
6776 * @param string $additionalWhereClause
6777 * If the caller wants to further restrict the search (used for components).
6778 * @param null $sortOrder
6779 * @param string $additionalFromClause
6780 * Should be clause with proper joins, effective to reduce where clause load.
6781 *
6782 * @return array
6783 */
6784 public function getSearchSQLParts($offset = 0, $rowCount = 0, $sort = NULL,
6785 $count = FALSE, $includeContactIds = FALSE,
6786 $sortByChar = FALSE, $groupContacts = FALSE,
6787 $additionalWhereClause = NULL, $sortOrder = NULL,
6788 $additionalFromClause = NULL) {
89d7bb76 6789 if ($includeContactIds) {
6790 $this->_includeContactIds = TRUE;
6791 $this->_whereClause = $this->whereClause();
6792 }
89d7bb76 6793 $onlyDeleted = in_array([
6794 'deleted_contacts',
6795 '=',
6796 '1',
6797 '0',
69078420 6798 '0',
89d7bb76 6799 ], $this->_params);
6800
6801 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
6802 // and that contact happens to be deleted, set $onlyDeleted to true
6803 foreach ($this->_params as $values) {
6804 $name = CRM_Utils_Array::value(0, $values);
6805 $op = CRM_Utils_Array::value(1, $values);
6806 $value = CRM_Utils_Array::value(2, $values);
6807 if ($name == 'contact_id' and $op == '=') {
6808 if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
6809 $onlyDeleted = TRUE;
6810 }
6811 break;
6812 }
6813 }
6814
6815 // building the query string
6816 $groupBy = $groupByCols = NULL;
6817 if (!$count) {
6818 if (isset($this->_groupByComponentClause)) {
6819 $groupByCols = preg_replace('/^GROUP BY /', '', trim($this->_groupByComponentClause));
6820 $groupByCols = explode(', ', $groupByCols);
6821 }
6822 elseif ($this->_useGroupBy) {
6823 $groupByCols = ['contact_a.id'];
6824 }
6825 }
6826 if ($this->_mode & CRM_Contact_BAO_Query::MODE_ACTIVITY && (!$count)) {
6827 $groupByCols = ['civicrm_activity.id'];
6828 }
6829 if (!empty($groupByCols)) {
6830 $groupBy = " GROUP BY " . implode(', ', $groupByCols);
6831 }
6832
fe3416bf 6833 $order = $orderBy = '';
89d7bb76 6834 if (!$count) {
caefed7d 6835 if (!$sortByChar) {
59733b26 6836 $order = $this->prepareOrderBy($sort, $sortOrder);
caefed7d 6837 }
89d7bb76 6838 }
caefed7d
MWMC
6839 // Cases where we are disabling FGB (FULL_GROUP_BY_MODE):
6840 // 1. When GROUP BY columns are present then disable FGB otherwise it demands to add ORDER BY columns in GROUP BY and eventually in SELECT
89d7bb76 6841 // clause. This will impact the search query output.
caefed7d 6842 $disableFullGroupByMode = (!empty($groupBy) || $groupContacts);
89d7bb76 6843
6844 if ($disableFullGroupByMode) {
6845 CRM_Core_DAO::disableFullGroupByMode();
6846 }
6847
6848 // CRM-15231
6849 $this->_sort = $sort;
6850
6851 //CRM-15967
6852 $this->includePseudoFieldsJoin($sort);
6853
6854 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
6855
6856 if ($additionalWhereClause) {
6857 $where = $where . ' AND ' . $additionalWhereClause;
6858 }
6859
6860 //additional from clause should be w/ proper joins.
6861 if ($additionalFromClause) {
6862 $from .= "\n" . $additionalFromClause;
6863 }
6864
6865 // if we are doing a transform, do it here
6866 // use the $from, $where and $having to get the contact ID
6867 if ($this->_displayRelationshipType) {
6868 $this->filterRelatedContacts($from, $where, $having);
6869 }
fe3416bf 6870 $limit = (!$count && $rowCount) ? " LIMIT " . CRM_Utils_Type::escape($offset, 'Int') . ", " . CRM_Utils_Type::escape($rowCount, 'Int') : '';
6871
6872 return [
6873 'select' => $select,
6874 'from' => $from,
6875 'where' => $where,
6876 'order_by' => $order,
6877 'group_by' => $groupBy,
6878 'having' => $having,
6879 'limit' => $limit,
6880 ];
89d7bb76 6881 }
6882
a0090e6b 6883 /**
6884 * Get the metadata for a given field.
6885 *
6886 * @param string $fieldName
6887 *
6888 * @return array
6889 */
6890 protected function getMetadataForField($fieldName) {
6891 if ($fieldName === 'contact_a.id') {
6892 // This seems to be the only anomaly.
6893 $fieldName = 'id';
6894 }
6895 $pseudoField = isset($this->_pseudoConstantsSelect[$fieldName]) ? $this->_pseudoConstantsSelect[$fieldName] : [];
6896 $field = isset($this->_fields[$fieldName]) ? $this->_fields[$fieldName] : $pseudoField;
6897 $field = array_merge($field, $pseudoField);
6898 if (!empty($field) && empty($field['name'])) {
6899 // standardising field formatting here - over time we can phase out variants.
6900 // all paths using this currently unit tested
124f3c1b 6901 $field['name'] = CRM_Utils_Array::value('field_name', $field, CRM_Utils_Array::value('idCol', $field, $fieldName));
a0090e6b 6902 }
6903 return $field;
6904 }
6905
6906 /**
6907 * Get the metadata for a given field, returning the 'real field' if it is a pseudofield.
6908 *
6909 * @param string $fieldName
6910 *
6911 * @return array
6912 */
6913 protected function getMetadataForRealField($fieldName) {
6914 $field = $this->getMetadataForField($fieldName);
124f3c1b 6915 if (!empty($field['is_pseudofield_for'])) {
6916 $field = $this->getMetadataForField($field['is_pseudofield_for']);
6917 $field['pseudofield_name'] = $fieldName;
6918 }
6919 elseif (!empty($field['pseudoconstant'])) {
6920 if (!empty($field['pseudoconstant']['optionGroupName'])) {
6921 $field['pseudofield_name'] = $field['pseudoconstant']['optionGroupName'];
6922 if (empty($field['table_name'])) {
6923 if (!empty($field['where'])) {
6924 $field['table_name'] = explode('.', $field['where'])[0];
6925 }
6926 else {
6927 $field['table_name'] = 'civicrm_contact';
6928 }
6929 }
6930 }
6931 }
6932 return $field;
a0090e6b 6933 }
6934
07f3c42b 6935 /**
6936 * If we have a field that is better rendered via the pseudoconstant handled them here.
6937 *
6938 * Rather than joining in the additional table we render the option value on output.
6939 *
6940 * @todo - so far this applies to a narrow range of pseudocontants. We are adding them
6941 * carefully with test coverage but aim to extend.
6942 *
07f3c42b 6943 * @param string $name
07f3c42b 6944 */
124f3c1b 6945 protected function addPseudoconstantFieldToSelect($name) {
6946 $field = $this->getMetadataForRealField($name);
6947 $realFieldName = $field['name'];
6948 $pseudoFieldName = CRM_Utils_Array::value('pseudofield_name', $field);
6949 if ($pseudoFieldName) {
6950 // @todo - we don't really need to build this array now we have metadata more available with getMetadataForField fn.
6951 $this->_pseudoConstantsSelect[$pseudoFieldName] = [
6952 'pseudoField' => $pseudoFieldName,
6953 'idCol' => $realFieldName,
6954 'field_name' => $field['name'],
6955 'bao' => $field['bao'],
6956 'pseudoconstant' => $field['pseudoconstant'],
6957 ];
6958 }
6959
6960 $this->_tables[$field['table_name']] = 1;
6961 $this->_element[$realFieldName] = 1;
6962 $this->_select[$field['name']] = str_replace('civicrm_contact.', 'contact_a.', "{$field['where']} as `$realFieldName`");
6963 }
6964
6965 /**
6966 * Is this pseudofield a foreign key constraint.
6967 *
6968 * We are trying to cautiously expand our pseudoconstant handling. This check allows us
6969 * to extend to a narrowly defined type (and then only if the pseudofield is in the fields
6970 * array which is done for contributions which are mostly handled as pseudoconstants.
6971 *
6972 * @param $fieldSpec
6973 *
6974 * @return bool
6975 */
6976 protected function isPseudoFieldAnFK($fieldSpec) {
6977 if (empty($fieldSpec['FKClassName'])
6978 || CRM_Utils_Array::value('keyColumn', $fieldSpec['pseudoconstant']) !== 'id'
6979 || CRM_Utils_Array::value('labelColumn', $fieldSpec['pseudoconstant']) !== 'name') {
6980 return FALSE;
6981 }
6982 return TRUE;
07f3c42b 6983 }
6984
8fc9f99a 6985 /**
6986 * Is the field a relative date field.
6987 *
6988 * @param string $fieldName
6989 *
6990 * @return bool
6991 */
6992 protected function isARelativeDateField($fieldName) {
6993 if (substr($fieldName, -9, 9) !== '_relative') {
6994 return FALSE;
6995 }
6996 $realField = substr($fieldName, 0, strlen($fieldName) - 9);
6997 return isset($this->_fields[$realField]);
6998 }
6999
33a17d7e 7000 /**
7001 * Get the specifications for the field, if available.
7002 *
7003 * @param string $fieldName
7004 * Fieldname as displayed on the form.
7005 *
7006 * @return array
7007 */
7008 public function getFieldSpec($fieldName) {
7009 if (isset($this->_fields[$fieldName])) {
7010 return $this->_fields[$fieldName];
7011 }
7012 $lowFieldName = str_replace('_low', '', $fieldName);
7013 if (isset($this->_fields[$lowFieldName])) {
7014 return array_merge($this->_fields[$lowFieldName], ['field_name' => $lowFieldName]);
7015 }
7016 $highFieldName = str_replace('_high', '', $fieldName);
7017 if (isset($this->_fields[$highFieldName])) {
7018 return array_merge($this->_fields[$highFieldName], ['field_name' => $highFieldName]);
7019 }
7020 return [];
7021 }
7022
7023 public function buildWhereForDate() {
7024
7025 }
7026
7027 /**
7028 * Is the field a relative date field.
7029 *
7030 * @param string $fieldName
7031 *
7032 * @return bool
7033 */
7034 protected function isADateRangeField($fieldName) {
7035 if (substr($fieldName, -4, 4) !== '_low' && substr($fieldName, -5, 5) !== '_high') {
7036 return FALSE;
7037 }
7038 return !empty($this->getFieldSpec($fieldName));
7039 }
7040
8fc9f99a 7041 /**
7042 * @param $values
7043 */
7044 protected function buildRelativeDateQuery(&$values) {
7045 $value = CRM_Utils_Array::value(2, $values);
7046 if (empty($value)) {
7047 return;
7048 }
7049 $fieldName = substr($values[0], 0, strlen($values[0]) - 9);
7050 $fieldSpec = $this->_fields[$fieldName];
7051 $tableName = $fieldSpec['table_name'];
7052 $filters = CRM_Core_OptionGroup::values('relative_date_filters');
7053 $grouping = CRM_Utils_Array::value(3, $values);
7f175707 7054 // If the table value is already set for a custom field it will be more nuanced than just '1'.
7055 $this->_tables[$tableName] = $this->_tables[$tableName] ?? 1;
7056 $this->_whereTables[$tableName] = $this->_whereTables[$tableName] ?? 1;
8fc9f99a 7057
7058 $dates = CRM_Utils_Date::getFromTo($value, NULL, NULL);
936ededf 7059 // Where end would be populated only if we are handling one of the weird ones with different from & to fields.
7060 $secondWhere = $fieldSpec['where_end'] ?? $fieldSpec['where'];
8fc9f99a 7061 if (empty($dates[0])) {
7062 // ie. no start date we only have end date
936ededf 7063 $this->_where[$grouping][] = $secondWhere . " <= '{$dates[1]}'";
8fc9f99a 7064
7065 $this->_qill[$grouping][] = ts('%1 is ', [$fieldSpec['title']]) . $filters[$value] . ' (' . ts("to %1", [
69078420
SL
7066 CRM_Utils_Date::customFormat($dates[1]),
7067 ]) . ')';
8fc9f99a 7068 }
7069 elseif (empty($dates[1])) {
936ededf 7070
8fc9f99a 7071 // ie. no end date we only have start date
7072 $this->_where[$grouping][] = $fieldSpec['where'] . " >= '{$dates[1]}'";
7073
7074 $this->_qill[$grouping][] = ts('%1 is ', [$fieldSpec['title']]) . $filters[$value] . ' (' . ts("from %1", [
69078420
SL
7075 CRM_Utils_Date::customFormat($dates[0]),
7076 ]) . ')';
8fc9f99a 7077 }
7078 else {
7079 // we have start and end dates.
bca2ad39 7080 $where = $fieldSpec['where'];
7081 if ($fieldSpec['table_name'] === 'civicrm_contact') {
7082 // Special handling for contact table as it has a known alias in advanced search.
7083 $where = str_replace('civicrm_contact.', 'contact_a.', $where);
7084 }
936ededf 7085 if ($secondWhere !== $fieldSpec['where']) {
7086 $this->_where[$grouping][] = $fieldSpec['where'] . ">= '{$dates[0]}' AND $secondWhere <='{$dates[1]}'";
7087 }
7088 else {
7089 $this->_where[$grouping][] = $where . " BETWEEN '{$dates[0]}' AND '{$dates[1]}'";
7090 }
8fc9f99a 7091
7092 $this->_qill[$grouping][] = ts('%1 is ', [$fieldSpec['title']]) . $filters[$value] . ' (' . ts("between %1 and %2", [
69078420
SL
7093 CRM_Utils_Date::customFormat($dates[0]),
7094 CRM_Utils_Date::customFormat($dates[1]),
7095 ]) . ')';
8fc9f99a 7096 }
7097 }
7098
33a17d7e 7099 /**
7100 * Build the query for a date field if it is a _high or _low field.
7101 *
7102 * @param $values
7103 *
7104 * @return bool
936ededf 7105 * @throws \CRM_Core_Exception
33a17d7e 7106 */
7107 public function buildDateRangeQuery($values) {
7108 if ($this->isADateRangeField($values[0])) {
7109 $fieldSpec = $this->getFieldSpec($values[0]);
7110 $title = empty($fieldSpec['unique_title']) ? $fieldSpec['title'] : $fieldSpec['unique_title'];
7111 $this->dateQueryBuilder($values, $fieldSpec['table_name'], $fieldSpec['field_name'], $fieldSpec['name'], $title);
7112 return TRUE;
7113 }
7114 return FALSE;
7115 }
7116
708ce91f 7117 /**
7118 * Add the address table into the query.
7119 *
7120 * @param string $tableKey
7121 * @param string $joinCondition
7122 *
7123 * @return array
7124 * - alias name
7125 * - address join.
7126 */
7127 protected function addAddressTable($tableKey, $joinCondition) {
7128 $tName = "$tableKey-address";
7129 $aName = "`$tableKey-address`";
7130 $this->_select["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
7131 $this->_element["{$tName}_id"] = 1;
7132 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$joinCondition)";
7133 $this->_tables[$tName] = $addressJoin;
7134
7135 return [
7136 $aName,
69078420 7137 $addressJoin,
708ce91f 7138 ];
7139 }
7140
d7570a7f 7141 /**
7142 * Get the clause for group status.
7143 *
7144 * @param int $grouping
7145 *
7146 * @return string
7147 */
7148 protected function getGroupStatusClause($grouping) {
7149 $statuses = $this->getSelectedGroupStatuses($grouping);
7150 return "status IN (" . implode(', ', $statuses) . ")";
7151 }
7152
7153 /**
7154 * Get an array of the statuses that have been selected.
7155 *
7156 * @param string $grouping
7157 *
7158 * @return array
7159 */
7160 protected function getSelectedGroupStatuses($grouping) {
7161 $statuses = [];
7162 $gcsValues = $this->getWhereValues('group_contact_status', $grouping);
7163 if ($gcsValues &&
7164 is_array($gcsValues[2])
7165 ) {
7166 foreach ($gcsValues[2] as $k => $v) {
7167 if ($v) {
7168 $statuses[] = "'" . CRM_Utils_Type::escape($k, 'String') . "'";
7169 }
7170 }
7171 }
7172 else {
7173 $statuses[] = "'Added'";
7174 }
7175 return $statuses;
7176 }
7177
9178793e 7178 /**
7179 * Get the qill value for the field.
7180 *
7181 * @param $name
7182 * @param array|int|string $value
7183 * @param $op
7184 *
7185 * @return string
7186 */
7187 protected function getQillForField($name, $value, $op): string {
7188 list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue(NULL, $name, $value, $op);
7189 return (string) ts("%1 %2 %3", [
7190 1 => ts('Email'),
7191 2 => $qillop,
7192 3 => $qillVal,
7193 ]);
7194 }
7195
e7830dbe 7196}