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