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