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