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