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