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