3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * This is the heart of the search query building mechanism.
37 class CRM_Contact_BAO_Query
{
40 * The various search modes.
42 * As of February 2017, entries not present for 4, 32, 64, 1024.
44 * MODE_ALL seems to be out of sync with the available constants;
45 * if this is intentionally excluding MODE_MAILING then that may
48 * Likewise if there's reason for the missing modes (4, 32, 64 etc).
53 NO_RETURN_PROPERTIES
= 'CRM_Contact_BAO_Query::NO_RETURN_PROPERTIES',
59 MODE_CONTACTSRELATED
= 32,
62 MODE_PLEDGEBANK
= 256,
72 * Constants for search operators
75 SEARCH_OPERATOR_AND
= 'AND',
76 SEARCH_OPERATOR_OR
= 'OR';
79 * The default set of return properties.
83 public static $_defaultReturnProperties = NULL;
86 * The default set of hier return properties.
90 public static $_defaultHierReturnProperties;
93 * The set of input params.
101 public $_paramLookup;
106 * The set of output params
110 public $_returnProperties;
120 * The name of the elements that are in the select clause
121 * used to extract the values.
128 * The tables involved in the query.
135 * The table involved in the where clause.
139 public $_whereTables;
142 * Array of WHERE clause components.
149 * The WHERE clause as a string.
153 public $_whereClause;
156 * Additional WHERE clause for permissions.
160 public $_permissionWhereClause;
170 * Additional permission from clause
174 public $_permissionFromClause;
177 * The from clause for the simple select and alphabetical
182 public $_simpleFromClause;
192 * The english language version of the query
199 * All the fields that could potentially be involved in
207 * The cache to translate the option values into labels.
214 * Are we in search mode.
218 public $_search = TRUE;
221 * Should we skip permission checking.
225 public $_skipPermission = FALSE;
228 * Should we skip adding of delete clause.
232 public $_skipDeleteClause = FALSE;
235 * Are we in strict mode (use equality over LIKE)
239 public $_strict = FALSE;
242 * What operator to use to group the clauses.
246 public $_operator = 'AND';
251 * Should we only search on primary location.
255 public $_primaryLocation = TRUE;
258 * Are contact ids part of the query.
262 public $_includeContactIds = FALSE;
265 * Should we use the smart group cache.
269 public $_smartGroupCache = TRUE;
272 * Should we display contacts with a specific relationship type.
276 public $_displayRelationshipType = NULL;
279 * Reference to the query object for custom values.
283 public $_customQuery;
286 * Should we enable the distinct clause, used if we are including
287 * more than one group
291 public $_useDistinct = FALSE;
294 * Should we just display one contact record
297 public $_useGroupBy = FALSE;
300 * The relationship type direction
304 public static $_relType;
311 public static $_activityRole;
314 * Consider the component activity type
315 * during activity search.
319 public static $_considerCompActivities;
322 * Consider with contact activities only,
323 * during activity search.
327 public static $_withContactActivitiesOnly;
330 * Use distinct component clause for component searches
334 public $_distinctComponentClause;
336 public $_rowCountClause;
339 * Use groupBy component clause for component searches
343 public $_groupByComponentClause;
346 * Track open panes, useful in advance search
350 public static $_openedPanes = [];
353 * For search builder - which custom fields are location-dependent
356 public $_locationSpecificCustomFields = [];
359 * The tables which have a dependency on location and/or address
363 public static $_dependencies = [
364 'civicrm_state_province' => 1,
365 'civicrm_country' => 1,
366 'civicrm_county' => 1,
367 'civicrm_address' => 1,
368 'civicrm_location_type' => 1,
372 * List of location specific fields.
375 public static $_locationSpecificFields = [
380 'supplemental_address_1',
381 'supplemental_address_2',
382 'supplemental_address_3',
385 'postal_code_suffix',
399 * Remember if we handle either end of a number or date range
400 * so we can skip the other
403 protected $_rangeCache = [];
405 * Set to true when $this->relationship is run to avoid adding twice
408 protected $_relationshipValuesAdded = FALSE;
411 * Set to the name of the temp table if one has been created
414 public static $_relationshipTempTable = NULL;
416 public $_pseudoConstantsSelect = [];
418 public $_groupUniqueKey = NULL;
419 public $_groupKeys = [];
422 * Class constructor which also does all the work.
424 * @param array $params
425 * @param array $returnProperties
426 * @param array $fields
427 * @param bool $includeContactIds
428 * @param bool $strict
429 * @param bool|int $mode - mode the search is operating on
431 * @param bool $skipPermission
432 * @param bool $searchDescendentGroups
433 * @param bool $smartGroupCache
434 * @param null $displayRelationshipType
435 * @param string $operator
436 * @param string $apiEntity
437 * @param bool|NULL $primaryLocationOnly
439 public function __construct(
440 $params = NULL, $returnProperties = NULL, $fields = NULL,
441 $includeContactIds = FALSE, $strict = FALSE, $mode = 1,
442 $skipPermission = FALSE, $searchDescendentGroups = TRUE,
443 $smartGroupCache = TRUE, $displayRelationshipType = NULL,
446 $primaryLocationOnly = NULL
448 if ($primaryLocationOnly === NULL) {
449 $primaryLocationOnly = Civi
::settings()->get('searchPrimaryDetailsOnly');
451 $this->_primaryLocation
= $primaryLocationOnly;
452 $this->_params
= &$params;
453 if ($this->_params
== NULL) {
457 if ($returnProperties === self
::NO_RETURN_PROPERTIES
) {
458 $this->_returnProperties
= [];
460 elseif (empty($returnProperties)) {
461 $this->_returnProperties
= self
::defaultReturnProperties($mode);
464 $this->_returnProperties
= &$returnProperties;
467 $this->_includeContactIds
= $includeContactIds;
468 $this->_strict
= $strict;
469 $this->_mode
= $mode;
470 $this->_skipPermission
= $skipPermission;
471 $this->_smartGroupCache
= $smartGroupCache;
472 $this->_displayRelationshipType
= $displayRelationshipType;
473 $this->setOperator($operator);
476 $this->_fields
= &$fields;
477 $this->_search
= FALSE;
478 $this->_skipPermission
= TRUE;
481 $this->_fields
= CRM_Contact_BAO_Contact
::exportableFields('All', FALSE, TRUE, TRUE, FALSE, !$skipPermission);
483 $fields = CRM_Core_Component
::getQueryFields(!$this->_skipPermission
);
484 unset($fields['note']);
485 $this->_fields
= array_merge($this->_fields
, $fields);
487 // add activity fields
488 $fields = CRM_Activity_BAO_Activity
::exportableFields();
489 $this->_fields
= array_merge($this->_fields
, $fields);
491 // add any fields provided by hook implementers
492 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
493 $this->_fields
= array_merge($this->_fields
, $extFields);
496 // basically do all the work once, and then reuse it
497 $this->initialize($apiEntity);
501 * Function which actually does all the work for the constructor.
503 * @param string $apiEntity
504 * The api entity being called.
505 * This sort-of duplicates $mode in a confusing way. Probably not by design.
507 public function initialize($apiEntity = NULL) {
509 $this->_element
= [];
511 $this->_whereTables
= [];
514 $this->_options
= [];
516 $this->_paramLookup
= [];
519 $this->_customQuery
= NULL;
521 // reset cached static variables - CRM-5803
522 self
::$_activityRole = NULL;
523 self
::$_considerCompActivities = NULL;
524 self
::$_withContactActivitiesOnly = NULL;
526 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
527 $this->_element
['contact_id'] = 1;
528 $this->_tables
['civicrm_contact'] = 1;
530 if (!empty($this->_params
)) {
531 $this->buildParamsLookup();
534 $this->_whereTables
= $this->_tables
;
536 $this->selectClause($apiEntity);
537 $this->_whereClause
= $this->whereClause($apiEntity);
538 if (array_key_exists('civicrm_contribution', $this->_whereTables
)) {
539 $component = 'contribution';
541 if (array_key_exists('civicrm_membership', $this->_whereTables
)) {
542 $component = 'membership';
544 if (isset($component) && !$this->_skipPermission
) {
545 // Unit test coverage in api_v3_FinancialTypeACLTest::testGetACLContribution.
546 CRM_Financial_BAO_FinancialType
::buildPermissionedClause($this->_whereClause
, $component);
549 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
, $apiEntity);
550 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
552 $this->openedSearchPanes(TRUE);
556 * Function for same purpose as convertFormValues.
558 * Like convert form values this function exists to pre-Process parameters from the form.
560 * It is unclear why they are different functions & likely relates to advances search
561 * versus search builder.
563 * The direction we are going is having the form convert values to a standardised format &
564 * moving away from weird & wonderful where clause switches.
566 * Fix and handle contact deletion nicely.
568 * this code is primarily for search builder use case where different clauses can specify if they want deleted.
572 public function buildParamsLookup() {
573 $trashParamExists = FALSE;
575 foreach ($this->_params
as $k => $param) {
576 if (!empty($param[0]) && $param[0] == 'contact_is_deleted') {
577 $trashParamExists = TRUE;
579 if (!empty($param[3])) {
580 $paramByGroup[$param[3]][$k] = $param;
584 if ($trashParamExists) {
585 $this->_skipDeleteClause
= TRUE;
587 //cycle through group sets and explicitly add trash param if not set
588 foreach ($paramByGroup as $setID => $set) {
590 !in_array(['contact_is_deleted', '=', '1', $setID, '0'], $this->_params
) &&
591 !in_array(['contact_is_deleted', '=', '0', $setID, '0'], $this->_params
)
594 'contact_is_deleted',
604 foreach ($this->_params
as $value) {
605 if (empty($value[0])) {
608 $cfID = CRM_Core_BAO_CustomField
::getKeyID($value[0]);
610 if (!array_key_exists($cfID, $this->_cfIDs
)) {
611 $this->_cfIDs
[$cfID] = [];
613 // Set wildcard value based on "and/or" selection
614 foreach ($this->_params
as $key => $param) {
615 if ($param[0] == $value[0] . '_operator') {
616 $value[4] = $param[2] == 'or';
620 $this->_cfIDs
[$cfID][] = $value;
623 if (!array_key_exists($value[0], $this->_paramLookup
)) {
624 $this->_paramLookup
[$value[0]] = [];
626 if ($value[0] !== 'group') {
627 // Just trying to unravel how group interacts here! This whole function is weird.
628 $this->_paramLookup
[$value[0]][] = $value;
634 * Some composite fields do not appear in the fields array hack to make them part of the query.
637 * The api entity being called.
638 * This sort-of duplicates $mode in a confusing way. Probably not by design.
640 public function addSpecialFields($apiEntity) {
641 static $special = ['contact_type', 'contact_sub_type', 'sort_name', 'display_name'];
642 // if get called via Contact.get API having address_id as return parameter
643 if ($apiEntity == 'Contact') {
644 $special[] = 'address_id';
646 foreach ($special as $name) {
647 if (!empty($this->_returnProperties
[$name])) {
648 if ($name == 'address_id') {
649 $this->_tables
['civicrm_address'] = 1;
650 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
651 $this->_element
['address_id'] = 1;
654 $this->_select
[$name] = "contact_a.{$name} as $name";
655 $this->_element
[$name] = 1;
662 * Given a list of conditions in params and a list of desired
663 * return Properties generate the required select and from
664 * clauses. Note that since the where clause introduces new
665 * tables, the initial attempt also retrieves all variables used
668 * @param string $apiEntity
669 * The api entity being called.
670 * This sort-of duplicates $mode in a confusing way. Probably not by design.
672 public function selectClause($apiEntity = NULL) {
674 // @todo Tidy up this. This arises because 1) we are ignoring the $mode & adding a new
675 // param ($apiEntity) instead - presumably an oversight & 2 because
676 // contact is not implemented as a component.
677 $this->addSpecialFields($apiEntity);
679 foreach ($this->_fields
as $name => $field) {
680 // skip component fields
681 // there are done by the alter query below
682 // and need not be done on every field
683 // @todo remove these & handle using metadata - only obscure fields
684 // that are hack-added should need to be excluded from the main loop.
686 (substr($name, 0, 12) == 'participant_') ||
687 (substr($name, 0, 7) == 'pledge_') ||
688 (substr($name, 0, 5) == 'case_')
693 // redirect to activity select clause
695 (substr($name, 0, 9) == 'activity_') ||
696 ($name == 'parent_id')
698 CRM_Activity_BAO_Query
::select($this);
701 // if this is a hierarchical name, we ignore it
702 $names = explode('-', $name);
703 if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) {
707 // make an exception for special cases, to add the field in select clause
708 $makeException = FALSE;
710 //special handling for groups/tags
711 if (in_array($name, ['groups', 'tags', 'notes'])
712 && isset($this->_returnProperties
[substr($name, 0, -1)])
714 // @todo instead of setting make exception to get us into
715 // an if clause that has handling for these fields buried with in it
716 // move the handling to here.
717 $makeException = TRUE;
720 // since note has 3 different options we need special handling
721 // note / note_subject / note_body
722 if ($name == 'notes') {
723 foreach (['note', 'note_subject', 'note_body'] as $noteField) {
724 if (isset($this->_returnProperties
[$noteField])) {
725 $makeException = TRUE;
731 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
733 !empty($this->_paramLookup
[$name])
734 ||
!empty($this->_returnProperties
[$name])
735 ||
$this->pseudoConstantNameIsInReturnProperties($field, $name)
739 // add to cfIDs array if not present
740 if (!array_key_exists($cfID, $this->_cfIDs
)) {
741 $this->_cfIDs
[$cfID] = [];
744 elseif (isset($field['where'])) {
745 list($tableName, $fieldName) = explode('.', $field['where'], 2);
746 if (isset($tableName)) {
747 if (CRM_Utils_Array
::value($tableName, self
::$_dependencies)) {
748 $this->_tables
['civicrm_address'] = 1;
749 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
750 $this->_element
['address_id'] = 1;
753 if ($tableName == 'im_provider' ||
$tableName == 'email_greeting' ||
754 $tableName == 'postal_greeting' ||
$tableName == 'addressee'
756 if ($tableName == 'im_provider') {
757 CRM_Core_OptionValue
::select($this);
760 if (in_array($tableName,
761 ['email_greeting', 'postal_greeting', 'addressee'])) {
762 $this->_element
["{$name}_id"] = 1;
763 $this->_select
["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
764 $this->_pseudoConstantsSelect
[$name] = ['pseudoField' => $tableName, 'idCol' => "{$name}_id"];
765 $this->_pseudoConstantsSelect
[$name]['select'] = "{$name}.{$fieldName} as $name";
766 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
768 if ($tableName == 'email_greeting') {
770 $this->_pseudoConstantsSelect
[$name]['join']
771 = " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
772 $this->_pseudoConstantsSelect
[$name]['join'] .=
773 " 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 ) ";
775 elseif ($tableName == 'postal_greeting') {
777 $this->_pseudoConstantsSelect
[$name]['join']
778 = " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
779 $this->_pseudoConstantsSelect
[$name]['join'] .=
780 " 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 ) ";
782 elseif ($tableName == 'addressee') {
784 $this->_pseudoConstantsSelect
[$name]['join']
785 = " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
786 $this->_pseudoConstantsSelect
[$name]['join'] .=
787 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
789 $this->_pseudoConstantsSelect
[$name]['table'] = $tableName;
792 $greetField = "{$name}_display";
793 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
794 $this->_element
[$greetField] = 1;
796 $greetField = "{$name}_custom";
797 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
798 $this->_element
[$greetField] = 1;
802 if (!in_array($tableName, ['civicrm_state_province', 'civicrm_country', 'civicrm_county'])) {
803 $this->_tables
[$tableName] = 1;
806 // also get the id of the tableName
807 $tName = substr($tableName, 8);
808 if (in_array($tName, ['country', 'state_province', 'county'])) {
809 if ($tName == 'state_province') {
810 $this->_pseudoConstantsSelect
['state_province_name'] = [
811 'pseudoField' => "{$tName}",
812 'idCol' => "{$tName}_id",
813 'bao' => 'CRM_Core_BAO_Address',
814 'table' => "civicrm_{$tName}",
815 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
818 $this->_pseudoConstantsSelect
[$tName] = [
819 'pseudoField' => 'state_province_abbreviation',
820 'idCol' => "{$tName}_id",
821 'table' => "civicrm_{$tName}",
822 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
826 $this->_pseudoConstantsSelect
[$name] = [
827 'pseudoField' => "{$tName}_id",
828 'idCol' => "{$tName}_id",
829 'bao' => 'CRM_Core_BAO_Address',
830 'table' => "civicrm_{$tName}",
831 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
835 $this->_select
["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
836 $this->_element
["{$tName}_id"] = 1;
838 elseif ($tName != 'contact') {
839 $this->_select
["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
840 $this->_element
["{$tName}_id"] = 1;
843 //special case for phone
844 if ($name == 'phone') {
845 $this->_select
['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
846 $this->_element
['phone_type_id'] = 1;
849 // if IM then select provider_id also
850 // to get "IM Service Provider" in a file to be exported, CRM-3140
852 $this->_select
['provider_id'] = "civicrm_im.provider_id as provider_id";
853 $this->_element
['provider_id'] = 1;
856 if ($tName == 'contact' && $fieldName == 'organization_name') {
857 // special case, when current employer is set for Individual contact
858 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
860 elseif ($tName == 'contact' && $fieldName === 'id') {
861 // Handled elsewhere, explicitly ignore. Possibly for all tables...
863 elseif (in_array($tName, ['country', 'county'])) {
864 $this->_pseudoConstantsSelect
[$name]['select'] = "{$field['where']} as `$name`";
865 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
867 elseif ($tName == 'state_province') {
868 $this->_pseudoConstantsSelect
[$tName]['select'] = "{$field['where']} as `$name`";
869 $this->_pseudoConstantsSelect
[$tName]['element'] = $name;
871 elseif (strpos($name, 'contribution_soft_credit') !== FALSE) {
872 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled($this->_params
)) {
873 $this->_select
[$name] = "{$field['where']} as `$name`";
876 elseif ($this->pseudoConstantNameIsInReturnProperties($field, $name)) {
877 $this->addPseudoconstantFieldToSelect($name);
880 $this->_select
[$name] = str_replace('civicrm_contact.', 'contact_a.', "{$field['where']} as `$name`");
882 if (!in_array($tName, ['state_province', 'country', 'county'])) {
883 $this->_element
[$name] = 1;
888 elseif ($name === 'tags') {
889 //@todo move this handling outside the big IF & ditch $makeException
890 $this->_useGroupBy
= TRUE;
891 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
892 $this->_element
[$name] = 1;
893 $this->_tables
['civicrm_tag'] = 1;
894 $this->_tables
['civicrm_entity_tag'] = 1;
896 elseif ($name === 'groups') {
897 //@todo move this handling outside the big IF & ditch $makeException
898 $this->_useGroupBy
= TRUE;
899 // Duplicates will be created here but better to sort them out in php land.
900 $this->_select
[$name] = "
902 GROUP_CONCAT(DISTINCT IF(civicrm_group_contact.status = 'Added', civicrm_group_contact.group_id, '')),
903 GROUP_CONCAT(DISTINCT civicrm_group_contact_cache.group_id)
906 $this->_element
[$name] = 1;
907 $this->_tables
['civicrm_group_contact'] = 1;
908 $this->_tables
['civicrm_group_contact_cache'] = 1;
909 $this->_pseudoConstantsSelect
["{$name}"] = [
910 'pseudoField' => "groups",
914 elseif ($name === 'notes') {
915 //@todo move this handling outside the big IF & ditch $makeException
916 // if note field is subject then return subject else body of the note
917 $noteColumn = 'note';
918 if (isset($noteField) && $noteField == 'note_subject') {
919 $noteColumn = 'subject';
922 $this->_useGroupBy
= TRUE;
923 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
924 $this->_element
[$name] = 1;
925 $this->_tables
['civicrm_note'] = 1;
927 elseif ($name === 'current_employer') {
928 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
929 $this->_element
[$name] = 1;
933 if ($cfID && !empty($field['is_search_range'])) {
934 // this is a custom field with range search enabled, so we better check for two/from values
935 if (!empty($this->_paramLookup
[$name . '_from'])) {
936 if (!array_key_exists($cfID, $this->_cfIDs
)) {
937 $this->_cfIDs
[$cfID] = [];
939 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
940 // search in the cdID array for the same grouping
942 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
943 if ($c[3] == $p[3]) {
944 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
949 $p[2] = ['from' => $p[2]];
950 $this->_cfIDs
[$cfID][] = $p;
954 if (!empty($this->_paramLookup
[$name . '_to'])) {
955 if (!array_key_exists($cfID, $this->_cfIDs
)) {
956 $this->_cfIDs
[$cfID] = [];
958 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
959 // search in the cdID array for the same grouping
961 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
962 if ($c[4] == $p[4]) {
963 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
968 $p[2] = ['to' => $p[2]];
969 $this->_cfIDs
[$cfID][] = $p;
976 // add location as hierarchical elements
977 $this->addHierarchicalElements();
979 // add multiple field like website
980 $this->addMultipleElements();
983 CRM_Core_Component
::alterQuery($this, 'select');
985 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'select');
987 if (!empty($this->_cfIDs
)) {
988 // @todo This function is the select function but instead of running 'select' it
989 // is running the whole query.
990 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
991 $this->_customQuery
->query();
992 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
993 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
994 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
995 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
996 $this->_options
= $this->_customQuery
->_options
;
1001 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
1003 public function addHierarchicalElements() {
1004 if (empty($this->_returnProperties
['location'])) {
1007 if (!is_array($this->_returnProperties
['location'])) {
1011 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
1015 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
1016 $addressCustomFieldIds = [];
1018 foreach ($this->_returnProperties
['location'] as $name => $elements) {
1019 $lCond = self
::getPrimaryCondition($name);
1020 $locationTypeId = is_numeric($name) ?
NULL : array_search($name, $locationTypes);
1023 if ($locationTypeId === FALSE) {
1026 $lCond = "location_type_id = $locationTypeId";
1027 $this->_useDistinct
= TRUE;
1029 //commented for CRM-3256
1030 $this->_useGroupBy
= TRUE;
1033 $name = str_replace(' ', '_', $name);
1034 $tName = "$name-location_type";
1035 $ltName = "`$name-location_type`";
1036 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1037 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
1038 $this->_element
["{$tName}_id"] = 1;
1039 $this->_element
["{$tName}"] = 1;
1041 $locationTypeName = $tName;
1042 $locationTypeJoin = [];
1045 foreach ($elements as $elementFullName => $dontCare) {
1047 $elementName = $elementCmpName = $elementFullName;
1049 if (substr($elementCmpName, 0, 5) == 'phone') {
1050 $elementCmpName = 'phone';
1053 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
1054 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
1055 $addressCustomFieldIds[$cfID][$name] = 1;
1058 // add address table - doesn't matter if we do it mutliple times - it's the same data
1059 // @todo ditch the double processing of addressJoin
1060 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
1061 && !in_array($elementCmpName, ['email', 'phone', 'im', 'openid'])
1063 list($aName, $addressJoin) = $this->addAddressTable($name, $lCond);
1064 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
1065 $processed[$aName] = 1;
1068 $cond = $elementType = '';
1069 if (strpos($elementName, '-') !== FALSE) {
1070 // this is either phone, email or IM
1071 list($elementName, $elementType) = explode('-', $elementName);
1073 if (($elementName != 'phone') && ($elementName != 'im')) {
1074 $cond = self
::getPrimaryCondition($elementType);
1076 // CRM-13011 : If location type is primary, do not restrict search to the phone
1077 // type id - we want the primary phone, regardless of what type it is.
1078 // Otherwise, restrict to the specified phone type for the given field.
1079 if ((!$cond) && ($elementName == 'phone')) {
1080 $cond = "phone_type_id = '$elementType'";
1082 elseif ((!$cond) && ($elementName == 'im')) {
1083 // IM service provider id, CRM-3140
1084 $cond = "provider_id = '$elementType'";
1086 $elementType = '-' . $elementType;
1089 $field = CRM_Utils_Array
::value($elementName, $this->_fields
);
1091 // hack for profile, add location id
1094 // fix for CRM-882( to handle phone types )
1095 !is_numeric($elementType)
1097 if (is_numeric($name)) {
1098 $field = CRM_Utils_Array
::value($elementName . "-Primary$elementType", $this->_fields
);
1101 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1104 elseif (is_numeric($name)) {
1105 //this for phone type to work
1106 if (in_array($elementName, ['phone', 'phone_ext'])) {
1107 $field = CRM_Utils_Array
::value($elementName . "-Primary" . $elementType, $this->_fields
);
1110 $field = CRM_Utils_Array
::value($elementName . "-Primary", $this->_fields
);
1114 //this is for phone type to work for profile edit
1115 if (in_array($elementName, ['phone', 'phone_ext'])) {
1116 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1119 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId", $this->_fields
);
1124 // Check if there is a value, if so also add to where Clause
1126 if ($this->_params
) {
1128 if (isset($locationTypeId)) {
1129 $nm .= "-$locationTypeId";
1131 if (!is_numeric($elementType)) {
1132 $nm .= "$elementType";
1135 foreach ($this->_params
as $id => $values) {
1136 if ((is_array($values) && $values[0] == $nm) ||
1137 (in_array($elementName, ['phone', 'im'])
1138 && (strpos($values[0], $nm) !== FALSE)
1148 if ($field && isset($field['where'])) {
1149 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1150 $pf = substr($tableName, 8);
1151 $tName = $name . '-' . $pf . $elementType;
1152 if (isset($tableName)) {
1153 if ($tableName == 'civicrm_state_province' ||
$tableName == 'civicrm_country' ||
$tableName == 'civicrm_county') {
1154 $this->_select
["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1157 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1160 $this->_element
["{$tName}_id"] = 1;
1161 if (substr($tName, -15) == '-state_province') {
1162 // FIXME: hack to fix CRM-1900
1163 $a = Civi
::settings()->get('address_format');
1165 if (substr_count($a, 'state_province_name') > 0) {
1166 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = [
1167 'pseudoField' => "{$pf}_id",
1168 'idCol' => "{$tName}_id",
1169 'bao' => 'CRM_Core_BAO_Address',
1171 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1174 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = [
1175 'pseudoField' => 'state_province_abbreviation',
1176 'idCol' => "{$tName}_id",
1178 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1182 if (substr($elementFullName, 0, 2) == 'im') {
1183 $provider = "{$name}-{$elementFullName}-provider_id";
1184 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1185 $this->_element
[$provider] = 1;
1187 if ($pf == 'country' ||
$pf == 'county') {
1188 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = [
1189 'pseudoField' => "{$pf}_id",
1190 'idCol' => "{$tName}_id",
1191 'bao' => 'CRM_Core_BAO_Address',
1193 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1196 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1200 if (in_array($pf, ['state_province', 'country', 'county'])) {
1201 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1204 $this->_element
["{$name}-{$elementFullName}"] = 1;
1207 if (empty($processed["`$tName`"])) {
1208 $processed["`$tName`"] = 1;
1209 $newName = $tableName . '_' . $index;
1210 switch ($tableName) {
1211 case 'civicrm_phone':
1212 case 'civicrm_email':
1214 case 'civicrm_openid':
1216 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id";
1217 if ($tableName != 'civicrm_phone') {
1218 $this->_tables
[$tName] .= " AND `$tName`.$lCond";
1220 elseif (is_numeric($name)) {
1221 $this->_select
[$tName] = "IF (`$tName`.is_primary = $name, `$tName`.phone, NULL) as `$tName`";
1224 // this special case to add phone type
1226 $phoneTypeCondition = " AND `$tName`.$cond ";
1227 //gross hack to pickup corrupted data also, CRM-7603
1228 if (strpos($cond, 'phone_type_id') !== FALSE) {
1229 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1230 if (!empty($lCond)) {
1231 $phoneTypeCondition .= " AND ( `$tName`.$lCond ) ";
1234 $this->_tables
[$tName] .= $phoneTypeCondition;
1237 //build locationType join
1238 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1241 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1245 case 'civicrm_state_province':
1246 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1247 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1248 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1250 $this->_whereTables
["{$name}-address"] = $addressJoin;
1254 case 'civicrm_country':
1255 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1256 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1257 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1259 $this->_whereTables
["{$name}-address"] = $addressJoin;
1263 case 'civicrm_county':
1264 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1265 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1266 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1268 $this->_whereTables
["{$name}-address"] = $addressJoin;
1274 $this->_whereTables
["{$name}-address"] = $addressJoin;
1283 // add location type join
1284 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1285 $this->_tables
[$locationTypeName] = $ltypeJoin;
1287 // table should be present in $this->_whereTables,
1288 // to add its condition in location type join, CRM-3939.
1289 if ($addWhereCount) {
1291 foreach ($this->_whereTables
as $tableName => $clause) {
1292 if (!empty($locationTypeJoin[$tableName])) {
1293 $locClause[] = $locationTypeJoin[$tableName];
1297 if (!empty($locClause)) {
1298 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1303 if (!empty($addressCustomFieldIds)) {
1304 $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
1305 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1306 foreach ($locTypeName as $name => $dnc) {
1307 $this->_locationSpecificCustomFields
[$cfID] = [$name, array_search($name, $locationTypes)];
1308 $fieldName = "$name-custom_{$cfID}";
1309 $tName = "$name-address-custom-{$cfID}";
1310 $aName = "`$name-address-custom-{$cfID}`";
1311 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1312 $this->_element
["{$tName}_id"] = 1;
1313 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1314 $this->_element
[$fieldName] = 1;
1315 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1322 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
1324 public function addMultipleElements() {
1325 if (empty($this->_returnProperties
['website'])) {
1328 if (!is_array($this->_returnProperties
['website'])) {
1332 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1333 foreach ($elements as $elementFullName => $dontCare) {
1334 $tName = "website-{$key}-{$elementFullName}";
1335 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1336 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1337 $this->_element
["{$tName}_id"] = 1;
1338 $this->_element
["{$tName}"] = 1;
1340 $type = "website-{$key}-website_type_id";
1341 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1342 $this->_element
[$type] = 1;
1343 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id AND `$tName`.website_type_id = $key )";
1349 * Generate the query based on what type of query we need.
1351 * @param bool $count
1352 * @param bool $sortByChar
1353 * @param bool $groupContacts
1354 * @param bool $onlyDeleted
1357 * sql query parts as an array
1359 public function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE, $onlyDeleted = FALSE) {
1360 // build permission clause
1361 $this->generatePermissionClause($onlyDeleted, $count);
1364 if (isset($this->_rowCountClause
)) {
1365 $select = "SELECT {$this->_rowCountClause}";
1367 elseif (isset($this->_distinctComponentClause
)) {
1368 // we add distinct to get the right count for components
1369 // for the more complex result set, we use GROUP BY the same id
1371 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} ) as rowCount";
1374 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1376 $from = $this->_simpleFromClause
;
1377 if ($this->_useDistinct
) {
1378 $this->_useGroupBy
= TRUE;
1381 elseif ($sortByChar) {
1382 // @fixme add the deprecated warning back in (it breaks CRM_Contact_SelectorTest::testSelectorQuery)
1383 // CRM_Core_Error::deprecatedFunctionWarning('sort by char is deprecated - use alphabetQuery method');
1384 $select = 'SELECT DISTINCT LEFT(contact_a.sort_name, 1) as sort_name';
1385 $from = $this->_simpleFromClause
;
1387 elseif ($groupContacts) {
1388 $select = 'SELECT contact_a.id as id';
1389 if ($this->_useDistinct
) {
1390 $this->_useGroupBy
= TRUE;
1392 $from = $this->_simpleFromClause
;
1395 if (!empty($this->_paramLookup
['group'])) {
1397 list($name, $op, $value, $grouping, $wildcard) = $this->_paramLookup
['group'][0];
1399 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
1400 $this->_paramLookup
['group'][0][1] = key($value);
1403 // Presumably the lines below come into manage groups screen.
1404 // make sure there is only one element
1405 // this is used when we are running under smog and need to know
1406 // how the contact was added (CRM-1203)
1407 $groups = (array) CRM_Utils_Array
::value($this->_paramLookup
['group'][0][1], $this->_paramLookup
['group'][0][2], $this->_paramLookup
['group'][0][2]);
1408 if ((count($this->_paramLookup
['group']) == 1) &&
1409 (count($groups) == 1)
1411 $groupId = $groups[0];
1413 //check if group is saved search
1414 $group = new CRM_Contact_BAO_Group();
1415 $group->id
= $groupId;
1418 if (!isset($group->saved_search_id
)) {
1419 $tbName = "civicrm_group_contact";
1420 // CRM-17254 don't retrieve extra fields if contact_id is specifically requested
1421 // as this will add load to an intentionally light query.
1422 // ideally this code would be removed as it appears to be to support CRM-1203
1423 // and passing in the required returnProperties from the url would
1424 // make more sense that globally applying the requirements of one form.
1425 if (($this->_returnProperties
!= ['contact_id'])) {
1426 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1427 $this->_element
['group_contact_id'] = 1;
1428 $this->_select
['status'] = "$tbName.status as status";
1429 $this->_element
['status'] = 1;
1433 $this->_useGroupBy
= TRUE;
1435 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1436 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1438 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1439 $this->_useDistinct
= FALSE;
1440 $this->_useGroupBy
= TRUE;
1444 $select = $this->getSelect();
1445 $from = $this->_fromClause
;
1449 if (!empty($this->_whereClause
)) {
1450 $where = "WHERE {$this->_whereClause}";
1453 if (!empty($this->_permissionWhereClause
) && empty($this->_displayRelationshipType
)) {
1454 if (empty($where)) {
1455 $where = "WHERE $this->_permissionWhereClause";
1458 $where = "$where AND $this->_permissionWhereClause";
1463 if (!empty($this->_having
)) {
1464 foreach ($this->_having
as $havingSets) {
1465 foreach ($havingSets as $havingSet) {
1466 $havingValue[] = $havingSet;
1469 $having = ' HAVING ' . implode(' AND ', $havingValue);
1472 // if we are doing a transform, do it here
1473 // use the $from, $where and $having to get the contact ID
1474 if ($this->_displayRelationshipType
) {
1475 $this->filterRelatedContacts($from, $where, $having);
1478 return [$select, $from, $where, $having];
1482 * Get where values from the parameters.
1484 * @param string $name
1485 * @param mixed $grouping
1489 public function getWhereValues($name, $grouping) {
1491 foreach ($this->_params
as $values) {
1492 if ($values[0] == $name && $values[3] == $grouping) {
1503 * @param bool $relative
1504 * @param string $from
1507 public static function fixDateValues($relative, &$from, &$to) {
1509 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1514 * Convert values from form-appropriate to query-object appropriate.
1516 * The query object is increasingly supporting the sql-filter syntax which is the most flexible syntax.
1517 * So, ideally we would convert all fields to look like
1520 * // Set the operator for legacy reasons, but it is ignored
1522 * // array in sql filter syntax
1523 * 2 => array('BETWEEN' => array(1,60),
1528 * There are some examples of the syntax in
1529 * https://github.com/civicrm/civicrm-core/tree/master/api/v3/examples/Relationship
1531 * More notes at CRM_Core_DAO::createSQLFilter
1533 * and a list of supported operators in CRM_Core_DAO
1535 * @param array $formValues
1536 * @param int $wildcard
1537 * @param bool $useEquals
1539 * @param string $apiEntity
1541 * @param array $entityReferenceFields
1542 * Field names of any entity reference fields (which will need reformatting to IN syntax).
1546 public static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL,
1547 $entityReferenceFields = []) {
1549 if (empty($formValues)) {
1553 self
::filterCountryFromValuesIfStateExists($formValues);
1555 // Handle relative dates first
1556 foreach (array_keys($formValues) as $id) {
1557 if (preg_match('/_date_relative$/', $id) ||
1558 $id == 'event_relative' ||
1559 $id == 'case_from_relative' ||
1560 $id == 'case_to_relative' ||
1561 $id == 'participant_relative'
1563 if ($id == 'event_relative') {
1564 $fromRange = 'event_start_date_low';
1565 $toRange = 'event_end_date_high';
1567 elseif ($id == 'participant_relative') {
1568 $fromRange = 'participant_register_date_low';
1569 $toRange = 'participant_register_date_high';
1571 elseif ($id == 'case_from_relative') {
1572 $fromRange = 'case_from_start_date_low';
1573 $toRange = 'case_from_start_date_high';
1575 elseif ($id == 'case_to_relative') {
1576 $fromRange = 'case_to_end_date_low';
1577 $toRange = 'case_to_end_date_high';
1580 $dateComponent = explode('_date_relative', $id);
1581 $fromRange = "{$dateComponent[0]}_date_low";
1582 $toRange = "{$dateComponent[0]}_date_high";
1585 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1586 CRM_Contact_BAO_Query
::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1591 foreach ($formValues as $id => $values) {
1592 if (self
::isAlreadyProcessedForQueryFormat($values)) {
1593 $params[] = $values;
1597 self
::legacyConvertFormValues($id, $values);
1599 // The form uses 1 field to represent two db fields
1600 if ($id == 'contact_type' && $values && (!is_array($values) ||
!array_intersect(array_keys($values), CRM_Core_DAO
::acceptedSQLOperators()))) {
1603 foreach ((array) $values as $key => $type) {
1604 $types = explode('__', is_numeric($type) ?
$key : $type, 2);
1605 $contactType[$types[0]] = $types[0];
1606 // Add sub-type if specified
1607 if (!empty($types[1])) {
1608 $subType[$types[1]] = $types[1];
1611 $params[] = ['contact_type', 'IN', $contactType, 0, 0];
1613 $params[] = ['contact_sub_type', 'IN', $subType, 0, 0];
1616 elseif ($id == 'privacy') {
1617 if (is_array($formValues['privacy'])) {
1618 $op = !empty($formValues['privacy']['do_not_toggle']) ?
'=' : '!=';
1619 foreach ($formValues['privacy'] as $key => $value) {
1621 $params[] = [$key, $op, $value, 0, 0];
1626 elseif ($id == 'email_on_hold') {
1627 if ($onHoldValue = CRM_Utils_Array
::value('email_on_hold', $formValues)) {
1628 // onHoldValue should be 0 or 1 or an array. Some legacy groups may hold ''
1629 // so in 5.11 we have an extra if that should become redundant over time.
1630 // https://lab.civicrm.org/dev/core/issues/745
1631 // @todo this renaming of email_on_hold to on_hold needs revisiting
1632 // it preceeds recent changes but causes the default not to reload.
1633 $onHoldValue = array_filter((array) $onHoldValue, 'is_numeric');
1634 if (!empty($onHoldValue)) {
1635 $params[] = ['on_hold', 'IN', $onHoldValue, 0, 0];
1639 elseif (substr($id, 0, 7) == 'custom_'
1641 substr($id, -9, 9) == '_relative'
1642 ||
substr($id, -5, 5) == '_from'
1643 ||
substr($id, -3, 3) == '_to'
1646 self
::convertCustomRelativeFields($formValues, $params, $values, $id);
1648 elseif (preg_match('/_date_relative$/', $id) ||
1649 $id == 'event_relative' ||
1650 $id == 'case_from_relative' ||
1651 $id == 'case_to_relative' ||
1652 $id == 'participant_relative'
1654 // Already handled in previous loop
1657 elseif (in_array($id, $entityReferenceFields) && !empty($values) && is_string($values) && (strpos($values, ',') !=
1659 $params[] = [$id, 'IN', explode(',', $values), 0, 0];
1662 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals, $apiEntity);
1667 $params[] = $values;
1674 * Function to support legacy format for groups and tags.
1677 * @param array|int $values
1680 public static function legacyConvertFormValues($id, &$values) {
1686 'membership_type_id',
1687 'membership_status_id',
1689 if (in_array($id, $legacyElements) && is_array($values)) {
1690 // prior to 4.7, formValues for some attributes (e.g. group, tag) are stored in array(id1 => 1, id2 => 1),
1691 // as per the recent Search fixes $values need to be in standard array(id1, id2) format
1692 $values = CRM_Utils_Array
::convertCheckboxFormatToArray($values);
1697 * Fix values from query from/to something no-one cared enough to document.
1700 * @param array $values
1701 * @param int $wildcard
1702 * @param bool $useEquals
1704 * @param string $apiEntity
1706 * @return array|null
1708 public static function fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL) {
1709 // skip a few search variables
1710 static $skipWhere = NULL;
1711 static $likeNames = NULL;
1714 // Change camelCase EntityName to lowercase with underscores
1715 $apiEntity = _civicrm_api_get_entity_name_from_camel($apiEntity);
1717 // check if $value is in OK (Operator as Key) format as used by Get API
1718 if (CRM_Utils_System
::isNull($values)) {
1730 'display_relationship_type',
1734 if (in_array($id, $skipWhere) ||
1735 substr($id, 0, 4) == '_qf_' ||
1736 substr($id, 0, 7) == 'hidden_'
1742 (substr($id, 0, strlen($apiEntity)) != $apiEntity) &&
1743 (substr($id, 0, 10) != 'financial_' && substr($id, 0, 8) != 'payment_') &&
1744 (substr($id, 0, 7) != 'custom_')
1746 $id = $apiEntity . '_' . $id;
1750 $likeNames = ['sort_name', 'email', 'note', 'display_name'];
1753 // email comes in via advanced search
1754 // so use wildcard always
1755 if ($id == 'email') {
1759 if (!$useEquals && in_array($id, $likeNames)) {
1760 $result = [$id, 'LIKE', $values, 0, 1];
1762 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1763 $result = [$id, 'LIKE', $values, 0, 0];
1765 elseif ($id == 'contact_type' ||
1766 (!empty($values) && is_array($values) && !in_array(key($values), CRM_Core_DAO
::acceptedSQLOperators(), TRUE))
1768 $result = [$id, 'IN', $values, 0, $wildcard];
1771 $result = [$id, '=', $values, 0, $wildcard];
1778 * Get the where clause for a single field.
1780 * @param array $values
1781 * @param string $apiEntity
1783 public function whereClauseSingle(&$values, $apiEntity = NULL) {
1784 if ($this->isARelativeDateField($values[0])) {
1785 $this->buildRelativeDateQuery($values);
1789 // do not process custom fields or prefixed contact ids or component params
1790 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1791 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1792 (substr($values[0], 0, 13) == 'contribution_') ||
1793 (substr($values[0], 0, 6) == 'event_') ||
1794 (substr($values[0], 0, 12) == 'participant_') ||
1795 (substr($values[0], 0, 7) == 'member_') ||
1796 (substr($values[0], 0, 6) == 'grant_') ||
1797 (substr($values[0], 0, 7) == 'pledge_') ||
1798 (substr($values[0], 0, 5) == 'case_') ||
1799 (substr($values[0], 0, 10) == 'financial_') ||
1800 (substr($values[0], 0, 8) == 'payment_') ||
1801 (substr($values[0], 0, 11) == 'membership_')
1806 // skip for hook injected fields / params
1807 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1808 if (array_key_exists($values[0], $extFields)) {
1812 switch ($values[0]) {
1813 case 'deleted_contacts':
1814 $this->deletedContacts($values);
1817 case 'contact_sub_type':
1818 $this->contactSubType($values);
1823 $this->group($values);
1826 // case tag comes from find contacts
1828 $this->tagSearch($values);
1832 case 'contact_tags':
1833 $this->tag($values);
1838 case 'note_subject':
1839 $this->notes($values);
1843 $this->ufUser($values);
1847 case 'display_name':
1848 $this->sortName($values);
1852 case 'postal_greeting':
1853 case 'email_greeting':
1854 $this->greetings($values);
1859 $this->email($values, $apiEntity);
1862 case 'phone_numeric':
1863 $this->phone_numeric($values);
1866 case 'phone_phone_type_id':
1867 case 'phone_location_type_id':
1868 $this->phone_option_group($values);
1871 case 'street_address':
1872 $this->street_address($values);
1875 case 'street_number':
1876 $this->street_number($values);
1879 case 'sortByCharacter':
1880 $this->sortByCharacter($values);
1883 case 'location_type':
1884 $this->locationType($values);
1888 $this->county($values);
1891 case 'state_province':
1892 case 'state_province_id':
1893 case 'state_province_name':
1894 $this->stateProvince($values);
1899 $this->country($values, FALSE);
1903 case 'postal_code_low':
1904 case 'postal_code_high':
1905 $this->postalCode($values);
1908 case 'activity_date':
1909 case 'activity_date_low':
1910 case 'activity_date_high':
1911 case 'activity_date_time_low':
1912 case 'activity_date_time_high':
1913 case 'activity_role':
1914 case 'activity_status_id':
1915 case 'activity_status':
1916 case 'activity_priority':
1917 case 'activity_priority_id':
1918 case 'followup_parent_id':
1920 case 'source_contact_id':
1921 case 'activity_text':
1922 case 'activity_option':
1923 case 'test_activities':
1924 case 'activity_type_id':
1925 case 'activity_type':
1926 case 'activity_survey_id':
1927 case 'activity_tags':
1928 case 'activity_taglist':
1929 case 'activity_test':
1930 case 'activity_campaign_id':
1931 case 'activity_engagement_level':
1933 case 'activity_result':
1934 case 'source_contact':
1935 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1940 case 'birth_date_low':
1941 case 'birth_date_high':
1942 case 'deceased_date_low':
1943 case 'deceased_date_high':
1944 $this->demographics($values);
1947 case 'age_asof_date':
1948 // handled by demographics
1951 case 'log_date_low':
1952 case 'log_date_high':
1953 $this->modifiedDates($values);
1957 $this->changeLog($values);
1960 case 'do_not_phone':
1961 case 'do_not_email':
1964 case 'do_not_trade':
1966 $this->privacy($values);
1969 case 'privacy_options':
1970 $this->privacyOptions($values);
1973 case 'privacy_operator':
1974 case 'privacy_toggle':
1975 // these are handled by privacy options
1978 case 'preferred_communication_method':
1979 $this->preferredCommunication($values);
1982 case 'relation_type_id':
1983 case 'relation_start_date_high':
1984 case 'relation_start_date_low':
1985 case 'relation_end_date_high':
1986 case 'relation_end_date_low':
1987 case 'relation_active_period_date_high':
1988 case 'relation_active_period_date_low':
1989 case 'relation_target_name':
1990 case 'relation_status':
1991 case 'relation_date_low':
1992 case 'relation_date_high':
1993 $this->relationship($values);
1994 $this->_relationshipValuesAdded
= TRUE;
1997 case 'task_status_id':
1998 $this->task($values);
2002 // since this case is handled with the above
2005 case 'prox_distance':
2006 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
2009 case 'prox_street_address':
2011 case 'prox_postal_code':
2012 case 'prox_state_province_id':
2013 case 'prox_country_id':
2014 case 'prox_geo_code_1':
2015 case 'prox_geo_code_2':
2016 // handled by the proximity_distance clause
2020 $this->restWhere($values);
2026 * Given a list of conditions in params generate the required where clause.
2028 * @param string $apiEntity
2032 public function whereClause($apiEntity = NULL) {
2033 $this->_where
[0] = [];
2034 $this->_qill
[0] = [];
2036 $this->includeContactIds();
2037 if (!empty($this->_params
)) {
2038 foreach (array_keys($this->_params
) as $id) {
2039 if (empty($this->_params
[$id][0])) {
2042 // check for both id and contact_id
2043 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
2044 $this->_where
[0][] = self
::buildClause("contact_a.id", $this->_params
[$id][1], $this->_params
[$id][2]);
2045 $field = CRM_Utils_Array
::value('id', $this->_fields
);
2046 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(
2047 'CRM_Contact_BAO_Contact',
2049 $this->_params
[$id][2],
2050 $this->_params
[$id][1]
2052 $this->_qill
[0][] = ts("%1 %2 %3", [
2053 1 => $field['title'],
2059 $this->whereClauseSingle($this->_params
[$id], $apiEntity);
2063 CRM_Core_Component
::alterQuery($this, 'where');
2065 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
2068 if ($this->_customQuery
) {
2069 // Added following if condition to avoid the wrong value display for 'my account' / any UF info.
2070 // Hope it wont affect the other part of civicrm.. if it does please remove it.
2071 if (!empty($this->_customQuery
->_where
)) {
2072 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
2075 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
2082 if (!empty($this->_where
)) {
2083 foreach ($this->_where
as $grouping => $values) {
2084 if ($grouping > 0 && !empty($values)) {
2085 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
2090 if (!empty($this->_where
[0])) {
2091 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
2093 if (!empty($clauses)) {
2094 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
2097 if ($validClauses > 1) {
2098 $this->_useDistinct
= TRUE;
2102 return implode(' AND ', $andClauses);
2106 * Generate where clause for any parameters not already handled.
2108 * @param array $values
2112 public function restWhere(&$values) {
2113 $name = CRM_Utils_Array
::value(0, $values);
2114 $op = CRM_Utils_Array
::value(1, $values);
2115 $value = CRM_Utils_Array
::value(2, $values);
2116 $grouping = CRM_Utils_Array
::value(3, $values);
2117 $wildcard = CRM_Utils_Array
::value(4, $values);
2119 if (isset($grouping) && empty($this->_where
[$grouping])) {
2120 $this->_where
[$grouping] = [];
2123 $multipleFields = ['url'];
2125 //check if the location type exists for fields
2127 $locType = explode('-', $name);
2129 if (!in_array($locType[0], $multipleFields)) {
2130 //add phone type if exists
2131 if (isset($locType[2]) && $locType[2]) {
2132 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
2136 $field = CRM_Utils_Array
::value($name, $this->_fields
);
2139 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
2148 $locationType = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
2149 if (isset($locType[1]) && is_numeric($locType[1])) {
2150 $lType = $locationType[$locType[1]];
2153 $field['title'] .= " ($lType)";
2156 if (substr($name, 0, 14) === 'state_province') {
2157 if (isset($locType[1]) && is_numeric($locType[1])) {
2159 $aName = "{$lType}-address";
2160 $where = "`$aName`.state_province_id";
2163 $where = "civicrm_address.state_province_id";
2166 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value);
2167 $this->_tables
[$aName] = $this->_whereTables
[$aName] = 1;
2168 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
2169 $this->_qill
[$grouping][] = ts("%1 %2 %3", [1 => $field['title'], 2 => $qillop, 3 => $qillVal]);
2171 elseif (!empty($field['pseudoconstant'])) {
2172 $this->optionValueQuery(
2173 $name, $op, $value, $grouping,
2174 'CRM_Contact_DAO_Contact',
2180 if ($name == 'gender_id') {
2181 self
::$_openedPanes[ts('Demographics')] = TRUE;
2184 elseif (substr($name, 0, 7) === 'country' ||
substr($name, 0, 6) === 'county') {
2185 $name = (substr($name, 0, 7) === 'country') ?
"country_id" : "county_id";
2186 if (isset($locType[1]) && is_numeric($locType[1])) {
2188 $aName = "{$lType}-address";
2189 $where = "`$aName`.$name";
2192 $where = "civicrm_address.$name";
2195 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2196 $this->_tables
[$aName] = $this->_whereTables
[$aName] = 1;
2198 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
2199 $this->_qill
[$grouping][] = ts("%1 %2 %3", [1 => $field['title'], 2 => $qillop, 3 => $qillVal]);
2201 elseif ($name === 'world_region') {
2202 $this->optionValueQuery(
2203 $name, $op, $value, $grouping,
2211 elseif ($name === 'is_deceased') {
2212 $this->setQillAndWhere($name, $op, $value, $grouping, $field);
2213 self
::$_openedPanes[ts('Demographics')] = TRUE;
2215 elseif ($name === 'created_date' ||
$name === 'modified_date' ||
$name === 'deceased_date' ||
$name === 'birth_date') {
2216 $appendDateTime = TRUE;
2217 if ($name === 'deceased_date' ||
$name === 'birth_date') {
2218 $appendDateTime = FALSE;
2219 self
::$_openedPanes[ts('Demographics')] = TRUE;
2221 $this->dateQueryBuilder($values, 'contact_a', $name, $name, $field['title'], $appendDateTime);
2223 elseif ($name === 'contact_id') {
2224 if (is_int($value)) {
2225 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
2226 $this->_qill
[$grouping][] = "$field[title] $op $value";
2229 elseif ($name === 'name') {
2230 $value = CRM_Core_DAO
::escapeString($value);
2233 $value = self
::getWildCardedValue($wildcard, $op, $value);
2235 CRM_Core_Error
::deprecatedFunctionWarning('Untested code path');
2236 // @todo it's likely this code path is obsolete / never called. It is definitely not
2237 // passed through in our test suite.
2238 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, "'$value'");
2239 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2241 elseif ($name === 'current_employer') {
2244 $value = self
::getWildCardedValue($wildcard, $op, $value);
2246 $ceWhereClause = self
::buildClause("contact_a.organization_name", $op,
2249 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2250 $this->_where
[$grouping][] = $ceWhereClause;
2251 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2253 elseif ($name === 'email_greeting') {
2254 CRM_Core_Error
::deprecatedFunctionWarning('pass in email_greeting_id or email_greeting_display');
2255 $filterCondition = ['greeting_type' => 'email_greeting'];
2256 $this->optionValueQuery(
2257 $name, $op, $value, $grouping,
2258 CRM_Core_PseudoConstant
::greeting($filterCondition),
2260 ts('Email Greeting')
2263 elseif ($name === 'postal_greeting') {
2264 CRM_Core_Error
::deprecatedFunctionWarning('pass in postal_greeting_id or postal_greeting_display');
2265 $filterCondition = ['greeting_type' => 'postal_greeting'];
2266 $this->optionValueQuery(
2267 $name, $op, $value, $grouping,
2268 CRM_Core_PseudoConstant
::greeting($filterCondition),
2270 ts('Postal Greeting')
2273 elseif ($name === 'addressee') {
2274 CRM_Core_Error
::deprecatedFunctionWarning('pass in addressee_id or addressee_display');
2275 $filterCondition = ['greeting_type' => 'addressee'];
2276 $this->optionValueQuery(
2277 $name, $op, $value, $grouping,
2278 CRM_Core_PseudoConstant
::greeting($filterCondition),
2283 elseif (substr($name, 0, 4) === 'url-') {
2284 $tName = 'civicrm_website';
2285 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2286 $value = CRM_Core_DAO
::escapeString($value);
2289 $value = self
::getWildCardedValue($wildcard, $op, $value);
2292 $this->_where
[$grouping][] = $d = self
::buildClause('civicrm_website.url', $op, $value);
2293 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2295 elseif ($name === 'contact_is_deleted') {
2296 $this->setQillAndWhere('is_deleted', $op, $value, $grouping, $field);
2298 elseif (!empty($field['where'])) {
2300 if (!empty($field['type'])) {
2301 $type = CRM_Utils_Type
::typeToString($field['type']);
2304 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2306 if (isset($locType[1]) &&
2307 is_numeric($locType[1])
2311 //get the location name
2312 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2313 $fieldName = "`$tName`.$fldName";
2315 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2316 $this->_tables
[$tName] = $this->_whereTables
[$tName] = 1;
2320 if ($tableName == 'civicrm_contact') {
2321 $fieldName = "contact_a.{$fieldName}";
2324 $fieldName = $field['where'];
2328 list($qillop, $qillVal) = self
::buildQillForFieldValue(NULL, $field['title'], $value, $op);
2329 $this->_qill
[$grouping][] = ts("%1 %2 %3", [
2330 1 => $field['title'],
2332 3 => (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) ?
$qillVal : "'$qillVal'",
2335 if (is_array($value)) {
2336 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2337 // for api style operators for functions that hit this point without worrying about regression
2338 // (the previous comments indicated the condition for hitting this point were unknown
2339 // per CRM-14743 we are adding modified_date & created_date operator support
2340 $operations = array_keys($value);
2341 foreach ($operations as $operator) {
2342 if (!in_array($operator, CRM_Core_DAO
::acceptedSQLOperators())) {
2343 //Via Contact get api value is not in array(operator => array(values)) format ONLY for IN/NOT IN operators
2344 //so this condition will satisfy the search for now
2345 if (strpos($op, 'IN') !== FALSE) {
2346 $value = [$op => $value];
2348 // we don't know when this might happen
2350 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", [1 => $operator]));
2354 $this->_where
[$grouping][] = CRM_Core_DAO
::createSQLFilter($fieldName, $value, $type);
2359 $value = self
::getWildCardedValue($wildcard, $op, $value);
2362 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2366 if ($setTables && isset($field['where'])) {
2367 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2368 if (isset($tableName)) {
2369 $this->_tables
[$tableName] = 1;
2370 $this->_whereTables
[$tableName] = 1;
2382 public static function getLocationTableName(&$where, &$locType) {
2383 if (isset($locType[1]) && is_numeric($locType[1])) {
2384 list($tbName, $fldName) = explode(".", $where);
2386 //get the location name
2387 $locationType = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
2388 $specialFields = ['email', 'im', 'phone', 'openid', 'phone_ext'];
2389 if (in_array($locType[0], $specialFields)) {
2390 //hack to fix / special handing for phone_ext
2391 if ($locType[0] == 'phone_ext') {
2392 $locType[0] = 'phone';
2394 if (isset($locType[2]) && $locType[2]) {
2395 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2398 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2401 elseif (in_array($locType[0],
2406 'street_number_suffix',
2408 'supplemental_address_1',
2409 'supplemental_address_2',
2410 'supplemental_address_3',
2413 'postal_code_suffix',
2419 //fix for search by profile with address fields.
2420 $tName = "{$locationType[$locType[1]]}-address";
2422 elseif (in_array($locType[0],
2430 $tName = "{$locationType[$locType[1]]}-email";
2432 elseif ($locType[0] == 'provider_id') {
2433 $tName = "{$locationType[$locType[1]]}-im";
2435 elseif ($locType[0] == 'openid') {
2436 $tName = "{$locationType[$locType[1]]}-openid";
2439 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2441 $tName = str_replace(' ', '_', $tName);
2442 return [$tName, $fldName];
2444 CRM_Core_Error
::fatal();
2448 * Given a result dao, extract the values and return that array
2450 * @param CRM_Core_DAO $dao
2453 * values for this query
2455 public function store($dao) {
2458 foreach ($this->_element
as $key => $dontCare) {
2459 if (property_exists($dao, $key)) {
2460 if (strpos($key, '-') !== FALSE) {
2461 $values = explode('-', $key);
2462 $lastElement = array_pop($values);
2464 $cnt = count($values);
2466 foreach ($values as $v) {
2467 if (!array_key_exists($v, $current)) {
2470 //bad hack for im_provider
2471 if ($lastElement == 'provider_id') {
2472 if ($count < $cnt) {
2473 $current = &$current[$v];
2476 $lastElement = "{$v}_{$lastElement}";
2480 $current = &$current[$v];
2485 $current[$lastElement] = $dao->$key;
2488 $value[$key] = $dao->$key;
2496 * Getter for tables array.
2500 public function tables() {
2501 return $this->_tables
;
2505 * Sometimes used to create the from clause, but, not reliably, set
2506 * this AND set tables.
2508 * It's unclear the intent - there is a 'simpleFrom' clause which
2509 * takes whereTables into account & a fromClause which doesn't.
2511 * logic may have eroded?
2515 public function whereTables() {
2516 return $this->_whereTables
;
2520 * Generate the where clause (used in match contacts and permissions)
2522 * @param array $params
2523 * @param array $fields
2524 * @param array $tables
2525 * @param $whereTables
2526 * @param bool $strict
2530 public static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2531 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2535 $tables = array_merge($query->tables(), $tables);
2536 $whereTables = array_merge($query->whereTables(), $whereTables);
2538 return $query->_whereClause
;
2542 * Create the from clause.
2544 * @param array $tables
2545 * Tables that need to be included in this from clause. If null,
2546 * return mimimal from clause (i.e. civicrm_contact).
2547 * @param array $inner
2548 * Tables that should be inner-joined.
2549 * @param array $right
2550 * Tables that should be right-joined.
2551 * @param bool $primaryLocation
2552 * Search on primary location. See note below.
2554 * Determines search mode based on bitwise MODE_* constants.
2555 * @param string|NULL $apiEntity
2556 * Determines search mode based on entity by string.
2558 * The $primaryLocation flag only seems to be used when
2559 * locationType() has been called. This may be a search option
2560 * exposed, or perhaps it's a "search all details" approach which
2561 * predates decoupling of location types and primary fields?
2563 * @see https://issues.civicrm.org/jira/browse/CRM-19967
2568 public static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1, $apiEntity = NULL) {
2570 $from = ' FROM civicrm_contact contact_a';
2571 if (empty($tables)) {
2575 if (!empty($tables['civicrm_worldregion'])) {
2576 $tables = array_merge(['civicrm_country' => 1], $tables);
2579 if ((!empty($tables['civicrm_state_province']) ||
!empty($tables['civicrm_country']) ||
2580 CRM_Utils_Array
::value('civicrm_county', $tables)) && empty($tables['civicrm_address'])) {
2581 $tables = array_merge(['civicrm_address' => 1],
2586 // add group_contact and group table is subscription history is present
2587 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2588 $tables = array_merge([
2589 'civicrm_group' => 1,
2590 'civicrm_group_contact' => 1,
2596 // to handle table dependencies of components
2597 CRM_Core_Component
::tableNames($tables);
2598 // to handle table dependencies of hook injected tables
2599 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2601 //format the table list according to the weight
2602 $info = CRM_Core_TableHierarchy
::info();
2604 foreach ($tables as $key => $value) {
2606 if (strpos($key, '-') !== FALSE) {
2607 $keyArray = explode('-', $key);
2608 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2610 elseif (strpos($key, '_') !== FALSE) {
2611 $keyArray = explode('_', $key);
2612 if (is_numeric(array_pop($keyArray))) {
2613 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2616 $k = CRM_Utils_Array
::value($key, $info, 99);
2620 $k = CRM_Utils_Array
::value($key, $info, 99);
2622 $tempTable[$k . ".$key"] = $key;
2626 foreach ($tempTable as $key) {
2627 $newTables[$key] = $tables[$key];
2630 $tables = $newTables;
2632 foreach ($tables as $name => $value) {
2637 if (!empty($inner[$name])) {
2640 elseif (!empty($right[$name])) {
2648 // if there is already a join statement in value, use value itself
2649 if (strpos($value, 'JOIN')) {
2650 $from .= " $value ";
2653 $from .= " $side JOIN $name ON ( $value ) ";
2658 $from .= self
::getEntitySpecificJoins($name, $mode, $side, $primaryLocation);
2664 * Get join statements for the from clause depending on entity type
2666 * @param string $name
2668 * @param string $side
2669 * @param string $primaryLocation
2672 protected static function getEntitySpecificJoins($name, $mode, $side, $primaryLocation) {
2673 $limitToPrimaryClause = $primaryLocation ?
"AND {$name}.is_primary = 1" : '';
2675 case 'civicrm_address':
2676 //CRM-14263 further handling of address joins further down...
2677 return " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id {$limitToPrimaryClause} )";
2679 case 'civicrm_state_province':
2680 // This is encountered when doing an export after having applied a 'sort' - it pretty much implies primary
2681 // but that will have been implied-in by the calling function.
2682 // test cover in testContactIDQuery
2683 return " $side JOIN civicrm_state_province ON ( civicrm_address.state_province_id = civicrm_state_province.id )";
2685 case 'civicrm_country':
2686 // This is encountered when doing an export after having applied a 'sort' - it pretty much implies primary
2687 // but that will have been implied-in by the calling function.
2688 // test cover in testContactIDQuery
2689 return " $side JOIN civicrm_country ON ( civicrm_address.country_id = civicrm_country.id )";
2691 case 'civicrm_phone':
2692 return " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id {$limitToPrimaryClause}) ";
2694 case 'civicrm_email':
2695 return " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id {$limitToPrimaryClause})";
2698 return " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id {$limitToPrimaryClause}) ";
2701 $from = " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2702 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2703 $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)";
2706 case 'civicrm_openid':
2707 return " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id {$limitToPrimaryClause} )";
2709 case 'civicrm_worldregion':
2710 // We can be sure from the calling function that country will already be joined in.
2711 // we really don't need world_region - we could use a pseudoconstant for it.
2712 return "$side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2714 case 'civicrm_location_type':
2715 return " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2717 case 'civicrm_group':
2718 return " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2720 case 'civicrm_group_contact':
2721 return " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2723 case 'civicrm_group_contact_cache':
2724 return " $side JOIN civicrm_group_contact_cache ON contact_a.id = civicrm_group_contact_cache.contact_id ";
2726 case 'civicrm_activity':
2727 case 'civicrm_activity_tag':
2728 case 'activity_type':
2729 case 'activity_status':
2731 case 'civicrm_activity_contact':
2732 case 'source_contact':
2733 case 'activity_priority':
2734 return CRM_Activity_BAO_Query
::from($name, $mode, $side);
2736 case 'civicrm_entity_tag':
2737 $from = " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact'";
2738 return "$from AND civicrm_entity_tag.entity_id = contact_a.id ) ";
2740 case 'civicrm_note':
2741 $from = " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact'";
2742 return "$from AND contact_a.id = civicrm_note.entity_id ) ";
2744 case 'civicrm_subscription_history':
2745 $from = " $side JOIN civicrm_subscription_history";
2746 $from .= " ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id";
2747 return "$from AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2749 case 'civicrm_relationship':
2750 if (self
::$_relType == 'reciprocal') {
2751 if (self
::$_relationshipTempTable) {
2752 // we have a temptable to join on
2753 $tbl = self
::$_relationshipTempTable;
2754 return " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2757 $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2758 $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)";
2762 elseif (self
::$_relType == 'b') {
2763 $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2764 return "$from $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2767 $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2768 return "$from $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2772 $from = " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2773 return "$from INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2776 return " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2778 case 'civicrm_grant':
2779 return CRM_Grant_BAO_Query
::from($name, $mode, $side);
2781 case 'civicrm_website':
2782 return " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2784 case 'civicrm_campaign':
2785 //Move to default case if not in either mode.
2786 if ($mode & CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
2787 return CRM_Contribute_BAO_Query
::from($name, $mode, $side);
2789 elseif ($mode & CRM_Contact_BAO_Query
::MODE_MAILING
) {
2790 return CRM_Mailing_BAO_Query
::from($name, $mode, $side);
2792 elseif ($mode & CRM_Contact_BAO_Query
::MODE_CAMPAIGN
) {
2793 return CRM_Campaign_BAO_Query
::from($name, $mode, $side);
2797 $locationTypeName = '';
2798 if (strpos($name, '-address') != 0) {
2799 $locationTypeName = 'address';
2801 elseif (strpos($name, '-phone') != 0) {
2802 $locationTypeName = 'phone';
2804 elseif (strpos($name, '-email') != 0) {
2805 $locationTypeName = 'email';
2807 elseif (strpos($name, '-im') != 0) {
2808 $locationTypeName = 'im';
2810 elseif (strpos($name, '-openid') != 0) {
2811 $locationTypeName = 'openid';
2814 if ($locationTypeName) {
2815 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2816 $parts = explode('-', $name);
2817 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
2818 foreach ($locationTypes as $locationTypeID => $locationType) {
2819 if ($parts[0] == str_replace(' ', '_', $locationType)) {
2820 $locationID = $locationTypeID;
2823 $from = " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2826 $from = CRM_Core_Component
::from($name, $mode, $side);
2828 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2835 * WHERE / QILL clause for deleted_contacts
2837 * @param array $values
2839 public function deletedContacts($values) {
2840 list($_, $_, $value, $grouping, $_) = $values;
2842 // *prepend* to the relevant grouping as this is quite an important factor
2843 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2848 * Where / qill clause for contact_type
2852 public function contactType(&$values) {
2853 list($name, $op, $value, $grouping, $wildcard) = $values;
2858 // account for search builder mapping multiple values
2859 if (!is_array($value)) {
2860 $values = self
::parseSearchBuilderString($value, 'String');
2861 if (is_array($values)) {
2862 $value = array_flip($values);
2866 if (is_array($value)) {
2867 foreach ($value as $k => $v) {
2872 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2873 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2876 if (!empty($subType)) {
2877 $subTypes[$subType] = 1;
2879 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2884 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2885 $contactType = $contactTypeANDSubType[0];
2886 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2887 if (!empty($subType)) {
2888 $subTypes[$subType] = 1;
2890 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2894 if (!empty($clause)) {
2896 if ($op == 'IN' ||
$op == 'NOT IN') {
2897 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2900 $type = array_pop($clause);
2901 $this->_where
[$grouping][] = self
::buildClause("contact_a.contact_type", $op, $contactType);
2904 $this->_qill
[$grouping][] = ts('Contact Type') . " $op " . implode(' ' . ts('or') . ' ', $quill);
2906 if (!empty($subTypes)) {
2907 $this->includeContactSubTypes($subTypes, $grouping);
2913 * Where / qill clause for contact_sub_type.
2915 * @param array $values
2917 public function contactSubType(&$values) {
2918 list($name, $op, $value, $grouping, $wildcard) = $values;
2919 $this->includeContactSubTypes($value, $grouping, $op);
2927 public function includeContactSubTypes($value, $grouping, $op = 'LIKE') {
2929 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2931 $value = $value[$op];
2935 $alias = "contact_a.contact_sub_type";
2936 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
2938 $op = str_replace('IN', 'LIKE', $op);
2939 $op = str_replace('=', 'LIKE', $op);
2940 $op = str_replace('!', 'NOT ', $op);
2942 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2943 $this->_where
[$grouping][] = self
::buildClause($alias, $op, $value, 'String');
2945 elseif (is_array($value)) {
2946 foreach ($value as $k => $v) {
2947 $clause[$k] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($v, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2951 $clause[$value] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2954 if (!empty($clause)) {
2955 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2957 $this->_qill
[$grouping][] = ts('Contact Subtype %1 ', [1 => $qillOperators[$op]]) . implode(' ' . ts('or') . ' ', array_keys($clause));
2961 * Where / qill clause for groups.
2965 public function group($values) {
2966 list($name, $op, $value, $grouping, $wildcard) = $values;
2968 // If the $value is in OK (operator as key) array format we need to extract the key as operator and value first
2969 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2971 $value = $value[$op];
2974 // Replace pseudo operators from search builder
2975 $op = str_replace('EMPTY', 'NULL', $op);
2977 if (strpos($op, 'NULL')) {
2981 if (is_array($value) && count($value) > 1) {
2982 if (strpos($op, 'IN') === FALSE && strpos($op, 'NULL') === FALSE) {
2983 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", [1 => $op]));
2985 $this->_useDistinct
= TRUE;
2988 if (isset($value)) {
2989 $value = CRM_Utils_Array
::value($op, $value, $value);
2992 if ($name == 'group_type') {
2993 $value = array_keys($this->getGroupsFromTypeCriteria($value));
2996 $regularGroupIDs = $smartGroupIDs = [];
2997 foreach ((array) $value as $id) {
2998 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
2999 $smartGroupIDs[] = $id;
3002 $regularGroupIDs[] = trim($id);
3006 $isNotOp = ($op == 'NOT IN' ||
$op == '!=');
3009 $gcsValues = $this->getWhereValues('group_contact_status', $grouping);
3011 is_array($gcsValues[2])
3013 foreach ($gcsValues[2] as $k => $v) {
3015 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
3020 $statii[] = "'Added'";
3023 if (count($regularGroupIDs) ||
empty($value)) {
3024 // include child groups IDs if any
3025 $childGroupIds = (array) CRM_Contact_BAO_Group
::getChildGroupIds($regularGroupIDs);
3026 foreach ($childGroupIds as $key => $id) {
3027 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
3028 $smartGroupIDs[] = $id;
3029 unset($childGroupIds[$key]);
3032 if (count($childGroupIds)) {
3033 $regularGroupIDs = array_merge($regularGroupIDs, $childGroupIds);
3036 if (empty($regularGroupIDs)) {
3037 $regularGroupIDs = [0];
3040 // if $regularGroupIDs is populated with regular child group IDs
3041 // then change the mysql operator to desired
3042 if (count($regularGroupIDs) > 1) {
3043 $op = strpos($op, 'IN') ?
$op : ($op == '!=') ?
'NOT IN' : 'IN';
3046 if (!empty($regularGroupIDs)) {
3047 $groupIds = CRM_Utils_Type
::validate(
3048 implode(',', (array) $regularGroupIDs),
3049 'CommaSeparatedIntegers'
3052 $gcTable = "`civicrm_group_contact-" . uniqid() . "`";
3053 $joinClause = ["contact_a.id = {$gcTable}.contact_id"];
3055 if (strpos($op, 'IN') !== FALSE) {
3056 $clause = "{$gcTable}.group_id $op ( $groupIds ) ";
3058 elseif ($op == '!=') {
3059 $clause = "{$gcTable}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact cgc WHERE cgc.group_id = $groupIds )";
3062 $clause = "{$gcTable}.group_id $op $groupIds ";
3064 $groupClause[] = "( {$clause} )";
3067 $joinClause[] = "{$gcTable}.status IN (" . implode(', ', $statii) . ")";
3069 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
3072 //CRM-19589: contact(s) removed from a Smart Group, resides in civicrm_group_contact table
3073 $groupContactCacheClause = '';
3074 if (count($smartGroupIDs) ||
empty($value)) {
3075 $this->_groupUniqueKey
= uniqid();
3076 $this->_groupKeys
[] = $this->_groupUniqueKey
;
3077 $gccTableAlias = "civicrm_group_contact_cache_{$this->_groupUniqueKey}";
3078 $groupContactCacheClause = $this->addGroupContactCache($smartGroupIDs, $gccTableAlias, "contact_a", $op);
3079 if (!empty($groupContactCacheClause)) {
3081 $groupIds = implode(',', (array) $smartGroupIDs);
3082 $gcTable = "civicrm_group_contact_{$this->_groupUniqueKey}";
3083 $joinClause = ["contact_a.id = {$gcTable}.contact_id"];
3084 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
3085 if (strpos($op, 'IN') !== FALSE) {
3086 $groupClause[] = "{$gcTable}.group_id $op ( $groupIds ) AND {$gccTableAlias}.group_id IS NULL";
3089 $groupClause[] = "{$gcTable}.group_id $op $groupIds AND {$gccTableAlias}.group_id IS NULL";
3092 $groupClause[] = " ( {$groupContactCacheClause} ) ";
3096 $and = ($op == 'IS NULL') ?
' AND ' : ' OR ';
3097 if (!empty($groupClause)) {
3098 $this->_where
[$grouping][] = ' ( ' . implode($and, $groupClause) . ' ) ';
3101 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Group', 'id', $value, $op);
3102 $this->_qill
[$grouping][] = ts("Group(s) %1 %2", [1 => $qillop, 2 => $qillVal]);
3103 if (strpos($op, 'NULL') === FALSE) {
3104 $this->_qill
[$grouping][] = ts("Group Status %1", [1 => implode(' ' . ts('or') . ' ', $statii)]);
3108 public function getGroupCacheTableKeys() {
3109 return $this->_groupKeys
;
3113 * Function translates selection of group type into a list of groups.
3118 public function getGroupsFromTypeCriteria($value) {
3120 foreach ((array) $value as $groupTypeValue) {
3121 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
3122 $groupIds = ($groupIds +
$groupList);
3128 * Prime smart group cache for smart groups in the search, and join
3129 * civicrm_group_contact_cache table into the query.
3131 * @param array $groups IDs of groups specified in search criteria.
3132 * @param string $tableAlias Alias to use for civicrm_group_contact_cache table.
3133 * @param string $joinTable Table on which to join civicrm_group_contact_cache
3134 * @param string $op SQL comparison operator (NULL, IN, !=, IS NULL, etc.)
3135 * @param string $joinColumn Column in $joinTable on which to join civicrm_group_contact_cache.contact_id
3137 * @return string WHERE clause component for smart group criteria.
3139 public function addGroupContactCache($groups, $tableAlias, $joinTable = "contact_a", $op, $joinColumn = 'id') {
3140 $isNullOp = (strpos($op, 'NULL') !== FALSE);
3141 $groupsIds = $groups;
3143 $operator = ['=' => 'IN', '!=' => 'NOT IN'];
3144 if (!empty($operator[$op]) && is_array($groups)) {
3145 $op = $operator[$op];
3147 if (!$isNullOp && !$groups) {
3150 elseif (strpos($op, 'IN') !== FALSE) {
3151 $groups = [$op => $groups];
3153 elseif (is_array($groups) && count($groups)) {
3154 $groups = ['IN' => $groups];
3157 // Find all the groups that are part of a saved search.
3158 $smartGroupClause = self
::buildClause("id", $op, $groups, 'Int');
3160 SELECT id, cache_date, saved_search_id, children
3162 WHERE $smartGroupClause
3163 AND ( saved_search_id != 0
3164 OR saved_search_id IS NOT NULL
3165 OR children IS NOT NULL )
3168 $group = CRM_Core_DAO
::executeQuery($sql);
3170 while ($group->fetch()) {
3171 $this->_useDistinct
= TRUE;
3172 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
3173 CRM_Contact_BAO_GroupContactCache
::load($group);
3176 if ($group->N
== 0 && $op != 'NOT IN') {
3180 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache {$tableAlias} ON {$joinTable}.{$joinColumn} = {$tableAlias}.contact_id ";
3182 if ($op == 'NOT IN') {
3183 return "{$tableAlias}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact_cache cgcc WHERE cgcc.group_id IN ( " . implode(',', (array) $groupsIds) . " ) )";
3185 return self
::buildClause("{$tableAlias}.group_id", $op, $groups, 'Int');
3189 * Where / qill clause for cms users
3193 public function ufUser(&$values) {
3194 list($name, $op, $value, $grouping, $wildcard) = $values;
3197 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3199 $this->_qill
[$grouping][] = ts('CMS User');
3201 elseif ($value == 0) {
3202 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3204 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
3205 $this->_qill
[$grouping][] = ts('Not a CMS User');
3210 * All tag search specific.
3212 * @param array $values
3214 public function tagSearch(&$values) {
3215 list($name, $op, $value, $grouping, $wildcard) = $values;
3218 $value = "%{$value}%";
3219 $escapedValue = CRM_Utils_Type
::escape("%{$value}%", 'String');
3221 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3222 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3224 $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
3225 $tTable = "`civicrm_tag-" . uniqid() . "`";
3227 if ($useAllTagTypes[2]) {
3228 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3229 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
3230 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
3232 // search tag in cases
3233 $etCaseTable = "`civicrm_entity_case_tag-" . uniqid() . "`";
3234 $tCaseTable = "`civicrm_case_tag-" . uniqid() . "`";
3235 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3236 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3237 LEFT JOIN civicrm_case
3238 ON (civicrm_case_contact.case_id = civicrm_case.id
3239 AND civicrm_case.is_deleted = 0 )
3240 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
3241 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
3242 // search tag in activities
3243 $etActTable = "`civicrm_entity_act_tag-" . uniqid() . "`";
3244 $tActTable = "`civicrm_act_tag-" . uniqid() . "`";
3245 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
3246 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3248 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3249 = " LEFT JOIN civicrm_activity_contact
3250 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3251 LEFT JOIN civicrm_activity
3252 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3253 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3254 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
3255 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
3257 $this->_where
[$grouping][] = "({$tTable}.name $op '" . $escapedValue . "' OR {$tCaseTable}.name $op '" . $escapedValue . "' OR {$tActTable}.name $op '" . $escapedValue . "')";
3258 $this->_qill
[$grouping][] = ts('Tag %1 %2', [1 => $tagTypesText[2], 2 => $op]) . ' ' . $value;
3261 $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
3262 $tTable = "`civicrm_tag-" . uniqid() . "`";
3263 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
3264 {$etTable}.entity_table = 'civicrm_contact' )
3265 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
3267 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
3268 $this->_qill
[$grouping][] = ts('Tagged %1', [1 => $op]) . ' ' . $value;
3273 * Where / qill clause for tag.
3275 * @param array $values
3277 public function tag(&$values) {
3278 list($name, $op, $value, $grouping, $wildcard) = $values;
3280 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_EntityTag', "tag_id", $value, $op, ['onlyActive' => FALSE]);
3281 // API/Search Builder format array(operator => array(values))
3282 if (is_array($value)) {
3283 if (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
3285 $value = $value[$op];
3287 if (count($value) > 1) {
3288 $this->_useDistinct
= TRUE;
3292 // implode array, then remove all spaces
3293 $value = str_replace(' ', '', implode(',', (array) $value));
3294 if (!empty($value)) {
3295 $value = CRM_Utils_Type
::validate(
3297 'CommaSeparatedIntegers'
3301 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3302 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3304 $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
3306 if ($useAllTagTypes[2]) {
3307 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3308 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3310 // search tag in cases
3311 $etCaseTable = "`civicrm_entity_case_tag-" . uniqid() . "`";
3312 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
3313 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3315 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3316 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3317 LEFT JOIN civicrm_case
3318 ON (civicrm_case_contact.case_id = civicrm_case.id
3319 AND civicrm_case.is_deleted = 0 )
3320 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3321 // search tag in activities
3322 $etActTable = "`civicrm_entity_act_tag-" . uniqid() . "`";
3323 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3324 = " LEFT JOIN civicrm_activity_contact
3325 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3326 LEFT JOIN civicrm_activity
3327 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3328 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3329 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3332 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
3333 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3336 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (" . $value . ") OR {$etCaseTable}.tag_id $op (" . $value . ") OR {$etActTable}.tag_id $op (" . $value . "))";
3340 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3341 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3344 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
3345 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3346 $op = str_replace('EMPTY', 'NULL', $op);
3347 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
3349 // CRM-16941: for tag tried with != operator we don't show contact who don't have given $value AND also in other tag
3350 elseif ($op == '!=') {
3351 $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') . ")";
3353 elseif ($op == '=' ||
strstr($op, 'IN')) {
3354 $op = ($op == '=') ?
'IN' : $op;
3355 $this->_where
[$grouping][] = "{$etTable}.tag_id $op ( $value )";
3358 $this->_qill
[$grouping][] = ts('Tagged %1 %2', [1 => $qillop, 2 => $qillVal]);
3362 * Where/qill clause for notes
3364 * @param array $values
3366 public function notes(&$values) {
3367 list($name, $op, $value, $grouping, $wildcard) = $values;
3369 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3370 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
3371 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
3373 $this->_useDistinct
= TRUE;
3375 $this->_tables
['civicrm_note'] = $this->_whereTables
['civicrm_note']
3376 = " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3379 $value = CRM_Core_DAO
::escapeString($n);
3381 if (strpos($value, '%') === FALSE) {
3382 $value = "%$value%";
3386 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
3392 if ($noteOption %
2 == 0) {
3393 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
3394 $label = ts('Note: Body Only');
3396 if ($noteOption %
3 == 0) {
3397 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
3398 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
3400 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3401 list($qillOp, $qillVal) = self
::buildQillForFieldValue(NULL, $name, $n, $op);
3402 $this->_qill
[$grouping][] = ts("%1 %2 %3", [1 => $label, 2 => $qillOp, 3 => $qillVal]);
3406 * @param string $name
3412 public function nameNullOrEmptyOp($name, $op, $grouping) {
3416 $this->_where
[$grouping][] = "contact_a.$name $op";
3417 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3421 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3422 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3425 case 'IS NOT EMPTY':
3426 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3427 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3436 * Where / qill clause for sort_name
3438 * @param array $values
3440 public function sortName(&$values) {
3441 list($fieldName, $op, $value, $grouping, $wildcard) = $values;
3443 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3444 if ($this->nameNullOrEmptyOp($fieldName, $op, $grouping)) {
3448 $input = $value = trim($value);
3450 if (!strlen($value)) {
3454 $config = CRM_Core_Config
::singleton();
3458 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3461 $firstChar = substr($value, 0, 1);
3462 $lastChar = substr($value, -1, 1);
3463 $quotes = ["'", '"'];
3464 // If string is quoted, strip quotes and otherwise don't alter it
3465 if ((strlen($value) > 2) && in_array($firstChar, $quotes) && in_array($lastChar, $quotes)) {
3466 $value = trim($value, implode('', $quotes));
3468 // Replace spaces with wildcards for a LIKE operation
3469 // UNLESS string contains a comma (this exception is a tiny bit questionable)
3470 elseif ($op == 'LIKE' && strpos($value, ',') === FALSE) {
3471 $value = str_replace(' ', '%', $value);
3473 $value = CRM_Core_DAO
::escapeString(trim($value));
3474 if (strlen($value)) {
3476 $value = "'" . self
::getWildCardedValue($wildcard, $op, $value) . "'";
3477 if ($fieldName == 'sort_name') {
3478 $wc = "contact_a.sort_name";
3481 $wc = "contact_a.display_name";
3483 $fieldsub[] = " ( $wc $op $value )";
3484 if ($config->includeNickNameInName
) {
3485 $wc = "contact_a.nick_name";
3486 $fieldsub[] = " ( $wc $op $value )";
3488 if ($config->includeEmailInName
) {
3489 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3491 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3494 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3496 $this->_where
[$grouping][] = $sub;
3497 if ($config->includeEmailInName
) {
3498 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3499 $this->_qill
[$grouping][] = ts('Name or Email') . " $op - '$input'";
3502 $this->_qill
[$grouping][] = ts('Name') . " $op - '$input'";
3507 * Where/qill clause for greeting fields.
3509 * @param array $values
3511 public function greetings(&$values) {
3512 list($name, $op, $value, $grouping, $wildcard) = $values;
3513 $name .= '_display';
3515 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
3516 $this->_qill
[$grouping][] = ts('Greeting %1 %2', [1 => $qillop, 2 => $qillVal]);
3517 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value, 'String');
3521 * Where / qill clause for email
3523 * @param array $values
3524 * @param string $apiEntity
3526 protected function email(&$values, $apiEntity) {
3527 list($name, $op, $value, $grouping, $wildcard) = $values;
3528 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3530 // CRM-18147: for Contact's GET API, email fieldname got appended with its entity as in {$apiEntiy}_{$name}
3531 // so following code is use build whereClause for contact's primart email id
3532 if (!empty($apiEntity)) {
3533 $dataType = 'String';
3534 if ($name == 'email_id') {
3535 $dataType = 'Integer';
3539 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.is_primary', '=', 1, 'Integer');
3540 $this->_where
[$grouping][] = self
::buildClause("civicrm_email.$name", $op, $value, $dataType);
3546 if (substr($n, 0, 1) == '"' &&
3547 substr($n, -1, 1) == '"'
3549 $n = substr($n, 1, -1);
3550 $value = CRM_Core_DAO
::escapeString($n);
3554 $value = self
::getWildCardedValue($wildcard, $op, $n);
3556 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3557 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3560 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3561 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3566 * Where / qill clause for phone number
3568 * @param array $values
3570 public function phone_numeric(&$values) {
3571 list($name, $op, $value, $grouping, $wildcard) = $values;
3572 // Strip non-numeric characters; allow wildcards
3573 $number = preg_replace('/[^\d%]/', '', $value);
3575 if (strpos($number, '%') === FALSE) {
3576 $number = "%$number%";
3579 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3580 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3581 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3586 * Where / qill clause for phone type/location
3588 * @param array $values
3590 public function phone_option_group($values) {
3591 list($name, $op, $value, $grouping, $wildcard) = $values;
3592 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3593 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3594 $optionName = $options[$value];
3595 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3596 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3597 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3601 * Where / qill clause for street_address.
3603 * @param array $values
3605 public function street_address(&$values) {
3606 list($name, $op, $value, $grouping) = $values;
3615 if (strpos($value, '%') === FALSE) {
3616 // only add wild card if not there
3617 $value = "%{$value}%";
3620 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, $value, 'String');
3621 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3624 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3625 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3628 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3632 * Where / qill clause for street_unit.
3634 * @param array $values
3636 public function street_number(&$values) {
3637 list($name, $op, $value, $grouping, $wildcard) = $values;
3645 if (strtolower($n) == 'odd') {
3646 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3647 $this->_qill
[$grouping][] = ts('Street Number is odd');
3649 elseif (strtolower($n) == 'even') {
3650 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3651 $this->_qill
[$grouping][] = ts('Street Number is even');
3655 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_number', $op, $value, 'String');
3656 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3659 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3663 * Where / qill clause for sorting by character.
3665 * @param array $values
3667 public function sortByCharacter(&$values) {
3668 list($name, $op, $value, $grouping, $wildcard) = $values;
3670 $name = trim($value);
3671 $cond = " contact_a.sort_name LIKE '" . CRM_Core_DAO
::escapeWildCardString($name) . "%'";
3672 $this->_where
[$grouping][] = $cond;
3673 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', [1 => $name]);
3677 * Where / qill clause for including contact ids.
3679 public function includeContactIDs() {
3680 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3685 foreach ($this->_params
as $id => $values) {
3686 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3687 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3690 CRM_Utils_Type
::validateAll($contactIds, 'Positive');
3691 if (!empty($contactIds)) {
3692 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3697 * Where / qill clause for postal code.
3699 * @param array $values
3701 public function postalCode(&$values) {
3702 // skip if the fields dont have anything to do with postal_code
3703 if (empty($this->_fields
['postal_code'])) {
3707 list($name, $op, $value, $grouping, $wildcard) = $values;
3709 // Handle numeric postal code range searches properly by casting the column as numeric
3710 if (is_numeric($value)) {
3711 $field = "IF (civicrm_address.postal_code REGEXP '^[0-9]{1,10}$', CAST(civicrm_address.postal_code AS UNSIGNED), 0)";
3712 $val = CRM_Utils_Type
::escape($value, 'Integer');
3715 $field = 'civicrm_address.postal_code';
3716 // Per CRM-17060 we might be looking at an 'IN' syntax so don't case arrays to string.
3717 if (!is_array($value)) {
3718 $val = CRM_Utils_Type
::escape($value, 'String');
3721 // Do we need to escape values here? I would expect buildClause does.
3726 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3728 if ($name == 'postal_code') {
3729 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3730 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3732 elseif ($name == 'postal_code_low') {
3733 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3734 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', [1 => $value]);
3736 elseif ($name == 'postal_code_high') {
3737 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3738 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', [1 => $value]);
3743 * Where / qill clause for location type.
3745 * @param array $values
3746 * @param null $status
3750 public function locationType(&$values, $status = NULL) {
3751 list($name, $op, $value, $grouping, $wildcard) = $values;
3753 if (is_array($value)) {
3754 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')';
3755 $this->_tables
['civicrm_address'] = 1;
3756 $this->_whereTables
['civicrm_address'] = 1;
3758 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3760 foreach ($value as $id) {
3761 $names[] = $locationType[$id];
3764 $this->_primaryLocation
= FALSE;
3767 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3770 return implode(' ' . ts('or') . ' ', $names);
3777 * @param bool $fromStateProvince
3779 * @return array|NULL
3781 public function country(&$values, $fromStateProvince = TRUE) {
3782 list($name, $op, $value, $grouping, $wildcard) = $values;
3784 if (!$fromStateProvince) {
3785 $stateValues = $this->getWhereValues('state_province', $grouping);
3786 if (!empty($stateValues)) {
3787 // return back to caller if there are state province values
3788 // since that handles this case
3793 $countryClause = $countryQill = NULL;
3794 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY']) ||
($values && !empty($value))) {
3795 $this->_tables
['civicrm_address'] = 1;
3796 $this->_whereTables
['civicrm_address'] = 1;
3798 $countryClause = self
::buildClause('civicrm_address.country_id', $op, $value, 'Positive');
3799 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, 'country_id', $value, $op);
3800 $countryQill = ts("%1 %2 %3", [1 => 'Country', 2 => $qillop, 3 => $qillVal]);
3802 if (!$fromStateProvince) {
3803 $this->_where
[$grouping][] = $countryClause;
3804 $this->_qill
[$grouping][] = $countryQill;
3808 if ($fromStateProvince) {
3809 if (!empty($countryClause)) {
3812 " ...AND... " . $countryQill,
3816 return [NULL, NULL];
3822 * Where / qill clause for county (if present).
3824 * @param array $values
3825 * @param null $status
3829 public function county(&$values, $status = NULL) {
3830 list($name, $op, $value, $grouping, $wildcard) = $values;
3832 if (!is_array($value)) {
3833 // force the county to be an array
3837 // check if the values are ids OR names of the counties
3838 $inputFormat = 'id';
3839 foreach ($value as $v) {
3840 if (!is_numeric($v)) {
3841 $inputFormat = 'name';
3849 elseif ($op == '!=') {
3853 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3854 $op = str_replace('EMPTY', 'NULL', $op);
3857 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
3858 $clause = "civicrm_address.county_id $op";
3860 elseif ($inputFormat == 'id') {
3861 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3863 $county = CRM_Core_PseudoConstant
::county();
3864 foreach ($value as $id) {
3865 $names[] = CRM_Utils_Array
::value($id, $county);
3870 $county = CRM_Core_PseudoConstant
::county();
3871 foreach ($value as $name) {
3872 $name = trim($name);
3873 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3875 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3878 $this->_tables
['civicrm_address'] = 1;
3879 $this->_whereTables
['civicrm_address'] = 1;
3881 $this->_where
[$grouping][] = $clause;
3883 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3886 return implode(' ' . ts('or') . ' ', $names);
3891 * Where / qill clause for state/province AND country (if present).
3893 * @param array $values
3894 * @param null $status
3898 public function stateProvince(&$values, $status = NULL) {
3899 list($name, $op, $value, $grouping, $wildcard) = $values;
3901 $stateClause = self
::buildClause('civicrm_address.state_province_id', $op, $value, 'Positive');
3902 $this->_tables
['civicrm_address'] = 1;
3903 $this->_whereTables
['civicrm_address'] = 1;
3905 $countryValues = $this->getWhereValues('country', $grouping);
3906 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3907 if ($countryClause) {
3908 $clause = "( $stateClause AND $countryClause )";
3911 $clause = $stateClause;
3914 $this->_where
[$grouping][] = $clause;
3915 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
3917 $this->_qill
[$grouping][] = ts("State/Province %1 %2 %3", [1 => $qillop, 2 => $qillVal, 3 => $countryQill]);
3920 return implode(' ' . ts('or') . ' ', $qillVal) . $countryQill;
3925 * Where / qill clause for change log.
3927 * @param array $values
3929 public function changeLog(&$values) {
3930 list($name, $op, $value, $grouping, $wildcard) = $values;
3932 $targetName = $this->getWhereValues('changed_by', $grouping);
3937 $name = trim($targetName[2]);
3938 $name = CRM_Core_DAO
::escapeString($name);
3939 $name = $targetName[4] ?
"%$name%" : $name;
3940 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3941 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3942 $fieldTitle = ts('Added By');
3943 foreach ($this->_params
as $params) {
3944 if ($params[0] == 'log_date') {
3945 if ($params[2] == 2) {
3946 $fieldTitle = ts('Modified By');
3951 list($qillop, $qillVal) = self
::buildQillForFieldValue(NULL, 'changed_by', $name, 'LIKE');
3952 $this->_qill
[$grouping][] = ts("%1 %2 '%3'", [
3962 public function modifiedDates($values) {
3963 $this->_useDistinct
= TRUE;
3965 // CRM-11281, default to added date if not set
3966 $fieldTitle = ts('Added Date');
3967 $fieldName = 'created_date';
3968 foreach (array_keys($this->_params
) as $id) {
3969 if ($this->_params
[$id][0] == 'log_date') {
3970 if ($this->_params
[$id][2] == 2) {
3971 $fieldTitle = ts('Modified Date');
3972 $fieldName = 'modified_date';
3977 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3979 self
::$_openedPanes[ts('Change Log')] = TRUE;
3985 public function demographics(&$values) {
3986 list($name, $op, $value, $grouping, $wildcard) = $values;
3988 if (($name == 'age_low') ||
($name == 'age_high')) {
3989 $this->ageRangeQueryBuilder($values,
3990 'contact_a', 'age', 'birth_date', ts('Age')
3993 elseif (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3995 $this->dateQueryBuilder($values,
3996 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3999 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
4001 $this->dateQueryBuilder($values,
4002 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
4006 self
::$_openedPanes[ts('Demographics')] = TRUE;
4012 public function privacy(&$values) {
4013 list($name, $op, $value, $grouping) = $values;
4014 //fixed for profile search listing CRM-4633
4015 if (strpbrk($value, "[")) {
4016 $value = "'{$value}'";
4018 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
4021 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
4023 $field = CRM_Utils_Array
::value($name, $this->_fields
);
4024 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
4025 $title = $field ?
$field['title'] : $name;
4026 $this->_qill
[$grouping][] = "$title $op $value";
4032 public function privacyOptions($values) {
4033 list($name, $op, $value, $grouping, $wildcard) = $values;
4035 if (empty($value) ||
!is_array($value)) {
4039 // get the operator and toggle values
4040 $opValues = $this->getWhereValues('privacy_operator', $grouping);
4043 strtolower($opValues[2] == 'AND')
4045 // @todo this line is logially unreachable
4049 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
4051 if ($toggleValues &&
4052 $toggleValues[2] == 2
4059 foreach ($value as $dontCare => $pOption) {
4060 $clauses[] = " ( contact_a.{$pOption} = 1 ) ";
4061 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
4062 $title = $field ?
$field['title'] : $pOption;
4063 $qill[] = " $title = 1 ";
4066 $this->_where
[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )';
4067 $this->_qill
[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )';
4073 public function preferredCommunication(&$values) {
4074 list($name, $op, $value, $grouping, $wildcard) = $values;
4076 if (!is_array($value)) {
4077 $value = str_replace(['(', ')'], '', explode(",", $value));
4079 elseif (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
4081 $value = $value[$op];
4083 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Contact', $name, $value, $op);
4085 if (self
::caseImportant($op)) {
4086 $value = implode("[[:cntrl:]]|[[:cntrl:]]", (array) $value);
4087 $op = (strstr($op, '!') ||
strstr($op, 'NOT')) ?
'NOT RLIKE' : 'RLIKE';
4088 $value = "[[:cntrl:]]" . $value . "[[:cntrl:]]";
4091 $this->_where
[$grouping][] = self
::buildClause("contact_a.preferred_communication_method", $op, $value);
4092 $this->_qill
[$grouping][] = ts('Preferred Communication Method %1 %2', [1 => $qillop, 2 => $qillVal]);
4096 * Where / qill clause for relationship.
4098 * @param array $values
4100 public function relationship(&$values) {
4101 list($name, $op, $value, $grouping, $wildcard) = $values;
4102 if ($this->_relationshipValuesAdded
) {
4105 // also get values array for relation_target_name
4106 // for relationship search we always do wildcard
4107 $relationType = $this->getWhereValues('relation_type_id', $grouping);
4108 $targetName = $this->getWhereValues('relation_target_name', $grouping);
4109 $relStatus = $this->getWhereValues('relation_status', $grouping);
4110 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
4112 $nameClause = $name = NULL;
4114 $name = trim($targetName[2]);
4115 if (substr($name, 0, 1) == '"' &&
4116 substr($name, -1, 1) == '"'
4118 $name = substr($name, 1, -1);
4119 $name = CRM_Core_DAO
::escapeString($name);
4120 $nameClause = "= '$name'";
4123 $name = CRM_Core_DAO
::escapeString($name);
4124 $nameClause = "LIKE '%{$name}%'";
4128 $relTypes = $relTypesIds = [];
4129 if (!empty($relationType)) {
4130 $relationType[2] = (array) $relationType[2];
4131 foreach ($relationType[2] as $relType) {
4132 $rel = explode('_', $relType);
4133 self
::$_relType = $rel[1];
4134 $params = ['id' => $rel[0]];
4136 $rTypeValue = CRM_Contact_BAO_RelationshipType
::retrieve($params, $typeValues);
4137 if (!empty($rTypeValue)) {
4138 if ($rTypeValue->name_a_b
== $rTypeValue->name_b_a
) {
4139 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4140 self
::$_relType = 'reciprocal';
4142 $relTypesIds[] = $rel[0];
4143 $relTypes[] = $relType;
4148 // if we are creating a temp table we build our own where for the relationship table
4149 $relationshipTempTable = NULL;
4150 if (self
::$_relType == 'reciprocal') {
4152 self
::$_relationshipTempTable = $relationshipTempTable = CRM_Core_DAO
::createTempTableName('civicrm_rel');
4154 $where[$grouping][] = " sort_name $nameClause ";
4156 $groupJoinTable = "civicrm_relationship";
4157 $groupJoinColumn = "contact_id_alt";
4160 $where = &$this->_where
;
4162 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4164 $groupJoinTable = "contact_b";
4165 $groupJoinColumn = "id";
4167 $allRelationshipType = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, NULL, TRUE);
4168 if ($nameClause ||
!$targetGroup) {
4169 if (!empty($relationType)) {
4171 foreach ($relTypes as $rel) {
4172 if (!empty($relQill)) {
4175 $relQill .= $allRelationshipType[$rel];
4177 $this->_qill
[$grouping][] = 'Relationship Type(s) ' . $relQill . " $name";
4180 $this->_qill
[$grouping][] = $name;
4184 //check to see if the target contact is in specified group
4186 //add contacts from static groups
4187 $this->_tables
['civicrm_relationship_group_contact'] = $this->_whereTables
['civicrm_relationship_group_contact']
4188 = " 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'";
4189 $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" .
4190 implode(",", $targetGroup[2]) . ") ) ";
4192 //add contacts from saved searches
4193 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", $groupJoinTable, $op, $groupJoinColumn);
4195 //set the group where clause
4197 $groupWhere[] = "( " . $ssWhere . " )";
4199 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4201 //Get the names of the target groups for the qill
4202 $groupNames = CRM_Core_PseudoConstant
::group();
4204 foreach ($targetGroup[2] as $groupId) {
4205 if (array_key_exists($groupId, $groupNames)) {
4206 $qillNames[] = $groupNames[$groupId];
4209 if (!empty($relationType)) {
4211 foreach ($relTypes as $rel) {
4212 if (!empty($relQill)) {
4215 $relQill .= CRM_Utils_Array
::value($rel, $allRelationshipType);
4217 $this->_qill
[$grouping][] = 'Relationship Type(s) ' . $relQill . " ( " . implode(", ", $qillNames) . " )";
4220 $this->_qill
[$grouping][] = implode(", ", $qillNames);
4224 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4225 $today = date('Ymd');
4226 //check for active, inactive and all relation status
4227 if ($relStatus[2] == 0) {
4228 $where[$grouping][] = "(
4229 civicrm_relationship.is_active = 1 AND
4230 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4231 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4233 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
4235 elseif ($relStatus[2] == 1) {
4236 $where[$grouping][] = "(
4237 civicrm_relationship.is_active = 0 OR
4238 civicrm_relationship.end_date < {$today} OR
4239 civicrm_relationship.start_date > {$today}
4241 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
4245 if (in_array(['deleted_contacts', '=', '1', '0', '0'], $this->_params
)) {
4248 $where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})";
4250 $this->addRelationshipPermissionClauses($grouping, $where);
4251 $this->addRelationshipDateClauses($grouping, $where);
4252 $this->addRelationshipActivePeriodClauses($grouping, $where);
4253 if (!empty($relTypes)) {
4254 $where[$grouping][] = 'civicrm_relationship.relationship_type_id IN (' . implode(',', $relTypesIds) . ')';
4256 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
4257 $this->_useDistinct
= TRUE;
4258 $this->_relationshipValuesAdded
= TRUE;
4259 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4261 if ($relationshipTempTable) {
4263 if (!empty($where[$grouping])) {
4264 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4265 $whereClause = str_replace('contact_b', 'c', $whereClause);
4268 CREATE TEMPORARY TABLE {$relationshipTempTable}
4270 `contact_id` int(10) unsigned NOT NULL DEFAULT '0',
4271 `contact_id_alt` int(10) unsigned NOT NULL DEFAULT '0',
4272 KEY `contact_id` (`contact_id`),
4273 KEY `contact_id_alt` (`contact_id_alt`)
4275 (SELECT contact_id_b as contact_id, contact_id_a as contact_id_alt, civicrm_relationship.id
4276 FROM civicrm_relationship
4277 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4280 (SELECT contact_id_a as contact_id, contact_id_b as contact_id_alt, civicrm_relationship.id
4281 FROM civicrm_relationship
4282 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4285 CRM_Core_DAO
::executeQuery($sql);
4290 * Add relationship permission criteria to where clause.
4292 * @param string $grouping
4293 * @param array $where Array to add "where" criteria to, in case you are generating a temp table.
4294 * Not the main query.
4296 public function addRelationshipPermissionClauses($grouping, &$where) {
4297 $relPermission = $this->getWhereValues('relation_permission', $grouping);
4298 if ($relPermission) {
4299 if (!is_array($relPermission[2])) {
4300 // this form value was scalar in previous versions of Civi
4301 $relPermission[2] = [$relPermission[2]];
4303 $where[$grouping][] = "(civicrm_relationship.is_permission_a_b IN (" . implode(",", $relPermission[2]) . "))";
4305 $allRelationshipPermissions = CRM_Contact_BAO_Relationship
::buildOptions('is_permission_a_b');
4307 $relPermNames = array_intersect_key($allRelationshipPermissions, array_flip($relPermission[2]));
4308 $this->_qill
[$grouping][] = ts('Permissioned Relationships') . ' - ' . implode(' OR ', $relPermNames);
4313 * Add start & end date criteria in
4314 * @param string $grouping
4315 * @param array $where
4316 * = array to add where clauses to, in case you are generating a temp table.
4317 * not the main query.
4319 public function addRelationshipDateClauses($grouping, &$where) {
4326 foreach ($dateTypes as $dateField) {
4327 $dateValueLow = $this->getWhereValues('relation_' . $dateField . '_low', $grouping);
4328 $dateValueHigh = $this->getWhereValues('relation_' . $dateField . '_high', $grouping);
4329 if (!empty($dateValueLow)) {
4330 $date = date('Ymd', strtotime($dateValueLow[2]));
4331 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4332 $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);
4334 if (!empty($dateValueHigh)) {
4335 $date = date('Ymd', strtotime($dateValueHigh[2]));
4336 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4337 $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);
4343 * Add start & end active period criteria in
4344 * @param string $grouping
4345 * @param array $where
4346 * = array to add where clauses to, in case you are generating a temp table.
4347 * not the main query.
4349 public function addRelationshipActivePeriodClauses($grouping, &$where) {
4351 $dateField = 'active_period_date';
4353 $dateValueLow = $this->getWhereValues('relation_active_period_date_low', $grouping);
4354 $dateValueHigh = $this->getWhereValues('relation_active_period_date_high', $grouping);
4355 $dateValueLowFormated = $dateValueHighFormated = NULL;
4356 if (!empty($dateValueLow) && !empty($dateValueHigh)) {
4357 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4358 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
4359 $this->_qill
[$grouping][] = (ts('Relationship was active between')) . " " . CRM_Utils_Date
::customFormat($dateValueLowFormated) . " and " . CRM_Utils_Date
::customFormat($dateValueHighFormated);
4361 elseif (!empty($dateValueLow)) {
4362 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4363 $this->_qill
[$grouping][] = (ts('Relationship was active after')) . " " . CRM_Utils_Date
::customFormat($dateValueLowFormated);
4365 elseif (!empty($dateValueHigh)) {
4366 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
4367 $this->_qill
[$grouping][] = (ts('Relationship was active before')) . " " . CRM_Utils_Date
::customFormat($dateValueHighFormated);
4370 if ($activePeriodClauses = self
::getRelationshipActivePeriodClauses($dateValueLowFormated, $dateValueHighFormated, TRUE)) {
4371 $where[$grouping][] = $activePeriodClauses;
4376 * Get start & end active period criteria
4378 public static function getRelationshipActivePeriodClauses($from, $to, $forceTableName) {
4379 $tableName = $forceTableName ?
'civicrm_relationship.' : '';
4380 if (!is_null($from) && !is_null($to)) {
4381 return '(((' . $tableName . 'start_date >= ' . $from . ' AND ' . $tableName . 'start_date <= ' . $to . ') OR
4382 (' . $tableName . 'end_date >= ' . $from . ' AND ' . $tableName . 'end_date <= ' . $to . ') OR
4383 (' . $tableName . 'start_date <= ' . $from . ' AND ' . $tableName . 'end_date >= ' . $to . ' )) OR
4384 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4385 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . ') OR
4386 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4388 elseif (!is_null($from)) {
4389 return '((' . $tableName . 'start_date >= ' . $from . ') OR
4390 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4391 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . '))';
4393 elseif (!is_null($to)) {
4394 return '((' . $tableName . 'start_date <= ' . $to . ') OR
4395 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4396 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4401 * Default set of return properties.
4406 * derault return properties
4408 public static function &defaultReturnProperties($mode = 1) {
4409 if (!isset(self
::$_defaultReturnProperties)) {
4410 self
::$_defaultReturnProperties = [];
4413 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4414 // add activity return properties
4415 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4416 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4419 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4422 if (empty(self
::$_defaultReturnProperties[$mode])) {
4423 self
::$_defaultReturnProperties[$mode] = [
4426 'legal_identifier' => 1,
4427 'external_identifier' => 1,
4428 'contact_type' => 1,
4429 'contact_sub_type' => 1,
4431 'display_name' => 1,
4432 'preferred_mail_format' => 1,
4439 'formal_title' => 1,
4440 'communication_style_id' => 1,
4443 'street_address' => 1,
4444 'supplemental_address_1' => 1,
4445 'supplemental_address_2' => 1,
4446 'supplemental_address_3' => 1,
4449 'postal_code_suffix' => 1,
4450 'state_province' => 1,
4452 'world_region' => 1,
4459 'household_name' => 1,
4460 'organization_name' => 1,
4461 'deceased_date' => 1,
4466 'current_employer' => 1,
4467 // FIXME: should we use defaultHierReturnProperties() for the below?
4468 'do_not_email' => 1,
4471 'do_not_phone' => 1,
4472 'do_not_trade' => 1,
4474 'contact_is_deleted' => 1,
4475 'preferred_communication_method' => 1,
4476 'preferred_language' => 1,
4480 return self
::$_defaultReturnProperties[$mode];
4484 * Get primary condition for a sql clause.
4488 * @return string|NULL
4490 public static function getPrimaryCondition($value) {
4491 if (is_numeric($value)) {
4492 $value = (int ) $value;
4493 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4499 * Wrapper for a simple search query.
4501 * @param array $params
4502 * @param array $returnProperties
4503 * @param bool $count
4507 public static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4508 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4509 list($select, $from, $where, $having) = $query->query();
4510 $groupBy = ($query->_useGroupBy
) ?
'GROUP BY contact_a.id' : '';
4512 $query = "$select $from $where $groupBy $having";
4517 * These are stub comments as this function needs more explanation - particularly in terms of how it
4518 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4520 * This function was originally written as a wrapper for the api query but is called from multiple places
4521 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4522 * but it is unclear as to whehter that is historical or there is a reason
4523 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4525 * @param array $params
4526 * @param array $returnProperties
4527 * @param null $fields
4528 * @param string $sort
4529 * @param int $offset
4530 * @param int $row_count
4531 * @param bool $smartGroupCache
4532 * ?? update smart group cache?.
4533 * @param bool $count
4534 * Return count obnly.
4535 * @param bool $skipPermissions
4536 * Should permissions be ignored or should the logged in user's permissions be applied.
4538 * This basically correlates to the component.
4539 * @param string $apiEntity
4540 * The api entity being called.
4541 * This sort-of duplicates $mode in a confusing way. Probably not by design.
4543 * @param bool|null $primaryLocationOnly
4546 public static function apiQuery(
4548 $returnProperties = NULL,
4553 $smartGroupCache = TRUE,
4555 $skipPermissions = TRUE,
4556 $mode = CRM_Contact_BAO_Query
::MODE_CONTACTS
,
4558 $primaryLocationOnly = NULL
4561 $query = new CRM_Contact_BAO_Query(
4562 $params, $returnProperties,
4563 NULL, TRUE, FALSE, $mode,
4565 TRUE, $smartGroupCache,
4567 $apiEntity, $primaryLocationOnly
4570 //this should add a check for view deleted if permissions are enabled
4571 if ($skipPermissions) {
4572 $query->_skipDeleteClause
= TRUE;
4574 $query->generatePermissionClause(FALSE, $count);
4576 // note : this modifies _fromClause and _simpleFromClause
4577 $query->includePseudoFieldsJoin($sort);
4579 list($select, $from, $where, $having) = $query->query($count);
4581 $options = $query->_options
;
4582 if (!empty($query->_permissionWhereClause
)) {
4583 if (empty($where)) {
4584 $where = "WHERE $query->_permissionWhereClause";
4587 $where = "$where AND $query->_permissionWhereClause";
4591 $sql = "$select $from $where $having";
4593 // add group by only when API action is not getcount
4594 // otherwise query fetches incorrect count
4595 if ($query->_useGroupBy
&& !$count) {
4596 $sql .= self
::getGroupByFromSelectColumns($query->_select
, 'contact_a.id');
4598 if (!empty($sort)) {
4599 $sort = CRM_Utils_Type
::escape($sort, 'String');
4600 $sql .= " ORDER BY $sort ";
4602 if ($row_count > 0 && $offset >= 0) {
4603 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4604 $row_count = CRM_Utils_Type
::escape($row_count, 'Int');
4605 $sql .= " LIMIT $offset, $row_count ";
4608 $dao = CRM_Core_DAO
::executeQuery($sql);
4610 // @todo derive this from the component class rather than hard-code two options.
4611 $entityIDField = ($mode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) ?
'contribution_id' : 'contact_id';
4614 while ($dao->fetch()) {
4616 $noRows = $dao->rowCount
;
4617 return [$noRows, NULL];
4619 $val = $query->store($dao);
4620 $convertedVals = $query->convertToPseudoNames($dao, TRUE, TRUE);
4622 if (!empty($convertedVals)) {
4623 $val = array_replace_recursive($val, $convertedVals);
4625 $values[$dao->$entityIDField] = $val;
4627 return [$values, $options];
4631 * Get the actual custom field name by stripping off the appended string.
4633 * The string could be _relative, _from, or _to
4635 * @todo use metadata rather than convention to do this.
4637 * @param string $parameterName
4638 * The name of the parameter submitted to the form.
4645 public static function getCustomFieldName($parameterName) {
4646 if (substr($parameterName, -5, 5) == '_from') {
4647 return substr($parameterName, 0, strpos($parameterName, '_from'));
4649 if (substr($parameterName, -9, 9) == '_relative') {
4650 return substr($parameterName, 0, strpos($parameterName, '_relative'));
4652 if (substr($parameterName, -3, 3) == '_to') {
4653 return substr($parameterName, 0, strpos($parameterName, '_to'));
4658 * Convert submitted values for relative custom fields to query object format.
4660 * The query will support the sqlOperator format so convert to that format.
4662 * @param array $formValues
4664 * @param array $params
4665 * Converted parameters for the query object.
4666 * @param string $values
4668 * @param string $fieldName
4669 * Submitted field name. (Matches form field not DB field.)
4671 protected static function convertCustomRelativeFields(&$formValues, &$params, $values, $fieldName) {
4672 if (empty($values)) {
4673 // e.g we might have relative set & from & to empty. The form flow is a bit funky &
4674 // this function gets called again after they fields have been converted which can get ugly.
4677 $customFieldName = self
::getCustomFieldName($fieldName);
4679 if (substr($fieldName, -9, 9) == '_relative') {
4680 list($from, $to) = CRM_Utils_Date
::getFromTo($values, NULL, NULL);
4683 if ($fieldName == $customFieldName . '_to' && CRM_Utils_Array
::value($customFieldName . '_from', $formValues)) {
4684 // Both to & from are set. We only need to acton one, choosing from.
4688 $from = CRM_Utils_Array
::value($customFieldName . '_from', $formValues, NULL);
4689 $to = CRM_Utils_Array
::value($customFieldName . '_to', $formValues, NULL);
4691 if (self
::isCustomDateField($customFieldName)) {
4692 list($from, $to) = CRM_Utils_Date
::getFromTo(NULL, $from, $to);
4698 $relativeFunction = ['BETWEEN' => [$from, $to]];
4701 $relativeFunction = ['>=' => $from];
4705 $relativeFunction = ['<=' => $to];
4717 * Are we dealing with custom field of type date.
4723 public static function isCustomDateField($fieldName) {
4724 if (($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($fieldName)) == FALSE) {
4727 if ('Date' == civicrm_api3('CustomField', 'getvalue', ['id' => $customFieldID, 'return' => 'data_type'])) {
4734 * Has this field already been reformatting to Query object syntax.
4736 * The form layer passed formValues to this function in preProcess & postProcess. Reason unknown. This seems
4737 * to come with associated double queries & is possibly damaging performance.
4739 * However, here we add a tested function to ensure convertFormValues identifies pre-processed fields & returns
4742 * @param mixed $values
4743 * Value in formValues for the field.
4747 public static function isAlreadyProcessedForQueryFormat($values) {
4748 if (!is_array($values)) {
4751 if (($operator = CRM_Utils_Array
::value(1, $values)) == FALSE) {
4754 return in_array($operator, CRM_Core_DAO
::acceptedSQLOperators());
4758 * If the state and country are passed remove state.
4760 * Country is implicit from the state, but including both results in
4761 * a poor query as there is no combined index on state AND country.
4765 * @param array $formValues
4767 public static function filterCountryFromValuesIfStateExists(&$formValues) {
4768 if (!empty($formValues['country']) && !empty($formValues['state_province'])) {
4769 // The use of array map sanitises the data by ensuring we are dealing with integers.
4770 $states = implode(', ', array_map('intval', $formValues['state_province']));
4771 $countryList = CRM_Core_DAO
::singleValueQuery(
4772 "SELECT GROUP_CONCAT(country_id) FROM civicrm_state_province WHERE id IN ($states)"
4774 if ($countryList == $formValues['country']) {
4775 unset($formValues['country']);
4781 * For some special cases, grouping by subset of select fields becomes mandatory.
4782 * Hence, full_group_by mode is handled by appending any_value
4783 * keyword to select fields not present in groupBy
4785 * @param array $selectClauses
4786 * @param array $groupBy - Columns already included in GROUP By clause.
4787 * @param string $aggregateFunction
4791 public static function appendAnyValueToSelect($selectClauses, $groupBy, $aggregateFunction = 'ANY_VALUE') {
4792 if (!CRM_Utils_SQL
::disableFullGroupByMode()) {
4793 $groupBy = array_map('trim', (array) $groupBy);
4794 $aggregateFunctions = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN|IF)[[:blank:]]*\(/i';
4795 foreach ($selectClauses as $key => &$val) {
4796 list($selectColumn, $alias) = array_pad(preg_split('/ as /i', $val), 2, NULL);
4797 // append ANY_VALUE() keyword
4798 if (!in_array($selectColumn, $groupBy) && preg_match($aggregateFunctions, trim($selectColumn)) !== 1) {
4799 $val = ($aggregateFunction == 'GROUP_CONCAT') ?
4800 str_replace($selectColumn, "$aggregateFunction(DISTINCT {$selectColumn})", $val) :
4801 str_replace($selectColumn, "$aggregateFunction({$selectColumn})", $val);
4806 return "SELECT " . implode(', ', $selectClauses) . " ";
4810 * For some special cases, where if non-aggregate ORDER BY columns are not present in GROUP BY
4811 * on full_group_by mode, then append the those missing columns to GROUP BY clause
4812 * keyword to select fields not present in groupBy
4814 * @param string $groupBy - GROUP BY clause where missing ORDER BY columns will be appended if not present
4815 * @param array $orderBys - ORDER BY sub-clauses
4818 public static function getGroupByFromOrderBy(&$groupBy, $orderBys) {
4819 if (!CRM_Utils_SQL
::disableFullGroupByMode()) {
4820 foreach ($orderBys as $orderBy) {
4821 // remove sort syntax from ORDER BY clauses if present
4822 $orderBy = str_ireplace([' DESC', ' ASC', '`'], '', $orderBy);
4823 // if ORDER BY column is not present in GROUP BY then append it to end
4824 if (preg_match('/(MAX|MIN)\(/i', trim($orderBy)) !== 1 && !strstr($groupBy, $orderBy)) {
4825 $groupBy .= ", {$orderBy}";
4832 * Include Select columns in groupBy clause.
4834 * @param array $selectClauses
4835 * @param array $groupBy - Columns already included in GROUP By clause.
4839 public static function getGroupByFromSelectColumns($selectClauses, $groupBy = NULL) {
4840 $groupBy = (array) $groupBy;
4841 $mysqlVersion = CRM_Core_DAO
::singleValueQuery('SELECT VERSION()');
4842 $sqlMode = CRM_Core_DAO
::singleValueQuery('SELECT @@sql_mode');
4844 //return if ONLY_FULL_GROUP_BY is not enabled.
4845 if (CRM_Utils_SQL
::supportsFullGroupBy() && !empty($sqlMode) && in_array('ONLY_FULL_GROUP_BY', explode(',', $sqlMode))) {
4846 $regexToExclude = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN|IF)[[:blank:]]*\(/i';
4847 foreach ($selectClauses as $key => $val) {
4848 $aliasArray = preg_split('/ as /i', $val);
4849 // if more than 1 alias we need to split by ','.
4850 if (count($aliasArray) > 2) {
4851 $aliasArray = preg_split('/,/', $val);
4852 foreach ($aliasArray as $key => $value) {
4853 $alias = current(preg_split('/ as /i', $value));
4854 if (!in_array($alias, $groupBy) && preg_match($regexToExclude, trim($alias)) !== 1) {
4855 $groupBy[] = $alias;
4860 list($selectColumn, $alias) = array_pad($aliasArray, 2, NULL);
4861 $dateRegex = '/^(DATE_FORMAT|DATE_ADD|CASE)/i';
4862 $tableName = current(explode('.', $selectColumn));
4863 $primaryKey = "{$tableName}.id";
4864 // exclude columns which are already included in groupBy and aggregate functions from select
4865 // CRM-18439 - Also exclude the columns which are functionally dependent on columns in $groupBy (MySQL 5.7+)
4866 if (!in_array($selectColumn, $groupBy) && !in_array($primaryKey, $groupBy) && preg_match($regexToExclude, trim($selectColumn)) !== 1) {
4867 if (!empty($alias) && preg_match($dateRegex, trim($selectColumn))) {
4868 $groupBy[] = $alias;
4871 $groupBy[] = $selectColumn;
4878 if (!empty($groupBy)) {
4879 return " GROUP BY " . implode(', ', $groupBy);
4885 * Create and query the db for an contact search.
4887 * @param int $offset
4888 * The offset for the query.
4889 * @param int $rowCount
4890 * The number of rows to return.
4891 * @param string|CRM_Utils_Sort $sort
4892 * The order by string.
4893 * @param bool $count
4894 * Is this a count only query ?.
4895 * @param bool $includeContactIds
4896 * Should we include contact ids?.
4897 * @param bool $sortByChar
4898 * If true returns the distinct array of first characters for search results.
4899 * @param bool $groupContacts
4900 * If true, return only the contact ids.
4901 * @param bool $returnQuery
4902 * Should we return the query as a string.
4903 * @param string $additionalWhereClause
4904 * If the caller wants to further restrict the search (used for components).
4905 * @param null $sortOrder
4906 * @param string $additionalFromClause
4907 * Should be clause with proper joins, effective to reduce where clause load.
4909 * @param bool $skipOrderAndLimit
4911 * @return CRM_Core_DAO
4913 public function searchQuery(
4914 $offset = 0, $rowCount = 0, $sort = NULL,
4915 $count = FALSE, $includeContactIds = FALSE,
4916 $sortByChar = FALSE, $groupContacts = FALSE,
4917 $returnQuery = FALSE,
4918 $additionalWhereClause = NULL, $sortOrder = NULL,
4919 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4922 $query = $this->getSearchSQL($offset, $rowCount, $sort, $count, $includeContactIds, $sortByChar, $groupContacts, $additionalWhereClause, $sortOrder, $additionalFromClause, $skipOrderAndLimit);
4928 return CRM_Core_DAO
::singleValueQuery($query);
4931 $dao = CRM_Core_DAO
::executeQuery($query);
4933 // We can always call this - it will only re-enable if it was originally enabled.
4934 CRM_Core_DAO
::reenableFullGroupByMode();
4936 if ($groupContacts) {
4938 while ($dao->fetch()) {
4941 return implode(',', $ids);
4948 * Create and query the db for the list of all first letters used by contacts
4950 * @return CRM_Core_DAO
4952 public function alphabetQuery() {
4953 $sqlParts = $this->getSearchSQLParts(NULL, NULL, NULL, FALSE, FALSE, TRUE);
4954 $query = "SELECT DISTINCT LEFT(contact_a.sort_name, 1) as sort_name
4955 {$this->_simpleFromClause}
4956 {$sqlParts['where']}
4957 {$sqlParts['having']}
4959 ORDER BY sort_name asc";
4960 $dao = CRM_Core_DAO
::executeQuery($query);
4965 * Fetch a list of contacts for displaying a search results page
4967 * @param array $cids
4968 * List of contact IDs
4969 * @param bool $includeContactIds
4970 * @return CRM_Core_DAO
4972 public function getCachedContacts($cids, $includeContactIds) {
4973 CRM_Utils_Type
::validateAll($cids, 'Positive');
4974 $this->_includeContactIds
= $includeContactIds;
4975 $onlyDeleted = in_array(['deleted_contacts', '=', '1', '0', '0'], $this->_params
);
4976 list($select, $from, $where) = $this->query(FALSE, FALSE, FALSE, $onlyDeleted);
4977 $select .= sprintf(", (%s) AS _wgt", $this->createSqlCase('contact_a.id', $cids));
4978 $where .= sprintf(' AND contact_a.id IN (%s)', implode(',', $cids));
4979 $order = 'ORDER BY _wgt';
4980 $groupBy = $this->_useGroupBy ?
' GROUP BY contact_a.id' : '';
4982 $query = "$select $from $where $groupBy $order $limit";
4984 return CRM_Core_DAO
::executeQuery($query);
4988 * Construct a SQL CASE expression.
4990 * @param string $idCol
4991 * The name of a column with ID's (eg 'contact_a.id').
4992 * @param array $cids
4993 * Array(int $weight => int $id).
4995 * CASE WHEN id=123 THEN 1 WHEN id=456 THEN 2 END
4997 private function createSqlCase($idCol, $cids) {
4999 foreach ($cids as $weight => $cid) {
5000 $buf .= " WHEN $idCol = $cid THEN $weight \n";
5007 * Populate $this->_permissionWhereClause with permission related clause and update other
5008 * query related properties.
5010 * Function calls ACL permission class and hooks to filter the query appropriately
5012 * Note that these 2 params were in the code when extracted from another function
5013 * and a second round extraction would be to make them properties of the class
5015 * @param bool $onlyDeleted
5016 * Only get deleted contacts.
5017 * @param bool $count
5018 * Return Count only.
5020 public function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
5021 if (!$this->_skipPermission
) {
5022 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
5023 CRM_Core_Permission
::VIEW
,
5025 $this->_whereTables
,
5028 $this->_skipDeleteClause
5031 // regenerate fromClause since permission might have added tables
5032 if ($this->_permissionWhereClause
) {
5033 //fix for row count in qill (in contribute/membership find)
5035 $this->_useDistinct
= TRUE;
5038 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
5039 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
5040 // note : this modifies _fromClause and _simpleFromClause
5041 $this->includePseudoFieldsJoin($this->_sort
);
5045 // add delete clause if needed even if we are skipping permission
5047 if (!$this->_skipDeleteClause
) {
5048 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
5049 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
5053 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
5062 public function setSkipPermission($val) {
5063 $this->_skipPermission
= $val;
5067 * @param null $context
5071 public function summaryContribution($context = NULL) {
5072 list($innerselect, $from, $where, $having) = $this->query(TRUE);
5073 if ($this->_permissionWhereClause
) {
5074 $where .= " AND " . $this->_permissionWhereClause
;
5076 if ($context == 'search') {
5077 $where .= " AND contact_a.is_deleted = 0 ";
5080 $this->appendFinancialTypeWhereAndFromToQueryStrings($where, $from);
5082 $summary = ['total' => []];
5083 $this->addBasicStatsToSummary($summary, $where, $from);
5085 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
5086 $this->addBasicSoftCreditStatsToStats($summary, $where, $from);
5089 $this->addBasicCancelStatsToSummary($summary, $where, $from);
5095 * Append financial ACL limits to the query from & where clauses, if applicable.
5097 * @param string $where
5098 * @param string $from
5100 public function appendFinancialTypeWhereAndFromToQueryStrings(&$where, &$from) {
5101 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
5104 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
5105 if (!empty($financialTypes)) {
5106 $where .= " AND civicrm_contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND li.id IS NULL";
5107 $from .= " LEFT JOIN civicrm_line_item li
5108 ON civicrm_contribution.id = li.contribution_id AND
5109 li.entity_table = 'civicrm_contribution' AND li.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ") ";
5112 $where .= " AND civicrm_contribution.financial_type_id IN (0)";
5117 * Getter for the qill object.
5121 public function qill() {
5122 return $this->_qill
;
5126 * Default set of return default hier return properties.
5130 public static function &defaultHierReturnProperties() {
5131 if (!isset(self
::$_defaultHierReturnProperties)) {
5132 self
::$_defaultHierReturnProperties = [
5135 'legal_identifier' => 1,
5136 'external_identifier' => 1,
5137 'contact_type' => 1,
5138 'contact_sub_type' => 1,
5140 'display_name' => 1,
5147 'formal_title' => 1,
5148 'communication_style_id' => 1,
5149 'email_greeting' => 1,
5150 'postal_greeting' => 1,
5154 'preferred_communication_method' => 1,
5155 'do_not_phone' => 1,
5156 'do_not_email' => 1,
5159 'do_not_trade' => 1,
5162 'location_type' => 1,
5163 'street_address' => 1,
5165 'state_province' => 1,
5167 'postal_code_suffix' => 1,
5170 'phone-Mobile' => 1,
5183 'location_type' => 1,
5184 'street_address' => 1,
5186 'state_province' => 1,
5188 'postal_code_suffix' => 1,
5191 'phone-Mobile' => 1,
5205 return self
::$_defaultHierReturnProperties;
5209 * Build query for a date field.
5211 * @param array $values
5212 * @param string $tableName
5213 * @param string $fieldName
5214 * @param string $dbFieldName
5215 * @param string $fieldTitle
5216 * @param bool $appendTimeStamp
5217 * @param string $dateFormat
5219 public function dateQueryBuilder(
5220 &$values, $tableName, $fieldName,
5221 $dbFieldName, $fieldTitle,
5222 $appendTimeStamp = TRUE,
5223 $dateFormat = 'YmdHis'
5225 list($name, $op, $value, $grouping, $wildcard) = $values;
5227 if ($name == "{$fieldName}_low" ||
5228 $name == "{$fieldName}_high"
5230 if (isset($this->_rangeCache
[$fieldName]) ||
!$value) {
5233 $this->_rangeCache
[$fieldName] = 1;
5235 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
5237 if ($name == $fieldName . '_low') {
5239 $firstPhrase = ts('greater than or equal to');
5240 $firstDate = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5242 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5243 if (!empty($secondValues) && $secondValues[2]) {
5245 $secondPhrase = ts('less than or equal to');
5246 $secondValue = $secondValues[2];
5248 if ($appendTimeStamp && strlen($secondValue) == 10) {
5249 $secondValue .= ' 23:59:59';
5251 $secondDate = CRM_Utils_Date
::processDate($secondValue, NULL, FALSE, $dateFormat);
5254 elseif ($name == $fieldName . '_high') {
5256 $firstPhrase = ts('less than or equal to');
5258 if ($appendTimeStamp && strlen($value) == 10) {
5259 $value .= ' 23:59:59';
5261 $firstDate = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5263 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5264 if (!empty($secondValues) && $secondValues[2]) {
5266 $secondPhrase = ts('greater than or equal to');
5267 $secondValue = $secondValues[2];
5268 $secondDate = CRM_Utils_Date
::processDate($secondValue, NULL, FALSE, $dateFormat);
5272 if (!$appendTimeStamp) {
5273 $firstDate = substr($firstDate, 0, 8);
5275 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
5278 if (!$appendTimeStamp) {
5279 $secondDate = substr($secondDate, 0, 8);
5281 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
5284 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5286 $this->_where
[$grouping][] = "
5287 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5288 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5290 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
5293 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5294 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5298 if ($name == $fieldName) {
5299 //In Get API, for operators other then '=' the $value is in array(op => value) format
5300 if (is_array($value) && !empty($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
5302 $value = $value[$op];
5305 $date = $format = NULL;
5306 if (strstr($op, 'IN')) {
5308 foreach ($value as &$date) {
5309 $date = CRM_Utils_Date
::processDate($date, NULL, FALSE, $dateFormat);
5310 if (!$appendTimeStamp) {
5311 $date = substr($date, 0, 8);
5313 $format[] = CRM_Utils_Date
::customFormat($date);
5315 $date = "('" . implode("','", $value) . "')";
5316 $format = implode(', ', $format);
5318 elseif ($value && (!strstr($op, 'NULL') && !strstr($op, 'EMPTY'))) {
5319 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5320 if (!$appendTimeStamp) {
5321 $date = substr($date, 0, 8);
5323 $format = CRM_Utils_Date
::customFormat($date);
5328 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op $date";
5331 $this->_where
[$grouping][] = self
::buildClause("{$tableName}.{$dbFieldName}", $op);
5334 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5336 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
5337 $this->_qill
[$grouping][] = "$fieldTitle $op $format";
5343 * @param string $tableName
5344 * @param string $fieldName
5345 * @param string $dbFieldName
5346 * @param $fieldTitle
5347 * @param null $options
5349 public function numberRangeBuilder(
5351 $tableName, $fieldName,
5352 $dbFieldName, $fieldTitle,
5355 list($name, $op, $value, $grouping, $wildcard) = $values;
5357 if ($name == "{$fieldName}_low" ||
5358 $name == "{$fieldName}_high"
5360 if (isset($this->_rangeCache
[$fieldName])) {
5363 $this->_rangeCache
[$fieldName] = 1;
5365 $secondOP = $secondPhrase = $secondValue = NULL;
5367 if ($name == "{$fieldName}_low") {
5369 $firstPhrase = ts('greater than');
5371 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5372 if (!empty($secondValues)) {
5374 $secondPhrase = ts('less than');
5375 $secondValue = $secondValues[2];
5380 $firstPhrase = ts('less than');
5382 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5383 if (!empty($secondValues)) {
5385 $secondPhrase = ts('greater than');
5386 $secondValue = $secondValues[2];
5391 $this->_where
[$grouping][] = "
5392 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5393 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5395 $displayValue = $options ?
$options[$value] : $value;
5396 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5398 $this->_qill
[$grouping][]
5399 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5402 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5403 $displayValue = $options ?
$options[$value] : $value;
5404 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5406 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5411 if ($name == $fieldName) {
5415 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5417 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5418 $displayValue = $options ?
$options[$value] : $value;
5419 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5425 * @param string $tableName
5426 * @param string $fieldName
5427 * @param string $dbFieldName
5428 * @param $fieldTitle
5429 * @param null $options
5431 public function ageRangeQueryBuilder(
5433 $tableName, $fieldName,
5434 $dbFieldName, $fieldTitle,
5437 list($name, $op, $value, $grouping, $wildcard) = $values;
5439 $asofDateValues = $this->getWhereValues("{$fieldName}_asof_date", $grouping);
5440 // will be treated as current day
5442 if ($asofDateValues) {
5443 $asofDate = CRM_Utils_Date
::processDate($asofDateValues[2]);
5444 $asofDateFormat = CRM_Utils_Date
::customFormat(substr($asofDate, 0, 8));
5445 $fieldTitle .= ' ' . ts('as of') . ' ' . $asofDateFormat;
5448 if ($name == "{$fieldName}_low" ||
5449 $name == "{$fieldName}_high"
5451 if (isset($this->_rangeCache
[$fieldName])) {
5454 $this->_rangeCache
[$fieldName] = 1;
5456 $secondOP = $secondPhrase = $secondValue = NULL;
5458 if ($name == "{$fieldName}_low") {
5459 $firstPhrase = ts('greater than or equal to');
5460 // NB: age > X means date of birth < Y
5462 $firstDate = self
::calcDateFromAge($asofDate, $value, 'min');
5464 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5465 if (!empty($secondValues)) {
5467 $secondPhrase = ts('less than or equal to');
5468 $secondValue = $secondValues[2];
5469 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'max');
5474 $firstPhrase = ts('less than or equal to');
5475 $firstDate = self
::calcDateFromAge($asofDate, $value, 'max');
5477 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5478 if (!empty($secondValues)) {
5480 $secondPhrase = ts('greater than or equal to');
5481 $secondValue = $secondValues[2];
5482 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'min');
5487 $this->_where
[$grouping][] = "
5488 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5489 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5491 $displayValue = $options ?
$options[$value] : $value;
5492 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5494 $this->_qill
[$grouping][]
5495 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5498 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5499 $displayValue = $options ?
$options[$value] : $value;
5500 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5502 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5508 * Calculate date from age.
5510 * @param string $asofDate
5512 * @param string $type
5516 public static function calcDateFromAge($asofDate, $age, $type) {
5517 $date = new DateTime($asofDate);
5518 if ($type == "min") {
5519 // minimum age is $age: dob <= date - age "235959"
5520 $date->sub(new DateInterval("P" . $age . "Y"));
5521 return $date->format('Ymd') . "235959";
5524 // max age is $age: dob >= date - (age + 1y) + 1d "000000"
5525 $date->sub(new DateInterval("P" . ($age +
1) . "Y"))->add(new DateInterval("P1D"));
5526 return $date->format('Ymd') . "000000";
5531 * Given the field name, operator, value & its data type
5532 * builds the where Clause for the query
5533 * used for handling 'IS NULL'/'IS NOT NULL' operators
5535 * @param string $field
5539 * @param string $value
5541 * @param string $dataType
5542 * Data type of the field.
5545 * Where clause for the query.
5547 public static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5549 $clause = "$field $op";
5557 $clause = ($dataType == 'Date') ?
" $field IS NULL " : " (NULLIF($field, '') IS NULL) ";
5560 case 'IS NOT EMPTY':
5561 $clause = ($dataType == 'Date') ?
" $field IS NOT NULL " : " (NULLIF($field, '') IS NOT NULL) ";
5565 return " {$clause} BINARY '{$value}' ";
5569 // I feel like this would be escaped properly if passed through $queryString = CRM_Core_DAO::createSqlFilter.
5570 if (!empty($value) && (!is_array($value) ||
!array_key_exists($op, $value))) {
5571 $value = [$op => (array) $value];
5575 if (empty($dataType) ||
$dataType == 'Date') {
5576 $dataType = 'String';
5578 if (is_array($value)) {
5579 //this could have come from the api - as in the restWhere section we potentially use the api operator syntax which is becoming more
5580 // widely used and consistent across the codebase
5581 // adding this here won't accept the search functions which don't submit an array
5582 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, $value, $dataType)) != FALSE) {
5584 return $queryString;
5586 if (!empty($value[0]) && $op === 'BETWEEN') {
5587 CRM_Core_Error
::deprecatedFunctionWarning('Fix search input params');
5588 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, [$op => $value], $dataType)) != FALSE) {
5589 return $queryString;
5592 throw new CRM_Core_Exception(ts('Failed to interpret input for search'));
5595 $value = CRM_Utils_Type
::escape($value, $dataType);
5596 // if we don't have a dataType we should assume
5597 if ($dataType == 'String' ||
$dataType == 'Text') {
5598 $value = "'" . $value . "'";
5600 return "$clause $value";
5605 * @param bool $reset
5609 public function openedSearchPanes($reset = FALSE) {
5610 if (!$reset ||
empty($this->_whereTables
)) {
5611 return self
::$_openedPanes;
5614 // pane name to table mapper
5616 ts('Contributions') => 'civicrm_contribution',
5617 ts('Memberships') => 'civicrm_membership',
5618 ts('Events') => 'civicrm_participant',
5619 ts('Relationships') => 'civicrm_relationship',
5620 ts('Activities') => 'civicrm_activity',
5621 ts('Pledges') => 'civicrm_pledge',
5622 ts('Cases') => 'civicrm_case',
5623 ts('Grants') => 'civicrm_grant',
5624 ts('Address Fields') => 'civicrm_address',
5625 ts('Notes') => 'civicrm_note',
5626 ts('Change Log') => 'civicrm_log',
5627 ts('Mailings') => 'civicrm_mailing',
5629 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
5631 foreach (array_keys($this->_whereTables
) as $table) {
5632 if ($panName = array_search($table, $panesMapper)) {
5633 self
::$_openedPanes[$panName] = TRUE;
5637 return self
::$_openedPanes;
5643 public function setOperator($operator) {
5644 $validOperators = ['AND', 'OR'];
5645 if (!in_array($operator, $validOperators)) {
5648 $this->_operator
= $operator;
5654 public function getOperator() {
5655 return $this->_operator
;
5663 public function filterRelatedContacts(&$from, &$where, &$having) {
5664 if (!isset(Civi
::$statics[__CLASS__
]['related_contacts_filter'])) {
5665 Civi
::$statics[__CLASS__
]['related_contacts_filter'] = [];
5667 $_rTempCache =& Civi
::$statics[__CLASS__
]['related_contacts_filter'];
5668 // since there only can be one instance of this filter in every query
5669 // skip if filter has already applied
5670 foreach ($_rTempCache as $acache) {
5671 foreach ($acache['queries'] as $aqcache) {
5672 if (strpos($from, $aqcache['from']) !== FALSE) {
5678 $arg_sig = sha1("$from $where $having");
5679 if (isset($_rTempCache[$arg_sig])) {
5680 $cache = $_rTempCache[$arg_sig];
5683 // create temp table with contact ids
5684 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
5686 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
5687 CRM_Core_DAO
::executeQuery($sql);
5690 REPLACE INTO $tableName ( contact_id )
5696 CRM_Core_DAO
::executeQuery($sql);
5698 $cache = ['tableName' => $tableName, 'queries' => []];
5699 $_rTempCache[$arg_sig] = $cache;
5701 // upsert the query depending on relationship type
5702 if (isset($cache['queries'][$this->_displayRelationshipType
])) {
5703 $qcache = $cache['queries'][$this->_displayRelationshipType
];
5706 $tableName = $cache['tableName'];
5711 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5712 if (is_numeric($this->_displayRelationshipType
)) {
5713 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5715 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5716 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5718 $qcache['where'] = "
5719 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5720 AND displayRelType.is_active = 1
5724 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5725 if ($dirOne == 'a') {
5726 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5727 $qcache['from'] .= "
5728 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5729 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5733 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5734 $qcache['from'] .= "
5735 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5736 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5739 $qcache['where'] = "
5740 WHERE displayRelType.relationship_type_id = $relType
5741 AND displayRelType.is_active = 1
5744 $qcache['relTypeLabel'] = $relationshipTypeLabel;
5745 $_rTempCache[$arg_sig]['queries'][$this->_displayRelationshipType
] = $qcache;
5747 $qillMessage = ts('Contacts with a Relationship Type of: ');
5748 $iqill = $qillMessage . "'" . $qcache['relTypeLabel'] . "'";
5749 if (!is_array($this->_qill
[0]) ||
!in_array($iqill, $this->_qill
[0])) {
5750 $this->_qill
[0][] = $iqill;
5752 if (strpos($from, $qcache['from']) === FALSE) {
5753 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5754 // this happens when we have an event_type in the quert (CRM-7969)
5755 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5756 $from .= $qcache['from'];
5757 $where = $qcache['where'];
5758 if (!empty($this->_permissionWhereClause
)) {
5759 $where .= "AND $this->_permissionWhereClause";
5767 * See CRM-19811 for why this is database hurty without apparent benefit.
5773 public static function caseImportant($op) {
5774 return in_array($op, ['LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY']) ?
FALSE : TRUE;
5778 * @param $returnProperties
5783 public static function componentPresent(&$returnProperties, $prefix) {
5784 foreach ($returnProperties as $name => $dontCare) {
5785 if (substr($name, 0, strlen($prefix)) == $prefix) {
5793 * Builds the necessary structures for all fields that are similar to option value look-ups.
5795 * @param string $name
5796 * the name of the field.
5798 * the sql operator, this function should handle ALL SQL operators.
5799 * @param string $value
5800 * depends on the operator and who's calling the query builder.
5801 * @param int $grouping
5802 * the index where to place the where clause.
5803 * @param string $daoName
5805 * @param array $field
5806 * an array that contains various properties of the field identified by $name.
5807 * @param string $label
5808 * The label for this field element.
5809 * @param string $dataType
5810 * The data type for this element.
5811 * @param bool $useIDsOnly
5813 public function optionValueQuery(
5821 $dataType = 'String',
5832 'communication_style_id',
5836 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5837 if ($tableName == 'civicrm_contact') {
5838 $wc = "contact_a.$fieldName";
5841 // Special handling for on_hold, so that we actually use the 'where'
5842 // property in order to limit the query by the on_hold status of the email,
5843 // instead of using email.id which would be nonsensical.
5844 if ($field['name'] == 'on_hold') {
5845 $wc = "{$field['where']}";
5848 $wc = "$tableName.id";
5853 CRM_Core_Error
::deprecatedFunctionWarning('pass $ids to this method');
5854 $wc = "{$field['where']}";
5856 if (in_array($name, $pseudoFields)) {
5857 if (!in_array($name, ['gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'])) {
5858 $wc = "contact_a.{$name}_id";
5860 $dataType = 'Positive';
5861 $value = (!$value) ?
0 : $value;
5863 if ($name == "world_region") {
5864 $field['name'] = $name;
5867 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue($daoName, $field['name'], $value, $op);
5868 $this->_qill
[$grouping][] = ts("%1 %2 %3", [1 => $label, 2 => $qillop, 3 => $qillVal]);
5869 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5873 * Check and explode a user defined numeric string into an array
5874 * this was the protocol used by search builder in the old old days before we had
5875 * super nice js widgets to do the hard work
5877 * @param string $string
5878 * @param string $dataType
5879 * The dataType we should check for the values, default integer.
5881 * @return bool|array
5882 * false if string does not match the pattern
5883 * array of numeric values if string does match the pattern
5885 public static function parseSearchBuilderString($string, $dataType = 'Integer') {
5886 $string = trim($string);
5887 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5891 $string = substr($string, 1, -1);
5892 $values = explode(',', $string);
5893 if (empty($values)) {
5898 foreach ($values as $v) {
5899 if ($dataType == 'Integer' && !is_numeric($v)) {
5902 elseif ($dataType == 'String' && !is_string($v)) {
5905 $returnValues[] = trim($v);
5908 if (empty($returnValues)) {
5912 return $returnValues;
5916 * Convert the pseudo constants id's to their names
5918 * @param CRM_Core_DAO $dao
5919 * @param bool $return
5920 * @param bool $usedForAPI
5922 * @return array|NULL
5924 public function convertToPseudoNames(&$dao, $return = FALSE, $usedForAPI = FALSE) {
5925 if (empty($this->_pseudoConstantsSelect
)) {
5929 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5930 if (!empty($this->_pseudoConstantsSelect
[$key]['sorting'])) {
5934 if (is_object($dao) && property_exists($dao, $value['idCol'])) {
5935 $val = $dao->{$value['idCol']};
5936 if ($key == 'groups') {
5937 $dao->groups
= $this->convertGroupIDStringToLabelString($dao, $val);
5941 if (CRM_Utils_System
::isNull($val)) {
5944 elseif (!empty($value['pseudoconstant'])) {
5945 // If pseudoconstant is set that is kind of defacto for 'we have a bit more info about this'
5946 // and we can use the metadata to figure it out.
5947 // ideally this bit of IF will absorb & replace all the rest in time as we move to
5948 // more metadata based choices.
5949 if (strpos($val, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
5950 $dbValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($val, CRM_Core_DAO
::VALUE_SEPARATOR
));
5951 foreach ($dbValues as $pseudoValue) {
5952 $convertedValues[] = CRM_Core_PseudoConstant
::getLabel($value['bao'], $value['idCol'], $pseudoValue);
5955 $dao->$key = ($usedForAPI) ?
$convertedValues : implode(', ', $convertedValues);
5956 $realFieldName = CRM_Utils_Array
::value('field_name', $this->_pseudoConstantsSelect
[$key]);
5957 if ($usedForAPI && $realFieldName) {
5958 // normally we would see 2 fields returned for pseudoConstants. An exception is
5959 // preferred_communication_method where there is no id-variant.
5960 // For the api we prioritise getting the real data returned.
5961 // over the resolved version
5962 $dao->$realFieldName = $dbValues;
5967 // This is basically the same as the default but since we have the bao we can use
5968 // a cached function.
5969 $dao->$key = CRM_Core_PseudoConstant
::getLabel($value['bao'], $value['idCol'], $val);
5972 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
5974 $idColumn = "{$key}_id";
5975 $dao->$idColumn = $val;
5977 if ($key == 'state_province_name') {
5978 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::stateProvince($val);
5981 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
5984 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5985 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5987 // @todo handle this in the section above for pseudoconstants.
5988 elseif (in_array($value['pseudoField'], ['participant_role_id', 'participant_role'])) {
5989 // @todo define bao on this & merge into the above condition.
5990 $viewValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $val);
5992 if ($value['pseudoField'] == 'participant_role') {
5993 $pseudoOptions = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'role_id');
5994 foreach ($viewValues as $k => $v) {
5995 $viewValues[$k] = $pseudoOptions[$v];
5998 $dao->$key = ($usedForAPI && count($viewValues) > 1) ?
$viewValues : implode(', ', $viewValues);
6001 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
6002 $dao->$key = $labels[$val];
6005 // return converted values in array format
6007 if (strpos($key, '-') !== FALSE) {
6008 $keyVal = explode('-', $key);
6009 $current = &$values;
6010 $lastElement = array_pop($keyVal);
6011 foreach ($keyVal as $v) {
6012 if (!array_key_exists($v, $current)) {
6015 $current = &$current[$v];
6017 $current[$lastElement] = $dao->$key;
6020 $values[$key] = $dao->$key;
6027 'gender_id' => 'gender',
6028 'prefix_id' => 'individual_prefix',
6029 'suffix_id' => 'individual_suffix',
6030 'communication_style_id' => 'communication_style',
6031 ] as $realField => $labelField) {
6032 // This is a temporary routine for handling these fields while
6033 // we figure out how to handled them based on metadata in
6034 /// export and search builder. CRM-19815, CRM-19830.
6035 if (isset($dao->$realField) && is_numeric($dao->$realField) && isset($dao->$labelField)) {
6036 $dao->$realField = $dao->$labelField;
6044 * Include pseudo fields LEFT JOIN.
6045 * @param string|array $sort can be a object or string
6047 * @return array|NULL
6049 public function includePseudoFieldsJoin($sort) {
6050 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
6053 $sort = is_string($sort) ?
$sort : $sort->orderBy();
6056 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
6057 if (!empty($value['table'])) {
6058 $regex = "/({$value['table']}\.|{$name})/";
6059 if (preg_match($regex, $sort)) {
6060 $this->_elemnt
[$value['element']] = 1;
6061 $this->_select
[$value['element']] = $value['select'];
6062 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
6063 $present[$value['table']] = $value['join'];
6067 $presentSimpleFrom = $present;
6069 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
6070 array_key_exists('civicrm_country', $presentSimpleFrom)
6072 unset($presentSimpleFrom['civicrm_country']);
6074 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
6075 array_key_exists('civicrm_country', $present)
6077 unset($present['civicrm_country']);
6080 $presentClause = $presentSimpleFromClause = NULL;
6081 if (!empty($present)) {
6082 $presentClause = implode(' ', $present);
6084 if (!empty($presentSimpleFrom)) {
6085 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
6088 $this->_fromClause
= $this->_fromClause
. $presentClause;
6089 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
6091 return [$presentClause, $presentSimpleFromClause];
6095 * Build qill for field.
6097 * Qill refers to the query detail visible on the UI.
6099 * @param string $daoName
6100 * @param string $fieldName
6101 * @param mixed $fieldValue
6103 * @param array $pseudoExtraParam
6105 * Type of the field per CRM_Utils_Type
6109 public static function buildQillForFieldValue(
6114 $pseudoExtraParam = [],
6115 $type = CRM_Utils_Type
::T_STRING
6117 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
6119 //API usually have fieldValue format as array(operator => array(values)),
6120 //so we need to separate operator out of fieldValue param
6121 if (is_array($fieldValue) && in_array(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
6122 $op = key($fieldValue);
6123 $fieldValue = $fieldValue[$op];
6126 // if Operator chosen is NULL/EMPTY then
6127 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
6128 return [CRM_Utils_Array
::value($op, $qillOperators, $op), ''];
6131 if ($fieldName == 'activity_type_id') {
6132 $pseudoOptions = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE);
6134 elseif ($fieldName == 'country_id') {
6135 $pseudoOptions = CRM_Core_PseudoConstant
::country();
6137 elseif ($fieldName == 'county_id') {
6138 $pseudoOptions = CRM_Core_PseudoConstant
::county();
6140 elseif ($fieldName == 'world_region') {
6141 $pseudoOptions = CRM_Core_PseudoConstant
::worldRegion();
6143 elseif ($daoName == 'CRM_Event_DAO_Event' && $fieldName == 'id') {
6144 $checkPermission = CRM_Utils_Array
::value('check_permission', $pseudoExtraParam, TRUE);
6145 $pseudoOptions = CRM_Event_BAO_Event
::getEvents(0, $fieldValue, TRUE, $checkPermission, TRUE);
6147 elseif ($fieldName == 'contribution_product_id') {
6148 $pseudoOptions = CRM_Contribute_PseudoConstant
::products();
6150 elseif ($daoName == 'CRM_Contact_DAO_Group' && $fieldName == 'id') {
6151 $pseudoOptions = CRM_Core_PseudoConstant
::group();
6153 elseif ($daoName == 'CRM_Batch_BAO_EntityBatch' && $fieldName == 'batch_id') {
6154 $pseudoOptions = CRM_Contribute_PseudoConstant
::batch();
6157 $pseudoOptions = CRM_Core_PseudoConstant
::get($daoName, $fieldName, $pseudoExtraParam);
6160 if (is_array($fieldValue)) {
6162 if (!empty($pseudoOptions)) {
6163 foreach ((array) $fieldValue as $val) {
6164 $qillString[] = CRM_Utils_Array
::value($val, $pseudoOptions, $val);
6166 $fieldValue = implode(', ', $qillString);
6169 if ($type == CRM_Utils_Type
::T_DATE
) {
6170 foreach ($fieldValue as $index => $value) {
6171 $fieldValue[$index] = CRM_Utils_Date
::customFormat($value);
6175 // @todo - this is a bit specific (one operator).
6176 // However it is covered by a unit test so can be altered later with
6178 if ($op == 'BETWEEN') {
6179 $separator = ' AND ';
6181 $fieldValue = implode($separator, $fieldValue);
6184 elseif (!empty($pseudoOptions) && array_key_exists($fieldValue, $pseudoOptions)) {
6185 $fieldValue = $pseudoOptions[$fieldValue];
6187 elseif ($type === CRM_Utils_Type
::T_DATE
) {
6188 $fieldValue = CRM_Utils_Date
::customFormat($fieldValue);
6191 return [CRM_Utils_Array
::value($op, $qillOperators, $op), $fieldValue];
6195 * Alter value to reflect wildcard settings.
6197 * The form will have tried to guess whether this is a good field to wildcard but there is
6198 * also a site-wide setting that specifies whether it is OK to append the wild card to the beginning
6199 * or only the end of the string
6201 * @param bool $wildcard
6202 * This is a bool made on an assessment 'elsewhere' on whether this is a good field to wildcard.
6204 * Generally '=' or 'LIKE'.
6205 * @param string $value
6206 * The search string.
6210 public static function getWildCardedValue($wildcard, $op, $value) {
6211 if ($wildcard && $op == 'LIKE') {
6212 if (CRM_Core_Config
::singleton()->includeWildCardInName
&& (substr($value, 0, 1) != '%')) {
6225 * Process special fields of Search Form in OK (Operator in Key) format
6227 * @param array $formValues
6228 * @param array $specialFields
6229 * Special params to be processed
6230 * @param array $changeNames
6231 * Array of fields whose name should be changed
6233 public static function processSpecialFormValue(&$formValues, $specialFields, $changeNames = []) {
6234 // Array of special fields whose value are considered only for NULL or EMPTY operators
6235 $nullableFields = ['contribution_batch_id'];
6237 foreach ($specialFields as $element) {
6238 $value = CRM_Utils_Array
::value($element, $formValues);
6240 if (is_array($value)) {
6241 if (in_array($element, array_keys($changeNames))) {
6242 unset($formValues[$element]);
6243 $element = $changeNames[$element];
6245 $formValues[$element] = ['IN' => $value];
6247 elseif (in_array($value, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
6248 $formValues[$element] = [$value => 1];
6250 elseif (!in_array($element, $nullableFields)) {
6251 // if wildcard is already present return searchString as it is OR append and/or prepend with wildcard
6252 $isWilcard = strstr($value, '%') ?
FALSE : CRM_Core_Config
::singleton()->includeWildCardInName
;
6253 $formValues[$element] = ['LIKE' => self
::getWildCardedValue($isWilcard, 'LIKE', $value)];
6260 * Parse and assimilate the various sort options.
6262 * Side-effect: if sorting on a common column from a related table (`city`, `postal_code`,
6263 * `email`), the related table may be joined automatically.
6265 * At time of writing, this code is deeply flawed and should be rewritten. For the moment,
6266 * it's been extracted to a standalone function.
6268 * @param string|CRM_Utils_Sort $sort
6269 * The order by string.
6270 * @param null $sortOrder
6271 * Who knows? Hu knows. He who knows Hu knows who.
6274 * list(string $orderByClause, string $additionalFromClause).
6276 protected function prepareOrderBy($sort, $sortOrder) {
6280 if (CRM_Core_Config
::singleton()->includeOrderByClause ||
6281 isset($this->_distinctComponentClause
)
6284 if (is_string($sort)) {
6288 $orderBy = trim($sort->orderBy());
6290 // Deliberately remove the backticks again, as they mess up the evil
6291 // string munging below. This balanced by re-escaping before use.
6292 $orderBy = str_replace('`', '', $orderBy);
6294 if (!empty($orderBy)) {
6295 // this is special case while searching for
6296 // change log CRM-1718
6297 if (preg_match('/sort_name/i', $orderBy)) {
6298 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
6302 $orderBy .= " $sortOrder";
6305 // always add contact_a.id to the ORDER clause
6306 // so the order is deterministic
6307 if (strpos('contact_a.id', $orderBy) === FALSE) {
6308 $orderBy .= ", contact_a.id";
6313 $orderBy = " contact_a.sort_name ASC, contact_a.id";
6319 // Remove this here & add it at the end for simplicity.
6320 $order = trim($orderBy);
6321 $orderByArray = explode(',', $order);
6323 foreach ($orderByArray as $orderByClause) {
6324 $orderByClauseParts = explode(' ', trim($orderByClause));
6325 $field = $orderByClauseParts[0];
6326 $direction = isset($orderByClauseParts[1]) ?
$orderByClauseParts[1] : 'asc';
6327 $fieldSpec = $this->getMetadataForRealField($field);
6329 // This is a hacky add-in for primary address joins. Feel free to iterate as it is unit tested.
6330 // @todo much more cleanup on location handling in addHierarchical elements. Potentially
6331 // add keys to $this->fields to represent the actual keys for locations.
6332 if (empty($fieldSpec) && substr($field, 0, 2) === '1-') {
6333 $fieldSpec = $this->getMetadataForField(substr($field, 2));
6334 $this->addAddressTable('1-' . str_replace('civicrm_', '', $fieldSpec['table_name']), 'is_primary = 1');
6337 if ($this->_returnProperties
=== []) {
6338 if (!empty($fieldSpec['table_name']) && !isset($this->_tables
[$fieldSpec['table_name']])) {
6339 $this->_tables
[$fieldSpec['table_name']] = 1;
6340 $order = $fieldSpec['where'] . ' ' . $direction;
6344 $cfID = CRM_Core_BAO_CustomField
::getKeyID($field);
6345 // add to cfIDs array if not present
6346 if (!empty($cfID) && !array_key_exists($cfID, $this->_cfIDs
)) {
6347 $this->_cfIDs
[$cfID] = [];
6348 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
6349 $this->_customQuery
->query();
6350 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
6351 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
6354 // By replacing the join to the option value table with the mysql construct
6355 // ORDER BY field('contribution_status_id', 2,1,4)
6356 // we can remove a join. In the case of the option value join it is
6357 /// a join known to cause slow queries.
6358 // @todo cover other pseudoconstant types. Limited to option group ones & Foreign keys
6359 // matching an id+name parrern in the
6360 // first instance for scope reasons. They require slightly different handling as the column (label)
6361 // is not declared for them.
6362 // @todo so far only integer fields are being handled. If we add string fields we need to look at
6364 $pseudoConstantMetadata = CRM_Utils_Array
::value('pseudoconstant', $fieldSpec, FALSE);
6365 if (!empty($pseudoConstantMetadata)
6367 if (!empty($pseudoConstantMetadata['optionGroupName'])
6368 ||
$this->isPseudoFieldAnFK($fieldSpec)
6370 $sortedOptions = $fieldSpec['bao']::buildOptions($fieldSpec['name'], NULL, [
6371 'orderColumn' => CRM_Utils_Array
::value('labelColumn', $pseudoConstantMetadata, 'label'),
6373 $fieldIDsInOrder = implode(',', array_keys($sortedOptions));
6374 // Pretty sure this validation ALSO happens in the order clause & this can't be reached but...
6375 // this might give some early warning.
6376 CRM_Utils_Type
::validate($fieldIDsInOrder, 'CommaSeparatedIntegers');
6377 $order = str_replace("$field", "field({$fieldSpec['name']},$fieldIDsInOrder)", $order);
6379 //CRM-12565 add "`" around $field if it is a pseudo constant
6380 // This appears to be for 'special' fields like locations with appended numbers or hyphens .. maybe.
6381 if (!empty($pseudoConstantMetadata['element']) && $pseudoConstantMetadata['element'] == $field) {
6382 $order = str_replace($field, "`{$field}`", $order);
6387 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6388 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6390 // The above code relies on crazy brittle string manipulation of a peculiarly-encoded ORDER BY
6391 // clause. But this magic helper which forgivingly reescapes ORDER BY.
6393 $order = CRM_Utils_Type
::escape($order, 'MysqlOrderBy');
6394 return ' ORDER BY ' . $order;
6399 * Convert a string of group IDs to a string of group labels.
6401 * The original string may include duplicates and groups the user does not have
6402 * permission to see.
6404 * @param CRM_Core_DAO $dao
6405 * @param string $val
6409 public function convertGroupIDStringToLabelString(&$dao, $val) {
6410 $groupIDs = explode(',', $val);
6411 // Note that groups that the user does not have permission to will be excluded (good).
6412 $groups = array_intersect_key(CRM_Core_PseudoConstant
::group(), array_flip($groupIDs));
6413 return implode(', ', $groups);
6418 * Set the qill and where properties for a field.
6420 * This function is intended as a short-term function to encourage refactoring
6421 * & re-use - but really we should just have less special-casing.
6423 * @param string $name
6425 * @param string|array $value
6426 * @param string $grouping
6427 * @param string $field
6429 public function setQillAndWhere($name, $op, $value, $grouping, $field) {
6430 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
6431 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
6432 $this->_qill
[$grouping][] = ts("%1 %2 %3", [
6433 1 => $field['title'],
6440 * Has the pseudoconstant of the field been requested.
6442 * For example if the field is payment_instrument_id then it
6443 * has been requested if either payment_instrument_id or payment_instrument
6444 * have been requested. Payment_instrument is the option groun name field value.
6446 * @param array $field
6447 * @param string $fieldName
6448 * The unique name of the field - ie. the one it will be aliased to in the query.
6452 private function pseudoConstantNameIsInReturnProperties($field, $fieldName = NULL) {
6453 $realField = $this->getMetadataForRealField($fieldName);
6454 if (!isset($realField['pseudoconstant'])) {
6457 $pseudoConstant = $realField['pseudoconstant'];
6458 if (empty($pseudoConstant['optionGroupName']) &&
6459 CRM_Utils_Array
::value('labelColumn', $pseudoConstant) !== 'name') {
6460 // We are increasing our pseudoconstant handling - but still very cautiously,
6461 // hence the check for labelColumn === name
6465 if (!empty($pseudoConstant['optionGroupName']) && CRM_Utils_Array
::value($pseudoConstant['optionGroupName'], $this->_returnProperties
)) {
6468 if (CRM_Utils_Array
::value($fieldName, $this->_returnProperties
)) {
6471 // Is this still required - the above goes off the unique name. Test with things like
6472 // communication_preferences & prefix_id.
6473 if (CRM_Utils_Array
::value($field['name'], $this->_returnProperties
)) {
6480 * Get Select Clause.
6484 public function getSelect() {
6485 $select = "SELECT ";
6486 if (isset($this->_distinctComponentClause
)) {
6487 $select .= "{$this->_distinctComponentClause}, ";
6489 $select .= implode(', ', $this->_select
);
6494 * Add basic statistics to the summary.
6496 * @param array $summary
6497 * @param string $where
6498 * @param string $from
6502 protected function addBasicStatsToSummary(&$summary, $where, $from) {
6503 $summary['total']['count'] = 0;
6504 $summary['total']['amount'] = $summary['total']['avg'] = [];
6507 SELECT COUNT( conts.total_amount ) as total_count,
6508 SUM( conts.total_amount ) as total_amount,
6509 AVG( conts.total_amount ) as total_avg,
6510 conts.currency as currency
6512 SELECT civicrm_contribution.total_amount, COUNT(civicrm_contribution.total_amount) as civicrm_contribution_total_amount_count,
6513 civicrm_contribution.currency
6515 $where AND civicrm_contribution.contribution_status_id = 1
6516 GROUP BY civicrm_contribution.id
6520 $dao = CRM_Core_DAO
::executeQuery($query);
6522 while ($dao->fetch()) {
6523 $summary['total']['count'] +
= $dao->total_count
;
6524 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
6525 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
6528 if (!empty($summary['total']['amount'])) {
6529 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
6530 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
6533 $summary['total']['amount'] = $summary['total']['avg'] = 0;
6539 * Add basic soft credit statistics to summary array.
6541 * @param array $summary
6542 * @param string $where
6543 * @param string $from
6545 protected function addBasicSoftCreditStatsToStats(&$summary, $where, $from) {
6547 SELECT COUNT( conts.total_amount ) as total_count,
6548 SUM( conts.total_amount ) as total_amount,
6549 AVG( conts.total_amount ) as total_avg,
6550 conts.currency as currency
6552 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency
6554 $where AND civicrm_contribution.contribution_status_id = 1 AND civicrm_contribution_soft.id IS NOT NULL
6555 GROUP BY civicrm_contribution_soft.id
6559 $dao = CRM_Core_DAO
::executeQuery($query);
6560 $summary['soft_credit']['count'] = 0;
6561 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = [];
6562 while ($dao->fetch()) {
6563 $summary['soft_credit']['count'] +
= $dao->total_count
;
6564 $summary['soft_credit']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
6565 $summary['soft_credit']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
6567 if (!empty($summary['soft_credit']['amount'])) {
6568 $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
6569 $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
6572 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
6577 * Add basic stats about cancelled contributions to the summary.
6579 * @param array $summary
6580 * @param string $where
6581 * @param string $from
6583 protected function addBasicCancelStatsToSummary(&$summary, $where, $from) {
6585 SELECT COUNT( conts.total_amount ) as cancel_count,
6586 SUM( conts.total_amount ) as cancel_amount,
6587 AVG( conts.total_amount ) as cancel_avg,
6588 conts.currency as currency
6590 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency
6592 $where AND civicrm_contribution.cancel_date IS NOT NULL
6593 GROUP BY civicrm_contribution.id
6597 $dao = CRM_Core_DAO
::executeQuery($query);
6600 if ($dao->fetch()) {
6601 $summary['cancel']['count'] = $dao->cancel_count
;
6602 $summary['cancel']['amount'] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
6603 $summary['cancel']['avg'] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
6607 $summary['cancel']['count'] = 0;
6608 $summary['cancel']['amount'] = $summary['cancel']['avg'] = [];
6609 while ($dao->fetch()) {
6610 $summary['cancel']['count'] +
= $dao->cancel_count
;
6611 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
6612 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
6614 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
6615 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
6620 * Create the sql query for an contact search.
6622 * @param int $offset
6623 * The offset for the query.
6624 * @param int $rowCount
6625 * The number of rows to return.
6626 * @param string|CRM_Utils_Sort $sort
6627 * The order by string.
6628 * @param bool $count
6629 * Is this a count only query ?.
6630 * @param bool $includeContactIds
6631 * Should we include contact ids?.
6632 * @param bool $sortByChar
6633 * If true returns the distinct array of first characters for search results.
6634 * @param bool $groupContacts
6635 * If true, return only the contact ids.
6636 * @param string $additionalWhereClause
6637 * If the caller wants to further restrict the search (used for components).
6638 * @param null $sortOrder
6639 * @param string $additionalFromClause
6640 * Should be clause with proper joins, effective to reduce where clause load.
6642 * @param bool $skipOrderAndLimit
6645 public function getSearchSQL(
6646 $offset = 0, $rowCount = 0, $sort = NULL,
6647 $count = FALSE, $includeContactIds = FALSE,
6648 $sortByChar = FALSE, $groupContacts = FALSE,
6649 $additionalWhereClause = NULL, $sortOrder = NULL,
6650 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE) {
6652 $sqlParts = $this->getSearchSQLParts($offset, $rowCount, $sort, $count, $includeContactIds, $sortByChar, $groupContacts, $additionalWhereClause, $sortOrder, $additionalFromClause);
6655 CRM_Core_Error
::deprecatedFunctionWarning('sort by char is deprecated - use alphabetQuery method');
6656 $sqlParts['order_by'] = 'ORDER BY sort_name asc';
6659 if ($skipOrderAndLimit) {
6660 CRM_Core_Error
::deprecatedFunctionWarning('skipOrderAndLimit is deprected - call getSearchSQLParts & construct it in the calling function');
6661 $query = "{$sqlParts['select']} {$sqlParts['from']} {$sqlParts['where']} {$sqlParts['having']} {$sqlParts['group_by']}";
6664 $query = "{$sqlParts['select']} {$sqlParts['from']} {$sqlParts['where']} {$sqlParts['having']} {$sqlParts['group_by']} {$sqlParts['order_by']} {$sqlParts['limit']}";
6670 * Get the component parts of the search query as an array.
6672 * @param int $offset
6673 * The offset for the query.
6674 * @param int $rowCount
6675 * The number of rows to return.
6676 * @param string|CRM_Utils_Sort $sort
6677 * The order by string.
6678 * @param bool $count
6679 * Is this a count only query ?.
6680 * @param bool $includeContactIds
6681 * Should we include contact ids?.
6682 * @param bool $sortByChar
6683 * If true returns the distinct array of first characters for search results.
6684 * @param bool $groupContacts
6685 * If true, return only the contact ids.
6686 * @param string $additionalWhereClause
6687 * If the caller wants to further restrict the search (used for components).
6688 * @param null $sortOrder
6689 * @param string $additionalFromClause
6690 * Should be clause with proper joins, effective to reduce where clause load.
6694 public function getSearchSQLParts($offset = 0, $rowCount = 0, $sort = NULL,
6695 $count = FALSE, $includeContactIds = FALSE,
6696 $sortByChar = FALSE, $groupContacts = FALSE,
6697 $additionalWhereClause = NULL, $sortOrder = NULL,
6698 $additionalFromClause = NULL) {
6699 if ($includeContactIds) {
6700 $this->_includeContactIds
= TRUE;
6701 $this->_whereClause
= $this->whereClause();
6703 $onlyDeleted = in_array([
6711 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
6712 // and that contact happens to be deleted, set $onlyDeleted to true
6713 foreach ($this->_params
as $values) {
6714 $name = CRM_Utils_Array
::value(0, $values);
6715 $op = CRM_Utils_Array
::value(1, $values);
6716 $value = CRM_Utils_Array
::value(2, $values);
6717 if ($name == 'contact_id' and $op == '=') {
6718 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
6719 $onlyDeleted = TRUE;
6725 // building the query string
6726 $groupBy = $groupByCols = NULL;
6728 if (isset($this->_groupByComponentClause
)) {
6729 $groupByCols = preg_replace('/^GROUP BY /', '', trim($this->_groupByComponentClause
));
6730 $groupByCols = explode(', ', $groupByCols);
6732 elseif ($this->_useGroupBy
) {
6733 $groupByCols = ['contact_a.id'];
6736 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
6737 $groupByCols = ['civicrm_activity.id'];
6739 if (!empty($groupByCols)) {
6740 $groupBy = " GROUP BY " . implode(', ', $groupByCols);
6743 $order = $orderBy = '';
6746 $order = $this->prepareOrderBy($sort, $sortOrder);
6749 // Cases where we are disabling FGB (FULL_GROUP_BY_MODE):
6750 // 1. When GROUP BY columns are present then disable FGB otherwise it demands to add ORDER BY columns in GROUP BY and eventually in SELECT
6751 // clause. This will impact the search query output.
6752 $disableFullGroupByMode = (!empty($groupBy) ||
$groupContacts);
6754 if ($disableFullGroupByMode) {
6755 CRM_Core_DAO
::disableFullGroupByMode();
6759 $this->_sort
= $sort;
6762 $this->includePseudoFieldsJoin($sort);
6764 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
6766 if ($additionalWhereClause) {
6767 $where = $where . ' AND ' . $additionalWhereClause;
6770 //additional from clause should be w/ proper joins.
6771 if ($additionalFromClause) {
6772 $from .= "\n" . $additionalFromClause;
6775 // if we are doing a transform, do it here
6776 // use the $from, $where and $having to get the contact ID
6777 if ($this->_displayRelationshipType
) {
6778 $this->filterRelatedContacts($from, $where, $having);
6780 $limit = (!$count && $rowCount) ?
" LIMIT " . CRM_Utils_Type
::escape($offset, 'Int') . ", " . CRM_Utils_Type
::escape($rowCount, 'Int') : '';
6783 'select' => $select,
6786 'order_by' => $order,
6787 'group_by' => $groupBy,
6788 'having' => $having,
6794 * Get the metadata for a given field.
6796 * @param string $fieldName
6800 protected function getMetadataForField($fieldName) {
6801 if ($fieldName === 'contact_a.id') {
6802 // This seems to be the only anomaly.
6805 $pseudoField = isset($this->_pseudoConstantsSelect
[$fieldName]) ?
$this->_pseudoConstantsSelect
[$fieldName] : [];
6806 $field = isset($this->_fields
[$fieldName]) ?
$this->_fields
[$fieldName] : $pseudoField;
6807 $field = array_merge($field, $pseudoField);
6808 if (!empty($field) && empty($field['name'])) {
6809 // standardising field formatting here - over time we can phase out variants.
6810 // all paths using this currently unit tested
6811 $field['name'] = CRM_Utils_Array
::value('field_name', $field, CRM_Utils_Array
::value('idCol', $field, $fieldName));
6817 * Get the metadata for a given field, returning the 'real field' if it is a pseudofield.
6819 * @param string $fieldName
6823 protected function getMetadataForRealField($fieldName) {
6824 $field = $this->getMetadataForField($fieldName);
6825 if (!empty($field['is_pseudofield_for'])) {
6826 $field = $this->getMetadataForField($field['is_pseudofield_for']);
6827 $field['pseudofield_name'] = $fieldName;
6829 elseif (!empty($field['pseudoconstant'])) {
6830 if (!empty($field['pseudoconstant']['optionGroupName'])) {
6831 $field['pseudofield_name'] = $field['pseudoconstant']['optionGroupName'];
6832 if (empty($field['table_name'])) {
6833 if (!empty($field['where'])) {
6834 $field['table_name'] = explode('.', $field['where'])[0];
6837 $field['table_name'] = 'civicrm_contact';
6846 * If we have a field that is better rendered via the pseudoconstant handled them here.
6848 * Rather than joining in the additional table we render the option value on output.
6850 * @todo - so far this applies to a narrow range of pseudocontants. We are adding them
6851 * carefully with test coverage but aim to extend.
6853 * @param string $name
6855 protected function addPseudoconstantFieldToSelect($name) {
6856 $field = $this->getMetadataForRealField($name);
6857 $realFieldName = $field['name'];
6858 $pseudoFieldName = CRM_Utils_Array
::value('pseudofield_name', $field);
6859 if ($pseudoFieldName) {
6860 // @todo - we don't really need to build this array now we have metadata more available with getMetadataForField fn.
6861 $this->_pseudoConstantsSelect
[$pseudoFieldName] = [
6862 'pseudoField' => $pseudoFieldName,
6863 'idCol' => $realFieldName,
6864 'field_name' => $field['name'],
6865 'bao' => $field['bao'],
6866 'pseudoconstant' => $field['pseudoconstant'],
6870 $this->_tables
[$field['table_name']] = 1;
6871 $this->_element
[$realFieldName] = 1;
6872 $this->_select
[$field['name']] = str_replace('civicrm_contact.', 'contact_a.', "{$field['where']} as `$realFieldName`");
6876 * Is this pseudofield a foreign key constraint.
6878 * We are trying to cautiously expand our pseudoconstant handling. This check allows us
6879 * to extend to a narrowly defined type (and then only if the pseudofield is in the fields
6880 * array which is done for contributions which are mostly handled as pseudoconstants.
6886 protected function isPseudoFieldAnFK($fieldSpec) {
6887 if (empty($fieldSpec['FKClassName'])
6888 || CRM_Utils_Array
::value('keyColumn', $fieldSpec['pseudoconstant']) !== 'id'
6889 || CRM_Utils_Array
::value('labelColumn', $fieldSpec['pseudoconstant']) !== 'name') {
6896 * Is the field a relative date field.
6898 * @param string $fieldName
6902 protected function isARelativeDateField($fieldName) {
6903 if (substr($fieldName, -9, 9) !== '_relative') {
6906 $realField = substr($fieldName, 0, strlen($fieldName) - 9);
6907 return isset($this->_fields
[$realField]);
6913 protected function buildRelativeDateQuery(&$values) {
6914 $value = CRM_Utils_Array
::value(2, $values);
6915 if (empty($value)) {
6918 $fieldName = substr($values[0], 0, strlen($values[0]) - 9);
6919 $fieldSpec = $this->_fields
[$fieldName];
6920 $tableName = $fieldSpec['table_name'];
6921 $filters = CRM_Core_OptionGroup
::values('relative_date_filters');
6922 $grouping = CRM_Utils_Array
::value(3, $values);
6923 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
6925 $dates = CRM_Utils_Date
::getFromTo($value, NULL, NULL);
6926 if (empty($dates[0])) {
6927 // ie. no start date we only have end date
6928 $this->_where
[$grouping][] = $fieldSpec['where'] . " <= '{$dates[1]}'";
6930 $this->_qill
[$grouping][] = ts('%1 is ', [$fieldSpec['title']]) . $filters[$value] . ' (' . ts("to %1", [
6931 CRM_Utils_Date
::customFormat($dates[1]),
6934 elseif (empty($dates[1])) {
6935 // ie. no end date we only have start date
6936 $this->_where
[$grouping][] = $fieldSpec['where'] . " >= '{$dates[1]}'";
6938 $this->_qill
[$grouping][] = ts('%1 is ', [$fieldSpec['title']]) . $filters[$value] . ' (' . ts("from %1", [
6939 CRM_Utils_Date
::customFormat($dates[0]),
6943 // we have start and end dates.
6944 $this->_where
[$grouping][] = $fieldSpec['where'] . " BETWEEN '{$dates[0]}' AND '{$dates[1]}'";
6946 $this->_qill
[$grouping][] = ts('%1 is ', [$fieldSpec['title']]) . $filters[$value] . ' (' . ts("between %1 and %2", [
6947 CRM_Utils_Date
::customFormat($dates[0]),
6948 CRM_Utils_Date
::customFormat($dates[1]),
6954 * Add the address table into the query.
6956 * @param string $tableKey
6957 * @param string $joinCondition
6963 protected function addAddressTable($tableKey, $joinCondition) {
6964 $tName = "$tableKey-address";
6965 $aName = "`$tableKey-address`";
6966 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
6967 $this->_element
["{$tName}_id"] = 1;
6968 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$joinCondition)";
6969 $this->_tables
[$tName] = $addressJoin;