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