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