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