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