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