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