3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * This is the heart of the search query building mechanism.
21 class CRM_Contact_BAO_Query
{
24 * The various search modes.
26 * As of February 2017, entries not present for 4, 32, 64, 1024.
28 * MODE_ALL seems to be out of sync with the available constants;
29 * if this is intentionally excluding MODE_MAILING then that may
32 * Likewise if there's reason for the missing modes (4, 32, 64 etc).
37 NO_RETURN_PROPERTIES
= 'CRM_Contact_BAO_Query::NO_RETURN_PROPERTIES',
43 MODE_CONTACTSRELATED
= 32,
46 MODE_PLEDGEBANK
= 256,
56 * Constants for search operators
59 SEARCH_OPERATOR_AND
= 'AND',
60 SEARCH_OPERATOR_OR
= 'OR';
63 * The default set of return properties.
67 public static $_defaultReturnProperties;
70 * The default set of hier return properties.
74 public static $_defaultHierReturnProperties;
77 * The set of input params.
90 * The set of output params
94 public $_returnProperties;
104 * The name of the elements that are in the select clause
105 * used to extract the values.
112 * The tables involved in the query.
119 * The table involved in the where clause.
123 public $_whereTables;
126 * Array of WHERE clause components.
133 * The WHERE clause as a string.
137 public $_whereClause;
140 * Additional WHERE clause for permissions.
144 public $_permissionWhereClause;
154 * Additional permission from clause
158 public $_permissionFromClause;
161 * The from clause for the simple select and alphabetical
166 public $_simpleFromClause;
176 * The english language version of the query
183 * All the fields that could potentially be involved in
191 * Fields hacked for legacy reasons.
193 * Generally where a field has a option group defining it's options we add them to
194 * the fields array as pseudofields - eg for gender we would add the key 'gender' to fields
195 * using CRM_Core_DAO::appendPseudoConstantsToFields($fields);
197 * The rendered results would hold an id in the gender_id field and the label in the pseudo 'Gender'
198 * field. The heading for the pseudofield would come form the the option group name & for the id field
201 * These fields are handled in a more legacy way - ie overwriting 'gender_id' with the label on output
202 * via the convertToPseudoNames function. Ideally we would convert them but they would then need to be fixed
203 * in some other places & there are also some issues around the name (ie. Gender currently has the label in the
204 * schema 'Gender' so adding a second 'Gender' field to search builder & export would be confusing and the standard is
205 * not fully agreed here.
209 protected $legacyHackedFields = [
210 'gender_id' => 'gender',
211 'prefix_id' => 'individual_prefix',
212 'suffix_id' => 'individual_suffix',
213 'communication_style_id' => 'communication_style',
217 * Are we in search mode.
221 public $_search = TRUE;
224 * Should we skip permission checking.
228 public $_skipPermission = FALSE;
231 * Should we skip adding of delete clause.
235 public $_skipDeleteClause = FALSE;
238 * Are we in strict mode (use equality over LIKE)
242 public $_strict = FALSE;
245 * What operator to use to group the clauses.
249 public $_operator = 'AND';
254 * Should we only search on primary location.
258 public $_primaryLocation = TRUE;
261 * Are contact ids part of the query.
265 public $_includeContactIds = FALSE;
268 * Should we use the smart group cache.
272 public $_smartGroupCache = TRUE;
275 * Should we display contacts with a specific relationship type.
279 public $_displayRelationshipType;
282 * Reference to the query object for custom values.
286 public $_customQuery;
289 * Should we enable the distinct clause, used if we are including
290 * more than one group
294 public $_useDistinct = FALSE;
297 * Should we just display one contact record
300 public $_useGroupBy = FALSE;
303 * The relationship type direction
307 public static $_relType;
314 public static $_activityRole;
317 * Consider the component activity type
318 * during activity search.
322 public static $_considerCompActivities;
325 * Consider with contact activities only,
326 * during activity search.
330 public static $_withContactActivitiesOnly;
333 * Use distinct component clause for component searches
337 public $_distinctComponentClause;
339 public $_rowCountClause;
342 * Use groupBy component clause for component searches
346 public $_groupByComponentClause;
349 * Track open panes, useful in advance search
353 public static $_openedPanes = [];
356 * For search builder - which custom fields are location-dependent
359 public $_locationSpecificCustomFields = [];
362 * The tables which have a dependency on location and/or address
366 public static $_dependencies = [
367 'civicrm_state_province' => 1,
368 'civicrm_country' => 1,
369 'civicrm_county' => 1,
370 'civicrm_address' => 1,
371 'civicrm_location_type' => 1,
375 * List of location specific fields.
378 public static $_locationSpecificFields = [
383 'supplemental_address_1',
384 'supplemental_address_2',
385 'supplemental_address_3',
388 'postal_code_suffix',
402 * Remember if we handle either end of a number or date range
403 * so we can skip the other
406 protected $_rangeCache = [];
408 * Set to true when $this->relationship is run to avoid adding twice.
412 protected $_relationshipValuesAdded = FALSE;
415 * Set to the name of the temp table if one has been created.
419 public static $_relationshipTempTable;
421 public $_pseudoConstantsSelect = [];
423 public $_groupUniqueKey;
424 public $_groupKeys = [];
427 * Class constructor which also does all the work.
429 * @param array $params
430 * @param array $returnProperties
431 * @param array $fields
432 * @param bool $includeContactIds
433 * @param bool $strict
434 * @param bool|int $mode - mode the search is operating on
436 * @param bool $skipPermission
437 * @param bool $searchDescendentGroups
438 * @param bool $smartGroupCache
439 * @param null $displayRelationshipType
440 * @param string $operator
441 * @param string $apiEntity
442 * @param bool|null $primaryLocationOnly
444 * @throws \CRM_Core_Exception
446 public function __construct(
447 $params = NULL, $returnProperties = NULL, $fields = NULL,
448 $includeContactIds = FALSE, $strict = FALSE, $mode = 1,
449 $skipPermission = FALSE, $searchDescendentGroups = TRUE,
450 $smartGroupCache = TRUE, $displayRelationshipType = NULL,
453 $primaryLocationOnly = NULL
455 if ($primaryLocationOnly === NULL) {
456 $primaryLocationOnly = Civi
::settings()->get('searchPrimaryDetailsOnly');
458 $this->_primaryLocation
= $primaryLocationOnly;
459 $this->_params
= &$params;
460 if ($this->_params
== NULL) {
464 if ($returnProperties === self
::NO_RETURN_PROPERTIES
) {
465 $this->_returnProperties
= [];
467 elseif (empty($returnProperties)) {
468 $this->_returnProperties
= self
::defaultReturnProperties($mode);
471 $this->_returnProperties
= &$returnProperties;
474 $this->_includeContactIds
= $includeContactIds;
475 $this->_strict
= $strict;
476 $this->_mode
= $mode;
477 $this->_skipPermission
= $skipPermission;
478 $this->_smartGroupCache
= $smartGroupCache;
479 $this->_displayRelationshipType
= $displayRelationshipType;
480 $this->setOperator($operator);
483 $this->_fields
= &$fields;
484 $this->_search
= FALSE;
485 $this->_skipPermission
= TRUE;
488 $this->_fields
= CRM_Contact_BAO_Contact
::exportableFields('All', FALSE, TRUE, TRUE, FALSE, !$skipPermission);
489 // The legacy hacked fields will output as a string rather than their underlying type.
490 foreach (array_keys($this->legacyHackedFields
) as $fieldName) {
491 $this->_fields
[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
493 $relationMetadata = CRM_Contact_BAO_Relationship
::fields();
494 $relationFields = array_intersect_key($relationMetadata, array_fill_keys(['relationship_start_date', 'relationship_end_date'], 1));
495 // No good option other than hard-coding metadata for this 'special' field in.
496 $relationFields['relation_active_period_date'] = [
497 'name' => 'relation_active_period_date',
498 'type' => CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
,
499 'title' => ts('Active Period'),
500 'table_name' => 'civicrm_relationship',
501 'where' => 'civicrm_relationship.start_date',
502 'where_end' => 'civicrm_relationship.end_date',
503 'html' => ['type' => 'SelectDate', 'formatType' => 'activityDateTime'],
505 $this->_fields
= array_merge($relationFields, $this->_fields
);
507 $fields = CRM_Core_Component
::getQueryFields(!$this->_skipPermission
);
508 unset($fields['note']);
509 $this->_fields
= array_merge($this->_fields
, $fields);
511 // add activity fields
512 $this->_fields
= array_merge($this->_fields
, CRM_Activity_BAO_Activity
::exportableFields());
513 $this->_fields
= array_merge($this->_fields
, CRM_Activity_BAO_Activity
::exportableFields('Case'));
514 // Add hack as no unique name is defined for the field but the search form is in denial.
515 $this->_fields
['activity_priority_id'] = $this->_fields
['priority_id'];
517 // add any fields provided by hook implementers
518 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
519 $this->_fields
= array_merge($this->_fields
, $extFields);
522 // basically do all the work once, and then reuse it
523 $this->initialize($apiEntity);
527 * Function which actually does all the work for the constructor.
529 * @param string $apiEntity
530 * The api entity being called.
531 * This sort-of duplicates $mode in a confusing way. Probably not by design.
533 * @throws \CRM_Core_Exception
535 public function initialize($apiEntity = NULL) {
537 $this->_element
= [];
539 $this->_whereTables
= [];
543 $this->_paramLookup
= [];
546 $this->_customQuery
= NULL;
548 // reset cached static variables - CRM-5803
549 self
::$_activityRole = NULL;
550 self
::$_considerCompActivities = NULL;
551 self
::$_withContactActivitiesOnly = NULL;
553 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
554 $this->_element
['contact_id'] = 1;
555 $this->_tables
['civicrm_contact'] = 1;
557 if (!empty($this->_params
)) {
558 $this->buildParamsLookup();
561 $this->_whereTables
= $this->_tables
;
563 $this->selectClause($apiEntity);
564 if (!empty($this->_cfIDs
)) {
565 // @todo This function is the select function but instead of running 'select' it
566 // is running the whole query.
567 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
568 $this->_customQuery
->query();
569 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
570 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
571 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
573 $isForcePrimaryOnly = !empty($apiEntity);
574 $this->_whereClause
= $this->whereClause($isForcePrimaryOnly);
575 if (array_key_exists('civicrm_contribution', $this->_whereTables
)) {
576 $component = 'contribution';
578 if (array_key_exists('civicrm_membership', $this->_whereTables
)) {
579 $component = 'membership';
581 if (isset($component) && !$this->_skipPermission
) {
582 // Unit test coverage in api_v3_FinancialTypeACLTest::testGetACLContribution.
583 CRM_Financial_BAO_FinancialType
::buildPermissionedClause($this->_whereClause
, $component);
586 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
, $apiEntity);
587 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
589 $this->openedSearchPanes(TRUE);
593 * Function for same purpose as convertFormValues.
595 * Like convert form values this function exists to pre-Process parameters from the form.
597 * It is unclear why they are different functions & likely relates to advances search
598 * versus search builder.
600 * The direction we are going is having the form convert values to a standardised format &
601 * moving away from weird & wonderful where clause switches.
603 * Fix and handle contact deletion nicely.
605 * this code is primarily for search builder use case where different clauses can specify if they want deleted.
607 * @see https://issues.civicrm.org/jira/browse/CRM-11971
609 public function buildParamsLookup() {
610 $trashParamExists = FALSE;
612 foreach ($this->_params
as $k => $param) {
613 if (!empty($param[0]) && $param[0] == 'contact_is_deleted') {
614 $trashParamExists = TRUE;
616 if (!empty($param[3])) {
617 $paramByGroup[$param[3]][$k] = $param;
621 if ($trashParamExists) {
622 $this->_skipDeleteClause
= TRUE;
624 //cycle through group sets and explicitly add trash param if not set
625 foreach ($paramByGroup as $setID => $set) {
627 !in_array(['contact_is_deleted', '=', '1', $setID, '0'], $this->_params
) &&
628 !in_array(['contact_is_deleted', '=', '0', $setID, '0'], $this->_params
)
631 'contact_is_deleted',
641 foreach ($this->_params
as $value) {
642 if (empty($value[0])) {
645 $cfID = CRM_Core_BAO_CustomField
::getKeyID(str_replace(['_relative', '_low', '_high', '_to', '_high'], '', $value[0]));
647 if (!array_key_exists($cfID, $this->_cfIDs
)) {
648 $this->_cfIDs
[$cfID] = [];
650 // Set wildcard value based on "and/or" selection
651 foreach ($this->_params
as $key => $param) {
652 if ($param[0] == $value[0] . '_operator') {
653 $value[4] = $param[2] == 'or';
657 $this->_cfIDs
[$cfID][] = $value;
660 if (!array_key_exists($value[0], $this->_paramLookup
)) {
661 $this->_paramLookup
[$value[0]] = [];
663 if ($value[0] !== 'group') {
664 // Just trying to unravel how group interacts here! This whole function is weird.
665 $this->_paramLookup
[$value[0]][] = $value;
671 * Some composite fields do not appear in the fields array hack to make them part of the query.
674 * The api entity being called.
675 * This sort-of duplicates $mode in a confusing way. Probably not by design.
677 public function addSpecialFields($apiEntity) {
678 static $special = ['contact_type', 'contact_sub_type', 'sort_name', 'display_name'];
679 // if get called via Contact.get API having address_id as return parameter
680 if ($apiEntity === 'Contact') {
681 $special[] = 'address_id';
683 foreach ($special as $name) {
684 if (!empty($this->_returnProperties
[$name])) {
685 if ($name === 'address_id') {
686 $this->_tables
['civicrm_address'] = 1;
687 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
688 $this->_element
['address_id'] = 1;
691 $this->_select
[$name] = "contact_a.{$name} as $name";
692 $this->_element
[$name] = 1;
699 * Given a list of conditions in params and a list of desired
700 * return Properties generate the required select and from
701 * clauses. Note that since the where clause introduces new
702 * tables, the initial attempt also retrieves all variables used
705 * @param string $apiEntity
706 * The api entity being called.
707 * This sort-of duplicates $mode in a confusing way. Probably not by design.
709 public function selectClause($apiEntity = NULL) {
711 // @todo Tidy up this. This arises because 1) we are ignoring the $mode & adding a new
712 // param ($apiEntity) instead - presumably an oversight & 2 because
713 // contact is not implemented as a component.
714 $this->addSpecialFields($apiEntity);
716 foreach ($this->_fields
as $name => $field) {
717 // skip component fields
718 // there are done by the alter query below
719 // and need not be done on every field
720 // @todo remove these & handle using metadata - only obscure fields
721 // that are hack-added should need to be excluded from the main loop.
723 (substr($name, 0, 12) === 'participant_') ||
724 (substr($name, 0, 7) === 'pledge_') ||
725 (substr($name, 0, 5) === 'case_')
730 // redirect to activity select clause
732 (substr($name, 0, 9) === 'activity_') ||
733 ($name === 'parent_id')
735 CRM_Activity_BAO_Query
::select($this);
738 // if this is a hierarchical name, we ignore it
739 $names = explode('-', $name);
740 if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) {
744 // make an exception for special cases, to add the field in select clause
745 $makeException = FALSE;
747 //special handling for groups/tags
748 if (in_array($name, ['groups', 'tags', 'notes'])
749 && isset($this->_returnProperties
[substr($name, 0, -1)])
751 // @todo instead of setting make exception to get us into
752 // an if clause that has handling for these fields buried with in it
753 // move the handling to here.
754 $makeException = TRUE;
757 // since note has 3 different options we need special handling
758 // note / note_subject / note_body
759 if ($name === 'notes') {
760 foreach (['note', 'note_subject', 'note_body'] as $noteField) {
761 if (isset($this->_returnProperties
[$noteField])) {
762 $makeException = TRUE;
768 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
770 !empty($this->_paramLookup
[$name])
771 ||
!empty($this->_returnProperties
[$name])
772 ||
$this->pseudoConstantNameIsInReturnProperties($field, $name)
776 // add to cfIDs array if not present
777 if (!array_key_exists($cfID, $this->_cfIDs
)) {
778 $this->_cfIDs
[$cfID] = [];
781 elseif (isset($field['where'])) {
782 list($tableName, $fieldName) = explode('.', $field['where'], 2);
783 if (isset($tableName)) {
784 if (!empty(self
::$_dependencies[$tableName])) {
785 $this->_tables
['civicrm_address'] = 1;
786 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
787 $this->_element
['address_id'] = 1;
790 if ($tableName === 'im_provider' ||
$tableName === 'email_greeting' ||
791 $tableName === 'postal_greeting' ||
$tableName === 'addressee'
793 if ($tableName === 'im_provider') {
794 CRM_Core_OptionValue
::select($this);
797 if (in_array($tableName,
798 ['email_greeting', 'postal_greeting', 'addressee'])) {
799 $this->_element
["{$name}_id"] = 1;
800 $this->_select
["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
801 $this->_pseudoConstantsSelect
[$name] = ['pseudoField' => $tableName, 'idCol' => "{$name}_id"];
802 $this->_pseudoConstantsSelect
[$name]['select'] = "{$name}.{$fieldName} as $name";
803 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
805 if ($tableName === 'email_greeting') {
807 $this->_pseudoConstantsSelect
[$name]['join']
808 = " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
809 $this->_pseudoConstantsSelect
[$name]['join'] .=
810 " 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 ) ";
812 elseif ($tableName === 'postal_greeting') {
814 $this->_pseudoConstantsSelect
[$name]['join']
815 = " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
816 $this->_pseudoConstantsSelect
[$name]['join'] .=
817 " 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 ) ";
819 elseif ($tableName == 'addressee') {
821 $this->_pseudoConstantsSelect
[$name]['join']
822 = " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
823 $this->_pseudoConstantsSelect
[$name]['join'] .=
824 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
826 $this->_pseudoConstantsSelect
[$name]['table'] = $tableName;
829 $greetField = "{$name}_display";
830 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
831 $this->_element
[$greetField] = 1;
833 $greetField = "{$name}_custom";
834 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
835 $this->_element
[$greetField] = 1;
839 if (!in_array($tableName, ['civicrm_state_province', 'civicrm_country', 'civicrm_county'])) {
840 $this->_tables
[$tableName] = 1;
843 // also get the id of the tableName
844 $tName = substr($tableName, 8);
845 if (in_array($tName, ['country', 'state_province', 'county'])) {
846 if ($tName == 'state_province') {
847 $this->_pseudoConstantsSelect
['state_province_name'] = [
848 'pseudoField' => "{$tName}",
849 'idCol' => "{$tName}_id",
850 'bao' => 'CRM_Core_BAO_Address',
851 'table' => "civicrm_{$tName}",
852 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
855 $this->_pseudoConstantsSelect
[$tName] = [
856 'pseudoField' => 'state_province_abbreviation',
857 'idCol' => "{$tName}_id",
858 'table' => "civicrm_{$tName}",
859 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
863 $this->_pseudoConstantsSelect
[$name] = [
864 'pseudoField' => "{$tName}_id",
865 'idCol' => "{$tName}_id",
866 'bao' => 'CRM_Core_BAO_Address',
867 'table' => "civicrm_{$tName}",
868 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
872 $this->_select
["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
873 $this->_element
["{$tName}_id"] = 1;
875 elseif ($tName != 'contact') {
876 $this->_select
["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
877 $this->_element
["{$tName}_id"] = 1;
880 //special case for phone
881 if ($name == 'phone') {
882 $this->_select
['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
883 $this->_element
['phone_type_id'] = 1;
886 // if IM then select provider_id also
887 // to get "IM Service Provider" in a file to be exported, CRM-3140
889 $this->_select
['provider_id'] = "civicrm_im.provider_id as provider_id";
890 $this->_element
['provider_id'] = 1;
893 if ($tName == 'contact' && $fieldName == 'organization_name') {
894 // special case, when current employer is set for Individual contact
895 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
897 elseif ($tName == 'contact' && $fieldName === 'id') {
898 // Handled elsewhere, explicitly ignore. Possibly for all tables...
900 elseif (in_array($tName, ['country', 'county'])) {
901 $this->_pseudoConstantsSelect
[$name]['select'] = "{$field['where']} as `$name`";
902 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
904 elseif ($tName == 'state_province') {
905 $this->_pseudoConstantsSelect
[$tName]['select'] = "{$field['where']} as `$name`";
906 $this->_pseudoConstantsSelect
[$tName]['element'] = $name;
908 elseif (strpos($name, 'contribution_soft_credit') !== FALSE) {
909 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled($this->_params
)) {
910 $this->_select
[$name] = "{$field['where']} as `$name`";
913 elseif ($this->pseudoConstantNameIsInReturnProperties($field, $name)) {
914 $this->addPseudoconstantFieldToSelect($name);
917 $this->_select
[$name] = str_replace('civicrm_contact.', 'contact_a.', "{$field['where']} as `$name`");
919 if (!in_array($tName, ['state_province', 'country', 'county'])) {
920 $this->_element
[$name] = 1;
925 elseif ($name === 'tags') {
926 //@todo move this handling outside the big IF & ditch $makeException
927 $this->_useGroupBy
= TRUE;
928 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
929 $this->_element
[$name] = 1;
930 $this->_tables
['civicrm_tag'] = 1;
931 $this->_tables
['civicrm_entity_tag'] = 1;
933 elseif ($name === 'groups') {
934 //@todo move this handling outside the big IF & ditch $makeException
935 $this->_useGroupBy
= TRUE;
936 // Duplicates will be created here but better to sort them out in php land.
937 $this->_select
[$name] = "
939 GROUP_CONCAT(DISTINCT IF(civicrm_group_contact.status = 'Added', civicrm_group_contact.group_id, '')),
940 GROUP_CONCAT(DISTINCT civicrm_group_contact_cache.group_id)
943 $this->_element
[$name] = 1;
944 $this->_tables
['civicrm_group_contact'] = 1;
945 $this->_tables
['civicrm_group_contact_cache'] = 1;
946 $this->_pseudoConstantsSelect
["{$name}"] = [
947 'pseudoField' => "groups",
951 elseif ($name === 'notes') {
952 //@todo move this handling outside the big IF & ditch $makeException
953 // if note field is subject then return subject else body of the note
954 $noteColumn = 'note';
955 if (isset($noteField) && $noteField === 'note_subject') {
956 $noteColumn = 'subject';
959 $this->_useGroupBy
= TRUE;
960 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
961 $this->_element
[$name] = 1;
962 $this->_tables
['civicrm_note'] = 1;
964 elseif ($name === 'current_employer') {
965 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
966 $this->_element
[$name] = 1;
970 if ($cfID && !empty($field['is_search_range'])) {
971 // this is a custom field with range search enabled, so we better check for two/from values
972 if (!empty($this->_paramLookup
[$name . '_from'])) {
973 if (!array_key_exists($cfID, $this->_cfIDs
)) {
974 $this->_cfIDs
[$cfID] = [];
976 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
977 // search in the cdID array for the same grouping
979 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
980 if ($c[3] == $p[3]) {
981 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
986 $p[2] = ['from' => $p[2]];
987 $this->_cfIDs
[$cfID][] = $p;
991 if (!empty($this->_paramLookup
[$name . '_to'])) {
992 if (!array_key_exists($cfID, $this->_cfIDs
)) {
993 $this->_cfIDs
[$cfID] = [];
995 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
996 // search in the cdID array for the same grouping
998 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
999 if ($c[4] == $p[4]) {
1000 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
1005 $p[2] = ['to' => $p[2]];
1006 $this->_cfIDs
[$cfID][] = $p;
1013 // add location as hierarchical elements
1014 $this->addHierarchicalElements();
1016 // add multiple field like website
1017 $this->addMultipleElements();
1020 CRM_Core_Component
::alterQuery($this, 'select');
1022 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'select');
1026 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
1028 public function addHierarchicalElements() {
1029 if (empty($this->_returnProperties
['location'])) {
1032 if (!is_array($this->_returnProperties
['location'])) {
1036 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
1040 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
1041 $addressCustomFieldIds = [];
1043 foreach ($this->_returnProperties
['location'] as $name => $elements) {
1044 $lCond = self
::getPrimaryCondition($name);
1045 $locationTypeId = is_numeric($name) ?
NULL : array_search($name, $locationTypes);
1048 if ($locationTypeId === FALSE) {
1051 $lCond = "location_type_id = $locationTypeId";
1052 $this->_useDistinct
= TRUE;
1054 //commented for CRM-3256
1055 $this->_useGroupBy
= TRUE;
1058 $name = str_replace(' ', '_', $name);
1059 $tName = "$name-location_type";
1060 $ltName = "`$name-location_type`";
1061 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1062 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
1063 $this->_element
["{$tName}_id"] = 1;
1064 $this->_element
["{$tName}"] = 1;
1066 $locationTypeName = $tName;
1067 $locationTypeJoin = [];
1070 foreach ($elements as $elementFullName => $dontCare) {
1072 $elementName = $elementCmpName = $elementFullName;
1074 if (substr($elementCmpName, 0, 5) == 'phone') {
1075 $elementCmpName = 'phone';
1078 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
1079 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
1080 $addressCustomFieldIds[$cfID][$name] = 1;
1083 // add address table - doesn't matter if we do it mutliple times - it's the same data
1084 // @todo ditch the double processing of addressJoin
1085 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
1086 && !in_array($elementCmpName, ['email', 'phone', 'im', 'openid'])
1088 list($aName, $addressJoin) = $this->addAddressTable($name, $lCond);
1089 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
1090 $processed[$aName] = 1;
1093 $cond = $elementType = '';
1094 if (strpos($elementName, '-') !== FALSE) {
1095 // this is either phone, email or IM
1096 list($elementName, $elementType) = explode('-', $elementName);
1098 if (($elementName != 'phone') && ($elementName != 'im')) {
1099 $cond = self
::getPrimaryCondition($elementType);
1101 // CRM-13011 : If location type is primary, do not restrict search to the phone
1102 // type id - we want the primary phone, regardless of what type it is.
1103 // Otherwise, restrict to the specified phone type for the given field.
1104 if ((!$cond) && ($elementName == 'phone')) {
1105 $cond = "phone_type_id = '$elementType'";
1107 elseif ((!$cond) && ($elementName == 'im')) {
1108 // IM service provider id, CRM-3140
1109 $cond = "provider_id = '$elementType'";
1111 $elementType = '-' . $elementType;
1114 $field = $this->_fields
[$elementName] ??
NULL;
1115 if (isset($this->_pseudoConstantsSelect
[$field['name']])) {
1116 $this->_pseudoConstantsSelect
[$name . '-' . $field['name']] = $this->_pseudoConstantsSelect
[$field['name']];
1119 // hack for profile, add location id
1122 // fix for CRM-882( to handle phone types )
1123 !is_numeric($elementType)
1125 if (is_numeric($name)) {
1126 $field = $this->_fields
[$elementName . "-Primary$elementType"] ??
NULL;
1129 $field = $this->_fields
[$elementName . "-$locationTypeId$elementType"] ??
NULL;
1132 elseif (is_numeric($name)) {
1133 //this for phone type to work
1134 if (in_array($elementName, ['phone', 'phone_ext'])) {
1135 $field = $this->_fields
[$elementName . "-Primary" . $elementType] ??
NULL;
1138 $field = $this->_fields
[$elementName . "-Primary"] ??
NULL;
1142 //this is for phone type to work for profile edit
1143 if (in_array($elementName, ['phone', 'phone_ext'])) {
1144 $field = $this->_fields
[$elementName . "-$locationTypeId$elementType"] ??
NULL;
1147 $field = $this->_fields
[$elementName . "-$locationTypeId"] ??
NULL;
1152 // Check if there is a value, if so also add to where Clause
1154 if ($this->_params
) {
1156 if (isset($locationTypeId)) {
1157 $nm .= "-$locationTypeId";
1159 if (!is_numeric($elementType)) {
1160 $nm .= "$elementType";
1163 foreach ($this->_params
as $id => $values) {
1164 if ((is_array($values) && $values[0] == $nm) ||
1165 (in_array($elementName, ['phone', 'im'])
1166 && (strpos($values[0], $nm) !== FALSE)
1176 if ($field && isset($field['where'])) {
1177 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1178 $pf = substr($tableName, 8);
1179 $tName = $name . '-' . $pf . $elementType;
1180 if (isset($tableName)) {
1181 if ($tableName == 'civicrm_state_province' ||
$tableName == 'civicrm_country' ||
$tableName == 'civicrm_county') {
1182 $this->_select
["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1185 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1188 $this->_element
["{$tName}_id"] = 1;
1189 if (substr($tName, -15) == '-state_province') {
1190 // FIXME: hack to fix CRM-1900
1191 $a = Civi
::settings()->get('address_format');
1193 if (substr_count($a, 'state_province_name') > 0) {
1194 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = [
1195 'pseudoField' => "{$pf}_id",
1196 'idCol' => "{$tName}_id",
1197 'bao' => 'CRM_Core_BAO_Address',
1199 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1202 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = [
1203 'pseudoField' => 'state_province_abbreviation',
1204 'idCol' => "{$tName}_id",
1206 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1210 if (substr($elementFullName, 0, 2) == 'im') {
1211 $provider = "{$name}-{$elementFullName}-provider_id";
1212 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1213 $this->_element
[$provider] = 1;
1215 if ($pf == 'country' ||
$pf == 'county') {
1216 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = [
1217 'pseudoField' => "{$pf}_id",
1218 'idCol' => "{$tName}_id",
1219 'bao' => 'CRM_Core_BAO_Address',
1221 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1224 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1228 if (in_array($pf, ['state_province', 'country', 'county'])) {
1229 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1232 $this->_element
["{$name}-{$elementFullName}"] = 1;
1235 if (empty($processed["`$tName`"])) {
1236 $processed["`$tName`"] = 1;
1237 $newName = $tableName . '_' . $index;
1238 switch ($tableName) {
1239 case 'civicrm_phone':
1240 case 'civicrm_email':
1242 case 'civicrm_openid':
1244 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id";
1245 if ($tableName != 'civicrm_phone') {
1246 $this->_tables
[$tName] .= " AND `$tName`.$lCond";
1248 elseif (is_numeric($name)) {
1249 $this->_select
[$tName] = "IF (`$tName`.is_primary = $name, `$tName`.phone, NULL) as `$tName`";
1252 // this special case to add phone type
1254 $phoneTypeCondition = " AND `$tName`.$cond ";
1255 //gross hack to pickup corrupted data also, CRM-7603
1256 if (strpos($cond, 'phone_type_id') !== FALSE) {
1257 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1258 if (!empty($lCond)) {
1259 $phoneTypeCondition .= " AND ( `$tName`.$lCond ) ";
1262 $this->_tables
[$tName] .= $phoneTypeCondition;
1265 //build locationType join
1266 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1269 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1273 case 'civicrm_state_province':
1274 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1275 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1276 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1278 $this->_whereTables
["{$name}-address"] = $addressJoin;
1282 case 'civicrm_country':
1283 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1284 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1285 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1287 $this->_whereTables
["{$name}-address"] = $addressJoin;
1291 case 'civicrm_county':
1292 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1293 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1294 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1296 $this->_whereTables
["{$name}-address"] = $addressJoin;
1301 if (isset($addressCustomFields[$elementName]['custom_field_id']) && !empty($addressCustomFields[$elementName]['custom_field_id'])) {
1302 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.id";
1305 $this->_whereTables
["{$name}-address"] = $addressJoin;
1314 // add location type join
1315 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1316 $this->_tables
[$locationTypeName] = $ltypeJoin;
1318 // table should be present in $this->_whereTables,
1319 // to add its condition in location type join, CRM-3939.
1320 if ($addWhereCount) {
1322 foreach ($this->_whereTables
as $tableName => $clause) {
1323 if (!empty($locationTypeJoin[$tableName])) {
1324 $locClause[] = $locationTypeJoin[$tableName];
1328 if (!empty($locClause)) {
1329 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1334 if (!empty($addressCustomFieldIds)) {
1335 $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
1336 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1337 foreach ($locTypeName as $name => $dnc) {
1338 $this->_locationSpecificCustomFields
[$cfID] = [$name, array_search($name, $locationTypes)];
1339 $fieldName = "$name-custom_{$cfID}";
1340 $tName = "$name-address-custom-{$cfID}";
1341 $aName = "`$name-address-custom-{$cfID}`";
1342 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1343 $this->_element
["{$tName}_id"] = 1;
1344 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1345 $this->_element
[$fieldName] = 1;
1346 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1353 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
1355 public function addMultipleElements() {
1356 if (empty($this->_returnProperties
['website'])) {
1359 if (!is_array($this->_returnProperties
['website'])) {
1363 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1364 foreach ($elements as $elementFullName => $dontCare) {
1365 $tName = "website-{$key}-{$elementFullName}";
1366 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1367 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1368 $this->_element
["{$tName}_id"] = 1;
1369 $this->_element
["{$tName}"] = 1;
1371 $type = "website-{$key}-website_type_id";
1372 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1373 $this->_element
[$type] = 1;
1374 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id AND `$tName`.website_type_id = $key )";
1380 * Generate the query based on what type of query we need.
1382 * @param bool $count
1383 * @param bool $sortByChar
1384 * @param bool $groupContacts
1385 * @param bool $onlyDeleted
1388 * sql query parts as an array
1390 public function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE, $onlyDeleted = FALSE) {
1391 // build permission clause
1392 $this->generatePermissionClause($onlyDeleted, $count);
1395 if (isset($this->_rowCountClause
)) {
1396 $select = "SELECT {$this->_rowCountClause}";
1398 elseif (isset($this->_distinctComponentClause
)) {
1399 // we add distinct to get the right count for components
1400 // for the more complex result set, we use GROUP BY the same id
1402 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} ) as rowCount";
1405 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1407 $from = $this->_simpleFromClause
;
1408 if ($this->_useDistinct
) {
1409 $this->_useGroupBy
= TRUE;
1412 elseif ($sortByChar) {
1413 // @fixme add the deprecated warning back in (it breaks CRM_Contact_SelectorTest::testSelectorQuery)
1414 // CRM_Core_Error::deprecatedFunctionWarning('sort by char is deprecated - use alphabetQuery method');
1415 $select = 'SELECT DISTINCT LEFT(contact_a.sort_name, 1) as sort_name';
1416 $from = $this->_simpleFromClause
;
1418 elseif ($groupContacts) {
1419 $select = 'SELECT contact_a.id as id';
1420 if ($this->_useDistinct
) {
1421 $this->_useGroupBy
= TRUE;
1423 $from = $this->_simpleFromClause
;
1426 if (!empty($this->_paramLookup
['group'])) {
1428 list($name, $op, $value, $grouping, $wildcard) = $this->_paramLookup
['group'][0];
1430 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
1431 $this->_paramLookup
['group'][0][1] = key($value);
1434 // Presumably the lines below come into manage groups screen.
1435 // make sure there is only one element
1436 // this is used when we are running under smog and need to know
1437 // how the contact was added (CRM-1203)
1438 $groups = (array) CRM_Utils_Array
::value($this->_paramLookup
['group'][0][1], $this->_paramLookup
['group'][0][2], $this->_paramLookup
['group'][0][2]);
1439 if ((count($this->_paramLookup
['group']) == 1) &&
1440 (count($groups) == 1)
1442 $groupId = $groups[0];
1444 //check if group is saved search
1445 $group = new CRM_Contact_BAO_Group();
1446 $group->id
= $groupId;
1449 if (!isset($group->saved_search_id
)) {
1450 $tbName = "civicrm_group_contact";
1451 // CRM-17254 don't retrieve extra fields if contact_id is specifically requested
1452 // as this will add load to an intentionally light query.
1453 // ideally this code would be removed as it appears to be to support CRM-1203
1454 // and passing in the required returnProperties from the url would
1455 // make more sense that globally applying the requirements of one form.
1456 if (($this->_returnProperties
!= ['contact_id'])) {
1457 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1458 $this->_element
['group_contact_id'] = 1;
1459 $this->_select
['status'] = "$tbName.status as status";
1460 $this->_element
['status'] = 1;
1464 $this->_useGroupBy
= TRUE;
1466 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1467 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1469 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1470 $this->_useDistinct
= FALSE;
1471 $this->_useGroupBy
= TRUE;
1475 $select = $this->getSelect();
1476 $from = $this->_fromClause
;
1480 if (!empty($this->_whereClause
)) {
1481 $where = "WHERE {$this->_whereClause}";
1484 if (!empty($this->_permissionWhereClause
) && empty($this->_displayRelationshipType
)) {
1485 if (!empty($this->_permissionFromClause
)) {
1486 $from .= " $this->_permissionFromClause";
1488 if (empty($where)) {
1489 $where = "WHERE $this->_permissionWhereClause";
1492 $where = "$where AND $this->_permissionWhereClause";
1497 if (!empty($this->_having
)) {
1498 foreach ($this->_having
as $havingSets) {
1499 foreach ($havingSets as $havingSet) {
1500 $havingValue[] = $havingSet;
1503 $having = ' HAVING ' . implode(' AND ', $havingValue);
1506 // if we are doing a transform, do it here
1507 // use the $from, $where and $having to get the contact ID
1508 if ($this->_displayRelationshipType
) {
1509 $this->filterRelatedContacts($from, $where, $having);
1512 return [$select, $from, $where, $having];
1516 * Get where values from the parameters.
1518 * @param string $name
1519 * @param mixed $grouping
1523 public function getWhereValues($name, $grouping) {
1525 foreach ($this->_params
as $values) {
1526 if ($values[0] == $name && $values[3] == $grouping) {
1537 * @param bool $relative
1538 * @param string $from
1541 public static function fixDateValues($relative, &$from, &$to) {
1543 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1548 * Convert values from form-appropriate to query-object appropriate.
1550 * The query object is increasingly supporting the sql-filter syntax which is the most flexible syntax.
1551 * So, ideally we would convert all fields to look like
1554 * // Set the operator for legacy reasons, but it is ignored
1556 * // array in sql filter syntax
1557 * 2 => array('BETWEEN' => array(1,60),
1562 * There are some examples of the syntax in
1563 * https://github.com/civicrm/civicrm-core/tree/master/api/v3/examples/Relationship
1565 * More notes at CRM_Core_DAO::createSQLFilter
1567 * and a list of supported operators in CRM_Core_DAO
1569 * @param array $formValues
1570 * @param int $wildcard
1571 * @param bool $useEquals
1573 * @param string $apiEntity
1575 * @param array $entityReferenceFields
1576 * Field names of any entity reference fields (which will need reformatting to IN syntax).
1580 public static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL,
1581 $entityReferenceFields = []) {
1583 if (empty($formValues)) {
1587 self
::filterCountryFromValuesIfStateExists($formValues);
1588 CRM_Core_BAO_CustomValue
::fixCustomFieldValue($formValues);
1590 foreach ($formValues as $id => $values) {
1591 if (self
::isAlreadyProcessedForQueryFormat($values)) {
1592 $params[] = $values;
1596 self
::legacyConvertFormValues($id, $values);
1598 // The form uses 1 field to represent two db fields
1599 if ($id === 'contact_type' && $values && (!is_array($values) ||
!array_intersect(array_keys($values), CRM_Core_DAO
::acceptedSQLOperators()))) {
1602 foreach ((array) $values as $key => $type) {
1603 $types = explode('__', is_numeric($type) ?
$key : $type, 2);
1604 $contactType[$types[0]] = $types[0];
1605 // Add sub-type if specified
1606 if (!empty($types[1])) {
1607 $subType[$types[1]] = $types[1];
1610 $params[] = ['contact_type', 'IN', $contactType, 0, 0];
1612 $params[] = ['contact_sub_type', 'IN', $subType, 0, 0];
1615 elseif ($id === 'privacy') {
1616 if (is_array($formValues['privacy'])) {
1617 $op = !empty($formValues['privacy']['do_not_toggle']) ?
'=' : '!=';
1618 foreach ($formValues['privacy'] as $key => $value) {
1620 $params[] = [$key, $op, $value, 0, 0];
1625 elseif ($id === 'email_on_hold') {
1626 if ($onHoldValue = CRM_Utils_Array
::value('email_on_hold', $formValues)) {
1627 // onHoldValue should be 0 or 1 or an array. Some legacy groups may hold ''
1628 // so in 5.11 we have an extra if that should become redundant over time.
1629 // https://lab.civicrm.org/dev/core/issues/745
1630 // @todo this renaming of email_on_hold to on_hold needs revisiting
1631 // it precedes recent changes but causes the default not to reload.
1632 $onHoldValue = array_filter((array) $onHoldValue, 'is_numeric');
1633 if (!empty($onHoldValue)) {
1634 $params[] = ['on_hold', 'IN', $onHoldValue, 0, 0];
1638 elseif (substr($id, 0, 7) === 'custom_'
1640 substr($id, -5, 5) === '_from'
1641 ||
substr($id, -3, 3) === '_to'
1644 self
::convertCustomRelativeFields($formValues, $params, $values, $id);
1646 elseif (in_array($id, $entityReferenceFields) && !empty($values) && is_string($values) && (strpos($values, ',') !=
1648 $params[] = [$id, 'IN', explode(',', $values), 0, 0];
1651 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals, $apiEntity);
1656 $params[] = $values;
1663 * Function to support legacy format for groups and tags.
1666 * @param array|int $values
1669 public static function legacyConvertFormValues($id, &$values) {
1675 'membership_type_id',
1676 'membership_status_id',
1678 if (in_array($id, $legacyElements) && is_array($values)) {
1679 // prior to 4.7, formValues for some attributes (e.g. group, tag) are stored in array(id1 => 1, id2 => 1),
1680 // as per the recent Search fixes $values need to be in standard array(id1, id2) format
1681 $values = CRM_Utils_Array
::convertCheckboxFormatToArray($values);
1686 * Fix values from query from/to something no-one cared enough to document.
1689 * @param array $values
1690 * @param int $wildcard
1691 * @param bool $useEquals
1693 * @param string $apiEntity
1695 * @return array|null
1697 public static function fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL) {
1698 // skip a few search variables
1699 static $skipWhere = NULL;
1700 static $likeNames = NULL;
1703 // Change camelCase EntityName to lowercase with underscores
1704 $apiEntity = _civicrm_api_get_entity_name_from_camel($apiEntity);
1706 // check if $value is in OK (Operator as Key) format as used by Get API
1707 if (CRM_Utils_System
::isNull($values)) {
1719 'display_relationship_type',
1723 if (in_array($id, $skipWhere) ||
1724 substr($id, 0, 4) == '_qf_' ||
1725 substr($id, 0, 7) == 'hidden_'
1731 (substr($id, 0, strlen($apiEntity)) != $apiEntity) &&
1732 (substr($id, 0, 10) != 'financial_' && substr($id, 0, 8) != 'payment_') &&
1733 (substr($id, 0, 7) != 'custom_')
1735 $id = $apiEntity . '_' . $id;
1739 $likeNames = ['sort_name', 'email', 'note', 'display_name'];
1742 // email comes in via advanced search
1743 // so use wildcard always
1744 if ($id == 'email') {
1748 if (!$useEquals && in_array($id, $likeNames)) {
1749 $result = [$id, 'LIKE', $values, 0, 1];
1751 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1752 $result = [$id, 'LIKE', $values, 0, 0];
1754 elseif ($id == 'contact_type' ||
1755 (!empty($values) && is_array($values) && !in_array(key($values), CRM_Core_DAO
::acceptedSQLOperators(), TRUE))
1757 $result = [$id, 'IN', $values, 0, $wildcard];
1760 $result = [$id, '=', $values, 0, $wildcard];
1767 * Get the where clause for a single field.
1769 * @param array $values
1770 * @param bool $isForcePrimaryOnly
1772 * @throws \CRM_Core_Exception
1774 public function whereClauseSingle(&$values, $isForcePrimaryOnly = FALSE) {
1775 if ($this->isARelativeDateField($values[0])) {
1776 $this->buildRelativeDateQuery($values);
1779 // @todo also handle _low, _high generically here with if ($query->buildDateRangeQuery($values)) {return}
1781 // do not process custom fields or prefixed contact ids or component params
1782 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1783 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1784 (substr($values[0], 0, 13) === 'contribution_') ||
1785 (substr($values[0], 0, 6) === 'event_') ||
1786 (substr($values[0], 0, 12) === 'participant_') ||
1787 (substr($values[0], 0, 7) === 'member_') ||
1788 (substr($values[0], 0, 6) === 'grant_') ||
1789 (substr($values[0], 0, 7) === 'pledge_') ||
1790 (substr($values[0], 0, 5) === 'case_') ||
1791 (substr($values[0], 0, 10) === 'financial_') ||
1792 (substr($values[0], 0, 8) === 'payment_') ||
1793 (substr($values[0], 0, 11) === 'membership_')
1794 // temporary fix for regression https://lab.civicrm.org/dev/core/issues/1551
1795 // ideally the metadata would allow this field to be parsed below & the special handling would not
1797 ||
$values[0] === 'mailing_id'
1802 // skip for hook injected fields / params
1803 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1804 if (array_key_exists($values[0], $extFields)) {
1808 switch ($values[0]) {
1809 case 'deleted_contacts':
1810 $this->deletedContacts($values);
1813 case 'contact_sub_type':
1814 $this->contactSubType($values);
1819 $this->group($values);
1822 // case tag comes from find contacts
1824 $this->tagSearch($values);
1828 case 'contact_tags':
1829 $this->tag($values);
1834 case 'note_subject':
1835 $this->notes($values);
1839 $this->ufUser($values);
1843 case 'display_name':
1844 $this->sortName($values);
1848 case 'postal_greeting':
1849 case 'email_greeting':
1850 $this->greetings($values);
1855 $this->email($values, $isForcePrimaryOnly);
1858 case 'phone_numeric':
1859 $this->phone_numeric($values);
1862 case 'phone_phone_type_id':
1863 case 'phone_location_type_id':
1864 $this->phone_option_group($values);
1867 case 'street_address':
1868 $this->street_address($values);
1871 case 'street_number':
1872 $this->street_number($values);
1875 case 'sortByCharacter':
1876 $this->sortByCharacter($values);
1879 case 'location_type':
1880 $this->locationType($values);
1884 $this->county($values);
1887 case 'state_province':
1888 case 'state_province_id':
1889 case 'state_province_name':
1890 $this->stateProvince($values);
1895 $this->country($values, FALSE);
1899 case 'postal_code_low':
1900 case 'postal_code_high':
1901 $this->postalCode($values);
1904 case 'activity_date':
1905 case 'activity_date_low':
1906 case 'activity_date_high':
1907 case 'activity_date_time_low':
1908 case 'activity_date_time_high':
1909 case 'activity_role':
1910 case 'activity_status_id':
1911 case 'activity_status':
1912 case 'activity_priority':
1913 case 'activity_priority_id':
1914 case 'followup_parent_id':
1916 case 'source_contact_id':
1917 case 'activity_text':
1918 case 'activity_option':
1919 case 'test_activities':
1920 case 'activity_type_id':
1921 case 'activity_type':
1922 case 'activity_survey_id':
1923 case 'activity_tags':
1924 case 'activity_taglist':
1925 case 'activity_test':
1926 case 'activity_campaign_id':
1927 case 'activity_engagement_level':
1929 case 'activity_result':
1930 case 'source_contact':
1931 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1936 case 'birth_date_low':
1937 case 'birth_date_high':
1938 case 'deceased_date_low':
1939 case 'deceased_date_high':
1940 $this->demographics($values);
1943 case 'age_asof_date':
1944 // handled by demographics
1947 case 'log_date_low':
1948 case 'log_date_high':
1949 $this->modifiedDates($values);
1953 $this->changeLog($values);
1956 case 'do_not_phone':
1957 case 'do_not_email':
1960 case 'do_not_trade':
1962 $this->privacy($values);
1965 case 'privacy_options':
1966 $this->privacyOptions($values);
1969 case 'privacy_operator':
1970 case 'privacy_toggle':
1971 // these are handled by privacy options
1974 case 'preferred_communication_method':
1975 $this->preferredCommunication($values);
1978 case 'relation_type_id':
1979 case 'relationship_start_date_high':
1980 case 'relationship_start_date_low':
1981 case 'relationship_end_date_high':
1982 case 'relationship_end_date_low':
1983 case 'relation_active_period_date_high':
1984 case 'relation_active_period_date_low':
1985 case 'relation_target_name':
1986 case 'relation_status':
1987 case 'relation_description':
1988 case 'relation_date_low':
1989 case 'relation_date_high':
1990 $this->relationship($values);
1991 $this->_relationshipValuesAdded
= TRUE;
1994 case 'task_status_id':
1995 $this->task($values);
1999 // since this case is handled with the above
2002 case 'prox_distance':
2003 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
2006 case 'prox_street_address':
2008 case 'prox_postal_code':
2009 case 'prox_state_province_id':
2010 case 'prox_country_id':
2011 case 'prox_geo_code_1':
2012 case 'prox_geo_code_2':
2013 // handled by the proximity_distance clause
2017 $this->restWhere($values);
2023 * Given a list of conditions in params generate the required where clause.
2025 * @param bool $isForcePrimaryEmailOnly
2028 * @throws \CRM_Core_Exception
2030 public function whereClause($isForcePrimaryEmailOnly = NULL) {
2031 $this->_where
[0] = [];
2032 $this->_qill
[0] = [];
2034 $this->includeContactIDs();
2035 if (!empty($this->_params
)) {
2036 foreach (array_keys($this->_params
) as $id) {
2037 if (empty($this->_params
[$id][0])) {
2040 // check for both id and contact_id
2041 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
2042 $this->_where
[0][] = self
::buildClause("contact_a.id", $this->_params
[$id][1], $this->_params
[$id][2]);
2043 $field = $this->_fields
['id'] ??
NULL;
2044 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(
2045 'CRM_Contact_BAO_Contact',
2047 $this->_params
[$id][2],
2048 $this->_params
[$id][1]
2050 $this->_qill
[0][] = ts("%1 %2 %3", [
2051 1 => $field['title'] ??
'',
2057 $this->whereClauseSingle($this->_params
[$id], $isForcePrimaryEmailOnly);
2061 CRM_Core_Component
::alterQuery($this, 'where');
2063 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
2066 if ($this->_customQuery
) {
2067 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
2068 // Added following if condition to avoid the wrong value display for 'my account' / any UF info.
2069 // Hope it wont affect the other part of civicrm.. if it does please remove it.
2070 if (!empty($this->_customQuery
->_where
)) {
2071 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
2073 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
2080 if (!empty($this->_where
)) {
2081 foreach ($this->_where
as $grouping => $values) {
2082 if ($grouping > 0 && !empty($values)) {
2083 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
2088 if (!empty($this->_where
[0])) {
2089 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
2091 if (!empty($clauses)) {
2092 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
2095 if ($validClauses > 1) {
2096 $this->_useDistinct
= TRUE;
2100 return implode(' AND ', $andClauses);
2104 * Generate where clause for any parameters not already handled.
2106 * @param array $values
2110 public function restWhere(&$values) {
2111 $name = $values[0] ??
NULL;
2112 $op = $values[1] ??
NULL;
2113 $value = $values[2] ??
NULL;
2114 $grouping = $values[3] ??
NULL;
2115 $wildcard = $values[4] ??
NULL;
2117 if (isset($grouping) && empty($this->_where
[$grouping])) {
2118 $this->_where
[$grouping] = [];
2121 $multipleFields = ['url'];
2123 //check if the location type exists for fields
2125 $locType = explode('-', $name);
2127 if (!in_array($locType[0], $multipleFields)) {
2128 //add phone type if exists
2129 if (isset($locType[2]) && $locType[2]) {
2130 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
2134 $field = $this->_fields
[$name] ??
NULL;
2137 $field = $this->_fields
[$locType[0]] ??
NULL;
2140 // Strip any trailing _high & _low that might be appended.
2141 $realFieldName = str_replace(['_high', '_low'], '', $name);
2142 if (isset($this->_fields
[$realFieldName])) {
2143 $field = $this->_fields
[str_replace(['_high', '_low'], '', $realFieldName)];
2144 $columnName = $field['column_name'] ??
$field['name'];
2145 $this->dateQueryBuilder($values, $field['table_name'], $realFieldName, $columnName, $field['title']);
2153 $locationType = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
2154 if (isset($locType[1]) && is_numeric($locType[1])) {
2155 $lType = $locationType[$locType[1]];
2158 $field['title'] .= " ($lType)";
2161 if (substr($name, 0, 14) === 'state_province') {
2162 if (isset($locType[1]) && is_numeric($locType[1])) {
2164 $aName = "{$lType}-address";
2165 $where = "`$aName`.state_province_id";
2168 $where = "civicrm_address.state_province_id";
2171 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value);
2172 $this->_tables
[$aName] = $this->_whereTables
[$aName] = 1;
2173 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
2174 $this->_qill
[$grouping][] = ts("%1 %2 %3", [1 => $field['title'], 2 => $qillop, 3 => $qillVal]);
2176 elseif (!empty($field['pseudoconstant'])) {
2177 // For the hacked fields we want to undo the hack to type to avoid missing the index by adding quotes.
2178 $dataType = !empty($this->legacyHackedFields
[$name]) ? CRM_Utils_Type
::T_INT
: $field['type'];
2179 $this->optionValueQuery(
2180 $name, $op, $value, $grouping,
2181 'CRM_Contact_DAO_Contact',
2183 $field['html']['label'] ??
$field['title'],
2184 CRM_Utils_Type
::typeToString($dataType)
2186 if ($name === 'gender_id') {
2187 self
::$_openedPanes[ts('Demographics')] = TRUE;
2190 elseif (substr($name, 0, 7) === 'country' ||
substr($name, 0, 6) === 'county') {
2191 $name = (substr($name, 0, 7) === 'country') ?
"country_id" : "county_id";
2192 if (isset($locType[1]) && is_numeric($locType[1])) {
2194 $aName = "{$lType}-address";
2195 $where = "`$aName`.$name";
2198 $where = "civicrm_address.$name";
2201 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2202 $this->_tables
[$aName] = $this->_whereTables
[$aName] = 1;
2204 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
2205 $this->_qill
[$grouping][] = ts("%1 %2 %3", [1 => $field['title'], 2 => $qillop, 3 => $qillVal]);
2207 elseif ($name === 'world_region') {
2208 $this->optionValueQuery(
2209 $name, $op, $value, $grouping,
2216 elseif ($name === 'is_deceased') {
2217 $this->setQillAndWhere($name, $op, $value, $grouping, $field);
2218 self
::$_openedPanes[ts('Demographics')] = TRUE;
2220 elseif ($name === 'created_date' ||
$name === 'modified_date' ||
$name === 'deceased_date' ||
$name === 'birth_date') {
2221 $appendDateTime = TRUE;
2222 if ($name === 'deceased_date' ||
$name === 'birth_date') {
2223 $appendDateTime = FALSE;
2224 self
::$_openedPanes[ts('Demographics')] = TRUE;
2226 $this->dateQueryBuilder($values, 'contact_a', $name, $name, $field['title'], $appendDateTime);
2228 elseif ($name === 'contact_id') {
2229 if (is_int($value)) {
2230 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
2231 $this->_qill
[$grouping][] = "$field[title] $op $value";
2234 elseif ($name === 'name') {
2235 $value = CRM_Core_DAO
::escapeString($value);
2238 $value = self
::getWildCardedValue($wildcard, $op, $value);
2240 CRM_Core_Error
::deprecatedFunctionWarning('Untested code path');
2241 // @todo it's likely this code path is obsolete / never called. It is definitely not
2242 // passed through in our test suite.
2243 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, "'$value'");
2244 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2246 elseif ($name === 'current_employer') {
2249 $value = self
::getWildCardedValue($wildcard, $op, $value);
2251 $ceWhereClause = self
::buildClause("contact_a.organization_name", $op,
2254 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2255 $this->_where
[$grouping][] = $ceWhereClause;
2256 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2258 elseif (substr($name, 0, 4) === 'url-') {
2259 $tName = 'civicrm_website';
2260 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2261 $value = CRM_Core_DAO
::escapeString($value);
2264 $value = self
::getWildCardedValue($wildcard, $op, $value);
2267 $this->_where
[$grouping][] = $d = self
::buildClause('civicrm_website.url', $op, $value);
2268 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2270 elseif ($name === 'contact_is_deleted') {
2271 $this->setQillAndWhere('is_deleted', $op, $value, $grouping, $field);
2273 elseif (!empty($field['where'])) {
2275 if (!empty($field['type'])) {
2276 $type = CRM_Utils_Type
::typeToString($field['type']);
2279 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2281 if (isset($locType[1]) &&
2282 is_numeric($locType[1])
2286 //get the location name
2287 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2288 $fieldName = "`$tName`.$fldName";
2290 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2291 $this->_tables
[$tName] = $this->_whereTables
[$tName] = 1;
2295 if ($tableName == 'civicrm_contact') {
2296 $fieldName = "contact_a.{$fieldName}";
2299 $fieldName = $field['where'];
2303 list($qillop, $qillVal) = self
::buildQillForFieldValue(NULL, $field['title'], $value, $op);
2304 $this->_qill
[$grouping][] = ts("%1 %2 %3", [
2305 1 => $field['title'],
2307 3 => (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) ?
$qillVal : "'$qillVal'",
2310 if (is_array($value)) {
2311 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2312 // for api style operators for functions that hit this point without worrying about regression
2313 // (the previous comments indicated the condition for hitting this point were unknown
2314 // per CRM-14743 we are adding modified_date & created_date operator support
2315 $operations = array_keys($value);
2316 foreach ($operations as $operator) {
2317 if (!in_array($operator, CRM_Core_DAO
::acceptedSQLOperators())) {
2318 //Via Contact get api value is not in array(operator => array(values)) format ONLY for IN/NOT IN operators
2319 //so this condition will satisfy the search for now
2320 if (strpos($op, 'IN') !== FALSE) {
2321 $value = [$op => $value];
2323 // we don't know when this might happen
2325 throw new CRM_Core_Exception(ts("%1 is not a valid operator", [1 => $operator]));
2329 $this->_where
[$grouping][] = CRM_Core_DAO
::createSQLFilter($fieldName, $value, $type);
2334 $value = self
::getWildCardedValue($wildcard, $op, $value);
2337 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2341 if ($setTables && isset($field['where'])) {
2342 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2343 if (isset($tableName)) {
2344 $this->_tables
[$tableName] = 1;
2345 $this->_whereTables
[$tableName] = 1;
2357 public static function getLocationTableName(&$where, &$locType) {
2358 if (isset($locType[1]) && is_numeric($locType[1])) {
2359 list($tbName, $fldName) = explode(".", $where);
2361 //get the location name
2362 $locationType = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
2363 $specialFields = ['email', 'im', 'phone', 'openid', 'phone_ext'];
2364 if (in_array($locType[0], $specialFields)) {
2365 //hack to fix / special handing for phone_ext
2366 if ($locType[0] == 'phone_ext') {
2367 $locType[0] = 'phone';
2369 if (isset($locType[2]) && $locType[2]) {
2370 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2373 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2376 elseif (in_array($locType[0],
2381 'street_number_suffix',
2383 'supplemental_address_1',
2384 'supplemental_address_2',
2385 'supplemental_address_3',
2388 'postal_code_suffix',
2394 //fix for search by profile with address fields.
2395 $tName = "{$locationType[$locType[1]]}-address";
2397 elseif (in_array($locType[0],
2405 $tName = "{$locationType[$locType[1]]}-email";
2407 elseif ($locType[0] == 'provider_id') {
2408 $tName = "{$locationType[$locType[1]]}-im";
2410 elseif ($locType[0] == 'openid') {
2411 $tName = "{$locationType[$locType[1]]}-openid";
2414 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2416 $tName = str_replace(' ', '_', $tName);
2417 return [$tName, $fldName];
2419 throw new CRM_Core_Exception('Cannot determine location table information');
2423 * Given a result dao, extract the values and return that array
2425 * @param CRM_Core_DAO $dao
2428 * values for this query
2430 public function store($dao) {
2433 foreach ($this->_element
as $key => $dontCare) {
2434 if (property_exists($dao, $key)) {
2435 if (strpos($key, '-') !== FALSE) {
2436 $values = explode('-', $key);
2437 $lastElement = array_pop($values);
2439 $cnt = count($values);
2441 foreach ($values as $v) {
2442 if (!array_key_exists($v, $current)) {
2445 //bad hack for im_provider
2446 if ($lastElement == 'provider_id') {
2447 if ($count < $cnt) {
2448 $current = &$current[$v];
2451 $lastElement = "{$v}_{$lastElement}";
2455 $current = &$current[$v];
2460 $current[$lastElement] = $dao->$key;
2463 $value[$key] = $dao->$key;
2471 * Getter for tables array.
2475 public function tables() {
2476 return $this->_tables
;
2480 * Sometimes used to create the from clause, but, not reliably, set
2481 * this AND set tables.
2483 * It's unclear the intent - there is a 'simpleFrom' clause which
2484 * takes whereTables into account & a fromClause which doesn't.
2486 * logic may have eroded?
2490 public function whereTables() {
2491 return $this->_whereTables
;
2495 * Generate the where clause (used in match contacts and permissions)
2497 * @param array $params
2498 * @param array $fields
2499 * @param array $tables
2500 * @param $whereTables
2501 * @param bool $strict
2504 * @throws \CRM_Core_Exception
2506 public static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2507 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2511 $tables = array_merge($query->tables(), $tables);
2512 $whereTables = array_merge($query->whereTables(), $whereTables);
2514 return $query->_whereClause
;
2518 * Create the from clause.
2520 * @param array $tables
2521 * Tables that need to be included in this from clause. If null,
2522 * return mimimal from clause (i.e. civicrm_contact).
2523 * @param array $inner
2524 * Tables that should be inner-joined.
2525 * @param array $right
2526 * Tables that should be right-joined.
2527 * @param bool $primaryLocation
2528 * Search on primary location. See note below.
2530 * Determines search mode based on bitwise MODE_* constants.
2531 * @param string|NULL $apiEntity
2532 * Determines search mode based on entity by string.
2534 * The $primaryLocation flag only seems to be used when
2535 * locationType() has been called. This may be a search option
2536 * exposed, or perhaps it's a "search all details" approach which
2537 * predates decoupling of location types and primary fields?
2539 * @see https://issues.civicrm.org/jira/browse/CRM-19967
2544 public static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1, $apiEntity = NULL) {
2546 $from = ' FROM civicrm_contact contact_a';
2547 if (empty($tables)) {
2551 if (!empty($tables['civicrm_worldregion'])) {
2552 $tables = array_merge(['civicrm_country' => 1], $tables);
2555 if ((!empty($tables['civicrm_state_province']) ||
!empty($tables['civicrm_country']) ||
2556 !empty($tables['civicrm_county'])) && empty($tables['civicrm_address'])) {
2557 $tables = array_merge(['civicrm_address' => 1],
2562 // add group_contact and group table is subscription history is present
2563 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2564 $tables = array_merge([
2565 'civicrm_group' => 1,
2566 'civicrm_group_contact' => 1,
2572 // to handle table dependencies of components
2573 CRM_Core_Component
::tableNames($tables);
2574 // to handle table dependencies of hook injected tables
2575 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2577 //format the table list according to the weight
2578 $info = CRM_Core_TableHierarchy
::info();
2580 foreach ($tables as $key => $value) {
2582 if (strpos($key, '-') !== FALSE) {
2583 $keyArray = explode('-', $key);
2584 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2586 elseif (strpos($key, '_') !== FALSE) {
2587 $keyArray = explode('_', $key);
2588 if (is_numeric(array_pop($keyArray))) {
2589 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2592 $k = CRM_Utils_Array
::value($key, $info, 99);
2596 $k = CRM_Utils_Array
::value($key, $info, 99);
2598 $tempTable[$k . ".$key"] = $key;
2602 foreach ($tempTable as $key) {
2603 $newTables[$key] = $tables[$key];
2606 $tables = $newTables;
2608 foreach ($tables as $name => $value) {
2613 if (!empty($inner[$name])) {
2616 elseif (!empty($right[$name])) {
2624 // if there is already a join statement in value, use value itself
2625 if (strpos($value, 'JOIN')) {
2626 $from .= " $value ";
2629 $from .= " $side JOIN $name ON ( $value ) ";
2634 $from .= ' ' . trim(self
::getEntitySpecificJoins($name, $mode, $side, $primaryLocation)) . ' ';
2640 * Get join statements for the from clause depending on entity type
2642 * @param string $name
2644 * @param string $side
2645 * @param string $primaryLocation
2648 protected static function getEntitySpecificJoins($name, $mode, $side, $primaryLocation) {
2649 $limitToPrimaryClause = $primaryLocation ?
"AND {$name}.is_primary = 1" : '';
2651 case 'civicrm_address':
2652 //CRM-14263 further handling of address joins further down...
2653 return " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id {$limitToPrimaryClause} )";
2655 case 'civicrm_state_province':
2656 // This is encountered when doing an export after having applied a 'sort' - it pretty much implies primary
2657 // but that will have been implied-in by the calling function.
2658 // test cover in testContactIDQuery
2659 return " $side JOIN civicrm_state_province ON ( civicrm_address.state_province_id = civicrm_state_province.id )";
2661 case 'civicrm_country':
2662 // This is encountered when doing an export after having applied a 'sort' - it pretty much implies primary
2663 // but that will have been implied-in by the calling function.
2664 // test cover in testContactIDQuery
2665 return " $side JOIN civicrm_country ON ( civicrm_address.country_id = civicrm_country.id )";
2667 case 'civicrm_phone':
2668 return " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id {$limitToPrimaryClause}) ";
2670 case 'civicrm_email':
2671 return " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id {$limitToPrimaryClause})";
2674 return " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id {$limitToPrimaryClause}) ";
2677 $from = " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2678 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2679 $from .= " $side JOIN civicrm_option_value im_provider ON (civicrm_im.provider_id = im_provider.value AND option_group_imProvider.id = im_provider.option_group_id)";
2682 case 'civicrm_openid':
2683 return " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id {$limitToPrimaryClause} )";
2685 case 'civicrm_worldregion':
2686 // We can be sure from the calling function that country will already be joined in.
2687 // we really don't need world_region - we could use a pseudoconstant for it.
2688 return " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2690 case 'civicrm_location_type':
2691 return " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2693 case 'civicrm_group':
2694 return " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2696 case 'civicrm_group_contact':
2697 return " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2699 case 'civicrm_group_contact_cache':
2700 return " $side JOIN civicrm_group_contact_cache ON contact_a.id = civicrm_group_contact_cache.contact_id ";
2702 case 'civicrm_activity':
2703 case 'civicrm_activity_tag':
2704 case 'activity_type':
2705 case 'activity_status':
2707 case 'civicrm_activity_contact':
2708 case 'source_contact':
2709 case 'activity_priority':
2710 return CRM_Activity_BAO_Query
::from($name, $mode, $side);
2712 case 'civicrm_entity_tag':
2713 $from = " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact'";
2714 return "$from AND civicrm_entity_tag.entity_id = contact_a.id ) ";
2716 case 'civicrm_note':
2717 $from = " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact'";
2718 return "$from AND contact_a.id = civicrm_note.entity_id ) ";
2720 case 'civicrm_subscription_history':
2721 $from = " $side JOIN civicrm_subscription_history";
2722 $from .= " ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id";
2723 return "$from AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2725 case 'civicrm_relationship':
2726 if (self
::$_relType == 'reciprocal') {
2727 if (self
::$_relationshipTempTable) {
2728 // we have a temptable to join on
2729 $tbl = self
::$_relationshipTempTable;
2730 return " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2733 $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2734 $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)";
2738 elseif (self
::$_relType == 'b') {
2739 $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2740 return "$from $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2743 $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2744 return "$from $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2748 $from = " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2749 return "$from INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2752 return " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2754 case 'civicrm_grant':
2755 return CRM_Grant_BAO_Query
::from($name, $mode, $side);
2757 case 'civicrm_website':
2758 return " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2760 case 'civicrm_campaign':
2761 //Move to default case if not in either mode.
2762 if ($mode & CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
2763 return CRM_Contribute_BAO_Query
::from($name, $mode, $side);
2765 elseif ($mode & CRM_Contact_BAO_Query
::MODE_MAILING
) {
2766 return CRM_Mailing_BAO_Query
::from($name, $mode, $side);
2768 elseif ($mode & CRM_Contact_BAO_Query
::MODE_CAMPAIGN
) {
2769 return CRM_Campaign_BAO_Query
::from($name, $mode, $side);
2773 $locationTypeName = '';
2774 if (strpos($name, '-address') != 0) {
2775 $locationTypeName = 'address';
2777 elseif (strpos($name, '-phone') != 0) {
2778 $locationTypeName = 'phone';
2780 elseif (strpos($name, '-email') != 0) {
2781 $locationTypeName = 'email';
2783 elseif (strpos($name, '-im') != 0) {
2784 $locationTypeName = 'im';
2786 elseif (strpos($name, '-openid') != 0) {
2787 $locationTypeName = 'openid';
2790 if ($locationTypeName) {
2791 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2792 $parts = explode('-', $name);
2793 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
2794 foreach ($locationTypes as $locationTypeID => $locationType) {
2795 if ($parts[0] == str_replace(' ', '_', $locationType)) {
2796 $locationID = $locationTypeID;
2799 $from = " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2802 $from = CRM_Core_Component
::from($name, $mode, $side);
2804 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2811 * WHERE / QILL clause for deleted_contacts
2813 * @param array $values
2815 public function deletedContacts($values) {
2816 list($_, $_, $value, $grouping, $_) = $values;
2818 // *prepend* to the relevant grouping as this is quite an important factor
2819 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2824 * Where / qill clause for contact_type
2828 * @throws \CRM_Core_Exception
2830 public function contactType(&$values) {
2831 list($name, $op, $value, $grouping, $wildcard) = $values;
2836 // account for search builder mapping multiple values
2837 if (!is_array($value)) {
2838 $values = self
::parseSearchBuilderString($value, 'String');
2839 if (is_array($values)) {
2840 $value = array_flip($values);
2844 if (is_array($value)) {
2845 foreach ($value as $k => $v) {
2850 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2851 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2854 if (!empty($subType)) {
2855 $subTypes[$subType] = 1;
2857 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2862 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2863 $contactType = $contactTypeANDSubType[0];
2864 $subType = $contactTypeANDSubType[1] ??
NULL;
2865 if (!empty($subType)) {
2866 $subTypes[$subType] = 1;
2868 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2872 if (!empty($clause)) {
2874 if ($op == 'IN' ||
$op == 'NOT IN') {
2875 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2878 $type = array_pop($clause);
2879 $this->_where
[$grouping][] = self
::buildClause("contact_a.contact_type", $op, $contactType);
2882 $this->_qill
[$grouping][] = ts('Contact Type') . " $op " . implode(' ' . ts('or') . ' ', $quill);
2884 if (!empty($subTypes)) {
2885 $this->includeContactSubTypes($subTypes, $grouping);
2891 * Where / qill clause for contact_sub_type.
2893 * @param array $values
2895 public function contactSubType(&$values) {
2896 list($name, $op, $value, $grouping, $wildcard) = $values;
2897 $this->includeContactSubTypes($value, $grouping, $op);
2905 * @throws \CRM_Core_Exception
2907 public function includeContactSubTypes($value, $grouping, $op = 'LIKE') {
2909 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2911 $value = $value[$op];
2915 $alias = "contact_a.contact_sub_type";
2916 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
2918 $op = str_replace('IN', 'LIKE', $op);
2919 $op = str_replace('=', 'LIKE', $op);
2920 $op = str_replace('!', 'NOT ', $op);
2922 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2923 $this->_where
[$grouping][] = self
::buildClause($alias, $op, $value, 'String');
2925 elseif (is_array($value)) {
2926 foreach ($value as $k => $v) {
2927 $clause[$k] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($v, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2931 $clause[$value] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2934 if (!empty($clause)) {
2935 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2937 $this->_qill
[$grouping][] = ts('Contact Subtype %1 ', [1 => $qillOperators[$op]]) . implode(' ' . ts('or') . ' ', array_keys($clause));
2941 * Where / qill clause for groups.
2945 * @throws \CRM_Core_Exception
2946 * @throws \Exception
2948 public function group($values) {
2949 list($name, $op, $value, $grouping, $wildcard) = $values;
2951 // If the $value is in OK (operator as key) array format we need to extract the key as operator and value first
2952 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2954 $value = $value[$op];
2956 // Translate EMPTY to NULL as EMPTY is cannot be used in it's intended meaning here
2957 // so has to be 'squashed into' NULL. (ie. group membership cannot be '').
2958 // even one group might equate to multiple when looking at children so IN is simpler.
2959 // @todo - also look at != casting but there are rows below to review.
2961 'IS EMPTY' => 'IS NULL',
2962 'IS NOT EMPTY' => 'IS NOT NULL',
2965 if (isset($opReplacements[$op])) {
2966 $op = $opReplacements[$op];
2969 if (strpos($op, 'NULL')) {
2973 if (is_array($value) && count($value) > 1) {
2974 if (strpos($op, 'IN') === FALSE && strpos($op, 'NULL') === FALSE) {
2975 throw new CRM_Core_Exception(ts("%1 is not a valid operator", [1 => $op]));
2977 $this->_useDistinct
= TRUE;
2980 if (isset($value)) {
2981 $value = CRM_Utils_Array
::value($op, $value, $value);
2984 if ($name === 'group_type') {
2985 $value = array_keys($this->getGroupsFromTypeCriteria($value));
2988 $regularGroupIDs = $smartGroupIDs = [];
2989 foreach ((array) $value as $id) {
2990 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
2991 $smartGroupIDs[] = (int) $id;
2994 $regularGroupIDs[] = (int) trim($id);
2997 $hasNonSmartGroups = count($regularGroupIDs);
2999 $isNotOp = ($op === 'NOT IN' ||
$op === '!=');
3001 $statusJoinClause = $this->getGroupStatusClause($grouping);
3002 // If we are searching for 'Removed' contacts then despite it being a smart group we only care about the group_contact table.
3003 $isGroupStatusSearch = (!empty($this->getSelectedGroupStatuses($grouping)) && $this->getSelectedGroupStatuses($grouping) !== ["'Added'"]);
3005 if ($hasNonSmartGroups ||
empty($value) ||
$isGroupStatusSearch) {
3006 // include child groups IDs if any
3007 $childGroupIds = (array) CRM_Contact_BAO_Group
::getChildGroupIds($regularGroupIDs);
3008 foreach ($childGroupIds as $key => $id) {
3009 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
3010 $smartGroupIDs[] = $id;
3011 unset($childGroupIds[$key]);
3014 if (count($childGroupIds)) {
3015 $regularGroupIDs = array_merge($regularGroupIDs, $childGroupIds);
3018 if (empty($regularGroupIDs)) {
3019 if ($isGroupStatusSearch) {
3020 $regularGroupIDs = $smartGroupIDs;
3022 // If it is still empty we want a filter that blocks all results.
3023 if (empty($regularGroupIDs)) {
3024 $regularGroupIDs = [0];
3028 $gcTable = '`civicrm_group_contact-' . uniqid() . "`";
3029 $joinClause = ["contact_a.id = {$gcTable}.contact_id"];
3031 // @todo consider just casting != to NOT IN & handling both together.
3034 if (!empty($regularGroupIDs)) {
3035 $groupIds = CRM_Utils_Type
::validate(implode(',', (array) $regularGroupIDs), 'CommaSeparatedIntegers');
3037 $clause = "{$gcTable}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact cgc WHERE cgc.group_id = $groupIds )";
3040 $clause = self
::buildClause("{$gcTable}.group_id", $op, $regularGroupIDs);
3042 $groupClause[] = "( {$clause} )";
3044 if ($statusJoinClause) {
3045 $joinClause[] = "{$gcTable}.$statusJoinClause";
3047 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
3050 //CRM-19589: contact(s) removed from a Smart Group, resides in civicrm_group_contact table
3051 // If we are only searching for Removed or Pending contacts we don't need to resolve the smart group
3052 // as that info is in the group_contact table.
3053 if ((count($smartGroupIDs) ||
empty($value)) && !$isGroupStatusSearch) {
3054 $this->_groupUniqueKey
= uniqid();
3055 $this->_groupKeys
[] = $this->_groupUniqueKey
;
3056 $gccTableAlias = "civicrm_group_contact_cache_{$this->_groupUniqueKey}";
3057 $groupContactCacheClause = $this->addGroupContactCache($smartGroupIDs, $gccTableAlias, "contact_a", $op);
3058 if (!empty($groupContactCacheClause)) {
3060 $groupIds = CRM_Utils_Type
::validate(implode(',', (array) $smartGroupIDs), 'CommaSeparatedIntegers');
3061 $gcTable = "civicrm_group_contact_{$this->_groupUniqueKey}";
3062 $joinClause = ["contact_a.id = {$gcTable}.contact_id"];
3063 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
3064 if (strpos($op, 'IN') !== FALSE) {
3065 $groupClause[] = "{$gcTable}.group_id $op ( $groupIds ) AND {$gccTableAlias}.group_id IS NULL";
3068 $groupClause[] = "{$gcTable}.group_id $op $groupIds AND {$gccTableAlias}.group_id IS NULL";
3071 $groupClause[] = " ( {$groupContactCacheClause} ) ";
3075 $and = ($op == 'IS NULL') ?
' AND ' : ' OR ';
3076 if (!empty($groupClause)) {
3077 $this->_where
[$grouping][] = ' ( ' . implode($and, $groupClause) . ' ) ';
3080 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Group', 'id', $value, $op);
3081 $this->_qill
[$grouping][] = ts("Group(s) %1 %2", [1 => $qillop, 2 => $qillVal]);
3082 if (strpos($op, 'NULL') === FALSE) {
3083 $this->_qill
[$grouping][] = ts("Group Status %1", [1 => implode(' ' . ts('or') . ' ', $this->getSelectedGroupStatuses($grouping))]);
3090 public function getGroupCacheTableKeys() {
3091 return $this->_groupKeys
;
3095 * Function translates selection of group type into a list of groups.
3100 public function getGroupsFromTypeCriteria($value) {
3102 foreach ((array) $value as $groupTypeValue) {
3103 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
3104 $groupIds = ($groupIds +
$groupList);
3110 * Prime smart group cache for smart groups in the search, and join
3111 * civicrm_group_contact_cache table into the query.
3113 * @param array $groups IDs of groups specified in search criteria.
3114 * @param string $tableAlias Alias to use for civicrm_group_contact_cache table.
3115 * @param string $joinTable Table on which to join civicrm_group_contact_cache
3116 * @param string $op SQL comparison operator (NULL, IN, !=, IS NULL, etc.)
3117 * @param string $joinColumn Column in $joinTable on which to join civicrm_group_contact_cache.contact_id
3119 * @return string WHERE clause component for smart group criteria.
3120 * @throws \CRM_Core_Exception
3122 public function addGroupContactCache($groups, $tableAlias, $joinTable = "contact_a", $op, $joinColumn = 'id') {
3123 $isNullOp = (strpos($op, 'NULL') !== FALSE);
3124 $groupsIds = $groups;
3126 $operator = ['=' => 'IN', '!=' => 'NOT IN'];
3127 if (!empty($operator[$op]) && is_array($groups)) {
3128 $op = $operator[$op];
3130 if (!$isNullOp && !$groups) {
3133 elseif (strpos($op, 'IN') !== FALSE) {
3134 $groups = [$op => $groups];
3136 elseif (is_array($groups) && count($groups)) {
3137 $groups = ['IN' => $groups];
3140 // Find all the groups that are part of a saved search.
3141 $smartGroupClause = self
::buildClause("id", $op, $groups, 'Int');
3143 SELECT id, cache_date, saved_search_id, children
3145 WHERE $smartGroupClause
3146 AND ( saved_search_id != 0
3147 OR saved_search_id IS NOT NULL
3148 OR children IS NOT NULL )
3151 $group = CRM_Core_DAO
::executeQuery($sql);
3153 while ($group->fetch()) {
3154 $this->_useDistinct
= TRUE;
3155 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
3156 CRM_Contact_BAO_GroupContactCache
::load($group);
3159 if ($group->N
== 0 && $op != 'NOT IN') {
3163 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache {$tableAlias} ON {$joinTable}.{$joinColumn} = {$tableAlias}.contact_id ";
3165 if ($op == 'NOT IN') {
3166 return "{$tableAlias}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact_cache cgcc WHERE cgcc.group_id IN ( " . implode(',', (array) $groupsIds) . " ) )";
3168 return self
::buildClause("{$tableAlias}.group_id", $op, $groups, 'Int');
3172 * Where / qill clause for cms users
3176 public function ufUser(&$values) {
3177 list($name, $op, $value, $grouping, $wildcard) = $values;
3180 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3182 $this->_qill
[$grouping][] = ts('CMS User');
3184 elseif ($value == 0) {
3185 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3187 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
3188 $this->_qill
[$grouping][] = ts('Not a CMS User');
3193 * All tag search specific.
3195 * @param array $values
3197 * @throws \CRM_Core_Exception
3199 public function tagSearch(&$values) {
3200 list($name, $op, $value, $grouping, $wildcard) = $values;
3203 $value = "%{$value}%";
3204 $escapedValue = CRM_Utils_Type
::escape("%{$value}%", 'String');
3206 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3207 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3209 $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
3210 $tTable = "`civicrm_tag-" . uniqid() . "`";
3212 if ($useAllTagTypes[2]) {
3213 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3214 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
3215 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
3217 // search tag in cases
3218 $etCaseTable = "`civicrm_entity_case_tag-" . uniqid() . "`";
3219 $tCaseTable = "`civicrm_case_tag-" . uniqid() . "`";
3220 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3221 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3222 LEFT JOIN civicrm_case
3223 ON (civicrm_case_contact.case_id = civicrm_case.id
3224 AND civicrm_case.is_deleted = 0 )
3225 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
3226 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
3227 // search tag in activities
3228 $etActTable = "`civicrm_entity_act_tag-" . uniqid() . "`";
3229 $tActTable = "`civicrm_act_tag-" . uniqid() . "`";
3230 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
3231 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3233 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3234 = " LEFT JOIN civicrm_activity_contact
3235 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3236 LEFT JOIN civicrm_activity
3237 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3238 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3239 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
3240 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
3242 $this->_where
[$grouping][] = "({$tTable}.name $op '" . $escapedValue . "' OR {$tCaseTable}.name $op '" . $escapedValue . "' OR {$tActTable}.name $op '" . $escapedValue . "')";
3243 $this->_qill
[$grouping][] = ts('Tag %1 %2', [1 => $tagTypesText[2], 2 => $op]) . ' ' . $value;
3246 $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
3247 $tTable = "`civicrm_tag-" . uniqid() . "`";
3248 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
3249 {$etTable}.entity_table = 'civicrm_contact' )
3250 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
3252 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
3253 $this->_qill
[$grouping][] = ts('Tagged %1', [1 => $op]) . ' ' . $value;
3258 * Where / qill clause for tag.
3260 * @param array $values
3262 * @throws \CRM_Core_Exception
3264 public function tag(&$values) {
3265 list($name, $op, $value, $grouping, $wildcard) = $values;
3267 // API/Search Builder format array(operator => array(values))
3268 if (is_array($value)) {
3269 if (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
3271 $value = $value[$op];
3273 if (count($value) > 1) {
3274 $this->_useDistinct
= TRUE;
3278 if (strpos($op, 'NULL') ||
strpos($op, 'EMPTY')) {
3282 $tagTree = CRM_Core_BAO_Tag
::getChildTags();
3283 foreach ((array) $value as $tagID) {
3284 if (!empty($tagTree[$tagID])) {
3285 $value = array_unique(array_merge($value, $tagTree[$tagID]));
3289 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_EntityTag', "tag_id", $value, $op, ['onlyActive' => FALSE]);
3291 // implode array, then remove all spaces
3292 $value = str_replace(' ', '', implode(',', (array) $value));
3293 if (!empty($value)) {
3294 $value = CRM_Utils_Type
::validate($value, 'CommaSeparatedIntegers');
3297 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3298 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3300 $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
3302 if (!empty($useAllTagTypes[2])) {
3303 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3304 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3306 // search tag in cases
3307 $etCaseTable = "`civicrm_entity_case_tag-" . uniqid() . "`";
3308 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
3309 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3311 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3312 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3313 LEFT JOIN civicrm_case
3314 ON (civicrm_case_contact.case_id = civicrm_case.id
3315 AND civicrm_case.is_deleted = 0 )
3316 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3317 // search tag in activities
3318 $etActTable = "`civicrm_entity_act_tag-" . uniqid() . "`";
3319 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3320 = " LEFT JOIN civicrm_activity_contact
3321 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3322 LEFT JOIN civicrm_activity
3323 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3324 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3325 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3328 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
3329 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3332 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (" . $value . ") OR {$etCaseTable}.tag_id $op (" . $value . ") OR {$etActTable}.tag_id $op (" . $value . "))";
3336 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3337 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3340 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
3341 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3342 $op = str_replace('EMPTY', 'NULL', $op);
3343 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
3345 // CRM-16941: for tag tried with != operator we don't show contact who don't have given $value AND also in other tag
3346 elseif ($op == '!=') {
3347 $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') . ")";
3349 elseif ($op == '=' ||
strstr($op, 'IN')) {
3350 $op = ($op == '=') ?
'IN' : $op;
3351 $this->_where
[$grouping][] = "{$etTable}.tag_id $op ( $value )";
3354 $this->_qill
[$grouping][] = ts('Tagged %1 %2', [1 => $qillop, 2 => $qillVal]);
3358 * Where/qill clause for notes
3360 * @param array $values
3362 * @throws \CRM_Core_Exception
3364 public function notes(&$values) {
3365 list($name, $op, $value, $grouping, $wildcard) = $values;
3367 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3368 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
3369 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
3371 $this->_useDistinct
= TRUE;
3373 $this->_tables
['civicrm_note'] = $this->_whereTables
['civicrm_note']
3374 = " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3377 $value = CRM_Core_DAO
::escapeString($n);
3379 if (strpos($value, '%') === FALSE) {
3380 $value = "%$value%";
3384 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
3390 if ($noteOption %
2 == 0) {
3391 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
3392 $label = ts('Note: Body Only');
3394 if ($noteOption %
3 == 0) {
3395 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
3396 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
3398 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3399 list($qillOp, $qillVal) = self
::buildQillForFieldValue(NULL, $name, $n, $op);
3400 $this->_qill
[$grouping][] = ts("%1 %2 %3", [1 => $label, 2 => $qillOp, 3 => $qillVal]);
3404 * @param string $name
3410 public function nameNullOrEmptyOp($name, $op, $grouping) {
3414 $this->_where
[$grouping][] = "contact_a.$name $op";
3415 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3419 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3420 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3423 case 'IS NOT EMPTY':
3424 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3425 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3434 * Where / qill clause for sort_name
3436 * @param array $values
3438 public function sortName(&$values) {
3439 list($fieldName, $op, $value, $grouping, $wildcard) = $values;
3441 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3442 if ($this->nameNullOrEmptyOp($fieldName, $op, $grouping)) {
3446 $input = $value = is_array($value) ?
trim($value['LIKE']) : trim($value);
3448 if (!strlen($value)) {
3452 $config = CRM_Core_Config
::singleton();
3456 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3459 $firstChar = substr($value, 0, 1);
3460 $lastChar = substr($value, -1, 1);
3461 $quotes = ["'", '"'];
3462 // If string is quoted, strip quotes and otherwise don't alter it
3463 if ((strlen($value) > 2) && in_array($firstChar, $quotes) && in_array($lastChar, $quotes)) {
3464 $value = trim($value, implode('', $quotes));
3466 // Replace spaces with wildcards for a LIKE operation
3467 // UNLESS string contains a comma (this exception is a tiny bit questionable)
3468 // Also need to check if there is space in between sort name.
3469 elseif ($op == 'LIKE' && strpos($value, ',') === FALSE && strpos($value, ' ') === TRUE) {
3470 $value = str_replace(' ', '%', $value);
3472 $value = CRM_Core_DAO
::escapeString(trim($value));
3473 if (strlen($value)) {
3475 $value = "'" . self
::getWildCardedValue($wildcard, $op, $value) . "'";
3476 if ($fieldName == 'sort_name') {
3477 $wc = "contact_a.sort_name";
3480 $wc = "contact_a.display_name";
3482 $fieldsub[] = " ( $wc $op $value )";
3483 if ($config->includeNickNameInName
) {
3484 $wc = "contact_a.nick_name";
3485 $fieldsub[] = " ( $wc $op $value )";
3487 if ($config->includeEmailInName
) {
3488 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3490 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3493 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3495 $this->_where
[$grouping][] = $sub;
3496 if ($config->includeEmailInName
) {
3497 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3498 $this->_qill
[$grouping][] = ts('Name or Email') . " $op - '$input'";
3501 $this->_qill
[$grouping][] = ts('Name') . " $op - '$input'";
3506 * Where/qill clause for greeting fields.
3508 * @param array $values
3510 * @throws \CRM_Core_Exception
3512 public function greetings(&$values) {
3513 list($name, $op, $value, $grouping, $wildcard) = $values;
3514 $name .= '_display';
3516 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
3517 $this->_qill
[$grouping][] = ts('Greeting %1 %2', [1 => $qillop, 2 => $qillVal]);
3518 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value, 'String');
3522 * Where / qill clause for email
3524 * @param array $values
3525 * @param string $isForcePrimaryOnly
3527 * @throws \CRM_Core_Exception
3529 protected function email(&$values, $isForcePrimaryOnly) {
3530 list($name, $op, $value, $grouping, $wildcard) = $values;
3531 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3533 // CRM-18147: for Contact's GET API, email fieldname got appended with its entity as in {$apiEntiy}_{$name}
3534 // so following code is use build whereClause for contact's primart email id
3535 if (!empty($isForcePrimaryOnly)) {
3536 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.is_primary', '=', 1, 'Integer');
3538 // @todo - this should come from the $this->_fields array
3539 $dbName = $name === 'email_id' ?
'id' : $name;
3541 if (is_array($value) ||
$name === 'email_id') {
3542 $this->_qill
[$grouping][] = $this->getQillForField($name, $value, $op, [], ts('Email'));
3543 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.' . $dbName, $op, $value, 'String');
3547 // Is this ever hit now? Ideally ensure always an array & handle above.
3550 if (substr($n, 0, 1) == '"' &&
3551 substr($n, -1, 1) == '"'
3553 $n = substr($n, 1, -1);
3554 $value = CRM_Core_DAO
::escapeString($n);
3558 $value = self
::getWildCardedValue($wildcard, $op, $n);
3560 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3561 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3564 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3565 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3570 * Where / qill clause for phone number
3572 * @param array $values
3574 * @throws \CRM_Core_Exception
3576 public function phone_numeric(&$values) {
3577 list($name, $op, $value, $grouping, $wildcard) = $values;
3578 // Strip non-numeric characters; allow wildcards
3579 $number = preg_replace('/[^\d%]/', '', $value);
3581 if (strpos($number, '%') === FALSE) {
3582 $number = "%$number%";
3585 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3586 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3587 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3592 * Where / qill clause for phone type/location
3594 * @param array $values
3596 * @throws \CRM_Core_Exception
3598 public function phone_option_group($values) {
3599 list($name, $op, $value, $grouping, $wildcard) = $values;
3600 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3601 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3602 $optionName = $options[$value];
3603 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3604 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3605 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3609 * Where / qill clause for street_address.
3611 * @param array $values
3613 * @throws \CRM_Core_Exception
3615 public function street_address(&$values) {
3616 list($name, $op, $value, $grouping) = $values;
3625 if (strpos($value, '%') === FALSE) {
3626 // only add wild card if not there
3627 $value = "%{$value}%";
3630 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, $value, 'String');
3631 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3634 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3635 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3638 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3642 * Where / qill clause for street_unit.
3644 * @param array $values
3646 * @throws \CRM_Core_Exception
3648 public function street_number(&$values) {
3649 list($name, $op, $value, $grouping, $wildcard) = $values;
3657 if (strtolower($n) == 'odd') {
3658 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3659 $this->_qill
[$grouping][] = ts('Street Number is odd');
3661 elseif (strtolower($n) == 'even') {
3662 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3663 $this->_qill
[$grouping][] = ts('Street Number is even');
3667 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_number', $op, $value, 'String');
3668 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3671 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3675 * Where / qill clause for sorting by character.
3677 * @param array $values
3679 public function sortByCharacter(&$values) {
3680 list($name, $op, $value, $grouping, $wildcard) = $values;
3682 $name = trim($value);
3683 $cond = " contact_a.sort_name LIKE '" . CRM_Core_DAO
::escapeWildCardString($name) . "%'";
3684 $this->_where
[$grouping][] = $cond;
3685 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', [1 => $name]);
3689 * Where / qill clause for including contact ids.
3691 public function includeContactIDs() {
3692 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3697 foreach ($this->_params
as $id => $values) {
3698 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3699 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3702 CRM_Utils_Type
::validateAll($contactIds, 'Positive');
3703 if (!empty($contactIds)) {
3704 $this->_where
[0][] = ' ( contact_a.id IN (' . implode(',', $contactIds) . " ) ) ";
3709 * Where / qill clause for postal code.
3711 * @param array $values
3713 * @throws \CRM_Core_Exception
3715 public function postalCode(&$values) {
3716 // skip if the fields dont have anything to do with postal_code
3717 if (empty($this->_fields
['postal_code'])) {
3721 list($name, $op, $value, $grouping, $wildcard) = $values;
3723 // Handle numeric postal code range searches properly by casting the column as numeric
3724 if (is_numeric($value)) {
3725 $field = "IF (civicrm_address.postal_code REGEXP '^[0-9]{1,10}$', CAST(civicrm_address.postal_code AS UNSIGNED), 0)";
3726 $val = CRM_Utils_Type
::escape($value, 'Integer');
3729 $field = 'civicrm_address.postal_code';
3730 // Per CRM-17060 we might be looking at an 'IN' syntax so don't case arrays to string.
3731 if (!is_array($value)) {
3732 $val = CRM_Utils_Type
::escape($value, 'String');
3735 // Do we need to escape values here? I would expect buildClause does.
3740 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3742 if ($name == 'postal_code') {
3743 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3744 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3746 elseif ($name == 'postal_code_low') {
3747 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3748 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', [1 => $value]);
3750 elseif ($name == 'postal_code_high') {
3751 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3752 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', [1 => $value]);
3757 * Where / qill clause for location type.
3759 * @param array $values
3760 * @param null $status
3764 public function locationType(&$values, $status = NULL) {
3765 list($name, $op, $value, $grouping, $wildcard) = $values;
3767 if (is_array($value)) {
3768 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')';
3769 $this->_tables
['civicrm_address'] = 1;
3770 $this->_whereTables
['civicrm_address'] = 1;
3772 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3774 foreach ($value as $id) {
3775 $names[] = $locationType[$id];
3778 $this->_primaryLocation
= FALSE;
3781 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3784 return implode(' ' . ts('or') . ' ', $names);
3791 * @param bool $fromStateProvince
3793 * @return array|NULL
3794 * @throws \CRM_Core_Exception
3796 public function country(&$values, $fromStateProvince = TRUE) {
3797 list($name, $op, $value, $grouping, $wildcard) = $values;
3799 if (!$fromStateProvince) {
3800 $stateValues = $this->getWhereValues('state_province', $grouping);
3801 if (!empty($stateValues)) {
3802 // return back to caller if there are state province values
3803 // since that handles this case
3808 $countryClause = $countryQill = NULL;
3809 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY']) ||
($values && !empty($value))) {
3810 $this->_tables
['civicrm_address'] = 1;
3811 $this->_whereTables
['civicrm_address'] = 1;
3813 $countryClause = self
::buildClause('civicrm_address.country_id', $op, $value, 'Positive');
3814 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, 'country_id', $value, $op);
3815 $countryQill = ts("%1 %2 %3", [1 => 'Country', 2 => $qillop, 3 => $qillVal]);
3817 if (!$fromStateProvince) {
3818 $this->_where
[$grouping][] = $countryClause;
3819 $this->_qill
[$grouping][] = $countryQill;
3823 if ($fromStateProvince) {
3824 if (!empty($countryClause)) {
3827 " ...AND... " . $countryQill,
3831 return [NULL, NULL];
3837 * Where / qill clause for county (if present).
3839 * @param array $values
3840 * @param null $status
3844 public function county(&$values, $status = NULL) {
3845 list($name, $op, $value, $grouping, $wildcard) = $values;
3847 if (!is_array($value)) {
3848 // force the county to be an array
3852 // check if the values are ids OR names of the counties
3853 $inputFormat = 'id';
3854 foreach ($value as $v) {
3855 if (!is_numeric($v)) {
3856 $inputFormat = 'name';
3864 elseif ($op == '!=') {
3868 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3869 $op = str_replace('EMPTY', 'NULL', $op);
3872 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
3873 $clause = "civicrm_address.county_id $op";
3875 elseif ($inputFormat == 'id') {
3876 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3878 $county = CRM_Core_PseudoConstant
::county();
3879 foreach ($value as $id) {
3880 $names[] = $county[$id] ??
NULL;
3885 $county = CRM_Core_PseudoConstant
::county();
3886 foreach ($value as $name) {
3887 $name = trim($name);
3888 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3890 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3893 $this->_tables
['civicrm_address'] = 1;
3894 $this->_whereTables
['civicrm_address'] = 1;
3896 $this->_where
[$grouping][] = $clause;
3898 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3901 return implode(' ' . ts('or') . ' ', $names);
3906 * Where / qill clause for state/province AND country (if present).
3908 * @param array $values
3909 * @param null $status
3912 * @throws \CRM_Core_Exception
3914 public function stateProvince(&$values, $status = NULL) {
3915 list($name, $op, $value, $grouping, $wildcard) = $values;
3917 $stateClause = self
::buildClause('civicrm_address.state_province_id', $op, $value, 'Positive');
3918 $this->_tables
['civicrm_address'] = 1;
3919 $this->_whereTables
['civicrm_address'] = 1;
3921 $countryValues = $this->getWhereValues('country', $grouping);
3922 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3923 if ($countryClause) {
3924 $clause = "( $stateClause AND $countryClause )";
3927 $clause = $stateClause;
3930 $this->_where
[$grouping][] = $clause;
3931 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
3933 $this->_qill
[$grouping][] = ts("State/Province %1 %2 %3", [1 => $qillop, 2 => $qillVal, 3 => $countryQill]);
3936 return implode(' ' . ts('or') . ' ', $qillVal) . $countryQill;
3941 * Where / qill clause for change log.
3943 * @param array $values
3945 public function changeLog(&$values) {
3946 list($name, $op, $value, $grouping, $wildcard) = $values;
3948 $targetName = $this->getWhereValues('changed_by', $grouping);
3953 $name = trim($targetName[2]);
3954 $name = CRM_Core_DAO
::escapeString($name);
3955 $name = $targetName[4] ?
"%$name%" : $name;
3956 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3957 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3958 $fieldTitle = ts('Altered By');
3960 list($qillop, $qillVal) = self
::buildQillForFieldValue(NULL, 'changed_by', $name, 'LIKE');
3961 $this->_qill
[$grouping][] = ts("%1 %2 '%3'", [
3971 * @throws \CRM_Core_Exception
3973 public function modifiedDates($values) {
3974 $this->_useDistinct
= TRUE;
3976 // CRM-11281, default to added date if not set
3977 $fieldTitle = ts('Added Date');
3978 $fieldName = 'created_date';
3979 foreach (array_keys($this->_params
) as $id) {
3980 if ($this->_params
[$id][0] == 'log_date') {
3981 if ($this->_params
[$id][2] == 2) {
3982 $fieldTitle = ts('Modified Date');
3983 $fieldName = 'modified_date';
3988 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3990 self
::$_openedPanes[ts('Change Log')] = TRUE;
3996 * @throws \CRM_Core_Exception
3998 public function demographics(&$values) {
3999 list($name, $op, $value, $grouping, $wildcard) = $values;
4001 if (($name == 'age_low') ||
($name == 'age_high')) {
4002 $this->ageRangeQueryBuilder($values,
4003 'contact_a', 'age', 'birth_date', ts('Age')
4006 elseif (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
4008 $this->dateQueryBuilder($values,
4009 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
4012 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
4014 $this->dateQueryBuilder($values,
4015 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
4019 self
::$_openedPanes[ts('Demographics')] = TRUE;
4025 public function privacy(&$values) {
4026 list($name, $op, $value, $grouping) = $values;
4027 if (is_array($value)) {
4028 if (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
4030 $value = $value[$op];
4033 $field = $this->_fields
[$name] ??
NULL;
4034 CRM_Utils_Type
::validate($value, 'Integer');
4035 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
4036 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
4037 $title = $field ?
$field['title'] : $name;
4038 $this->_qill
[$grouping][] = "$title $op $value";
4044 public function privacyOptions($values) {
4045 list($name, $op, $value, $grouping, $wildcard) = $values;
4047 if (empty($value) ||
!is_array($value)) {
4051 // get the operator and toggle values
4052 $opValues = $this->getWhereValues('privacy_operator', $grouping);
4055 strtolower($opValues[2] == 'AND')
4057 // @todo this line is logially unreachable
4061 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
4063 if ($toggleValues &&
4064 $toggleValues[2] == 2
4071 foreach ($value as $dontCare => $pOption) {
4072 $clauses[] = " ( contact_a.{$pOption} = 1 ) ";
4073 $field = $this->_fields
[$pOption] ??
NULL;
4074 $title = $field ?
$field['title'] : $pOption;
4075 $qill[] = " $title = 1 ";
4078 $this->_where
[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )';
4079 $this->_qill
[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )';
4085 * @throws \CRM_Core_Exception
4087 public function preferredCommunication(&$values) {
4088 list($name, $op, $value, $grouping, $wildcard) = $values;
4090 if (!is_array($value)) {
4091 $value = str_replace(['(', ')'], '', explode(",", $value));
4093 elseif (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
4095 $value = $value[$op];
4097 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Contact', $name, $value, $op);
4099 if (self
::caseImportant($op)) {
4100 $value = implode("[[:cntrl:]]|[[:cntrl:]]", (array) $value);
4101 $op = (strstr($op, '!') ||
strstr($op, 'NOT')) ?
'NOT RLIKE' : 'RLIKE';
4102 $value = "[[:cntrl:]]" . $value . "[[:cntrl:]]";
4105 $this->_where
[$grouping][] = self
::buildClause("contact_a.preferred_communication_method", $op, $value);
4106 $this->_qill
[$grouping][] = ts('Preferred Communication Method %1 %2', [1 => $qillop, 2 => $qillVal]);
4110 * Where / qill clause for relationship.
4112 * @param array $values
4114 public function relationship(&$values) {
4115 list($name, $op, $value, $grouping, $wildcard) = $values;
4116 if ($this->_relationshipValuesAdded
) {
4119 // also get values array for relation_target_name
4120 // for relationship search we always do wildcard
4121 $relationType = $this->getWhereValues('relation_type_id', $grouping);
4122 $description = $this->getWhereValues('relation_description', $grouping);
4123 $targetName = $this->getWhereValues('relation_target_name', $grouping);
4124 $relStatus = $this->getWhereValues('relation_status', $grouping);
4125 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
4127 $nameClause = $name = NULL;
4129 $name = trim($targetName[2]);
4130 if (substr($name, 0, 1) == '"' &&
4131 substr($name, -1, 1) == '"'
4133 $name = substr($name, 1, -1);
4134 $name = CRM_Core_DAO
::escapeString($name);
4135 $nameClause = "= '$name'";
4138 $name = CRM_Core_DAO
::escapeString($name);
4139 $nameClause = "LIKE '%{$name}%'";
4143 $relTypes = $relTypesIds = [];
4144 if (!empty($relationType)) {
4145 $relationType[2] = (array) $relationType[2];
4146 foreach ($relationType[2] as $relType) {
4147 $rel = explode('_', $relType);
4148 self
::$_relType = $rel[1];
4149 $params = ['id' => $rel[0]];
4151 $rTypeValue = CRM_Contact_BAO_RelationshipType
::retrieve($params, $typeValues);
4152 if (!empty($rTypeValue)) {
4153 if ($rTypeValue->name_a_b
== $rTypeValue->name_b_a
) {
4154 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4155 self
::$_relType = 'reciprocal';
4157 $relTypesIds[] = $rel[0];
4158 $relTypes[] = $relType;
4163 // if we are creating a temp table we build our own where for the relationship table
4164 $relationshipTempTable = NULL;
4165 if (self
::$_relType == 'reciprocal') {
4167 self
::$_relationshipTempTable = $relationshipTempTable = CRM_Utils_SQL_TempTable
::build()
4168 ->createWithColumns("`contact_id` int(10) unsigned NOT NULL DEFAULT '0', `contact_id_alt` int(10) unsigned NOT NULL DEFAULT '0', id int unsigned, KEY `contact_id` (`contact_id`), KEY `contact_id_alt` (`contact_id_alt`)")
4171 $where[$grouping][] = " sort_name $nameClause ";
4173 $groupJoinTable = "civicrm_relationship";
4174 $groupJoinColumn = "contact_id_alt";
4177 $where = &$this->_where
;
4179 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4181 $groupJoinTable = "contact_b";
4182 $groupJoinColumn = "id";
4184 $allRelationshipType = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, NULL, TRUE, 'label', FALSE);
4185 if ($nameClause ||
!$targetGroup) {
4186 if (!empty($relationType)) {
4188 foreach ($relTypes as $rel) {
4189 if (!empty($relQill)) {
4192 $relQill .= $allRelationshipType[$rel];
4194 $this->_qill
[$grouping][] = 'Relationship Type(s) ' . $relQill . " $name";
4197 $this->_qill
[$grouping][] = $name;
4201 //check to see if the target contact is in specified group
4203 //add contacts from static groups
4204 $this->_tables
['civicrm_relationship_group_contact'] = $this->_whereTables
['civicrm_relationship_group_contact']
4205 = " 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'";
4206 $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" .
4207 implode(",", $targetGroup[2]) . ") ) ";
4209 //add contacts from saved searches
4210 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", $groupJoinTable, $op, $groupJoinColumn);
4212 //set the group where clause
4214 $groupWhere[] = "( " . $ssWhere . " )";
4216 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4218 //Get the names of the target groups for the qill
4219 $groupNames = CRM_Core_PseudoConstant
::group();
4221 foreach ($targetGroup[2] as $groupId) {
4222 if (array_key_exists($groupId, $groupNames)) {
4223 $qillNames[] = $groupNames[$groupId];
4226 if (!empty($relationType)) {
4228 foreach ($relTypes as $rel) {
4229 if (!empty($relQill)) {
4232 $relQill .= CRM_Utils_Array
::value($rel, $allRelationshipType);
4234 $this->_qill
[$grouping][] = 'Relationship Type(s) ' . $relQill . " ( " . implode(", ", $qillNames) . " )";
4237 $this->_qill
[$grouping][] = implode(", ", $qillNames);
4242 if (!empty($description[2]) && trim($description[2])) {
4243 $this->_qill
[$grouping][] = ts('Relationship description - ' . $description[2]);
4244 $description = CRM_Core_DAO
::escapeString(trim($description[2]));
4245 $where[$grouping][] = "civicrm_relationship.description LIKE '%{$description}%'";
4248 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4249 $today = date('Ymd');
4250 //check for active, inactive and all relation status
4251 if (empty($relStatus[2])) {
4252 $where[$grouping][] = "(
4253 civicrm_relationship.is_active = 1 AND
4254 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4255 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4257 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
4259 elseif ($relStatus[2] == 1) {
4260 $where[$grouping][] = "(
4261 civicrm_relationship.is_active = 0 OR
4262 civicrm_relationship.end_date < {$today} OR
4263 civicrm_relationship.start_date > {$today}
4265 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
4269 if (in_array(['deleted_contacts', '=', '1', '0', '0'], $this->_params
)) {
4272 $where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})";
4274 $this->addRelationshipPermissionClauses($grouping, $where);
4275 $this->addRelationshipDateClauses($grouping, $where);
4276 $this->addRelationshipActivePeriodClauses($grouping, $where);
4277 if (!empty($relTypes)) {
4278 $where[$grouping][] = 'civicrm_relationship.relationship_type_id IN (' . implode(',', $relTypesIds) . ')';
4280 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
4281 $this->_useDistinct
= TRUE;
4282 $this->_relationshipValuesAdded
= TRUE;
4283 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4285 if ($relationshipTempTable) {
4287 if (!empty($where[$grouping])) {
4288 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4289 $whereClause = str_replace('contact_b', 'c', $whereClause);
4292 INSERT INTO {$relationshipTempTable} (contact_id, contact_id_alt, id)
4293 (SELECT contact_id_b as contact_id, contact_id_a as contact_id_alt, civicrm_relationship.id
4294 FROM civicrm_relationship
4295 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4298 (SELECT contact_id_a as contact_id, contact_id_b as contact_id_alt, civicrm_relationship.id
4299 FROM civicrm_relationship
4300 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4303 CRM_Core_DAO
::executeQuery($sql);
4308 * Add relationship permission criteria to where clause.
4310 * @param string $grouping
4311 * @param array $where Array to add "where" criteria to, in case you are generating a temp table.
4312 * Not the main query.
4314 public function addRelationshipPermissionClauses($grouping, &$where) {
4315 $relPermission = $this->getWhereValues('relation_permission', $grouping);
4316 if ($relPermission) {
4317 if (!is_array($relPermission[2])) {
4318 // this form value was scalar in previous versions of Civi
4319 $relPermission[2] = [$relPermission[2]];
4321 $where[$grouping][] = "(civicrm_relationship.is_permission_a_b IN (" . implode(",", $relPermission[2]) . "))";
4323 $allRelationshipPermissions = CRM_Contact_BAO_Relationship
::buildOptions('is_permission_a_b');
4325 $relPermNames = array_intersect_key($allRelationshipPermissions, array_flip($relPermission[2]));
4326 $this->_qill
[$grouping][] = ts('Permissioned Relationships') . ' - ' . implode(' OR ', $relPermNames);
4331 * Add start & end date criteria in
4332 * @param string $grouping
4333 * @param array $where
4334 * = array to add where clauses to, in case you are generating a temp table.
4335 * not the main query.
4337 public function addRelationshipDateClauses($grouping, &$where) {
4338 foreach (['start_date', 'end_date'] as $dateField) {
4339 $dateValueLow = $this->getWhereValues('relationship_' . $dateField . '_low', $grouping);
4340 $dateValueHigh = $this->getWhereValues('relationship_' . $dateField . '_high', $grouping);
4341 if (!empty($dateValueLow)) {
4342 $date = date('Ymd', strtotime($dateValueLow[2]));
4343 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4344 $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);
4346 if (!empty($dateValueHigh)) {
4347 $date = date('Ymd', strtotime($dateValueHigh[2]));
4348 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4349 $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);
4355 * Add start & end active period criteria in
4356 * @param string $grouping
4357 * @param array $where
4358 * = array to add where clauses to, in case you are generating a temp table.
4359 * not the main query.
4361 public function addRelationshipActivePeriodClauses($grouping, &$where) {
4363 $dateField = 'active_period_date';
4365 $dateValueLow = $this->getWhereValues('relation_active_period_date_low', $grouping);
4366 $dateValueHigh = $this->getWhereValues('relation_active_period_date_high', $grouping);
4367 $dateValueLowFormated = $dateValueHighFormated = NULL;
4368 if (!empty($dateValueLow) && !empty($dateValueHigh)) {
4369 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4370 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
4371 $this->_qill
[$grouping][] = (ts('Relationship was active between')) . " " . CRM_Utils_Date
::customFormat($dateValueLowFormated) . " and " . CRM_Utils_Date
::customFormat($dateValueHighFormated);
4373 elseif (!empty($dateValueLow)) {
4374 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4375 $this->_qill
[$grouping][] = (ts('Relationship was active after')) . " " . CRM_Utils_Date
::customFormat($dateValueLowFormated);
4377 elseif (!empty($dateValueHigh)) {
4378 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
4379 $this->_qill
[$grouping][] = (ts('Relationship was active before')) . " " . CRM_Utils_Date
::customFormat($dateValueHighFormated);
4382 if ($activePeriodClauses = self
::getRelationshipActivePeriodClauses($dateValueLowFormated, $dateValueHighFormated, TRUE)) {
4383 $where[$grouping][] = $activePeriodClauses;
4388 * Get start & end active period criteria
4392 * @param $forceTableName
4396 public static function getRelationshipActivePeriodClauses($from, $to, $forceTableName) {
4397 $tableName = $forceTableName ?
'civicrm_relationship.' : '';
4398 if (!is_null($from) && !is_null($to)) {
4399 return '(((' . $tableName . 'start_date >= ' . $from . ' AND ' . $tableName . 'start_date <= ' . $to . ') OR
4400 (' . $tableName . 'end_date >= ' . $from . ' AND ' . $tableName . 'end_date <= ' . $to . ') OR
4401 (' . $tableName . 'start_date <= ' . $from . ' AND ' . $tableName . 'end_date >= ' . $to . ' )) OR
4402 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4403 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . ') OR
4404 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4406 elseif (!is_null($from)) {
4407 return '((' . $tableName . 'start_date >= ' . $from . ') OR
4408 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4409 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . '))';
4411 elseif (!is_null($to)) {
4412 return '((' . $tableName . 'start_date <= ' . $to . ') OR
4413 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4414 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4419 * Default set of return properties.
4424 * derault return properties
4426 public static function &defaultReturnProperties($mode = 1) {
4427 if (!isset(self
::$_defaultReturnProperties)) {
4428 self
::$_defaultReturnProperties = [];
4431 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4432 // add activity return properties
4433 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4434 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4437 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4440 if (empty(self
::$_defaultReturnProperties[$mode])) {
4441 self
::$_defaultReturnProperties[$mode] = [
4444 'legal_identifier' => 1,
4445 'external_identifier' => 1,
4446 'contact_type' => 1,
4447 'contact_sub_type' => 1,
4449 'display_name' => 1,
4450 'preferred_mail_format' => 1,
4457 'formal_title' => 1,
4458 'communication_style_id' => 1,
4461 'street_address' => 1,
4462 'supplemental_address_1' => 1,
4463 'supplemental_address_2' => 1,
4464 'supplemental_address_3' => 1,
4467 'postal_code_suffix' => 1,
4468 'state_province' => 1,
4470 'world_region' => 1,
4477 'household_name' => 1,
4478 'organization_name' => 1,
4479 'deceased_date' => 1,
4484 'current_employer' => 1,
4485 // FIXME: should we use defaultHierReturnProperties() for the below?
4486 'do_not_email' => 1,
4489 'do_not_phone' => 1,
4490 'do_not_trade' => 1,
4492 'contact_is_deleted' => 1,
4493 'preferred_communication_method' => 1,
4494 'preferred_language' => 1,
4498 return self
::$_defaultReturnProperties[$mode];
4502 * Get primary condition for a sql clause.
4506 * @return string|NULL
4508 public static function getPrimaryCondition($value) {
4509 if (is_numeric($value)) {
4510 $value = (int ) $value;
4511 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4517 * Wrapper for a simple search query.
4519 * @param array $params
4520 * @param array $returnProperties
4521 * @param bool $count
4524 * @throws \CRM_Core_Exception
4526 public static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4527 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4528 list($select, $from, $where, $having) = $query->query();
4529 $groupBy = ($query->_useGroupBy
) ?
'GROUP BY contact_a.id' : '';
4531 $query = "$select $from $where $groupBy $having";
4536 * These are stub comments as this function needs more explanation - particularly in terms of how it
4537 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4539 * This function was originally written as a wrapper for the api query but is called from multiple places
4540 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4541 * but it is unclear as to whehter that is historical or there is a reason
4542 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4544 * @param array $params
4545 * @param array $returnProperties
4546 * @param null $fields
4547 * @param string $sort
4548 * @param int $offset
4549 * @param int $row_count
4550 * @param bool $smartGroupCache
4551 * ?? update smart group cache?.
4552 * @param bool $count
4553 * Return count obnly.
4554 * @param bool $skipPermissions
4555 * Should permissions be ignored or should the logged in user's permissions be applied.
4557 * This basically correlates to the component.
4558 * @param string $apiEntity
4559 * The api entity being called.
4560 * This sort-of duplicates $mode in a confusing way. Probably not by design.
4562 * @param bool|null $primaryLocationOnly
4565 * @throws \CRM_Core_Exception
4567 public static function apiQuery(
4569 $returnProperties = NULL,
4574 $smartGroupCache = TRUE,
4576 $skipPermissions = TRUE,
4577 $mode = CRM_Contact_BAO_Query
::MODE_CONTACTS
,
4579 $primaryLocationOnly = NULL
4582 $query = new CRM_Contact_BAO_Query(
4583 $params, $returnProperties,
4584 NULL, TRUE, FALSE, $mode,
4586 TRUE, $smartGroupCache,
4588 $apiEntity, $primaryLocationOnly
4591 //this should add a check for view deleted if permissions are enabled
4592 if ($skipPermissions) {
4593 $query->_skipDeleteClause
= TRUE;
4595 $query->generatePermissionClause(FALSE, $count);
4597 // note : this modifies _fromClause and _simpleFromClause
4598 $query->includePseudoFieldsJoin($sort);
4600 list($select, $from, $where, $having) = $query->query($count);
4602 if (!empty($query->_permissionWhereClause
)) {
4603 if (!empty($query->_permissionFromClause
) && !stripos($from, 'aclContactCache')) {
4604 $from .= " $query->_permissionFromClause";
4606 if (empty($where)) {
4607 $where = "WHERE $query->_permissionWhereClause";
4610 $where = "$where AND $query->_permissionWhereClause";
4614 $sql = "$select $from $where $having";
4616 // add group by only when API action is not getcount
4617 // otherwise query fetches incorrect count
4618 if ($query->_useGroupBy
&& !$count) {
4619 $sql .= self
::getGroupByFromSelectColumns($query->_select
, 'contact_a.id');
4621 if (!empty($sort)) {
4622 $sort = CRM_Utils_Type
::escape($sort, 'String');
4623 $sql .= " ORDER BY $sort ";
4625 if ($row_count > 0 && $offset >= 0) {
4626 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4627 $row_count = CRM_Utils_Type
::escape($row_count, 'Int');
4628 $sql .= " LIMIT $offset, $row_count ";
4631 $dao = CRM_Core_DAO
::executeQuery($sql);
4633 // @todo derive this from the component class rather than hard-code two options.
4634 $entityIDField = ($mode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) ?
'contribution_id' : 'contact_id';
4637 while ($dao->fetch()) {
4639 $noRows = $dao->rowCount
;
4640 return [$noRows, NULL];
4642 $val = $query->store($dao);
4643 $convertedVals = $query->convertToPseudoNames($dao, TRUE, TRUE);
4645 if (!empty($convertedVals)) {
4646 $val = array_replace_recursive($val, $convertedVals);
4648 $values[$dao->$entityIDField] = $val;
4654 * Get the actual custom field name by stripping off the appended string.
4656 * The string could be _relative, _from, or _to
4658 * @todo use metadata rather than convention to do this.
4660 * @param string $parameterName
4661 * The name of the parameter submitted to the form.
4668 public static function getCustomFieldName($parameterName) {
4669 if (substr($parameterName, -5, 5) == '_from') {
4670 return substr($parameterName, 0, strpos($parameterName, '_from'));
4672 if (substr($parameterName, -9, 9) == '_relative') {
4673 return substr($parameterName, 0, strpos($parameterName, '_relative'));
4675 if (substr($parameterName, -3, 3) == '_to') {
4676 return substr($parameterName, 0, strpos($parameterName, '_to'));
4681 * Convert submitted values for relative custom fields to query object format.
4683 * The query will support the sqlOperator format so convert to that format.
4685 * @param array $formValues
4687 * @param array $params
4688 * Converted parameters for the query object.
4689 * @param string $values
4691 * @param string $fieldName
4692 * Submitted field name. (Matches form field not DB field.)
4694 protected static function convertCustomRelativeFields(&$formValues, &$params, $values, $fieldName) {
4695 if (empty($values)) {
4696 // e.g we might have relative set & from & to empty. The form flow is a bit funky &
4697 // this function gets called again after they fields have been converted which can get ugly.
4700 $customFieldName = self
::getCustomFieldName($fieldName);
4702 if (substr($fieldName, -9, 9) == '_relative') {
4703 list($from, $to) = CRM_Utils_Date
::getFromTo($values, NULL, NULL);
4706 if ($fieldName == $customFieldName . '_to' && !empty($formValues[$customFieldName . '_from'])) {
4707 // Both to & from are set. We only need to acton one, choosing from.
4711 $from = $formValues[$customFieldName . '_from'] ??
NULL;
4712 $to = $formValues[$customFieldName . '_to'] ??
NULL;
4714 if (self
::isCustomDateField($customFieldName)) {
4715 list($from, $to) = CRM_Utils_Date
::getFromTo(NULL, $from, $to);
4721 $relativeFunction = ['BETWEEN' => [$from, $to]];
4724 $relativeFunction = ['>=' => $from];
4728 $relativeFunction = ['<=' => $to];
4740 * Are we dealing with custom field of type date.
4745 * @throws \CiviCRM_API3_Exception
4747 public static function isCustomDateField($fieldName) {
4748 if (($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($fieldName)) == FALSE) {
4752 $customFieldDataType = civicrm_api3('CustomField', 'getvalue', ['id' => $customFieldID, 'return' => 'data_type']);
4753 if ('Date' == $customFieldDataType) {
4757 catch (CiviCRM_API3_Exception
$e) {
4763 * Has this field already been reformatting to Query object syntax.
4765 * The form layer passed formValues to this function in preProcess & postProcess. Reason unknown. This seems
4766 * to come with associated double queries & is possibly damaging performance.
4768 * However, here we add a tested function to ensure convertFormValues identifies pre-processed fields & returns
4771 * @param mixed $values
4772 * Value in formValues for the field.
4776 public static function isAlreadyProcessedForQueryFormat($values) {
4777 if (!is_array($values)) {
4780 if (($operator = CRM_Utils_Array
::value(1, $values)) == FALSE) {
4783 return in_array($operator, CRM_Core_DAO
::acceptedSQLOperators());
4787 * If the state and country are passed remove state.
4789 * Country is implicit from the state, but including both results in
4790 * a poor query as there is no combined index on state AND country.
4792 * @see https://issues.civicrm.org/jira/browse/CRM-18125
4794 * @param array $formValues
4796 public static function filterCountryFromValuesIfStateExists(&$formValues) {
4797 if (!empty($formValues['country']) && !empty($formValues['state_province'])) {
4798 // The use of array map sanitises the data by ensuring we are dealing with integers.
4799 $states = implode(', ', array_map('intval', $formValues['state_province']));
4800 $countryList = CRM_Core_DAO
::singleValueQuery(
4801 "SELECT GROUP_CONCAT(country_id) FROM civicrm_state_province WHERE id IN ($states)"
4803 if ($countryList == $formValues['country']) {
4804 unset($formValues['country']);
4810 * For some special cases, grouping by subset of select fields becomes mandatory.
4811 * Hence, full_group_by mode is handled by appending any_value
4812 * keyword to select fields not present in groupBy
4814 * @param array $selectClauses
4815 * @param array $groupBy - Columns already included in GROUP By clause.
4816 * @param string $aggregateFunction
4820 public static function appendAnyValueToSelect($selectClauses, $groupBy, $aggregateFunction = 'ANY_VALUE') {
4821 if (!CRM_Utils_SQL
::disableFullGroupByMode()) {
4822 $groupBy = array_map('trim', (array) $groupBy);
4823 $aggregateFunctions = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN|IF)[[:blank:]]*\(/i';
4824 foreach ($selectClauses as $key => &$val) {
4825 list($selectColumn, $alias) = array_pad(preg_split('/ as /i', $val), 2, NULL);
4826 // append ANY_VALUE() keyword
4827 if (!in_array($selectColumn, $groupBy) && preg_match($aggregateFunctions, trim($selectColumn)) !== 1) {
4828 $val = ($aggregateFunction == 'GROUP_CONCAT') ?
4829 str_replace($selectColumn, "$aggregateFunction(DISTINCT {$selectColumn})", $val) :
4830 str_replace($selectColumn, "$aggregateFunction({$selectColumn})", $val);
4835 return "SELECT " . implode(', ', $selectClauses) . " ";
4839 * For some special cases, where if non-aggregate ORDER BY columns are not present in GROUP BY
4840 * on full_group_by mode, then append the those missing columns to GROUP BY clause
4841 * keyword to select fields not present in groupBy
4843 * @param string $groupBy - GROUP BY clause where missing ORDER BY columns will be appended if not present
4844 * @param array $orderBys - ORDER BY sub-clauses
4847 public static function getGroupByFromOrderBy(&$groupBy, $orderBys) {
4848 if (!CRM_Utils_SQL
::disableFullGroupByMode()) {
4849 foreach ($orderBys as $orderBy) {
4850 // remove sort syntax from ORDER BY clauses if present
4851 $orderBy = str_ireplace([' DESC', ' ASC', '`'], '', $orderBy);
4852 // if ORDER BY column is not present in GROUP BY then append it to end
4853 if (preg_match('/(MAX|MIN)\(/i', trim($orderBy)) !== 1 && !strstr($groupBy, $orderBy)) {
4854 $groupBy .= ", {$orderBy}";
4861 * Include Select columns in groupBy clause.
4863 * @param array $selectClauses
4864 * @param array $groupBy - Columns already included in GROUP By clause.
4868 public static function getGroupByFromSelectColumns($selectClauses, $groupBy = NULL) {
4869 $groupBy = (array) $groupBy;
4870 $mysqlVersion = CRM_Core_DAO
::singleValueQuery('SELECT VERSION()');
4871 $sqlMode = CRM_Core_DAO
::singleValueQuery('SELECT @@sql_mode');
4873 //return if ONLY_FULL_GROUP_BY is not enabled.
4874 if (CRM_Utils_SQL
::supportsFullGroupBy() && !empty($sqlMode) && in_array('ONLY_FULL_GROUP_BY', explode(',', $sqlMode))) {
4875 $regexToExclude = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN|IF)[[:blank:]]*\(/i';
4876 foreach ($selectClauses as $key => $val) {
4877 $aliasArray = preg_split('/ as /i', $val);
4878 // if more than 1 alias we need to split by ','.
4879 if (count($aliasArray) > 2) {
4880 $aliasArray = preg_split('/,/', $val);
4881 foreach ($aliasArray as $key => $value) {
4882 $alias = current(preg_split('/ as /i', $value));
4883 if (!in_array($alias, $groupBy) && preg_match($regexToExclude, trim($alias)) !== 1) {
4884 $groupBy[] = $alias;
4889 list($selectColumn, $alias) = array_pad($aliasArray, 2, NULL);
4890 $dateRegex = '/^(DATE_FORMAT|DATE_ADD|CASE)/i';
4891 $tableName = current(explode('.', $selectColumn));
4892 $primaryKey = "{$tableName}.id";
4893 // exclude columns which are already included in groupBy and aggregate functions from select
4894 // CRM-18439 - Also exclude the columns which are functionally dependent on columns in $groupBy (MySQL 5.7+)
4895 if (!in_array($selectColumn, $groupBy) && !in_array($primaryKey, $groupBy) && preg_match($regexToExclude, trim($selectColumn)) !== 1) {
4896 if (!empty($alias) && preg_match($dateRegex, trim($selectColumn))) {
4897 $groupBy[] = $alias;
4900 $groupBy[] = $selectColumn;
4907 if (!empty($groupBy)) {
4908 return " GROUP BY " . implode(', ', $groupBy);
4914 * Create and query the db for an contact search.
4916 * @param int $offset
4917 * The offset for the query.
4918 * @param int $rowCount
4919 * The number of rows to return.
4920 * @param string|CRM_Utils_Sort $sort
4921 * The order by string.
4922 * @param bool $count
4923 * Is this a count only query ?.
4924 * @param bool $includeContactIds
4925 * Should we include contact ids?.
4926 * @param bool $sortByChar
4927 * If true returns the distinct array of first characters for search results.
4928 * @param bool $groupContacts
4929 * If true, return only the contact ids.
4930 * @param bool $returnQuery
4931 * Should we return the query as a string.
4932 * @param string $additionalWhereClause
4933 * If the caller wants to further restrict the search (used for components).
4934 * @param null $sortOrder
4935 * @param string $additionalFromClause
4936 * Should be clause with proper joins, effective to reduce where clause load.
4938 * @param bool $skipOrderAndLimit
4940 * @return CRM_Core_DAO
4942 public function searchQuery(
4943 $offset = 0, $rowCount = 0, $sort = NULL,
4944 $count = FALSE, $includeContactIds = FALSE,
4945 $sortByChar = FALSE, $groupContacts = FALSE,
4946 $returnQuery = FALSE,
4947 $additionalWhereClause = NULL, $sortOrder = NULL,
4948 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4951 $query = $this->getSearchSQL($offset, $rowCount, $sort, $count, $includeContactIds, $sortByChar, $groupContacts, $additionalWhereClause, $sortOrder, $additionalFromClause, $skipOrderAndLimit);
4957 return CRM_Core_DAO
::singleValueQuery($query);
4960 $dao = CRM_Core_DAO
::executeQuery($query);
4962 // We can always call this - it will only re-enable if it was originally enabled.
4963 CRM_Core_DAO
::reenableFullGroupByMode();
4965 if ($groupContacts) {
4967 while ($dao->fetch()) {
4970 return implode(',', $ids);
4977 * Create and query the db for the list of all first letters used by contacts
4979 * @return CRM_Core_DAO
4981 public function alphabetQuery() {
4982 $sqlParts = $this->getSearchSQLParts(NULL, NULL, NULL, FALSE, FALSE, TRUE);
4983 $query = "SELECT DISTINCT LEFT(contact_a.sort_name, 1) as sort_name
4985 {$sqlParts['where']}";
4986 $dao = CRM_Core_DAO
::executeQuery($query);
4991 * Fetch a list of contacts for displaying a search results page
4993 * @param array $cids
4994 * List of contact IDs
4995 * @param bool $includeContactIds
4996 * @return CRM_Core_DAO
4998 public function getCachedContacts($cids, $includeContactIds) {
4999 CRM_Core_DAO
::disableFullGroupByMode();
5000 CRM_Utils_Type
::validateAll($cids, 'Positive');
5001 $this->_includeContactIds
= $includeContactIds;
5002 $onlyDeleted = in_array(['deleted_contacts', '=', '1', '0', '0'], $this->_params
);
5003 list($select, $from, $where) = $this->query(FALSE, FALSE, FALSE, $onlyDeleted);
5004 $select .= sprintf(", (%s) AS _wgt", $this->createSqlCase('contact_a.id', $cids));
5005 $where .= sprintf(' AND contact_a.id IN (%s)', implode(',', $cids));
5006 $order = 'ORDER BY _wgt';
5007 $groupBy = $this->_useGroupBy ?
' GROUP BY contact_a.id' : '';
5009 $query = "$select $from $where $groupBy $order $limit";
5011 $result = CRM_Core_DAO
::executeQuery($query);
5012 CRM_Core_DAO
::reenableFullGroupByMode();
5017 * Construct a SQL CASE expression.
5019 * @param string $idCol
5020 * The name of a column with ID's (eg 'contact_a.id').
5021 * @param array $cids
5022 * Array(int $weight => int $id).
5024 * CASE WHEN id=123 THEN 1 WHEN id=456 THEN 2 END
5026 private function createSqlCase($idCol, $cids) {
5028 foreach ($cids as $weight => $cid) {
5029 $buf .= " WHEN $idCol = $cid THEN $weight \n";
5036 * Populate $this->_permissionWhereClause with permission related clause and update other
5037 * query related properties.
5039 * Function calls ACL permission class and hooks to filter the query appropriately
5041 * Note that these 2 params were in the code when extracted from another function
5042 * and a second round extraction would be to make them properties of the class
5044 * @param bool $onlyDeleted
5045 * Only get deleted contacts.
5046 * @param bool $count
5047 * Return Count only.
5049 public function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
5050 if (!$this->_skipPermission
) {
5051 $permissionClauses = CRM_Contact_BAO_Contact_Permission
::cacheClause();
5052 $this->_permissionWhereClause
= $permissionClauses[1];
5053 $this->_permissionFromClause
= $permissionClauses[0];
5055 if (CRM_Core_Permission
::check('access deleted contacts')) {
5056 if (!$onlyDeleted) {
5057 $this->_permissionWhereClause
= str_replace('( 1 )', '(contact_a.is_deleted = 0)', $this->_permissionWhereClause
);
5060 if ($this->_permissionWhereClause
=== '( 1 )') {
5061 $this->_permissionWhereClause
= str_replace('( 1 )', '(contact_a.is_deleted)', $this->_permissionWhereClause
);
5064 $this->_permissionWhereClause
.= " AND (contact_a.is_deleted) ";
5069 if (isset($this->_tables
['civicrm_activity'])) {
5070 $bao = new CRM_Activity_BAO_Activity();
5071 $clauses = $subclauses = [];
5072 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
5073 if ($vals && $field !== 'id') {
5074 $clauses[] = $bao->tableName() . ".$field " . $vals;
5077 $subclauses[] = "$field " . implode(" AND $field ", (array) $vals);
5081 $clauses[] = $bao->tableName() . '.`id` IN (SELECT `id` FROM `' . $bao->tableName() . '` WHERE ' . implode(' AND ', $subclauses) . ')';
5083 if (!empty($clauses) && $this->_permissionWhereClause
) {
5084 $this->_permissionWhereClause
.= ' AND (' . implode(' AND ', $clauses) . ')';
5086 elseif (!empty($clauses)) {
5087 $this->_permissionWhereClause
.= '(' . implode(' AND ', $clauses) . ')';
5092 // add delete clause if needed even if we are skipping permission
5094 if (!$this->_skipDeleteClause
) {
5095 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
5096 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
5100 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
5109 public function setSkipPermission($val) {
5110 $this->_skipPermission
= $val;
5114 * @param null $context
5117 * @throws \CRM_Core_Exception
5119 public function summaryContribution($context = NULL) {
5120 list($innerselect, $from, $where, $having) = $this->query(TRUE);
5121 if (!empty($this->_permissionFromClause
) && !stripos($from, 'aclContactCache')) {
5122 $from .= " $this->_permissionFromClause";
5124 if ($this->_permissionWhereClause
) {
5125 $where .= " AND " . $this->_permissionWhereClause
;
5127 if ($context == 'search') {
5128 $where .= " AND contact_a.is_deleted = 0 ";
5131 $this->appendFinancialTypeWhereAndFromToQueryStrings($where, $from);
5133 $summary = ['total' => []];
5134 $this->addBasicStatsToSummary($summary, $where, $from);
5136 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
5137 $this->addBasicSoftCreditStatsToStats($summary, $where, $from);
5140 $this->addBasicCancelStatsToSummary($summary, $where, $from);
5146 * Append financial ACL limits to the query from & where clauses, if applicable.
5148 * @param string $where
5149 * @param string $from
5151 public function appendFinancialTypeWhereAndFromToQueryStrings(&$where, &$from) {
5152 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
5155 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
5156 if (!empty($financialTypes)) {
5157 $where .= " AND civicrm_contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND li.id IS NULL";
5158 $from .= " LEFT JOIN civicrm_line_item li
5159 ON civicrm_contribution.id = li.contribution_id AND
5160 li.entity_table = 'civicrm_contribution' AND li.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ") ";
5163 $where .= " AND civicrm_contribution.financial_type_id IN (0)";
5168 * Getter for the qill object.
5172 public function qill() {
5173 return $this->_qill
;
5177 * Default set of return default hier return properties.
5181 public static function &defaultHierReturnProperties() {
5182 if (!isset(self
::$_defaultHierReturnProperties)) {
5183 self
::$_defaultHierReturnProperties = [
5186 'legal_identifier' => 1,
5187 'external_identifier' => 1,
5188 'contact_type' => 1,
5189 'contact_sub_type' => 1,
5191 'display_name' => 1,
5198 'formal_title' => 1,
5199 'communication_style_id' => 1,
5200 'email_greeting' => 1,
5201 'postal_greeting' => 1,
5205 'preferred_communication_method' => 1,
5206 'do_not_phone' => 1,
5207 'do_not_email' => 1,
5210 'do_not_trade' => 1,
5213 'location_type' => 1,
5214 'street_address' => 1,
5216 'state_province' => 1,
5218 'postal_code_suffix' => 1,
5221 'phone-Mobile' => 1,
5234 'location_type' => 1,
5235 'street_address' => 1,
5237 'state_province' => 1,
5239 'postal_code_suffix' => 1,
5242 'phone-Mobile' => 1,
5256 return self
::$_defaultHierReturnProperties;
5260 * Build query for a date field.
5262 * @param array $values
5263 * @param string $tableName
5264 * @param string $fieldName
5265 * @param string $dbFieldName
5266 * @param string $fieldTitle
5267 * @param bool $appendTimeStamp
5268 * @param string $dateFormat
5269 * @param string|null $highDBFieldName
5270 * Optional field name for when the 'high' part of the calculation uses a different field than the 'low' part.
5271 * This is an obscure situation & one we don't want to do more of but supporting them here is the only way for now.
5272 * Examples are event date & relationship active date -in both cases we are looking for things greater than the start
5273 * date & less than the end date.
5275 * @throws \CRM_Core_Exception
5277 public function dateQueryBuilder(
5278 $values, $tableName, $fieldName,
5279 $dbFieldName, $fieldTitle,
5280 $appendTimeStamp = TRUE,
5281 $dateFormat = 'YmdHis',
5282 $highDBFieldName = NULL
5284 // @todo - remove dateFormat - pretty sure it's never passed in...
5285 list($name, $op, $value, $grouping, $wildcard) = $values;
5286 if ($name !== $fieldName && $name !== "{$fieldName}_low" && $name !== "{$fieldName}_high") {
5287 CRM_Core_Error
::deprecatedFunctionWarning('Date query builder called unexpectedly');
5290 if ($tableName === 'civicrm_contact') {
5291 // Special handling for contact table as it has a known alias in advanced search.
5292 $tableName = 'contact_a';
5294 if ($name === "{$fieldName}_low" ||
5295 $name === "{$fieldName}_high"
5297 if (isset($this->_rangeCache
[$fieldName]) ||
!$value) {
5300 $this->_rangeCache
[$fieldName] = 1;
5302 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
5304 if ($name == $fieldName . '_low') {
5306 $firstPhrase = ts('greater than or equal to');
5307 $firstDate = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5309 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5310 if (!empty($secondValues) && $secondValues[2]) {
5312 $secondPhrase = ts('less than or equal to');
5313 $secondValue = $secondValues[2];
5315 if ($appendTimeStamp && strlen($secondValue) == 10) {
5316 $secondValue .= ' 23:59:59';
5318 $secondDate = CRM_Utils_Date
::processDate($secondValue, NULL, FALSE, $dateFormat);
5321 elseif ($name == $fieldName . '_high') {
5323 $firstPhrase = ts('less than or equal to');
5325 if ($appendTimeStamp && strlen($value) == 10) {
5326 $value .= ' 23:59:59';
5328 $firstDate = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5330 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5331 if (!empty($secondValues) && $secondValues[2]) {
5333 $secondPhrase = ts('greater than or equal to');
5334 $secondValue = $secondValues[2];
5335 $secondDate = CRM_Utils_Date
::processDate($secondValue, NULL, FALSE, $dateFormat);
5339 if (!$appendTimeStamp) {
5340 $firstDate = substr($firstDate, 0, 8);
5342 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
5345 if (!$appendTimeStamp) {
5346 $secondDate = substr($secondDate, 0, 8);
5348 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
5352 $highDBFieldName = $highDBFieldName ??
$dbFieldName;
5353 $this->_where
[$grouping][] = "
5354 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5355 ( {$tableName}.{$highDBFieldName} $secondOP '$secondDate' )
5357 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
5360 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5361 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5365 if ($name == $fieldName) {
5366 //In Get API, for operators other then '=' the $value is in array(op => value) format
5367 if (is_array($value) && !empty($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
5369 $value = $value[$op];
5372 $date = $format = NULL;
5373 if (strstr($op, 'IN')) {
5375 foreach ($value as &$date) {
5376 $date = CRM_Utils_Date
::processDate($date, NULL, FALSE, $dateFormat);
5377 if (!$appendTimeStamp) {
5378 $date = substr($date, 0, 8);
5380 $format[] = CRM_Utils_Date
::customFormat($date);
5382 $date = "('" . implode("','", $value) . "')";
5383 $format = implode(', ', $format);
5385 elseif ($value && (!strstr($op, 'NULL') && !strstr($op, 'EMPTY'))) {
5386 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5387 if (!$appendTimeStamp) {
5388 $date = substr($date, 0, 8);
5390 $format = CRM_Utils_Date
::customFormat($date);
5395 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op $date";
5398 $this->_where
[$grouping][] = self
::buildClause("{$tableName}.{$dbFieldName}", $op);
5401 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
5402 $this->_qill
[$grouping][] = "$fieldTitle $op $format";
5405 // Ensure the tables are set, but don't whomp anything.
5406 $this->_tables
[$tableName] = $this->_tables
[$tableName] ??
1;
5407 $this->_whereTables
[$tableName] = $this->_whereTables
[$tableName] ??
1;
5412 * @param string $tableName
5413 * @param string $fieldName
5414 * @param string $dbFieldName
5415 * @param $fieldTitle
5416 * @param null $options
5418 public function numberRangeBuilder(
5420 $tableName, $fieldName,
5421 $dbFieldName, $fieldTitle,
5424 list($name, $op, $value, $grouping, $wildcard) = $values;
5426 if ($name == "{$fieldName}_low" ||
5427 $name == "{$fieldName}_high"
5429 if (isset($this->_rangeCache
[$fieldName])) {
5432 $this->_rangeCache
[$fieldName] = 1;
5434 $secondOP = $secondPhrase = $secondValue = NULL;
5436 if ($name == "{$fieldName}_low") {
5438 $firstPhrase = ts('greater than');
5440 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5441 if (!empty($secondValues)) {
5443 $secondPhrase = ts('less than');
5444 $secondValue = $secondValues[2];
5449 $firstPhrase = ts('less than');
5451 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5452 if (!empty($secondValues)) {
5454 $secondPhrase = ts('greater than');
5455 $secondValue = $secondValues[2];
5460 $this->_where
[$grouping][] = "
5461 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5462 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5464 $displayValue = $options ?
$options[$value] : $value;
5465 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5467 $this->_qill
[$grouping][]
5468 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5471 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5472 $displayValue = $options ?
$options[$value] : $value;
5473 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5475 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5480 if ($name == $fieldName) {
5484 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5486 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5487 $displayValue = $options ?
$options[$value] : $value;
5488 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5494 * @param string $tableName
5495 * @param string $fieldName
5496 * @param string $dbFieldName
5497 * @param $fieldTitle
5498 * @param null $options
5500 public function ageRangeQueryBuilder(
5502 $tableName, $fieldName,
5503 $dbFieldName, $fieldTitle,
5506 list($name, $op, $value, $grouping, $wildcard) = $values;
5508 $asofDateValues = $this->getWhereValues("{$fieldName}_asof_date", $grouping);
5509 // will be treated as current day
5511 if ($asofDateValues) {
5512 $asofDate = CRM_Utils_Date
::processDate($asofDateValues[2]);
5513 $asofDateFormat = CRM_Utils_Date
::customFormat(substr($asofDate, 0, 8));
5514 $fieldTitle .= ' ' . ts('as of') . ' ' . $asofDateFormat;
5517 if ($name == "{$fieldName}_low" ||
5518 $name == "{$fieldName}_high"
5520 if (isset($this->_rangeCache
[$fieldName])) {
5523 $this->_rangeCache
[$fieldName] = 1;
5525 $secondOP = $secondPhrase = $secondValue = NULL;
5527 if ($name == "{$fieldName}_low") {
5528 $firstPhrase = ts('greater than or equal to');
5529 // NB: age > X means date of birth < Y
5531 $firstDate = self
::calcDateFromAge($asofDate, $value, 'min');
5533 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5534 if (!empty($secondValues)) {
5536 $secondPhrase = ts('less than or equal to');
5537 $secondValue = $secondValues[2];
5538 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'max');
5543 $firstPhrase = ts('less than or equal to');
5544 $firstDate = self
::calcDateFromAge($asofDate, $value, 'max');
5546 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5547 if (!empty($secondValues)) {
5549 $secondPhrase = ts('greater than or equal to');
5550 $secondValue = $secondValues[2];
5551 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'min');
5556 $this->_where
[$grouping][] = "
5557 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5558 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5560 $displayValue = $options ?
$options[$value] : $value;
5561 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5563 $this->_qill
[$grouping][]
5564 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5567 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5568 $displayValue = $options ?
$options[$value] : $value;
5569 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5571 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5577 * Calculate date from age.
5579 * @param string $asofDate
5581 * @param string $type
5584 * @throws \Exception
5586 public static function calcDateFromAge($asofDate, $age, $type) {
5587 $date = new DateTime($asofDate);
5588 if ($type == "min") {
5589 // minimum age is $age: dob <= date - age "235959"
5590 $date->sub(new DateInterval("P" . $age . "Y"));
5591 return $date->format('Ymd') . "235959";
5594 // max age is $age: dob >= date - (age + 1y) + 1d "000000"
5595 $date->sub(new DateInterval("P" . ($age +
1) . "Y"))->add(new DateInterval("P1D"));
5596 return $date->format('Ymd') . "000000";
5601 * Given the field name, operator, value & its data type
5602 * builds the where Clause for the query
5603 * used for handling 'IS NULL'/'IS NOT NULL' operators
5605 * @param string $field
5609 * @param string $value
5611 * @param string $dataType
5612 * Data type of the field.
5615 * Where clause for the query.
5616 * @throws \CRM_Core_Exception
5618 public static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5620 $clause = "$field $op";
5628 $clause = ($dataType == 'Date') ?
" $field IS NULL " : " (NULLIF($field, '') IS NULL) ";
5631 case 'IS NOT EMPTY':
5632 $clause = ($dataType == 'Date') ?
" $field IS NOT NULL " : " (NULLIF($field, '') IS NOT NULL) ";
5636 return " {$clause} BINARY '{$value}' ";
5640 // I feel like this would be escaped properly if passed through $queryString = CRM_Core_DAO::createSqlFilter.
5641 if (!empty($value) && (!is_array($value) ||
!array_key_exists($op, $value))) {
5642 $value = [$op => (array) $value];
5646 if (empty($dataType) ||
$dataType == 'Date') {
5647 $dataType = 'String';
5649 if (is_array($value)) {
5650 //this could have come from the api - as in the restWhere section we potentially use the api operator syntax which is becoming more
5651 // widely used and consistent across the codebase
5652 // adding this here won't accept the search functions which don't submit an array
5653 if (($queryString = CRM_Core_DAO
::createSQLFilter($field, $value, $dataType)) != FALSE) {
5655 return $queryString;
5657 if (!empty($value[0]) && $op === 'BETWEEN') {
5658 CRM_Core_Error
::deprecatedFunctionWarning('Fix search input params');
5659 if (($queryString = CRM_Core_DAO
::createSQLFilter($field, [$op => $value], $dataType)) != FALSE) {
5660 return $queryString;
5663 throw new CRM_Core_Exception(ts('Failed to interpret input for search'));
5666 $value = CRM_Utils_Type
::escape($value, $dataType);
5667 // if we don't have a dataType we should assume
5668 if ($dataType == 'String' ||
$dataType == 'Text') {
5669 $value = "'" . $value . "'";
5671 return "$clause $value";
5676 * @param bool $reset
5680 public function openedSearchPanes($reset = FALSE) {
5681 if (!$reset ||
empty($this->_whereTables
)) {
5682 return self
::$_openedPanes;
5685 // pane name to table mapper
5687 ts('Contributions') => 'civicrm_contribution',
5688 ts('Memberships') => 'civicrm_membership',
5689 ts('Events') => 'civicrm_participant',
5690 ts('Relationships') => 'civicrm_relationship',
5691 ts('Activities') => 'civicrm_activity',
5692 ts('Pledges') => 'civicrm_pledge',
5693 ts('Cases') => 'civicrm_case',
5694 ts('Grants') => 'civicrm_grant',
5695 ts('Address Fields') => 'civicrm_address',
5696 ts('Notes') => 'civicrm_note',
5697 ts('Change Log') => 'civicrm_log',
5698 ts('Mailings') => 'civicrm_mailing',
5700 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
5702 foreach (array_keys($this->_whereTables
) as $table) {
5703 if ($panName = array_search($table, $panesMapper)) {
5704 self
::$_openedPanes[$panName] = TRUE;
5708 return self
::$_openedPanes;
5714 public function setOperator($operator) {
5715 $validOperators = ['AND', 'OR'];
5716 if (!in_array($operator, $validOperators)) {
5719 $this->_operator
= $operator;
5725 public function getOperator() {
5726 return $this->_operator
;
5734 public function filterRelatedContacts(&$from, &$where, &$having) {
5735 if (!isset(Civi
::$statics[__CLASS__
]['related_contacts_filter'])) {
5736 Civi
::$statics[__CLASS__
]['related_contacts_filter'] = [];
5738 $_rTempCache =& Civi
::$statics[__CLASS__
]['related_contacts_filter'];
5739 // since there only can be one instance of this filter in every query
5740 // skip if filter has already applied
5741 foreach ($_rTempCache as $acache) {
5742 foreach ($acache['queries'] as $aqcache) {
5743 if (strpos($from, $aqcache['from']) !== FALSE) {
5749 $arg_sig = sha1("$from $where $having");
5750 if (isset($_rTempCache[$arg_sig])) {
5751 $cache = $_rTempCache[$arg_sig];
5754 // create temp table with contact ids
5756 $tableName = CRM_Utils_SQL_TempTable
::build()->createWithColumns('contact_id int primary key')->setMemory(TRUE)->getName();
5759 REPLACE INTO $tableName ( contact_id )
5765 CRM_Core_DAO
::executeQuery($sql);
5767 $cache = ['tableName' => $tableName, 'queries' => []];
5768 $_rTempCache[$arg_sig] = $cache;
5770 // upsert the query depending on relationship type
5771 if (isset($cache['queries'][$this->_displayRelationshipType
])) {
5772 $qcache = $cache['queries'][$this->_displayRelationshipType
];
5775 $tableName = $cache['tableName'];
5780 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5781 if (is_numeric($this->_displayRelationshipType
)) {
5782 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5784 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5785 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5787 $qcache['where'] = "
5788 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5789 AND displayRelType.is_active = 1
5793 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5794 if ($dirOne == 'a') {
5795 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5796 $qcache['from'] .= "
5797 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5798 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5802 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5803 $qcache['from'] .= "
5804 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5805 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5808 $qcache['where'] = "
5809 WHERE displayRelType.relationship_type_id = $relType
5810 AND displayRelType.is_active = 1
5813 $qcache['relTypeLabel'] = $relationshipTypeLabel;
5814 $_rTempCache[$arg_sig]['queries'][$this->_displayRelationshipType
] = $qcache;
5816 $qillMessage = ts('Contacts with a Relationship Type of: ');
5817 $iqill = $qillMessage . "'" . $qcache['relTypeLabel'] . "'";
5818 if (!is_array($this->_qill
[0]) ||
!in_array($iqill, $this->_qill
[0])) {
5819 $this->_qill
[0][] = $iqill;
5821 if (strpos($from, $qcache['from']) === FALSE) {
5822 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5823 // this happens when we have an event_type in the quert (CRM-7969)
5824 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5825 $from .= $qcache['from'];
5826 $where = $qcache['where'];
5827 if (!empty($this->_permissionFromClause
) && !stripos($from, 'aclContactCache')) {
5828 $from .= " $this->_permissionFromClause";
5830 if (!empty($this->_permissionWhereClause
)) {
5831 $where .= "AND $this->_permissionWhereClause";
5839 * See CRM-19811 for why this is database hurty without apparent benefit.
5845 public static function caseImportant($op) {
5846 return !in_array($op, ['LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY']);
5850 * @param $returnProperties
5855 public static function componentPresent(&$returnProperties, $prefix) {
5856 foreach ($returnProperties as $name => $dontCare) {
5857 if (substr($name, 0, strlen($prefix)) == $prefix) {
5865 * Builds the necessary structures for all fields that are similar to option value look-ups.
5867 * @param string $name
5868 * the name of the field.
5870 * the sql operator, this function should handle ALL SQL operators.
5871 * @param string $value
5872 * depends on the operator and who's calling the query builder.
5873 * @param int $grouping
5874 * the index where to place the where clause.
5875 * @param string $daoName
5877 * @param array $field
5878 * an array that contains various properties of the field identified by $name.
5879 * @param string $label
5880 * The label for this field element.
5881 * @param string $dataType
5883 * @throws \CRM_Core_Exception
5885 public function optionValueQuery(
5893 $dataType = 'String'
5902 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5903 if ($tableName == 'civicrm_contact') {
5904 $wc = "contact_a.$fieldName";
5907 // Special handling for on_hold, so that we actually use the 'where'
5908 // property in order to limit the query by the on_hold status of the email,
5909 // instead of using email.id which would be nonsensical.
5910 if ($field['name'] === 'on_hold') {
5911 $wc = $field['where'];
5914 $wc = "$tableName.id";
5918 if (in_array($name, $pseudoFields)) {
5919 $wc = "contact_a.{$name}_id";
5920 $dataType = 'Positive';
5921 $value = (!$value) ?
0 : $value;
5923 if ($name == "world_region") {
5924 $field['name'] = $name;
5927 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue($daoName, $field['name'], $value, $op);
5928 $this->_qill
[$grouping][] = ts("%1 %2 %3", [1 => $label, 2 => $qillop, 3 => $qillVal]);
5929 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5933 * Check and explode a user defined numeric string into an array
5934 * this was the protocol used by search builder in the old old days before we had
5935 * super nice js widgets to do the hard work
5937 * @param string $string
5938 * @param string $dataType
5939 * The dataType we should check for the values, default integer.
5941 * @return bool|array
5942 * false if string does not match the pattern
5943 * array of numeric values if string does match the pattern
5945 public static function parseSearchBuilderString($string, $dataType = 'Integer') {
5946 $string = trim($string);
5947 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5951 $string = substr($string, 1, -1);
5952 $values = explode(',', $string);
5953 if (empty($values)) {
5958 foreach ($values as $v) {
5959 if ($dataType == 'Integer' && !is_numeric($v)) {
5962 elseif ($dataType == 'String' && !is_string($v)) {
5965 $returnValues[] = trim($v);
5968 if (empty($returnValues)) {
5972 return $returnValues;
5976 * Convert the pseudo constants id's to their names
5978 * @param CRM_Core_DAO $dao
5979 * @param bool $return
5980 * @param bool $usedForAPI
5982 * @return array|NULL
5984 public function convertToPseudoNames(&$dao, $return = FALSE, $usedForAPI = FALSE) {
5985 if (empty($this->_pseudoConstantsSelect
)) {
5989 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5990 if (!empty($this->_pseudoConstantsSelect
[$key]['sorting'])) {
5994 if (is_object($dao) && property_exists($dao, $value['idCol'])) {
5995 $val = $dao->{$value['idCol']};
5996 if ($key == 'groups') {
5997 $dao->groups
= $this->convertGroupIDStringToLabelString($dao, $val);
6001 if (CRM_Utils_System
::isNull($val)) {
6004 elseif (!empty($value['pseudoconstant'])) {
6005 // If pseudoconstant is set that is kind of defacto for 'we have a bit more info about this'
6006 // and we can use the metadata to figure it out.
6007 // ideally this bit of IF will absorb & replace all the rest in time as we move to
6008 // more metadata based choices.
6009 if (strpos($val, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
6010 $dbValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($val, CRM_Core_DAO
::VALUE_SEPARATOR
));
6011 foreach ($dbValues as $pseudoValue) {
6012 $convertedValues[] = CRM_Core_PseudoConstant
::getLabel($value['bao'], $value['idCol'], $pseudoValue);
6015 $dao->$key = ($usedForAPI) ?
$convertedValues : implode(', ', $convertedValues);
6016 $realFieldName = $this->_pseudoConstantsSelect
[$key]['field_name'] ??
NULL;
6017 if ($usedForAPI && $realFieldName) {
6018 // normally we would see 2 fields returned for pseudoConstants. An exception is
6019 // preferred_communication_method where there is no id-variant.
6020 // For the api we prioritise getting the real data returned.
6021 // over the resolved version
6022 $dao->$realFieldName = $dbValues;
6027 // This is basically the same as the default but since we have the bao we can use
6028 // a cached function.
6029 $dao->$key = CRM_Core_PseudoConstant
::getLabel($value['bao'], $value['idCol'], $val);
6032 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
6034 $idColumn = "{$key}_id";
6035 $dao->$idColumn = $val;
6037 if ($key == 'state_province_name') {
6038 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::stateProvince($val);
6041 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
6044 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
6045 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
6047 // @todo handle this in the section above for pseudoconstants.
6048 elseif (in_array($value['pseudoField'], ['participant_role_id', 'participant_role'])) {
6049 // @todo define bao on this & merge into the above condition.
6050 $viewValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $val);
6052 if ($value['pseudoField'] == 'participant_role') {
6053 $pseudoOptions = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'role_id');
6054 foreach ($viewValues as $k => $v) {
6055 $viewValues[$k] = $pseudoOptions[$v];
6058 $dao->$key = ($usedForAPI && count($viewValues) > 1) ?
$viewValues : implode(', ', $viewValues);
6061 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
6062 $dao->$key = $labels[$val];
6065 // return converted values in array format
6067 if (strpos($key, '-') !== FALSE) {
6068 $keyVal = explode('-', $key);
6069 $current = &$values;
6070 $lastElement = array_pop($keyVal);
6071 foreach ($keyVal as $v) {
6072 if (!array_key_exists($v, $current)) {
6075 $current = &$current[$v];
6077 $current[$lastElement] = $dao->$key;
6080 $values[$key] = $dao->$key;
6086 foreach ($this->legacyHackedFields
as $realField => $labelField) {
6087 // This is a temporary routine for handling these fields while
6088 // we figure out how to handled them based on metadata in
6089 /// export and search builder. CRM-19815, CRM-19830.
6090 if (isset($dao->$realField) && is_numeric($dao->$realField) && isset($dao->$labelField)) {
6091 $dao->$realField = $dao->$labelField;
6099 * Include pseudo fields LEFT JOIN.
6100 * @param string|array $sort can be a object or string
6102 * @return array|NULL
6104 public function includePseudoFieldsJoin($sort) {
6105 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
6108 $sort = is_string($sort) ?
$sort : $sort->orderBy();
6111 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
6112 if (!empty($value['table'])) {
6113 $regex = "/({$value['table']}\.|{$name})/";
6114 if (preg_match($regex, $sort)) {
6115 $this->_elemnt
[$value['element']] = 1;
6116 $this->_select
[$value['element']] = $value['select'];
6117 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
6118 $present[$value['table']] = $value['join'];
6122 $presentSimpleFrom = $present;
6124 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
6125 array_key_exists('civicrm_country', $presentSimpleFrom)
6127 unset($presentSimpleFrom['civicrm_country']);
6129 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
6130 array_key_exists('civicrm_country', $present)
6132 unset($present['civicrm_country']);
6135 $presentClause = $presentSimpleFromClause = NULL;
6136 if (!empty($present)) {
6137 $presentClause = implode(' ', $present);
6139 if (!empty($presentSimpleFrom)) {
6140 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
6143 $this->_fromClause
= $this->_fromClause
. $presentClause;
6144 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
6146 return [$presentClause, $presentSimpleFromClause];
6150 * Build qill for field.
6152 * Qill refers to the query detail visible on the UI.
6154 * @param string $daoName
6155 * @param string $fieldName
6156 * @param mixed $fieldValue
6158 * @param array $pseudoExtraParam
6160 * Type of the field per CRM_Utils_Type
6164 public static function buildQillForFieldValue(
6169 $pseudoExtraParam = [],
6170 $type = CRM_Utils_Type
::T_STRING
6172 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
6174 //API usually have fieldValue format as array(operator => array(values)),
6175 //so we need to separate operator out of fieldValue param
6176 if (is_array($fieldValue) && in_array(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
6177 $op = key($fieldValue);
6178 $fieldValue = $fieldValue[$op];
6181 // if Operator chosen is NULL/EMPTY then
6182 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
6183 return [CRM_Utils_Array
::value($op, $qillOperators, $op), ''];
6186 // @todo - if the right BAO is passed in special handling for the below
6187 // fields should not be required. testQillOptions.
6188 if ($fieldName == 'country_id') {
6189 $pseudoOptions = CRM_Core_PseudoConstant
::country();
6191 elseif ($fieldName == 'county_id') {
6192 $pseudoOptions = CRM_Core_PseudoConstant
::county();
6194 elseif ($fieldName == 'world_region') {
6195 $pseudoOptions = CRM_Core_PseudoConstant
::worldRegion();
6197 elseif ($daoName == 'CRM_Event_DAO_Event' && $fieldName == 'id') {
6198 $checkPermission = CRM_Utils_Array
::value('check_permission', $pseudoExtraParam, TRUE);
6199 $pseudoOptions = CRM_Event_BAO_Event
::getEvents(0, $fieldValue, TRUE, $checkPermission, TRUE);
6201 elseif ($fieldName == 'contribution_product_id') {
6202 $pseudoOptions = CRM_Contribute_PseudoConstant
::products();
6204 elseif ($daoName == 'CRM_Contact_DAO_Group' && $fieldName == 'id') {
6205 $pseudoOptions = CRM_Core_PseudoConstant
::group();
6207 elseif ($daoName == 'CRM_Batch_BAO_EntityBatch' && $fieldName == 'batch_id') {
6208 $pseudoOptions = CRM_Contribute_PseudoConstant
::batch();
6211 $pseudoOptions = CRM_Core_PseudoConstant
::get($daoName, $fieldName, $pseudoExtraParam);
6214 if (is_array($fieldValue)) {
6216 if (!empty($pseudoOptions)) {
6217 foreach ((array) $fieldValue as $val) {
6218 $qillString[] = CRM_Utils_Array
::value($val, $pseudoOptions, $val);
6220 $fieldValue = implode(', ', $qillString);
6223 if ($type == CRM_Utils_Type
::T_DATE
) {
6224 foreach ($fieldValue as $index => $value) {
6225 $fieldValue[$index] = CRM_Utils_Date
::customFormat($value);
6229 // @todo - this is a bit specific (one operator).
6230 // However it is covered by a unit test so can be altered later with
6232 if ($op === 'BETWEEN') {
6233 $separator = ' AND ';
6235 $fieldValue = implode($separator, $fieldValue);
6238 elseif (!empty($pseudoOptions) && array_key_exists($fieldValue, $pseudoOptions)) {
6239 $fieldValue = $pseudoOptions[$fieldValue];
6241 elseif ($type === CRM_Utils_Type
::T_DATE
) {
6242 $fieldValue = CRM_Utils_Date
::customFormat($fieldValue);
6245 return [CRM_Utils_Array
::value($op, $qillOperators, $op), $fieldValue];
6249 * Get the qill (search description for field) for the specified field.
6251 * @param string $daoName
6252 * @param string $name
6253 * @param string $value
6254 * @param string|array $op
6255 * @param string $label
6259 public static function getQillValue($daoName, string $name, $value, $op, string $label) {
6260 list($op, $value) = self
::buildQillForFieldValue($daoName, $name, $value, $op);
6261 return ts('%1 %2 %3', [1 => $label, 2 => $op, 3 => $value]);
6265 * Alter value to reflect wildcard settings.
6267 * The form will have tried to guess whether this is a good field to wildcard but there is
6268 * also a site-wide setting that specifies whether it is OK to append the wild card to the beginning
6269 * or only the end of the string
6271 * @param bool $wildcard
6272 * This is a bool made on an assessment 'elsewhere' on whether this is a good field to wildcard.
6274 * Generally '=' or 'LIKE'.
6275 * @param string $value
6276 * The search string.
6280 public static function getWildCardedValue($wildcard, $op, $value) {
6281 if ($wildcard && $op === 'LIKE') {
6282 if (CRM_Core_Config
::singleton()->includeWildCardInName
&& (substr($value, 0, 1) != '%')) {
6295 * Process special fields of Search Form in OK (Operator in Key) format
6297 * @param array $formValues
6298 * @param array $specialFields
6299 * Special params to be processed
6300 * @param array $changeNames
6301 * Array of fields whose name should be changed
6303 public static function processSpecialFormValue(&$formValues, $specialFields, $changeNames = []) {
6304 // Array of special fields whose value are considered only for NULL or EMPTY operators
6305 $nullableFields = ['contribution_batch_id'];
6307 foreach ($specialFields as $element) {
6308 $value = $formValues[$element] ??
NULL;
6310 if (is_array($value)) {
6311 if (in_array($element, array_keys($changeNames))) {
6312 unset($formValues[$element]);
6313 $element = $changeNames[$element];
6315 $formValues[$element] = ['IN' => $value];
6317 elseif (in_array($value, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
6318 $formValues[$element] = [$value => 1];
6320 elseif (!in_array($element, $nullableFields)) {
6321 // if wildcard is already present return searchString as it is OR append and/or prepend with wildcard
6322 $isWilcard = strstr($value, '%') ?
FALSE : CRM_Core_Config
::singleton()->includeWildCardInName
;
6323 $formValues[$element] = ['LIKE' => self
::getWildCardedValue($isWilcard, 'LIKE', $value)];
6330 * Parse and assimilate the various sort options.
6332 * Side-effect: if sorting on a common column from a related table (`city`, `postal_code`,
6333 * `email`), the related table may be joined automatically.
6335 * At time of writing, this code is deeply flawed and should be rewritten. For the moment,
6336 * it's been extracted to a standalone function.
6338 * @param string|CRM_Utils_Sort $sort
6339 * The order by string.
6340 * @param null $sortOrder
6341 * Who knows? Hu knows. He who knows Hu knows who.
6344 * list(string $orderByClause, string $additionalFromClause).
6346 * @throws \CRM_Core_Exception
6348 protected function prepareOrderBy($sort, $sortOrder) {
6352 if (CRM_Core_Config
::singleton()->includeOrderByClause ||
6353 isset($this->_distinctComponentClause
)
6356 if (is_string($sort)) {
6360 $orderBy = trim($sort->orderBy());
6362 // Deliberately remove the backticks again, as they mess up the evil
6363 // string munging below. This balanced by re-escaping before use.
6364 $orderBy = str_replace('`', '', $orderBy);
6366 if (!empty($orderBy)) {
6367 // this is special case while searching for
6368 // change log CRM-1718
6369 if (preg_match('/sort_name/i', $orderBy)) {
6370 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
6374 $orderBy .= " $sortOrder";
6377 // always add contact_a.id to the ORDER clause
6378 // so the order is deterministic
6379 if (strpos('contact_a.id', $orderBy) === FALSE) {
6380 $orderBy .= ", contact_a.id";
6385 $orderBy = " contact_a.sort_name ASC, contact_a.id";
6391 // Remove this here & add it at the end for simplicity.
6392 $order = trim($orderBy);
6393 $orderByArray = explode(',', $order);
6395 foreach ($orderByArray as $orderByClause) {
6396 $orderByClauseParts = explode(' ', trim($orderByClause));
6397 $field = $orderByClauseParts[0];
6398 $direction = $orderByClauseParts[1] ??
'asc';
6399 $fieldSpec = $this->getMetadataForRealField($field);
6401 // This is a hacky add-in for primary address joins. Feel free to iterate as it is unit tested.
6402 // @todo much more cleanup on location handling in addHierarchical elements. Potentially
6403 // add keys to $this->fields to represent the actual keys for locations.
6404 if (empty($fieldSpec) && substr($field, 0, 2) === '1-') {
6405 $fieldSpec = $this->getMetadataForField(substr($field, 2));
6406 $this->addAddressTable('1-' . str_replace('civicrm_', '', $fieldSpec['table_name']), 'is_primary = 1');
6409 if ($this->_returnProperties
=== []) {
6410 if (!empty($fieldSpec['table_name']) && !isset($this->_tables
[$fieldSpec['table_name']])) {
6411 $this->_tables
[$fieldSpec['table_name']] = 1;
6412 $order = $fieldSpec['where'] . ' ' . $direction;
6416 $cfID = CRM_Core_BAO_CustomField
::getKeyID($field);
6417 // add to cfIDs array if not present
6418 if (!empty($cfID) && !array_key_exists($cfID, $this->_cfIDs
)) {
6419 $this->_cfIDs
[$cfID] = [];
6420 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
6421 $this->_customQuery
->query();
6422 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
6423 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
6426 // By replacing the join to the option value table with the mysql construct
6427 // ORDER BY field('contribution_status_id', 2,1,4)
6428 // we can remove a join. In the case of the option value join it is
6429 /// a join known to cause slow queries.
6430 // @todo cover other pseudoconstant types. Limited to option group ones & Foreign keys
6431 // matching an id+name parrern in the
6432 // first instance for scope reasons. They require slightly different handling as the column (label)
6433 // is not declared for them.
6434 // @todo so far only integer fields are being handled. If we add string fields we need to look at
6436 $pseudoConstantMetadata = CRM_Utils_Array
::value('pseudoconstant', $fieldSpec, FALSE);
6437 if (!empty($pseudoConstantMetadata)
6439 if (!empty($pseudoConstantMetadata['optionGroupName'])
6440 ||
$this->isPseudoFieldAnFK($fieldSpec)
6442 // dev/core#1305 @todo this is not the right thing to do but for now avoid fatal error
6443 if (empty($fieldSpec['bao'])) {
6446 $sortedOptions = $fieldSpec['bao']::buildOptions($fieldSpec['name']);
6447 natcasesort($sortedOptions);
6448 $fieldIDsInOrder = implode(',', array_keys($sortedOptions));
6449 // Pretty sure this validation ALSO happens in the order clause & this can't be reached but...
6450 // this might give some early warning.
6451 CRM_Utils_Type
::validate($fieldIDsInOrder, 'CommaSeparatedIntegers');
6452 // use where if it's set to fully qualify ambiguous column names
6453 // i.e. civicrm_contribution.contribution_status_id instead of contribution_status_id
6454 $pseudoColumnName = $fieldSpec['where'] ??
$fieldSpec['name'];
6455 $order = str_replace("$field", "field($pseudoColumnName,$fieldIDsInOrder)", $order);
6457 //CRM-12565 add "`" around $field if it is a pseudo constant
6458 // This appears to be for 'special' fields like locations with appended numbers or hyphens .. maybe.
6459 if (!empty($pseudoConstantMetadata['element']) && $pseudoConstantMetadata['element'] == $field) {
6460 $order = str_replace($field, "`{$field}`", $order);
6465 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6466 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6468 // The above code relies on crazy brittle string manipulation of a peculiarly-encoded ORDER BY
6469 // clause. But this magic helper which forgivingly reescapes ORDER BY.
6471 $order = CRM_Utils_Type
::escape($order, 'MysqlOrderBy');
6472 return ' ORDER BY ' . $order;
6477 * Convert a string of group IDs to a string of group labels.
6479 * The original string may include duplicates and groups the user does not have
6480 * permission to see.
6482 * @param CRM_Core_DAO $dao
6483 * @param string $val
6487 public function convertGroupIDStringToLabelString(&$dao, $val) {
6488 $groupIDs = explode(',', $val);
6489 // Note that groups that the user does not have permission to will be excluded (good).
6490 $groups = array_intersect_key(CRM_Core_PseudoConstant
::group(), array_flip($groupIDs));
6491 return implode(', ', $groups);
6496 * Set the qill and where properties for a field.
6498 * This function is intended as a short-term function to encourage refactoring
6499 * & re-use - but really we should just have less special-casing.
6501 * @param string $name
6503 * @param string|array $value
6504 * @param string $grouping
6505 * @param array $field
6507 * @throws \CRM_Core_Exception
6509 public function setQillAndWhere($name, $op, $value, $grouping, $field) {
6510 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
6511 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
6512 $this->_qill
[$grouping][] = ts("%1 %2 %3", [
6513 1 => $field['title'],
6520 * Has the pseudoconstant of the field been requested.
6522 * For example if the field is payment_instrument_id then it
6523 * has been requested if either payment_instrument_id or payment_instrument
6524 * have been requested. Payment_instrument is the option groun name field value.
6526 * @param array $field
6527 * @param string $fieldName
6528 * The unique name of the field - ie. the one it will be aliased to in the query.
6532 private function pseudoConstantNameIsInReturnProperties($field, $fieldName = NULL) {
6533 $realField = $this->getMetadataForRealField($fieldName);
6534 if (!isset($realField['pseudoconstant'])) {
6537 $pseudoConstant = $realField['pseudoconstant'];
6538 if (empty($pseudoConstant['optionGroupName']) &&
6539 CRM_Utils_Array
::value('labelColumn', $pseudoConstant) !== 'name') {
6540 // We are increasing our pseudoconstant handling - but still very cautiously,
6541 // hence the check for labelColumn === name
6545 if (!empty($pseudoConstant['optionGroupName']) && !empty($this->_returnProperties
[$pseudoConstant['optionGroupName']])) {
6548 if (!empty($this->_returnProperties
[$fieldName])) {
6551 // Is this still required - the above goes off the unique name. Test with things like
6552 // communication_preferences & prefix_id.
6553 if (!empty($this->_returnProperties
[$field['name']])) {
6560 * Get Select Clause.
6564 public function getSelect() {
6565 $select = 'SELECT ';
6566 if (isset($this->_distinctComponentClause
)) {
6567 $select .= "{$this->_distinctComponentClause}, ";
6569 $select .= implode(', ', $this->_select
);
6574 * Add basic statistics to the summary.
6576 * @param array $summary
6577 * @param string $where
6578 * @param string $from
6581 * @throws \CRM_Core_Exception
6583 protected function addBasicStatsToSummary(&$summary, $where, $from) {
6584 $summary['total']['count'] = 0;
6585 $summary['total']['amount'] = $summary['total']['avg'] = [];
6588 SELECT COUNT( conts.total_amount ) as total_count,
6589 SUM( conts.total_amount ) as total_amount,
6590 AVG( conts.total_amount ) as total_avg,
6591 conts.currency as currency
6593 SELECT civicrm_contribution.total_amount, COUNT(civicrm_contribution.total_amount) as civicrm_contribution_total_amount_count,
6594 civicrm_contribution.currency
6596 $where AND civicrm_contribution.contribution_status_id = 1
6597 GROUP BY civicrm_contribution.id
6601 $dao = CRM_Core_DAO
::executeQuery($query);
6603 while ($dao->fetch()) {
6604 $summary['total']['count'] +
= $dao->total_count
;
6605 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
6606 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
6609 if (!empty($summary['total']['amount'])) {
6610 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
6611 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
6614 $summary['total']['amount'] = $summary['total']['avg'] = 0;
6620 * Add basic soft credit statistics to summary array.
6622 * @param array $summary
6623 * @param string $where
6624 * @param string $from
6626 * @throws \CRM_Core_Exception
6628 protected function addBasicSoftCreditStatsToStats(&$summary, $where, $from) {
6630 SELECT COUNT( conts.total_amount ) as total_count,
6631 SUM( conts.total_amount ) as total_amount,
6632 AVG( conts.total_amount ) as total_avg,
6633 conts.currency as currency
6635 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency
6637 $where AND civicrm_contribution.contribution_status_id = 1 AND civicrm_contribution_soft.id IS NOT NULL
6638 GROUP BY civicrm_contribution_soft.id
6642 $dao = CRM_Core_DAO
::executeQuery($query);
6643 $summary['soft_credit']['count'] = 0;
6644 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = [];
6645 while ($dao->fetch()) {
6646 $summary['soft_credit']['count'] +
= $dao->total_count
;
6647 $summary['soft_credit']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
6648 $summary['soft_credit']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
6650 if (!empty($summary['soft_credit']['amount'])) {
6651 $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
6652 $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
6655 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
6660 * Add basic stats about cancelled contributions to the summary.
6662 * @param array $summary
6663 * @param string $where
6664 * @param string $from
6666 * @throws \CRM_Core_Exception
6668 protected function addBasicCancelStatsToSummary(&$summary, $where, $from) {
6670 SELECT COUNT( conts.total_amount ) as cancel_count,
6671 SUM( conts.total_amount ) as cancel_amount,
6672 AVG( conts.total_amount ) as cancel_avg,
6673 conts.currency as currency
6675 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency
6677 $where AND civicrm_contribution.cancel_date IS NOT NULL
6678 GROUP BY civicrm_contribution.id
6682 $dao = CRM_Core_DAO
::executeQuery($query);
6685 if ($dao->fetch()) {
6686 $summary['cancel']['count'] = $dao->cancel_count
;
6687 $summary['cancel']['amount'] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
6688 $summary['cancel']['avg'] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
6692 $summary['cancel']['count'] = 0;
6693 $summary['cancel']['amount'] = $summary['cancel']['avg'] = [];
6694 while ($dao->fetch()) {
6695 $summary['cancel']['count'] +
= $dao->cancel_count
;
6696 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
6697 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
6699 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
6700 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
6705 * Create the sql query for an contact search.
6707 * @param int $offset
6708 * The offset for the query.
6709 * @param int $rowCount
6710 * The number of rows to return.
6711 * @param string|CRM_Utils_Sort $sort
6712 * The order by string.
6713 * @param bool $count
6714 * Is this a count only query ?.
6715 * @param bool $includeContactIds
6716 * Should we include contact ids?.
6717 * @param bool $sortByChar
6718 * If true returns the distinct array of first characters for search results.
6719 * @param bool $groupContacts
6720 * If true, return only the contact ids.
6721 * @param string $additionalWhereClause
6722 * If the caller wants to further restrict the search (used for components).
6723 * @param null $sortOrder
6724 * @param string $additionalFromClause
6725 * Should be clause with proper joins, effective to reduce where clause load.
6727 * @param bool $skipOrderAndLimit
6731 * @throws \CRM_Core_Exception
6733 public function getSearchSQL(
6734 $offset = 0, $rowCount = 0, $sort = NULL,
6735 $count = FALSE, $includeContactIds = FALSE,
6736 $sortByChar = FALSE, $groupContacts = FALSE,
6737 $additionalWhereClause = NULL, $sortOrder = NULL,
6738 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE) {
6740 $sqlParts = $this->getSearchSQLParts($offset, $rowCount, $sort, $count, $includeContactIds, $sortByChar, $groupContacts, $additionalWhereClause, $sortOrder, $additionalFromClause);
6743 CRM_Core_Error
::deprecatedFunctionWarning('sort by char is deprecated - use alphabetQuery method');
6744 $sqlParts['order_by'] = 'ORDER BY sort_name asc';
6747 if ($skipOrderAndLimit) {
6748 CRM_Core_Error
::deprecatedFunctionWarning('skipOrderAndLimit is deprected - call getSearchSQLParts & construct it in the calling function');
6749 $query = "{$sqlParts['select']} {$sqlParts['from']} {$sqlParts['where']} {$sqlParts['having']} {$sqlParts['group_by']}";
6752 $query = "{$sqlParts['select']} {$sqlParts['from']} {$sqlParts['where']} {$sqlParts['having']} {$sqlParts['group_by']} {$sqlParts['order_by']} {$sqlParts['limit']}";
6758 * Get the component parts of the search query as an array.
6760 * @param int $offset
6761 * The offset for the query.
6762 * @param int $rowCount
6763 * The number of rows to return.
6764 * @param string|CRM_Utils_Sort $sort
6765 * The order by string.
6766 * @param bool $count
6767 * Is this a count only query ?.
6768 * @param bool $includeContactIds
6769 * Should we include contact ids?.
6770 * @param bool $sortByChar
6771 * If true returns the distinct array of first characters for search results.
6772 * @param bool $groupContacts
6773 * If true, return only the contact ids.
6774 * @param string $additionalWhereClause
6775 * If the caller wants to further restrict the search (used for components).
6776 * @param null $sortOrder
6777 * @param string $additionalFromClause
6778 * Should be clause with proper joins, effective to reduce where clause load.
6781 * @throws \CRM_Core_Exception
6783 public function getSearchSQLParts($offset = 0, $rowCount = 0, $sort = NULL,
6784 $count = FALSE, $includeContactIds = FALSE,
6785 $sortByChar = FALSE, $groupContacts = FALSE,
6786 $additionalWhereClause = NULL, $sortOrder = NULL,
6787 $additionalFromClause = NULL) {
6788 if ($includeContactIds) {
6789 $this->_includeContactIds
= TRUE;
6790 $this->_whereClause
= $this->whereClause();
6792 $onlyDeleted = in_array([
6800 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
6801 // and that contact happens to be deleted, set $onlyDeleted to true
6802 foreach ($this->_params
as $values) {
6803 $name = $values[0] ??
NULL;
6804 $op = $values[1] ??
NULL;
6805 $value = $values[2] ??
NULL;
6806 if ($name === 'contact_id' and $op === '=') {
6807 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
6808 $onlyDeleted = TRUE;
6814 // building the query string
6815 $groupBy = $groupByCols = NULL;
6817 if (isset($this->_groupByComponentClause
)) {
6818 $groupByCols = preg_replace('/^GROUP BY /', '', trim($this->_groupByComponentClause
));
6819 $groupByCols = explode(', ', $groupByCols);
6821 elseif ($this->_useGroupBy
) {
6822 $groupByCols = ['contact_a.id'];
6825 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
6826 $groupByCols = ['civicrm_activity.id'];
6828 if (!empty($groupByCols)) {
6829 $groupBy = " GROUP BY " . implode(', ', $groupByCols);
6832 $order = $orderBy = '';
6835 $order = $this->prepareOrderBy($sort, $sortOrder);
6838 // Cases where we are disabling FGB (FULL_GROUP_BY_MODE):
6839 // 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
6840 // clause. This will impact the search query output.
6841 $disableFullGroupByMode = (!empty($groupBy) ||
$groupContacts);
6843 if ($disableFullGroupByMode) {
6844 CRM_Core_DAO
::disableFullGroupByMode();
6848 $this->_sort
= $sort;
6851 $this->includePseudoFieldsJoin($sort);
6853 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
6855 if ($additionalWhereClause) {
6856 $where = $where . ' AND ' . $additionalWhereClause;
6859 //additional from clause should be w/ proper joins.
6860 if ($additionalFromClause) {
6861 $from .= "\n" . $additionalFromClause;
6864 // if we are doing a transform, do it here
6865 // use the $from, $where and $having to get the contact ID
6866 if ($this->_displayRelationshipType
) {
6867 $this->filterRelatedContacts($from, $where, $having);
6869 $limit = (!$count && $rowCount) ?
" LIMIT " . CRM_Utils_Type
::escape($offset, 'Int') . ", " . CRM_Utils_Type
::escape($rowCount, 'Int') : '';
6872 'select' => $select,
6875 'order_by' => $order,
6876 'group_by' => $groupBy,
6877 'having' => $having,
6883 * Get the metadata for a given field.
6885 * @param string $fieldName
6889 protected function getMetadataForField($fieldName) {
6890 if ($fieldName === 'contact_a.id') {
6891 // This seems to be the only anomaly.
6894 $pseudoField = $this->_pseudoConstantsSelect
[$fieldName] ??
[];
6895 $field = $this->_fields
[$fieldName] ??
$pseudoField;
6896 $field = array_merge($field, $pseudoField);
6897 if (!empty($field) && empty($field['name'])) {
6898 // standardising field formatting here - over time we can phase out variants.
6899 // all paths using this currently unit tested
6900 $field['name'] = CRM_Utils_Array
::value('field_name', $field, CRM_Utils_Array
::value('idCol', $field, $fieldName));
6906 * Get the metadata for a given field, returning the 'real field' if it is a pseudofield.
6908 * @param string $fieldName
6912 public function getMetadataForRealField($fieldName) {
6913 $field = $this->getMetadataForField($fieldName);
6914 if (!empty($field['is_pseudofield_for'])) {
6915 $field = $this->getMetadataForField($field['is_pseudofield_for']);
6916 $field['pseudofield_name'] = $fieldName;
6918 elseif (!empty($field['pseudoconstant'])) {
6919 if (!empty($field['pseudoconstant']['optionGroupName'])) {
6920 $field['pseudofield_name'] = $field['pseudoconstant']['optionGroupName'];
6921 if (empty($field['table_name'])) {
6922 if (!empty($field['where'])) {
6923 $field['table_name'] = explode('.', $field['where'])[0];
6926 $field['table_name'] = 'civicrm_contact';
6935 * Get the field datatype, using the type in the database rather than the pseudofield, if a pseudofield.
6937 * @param string $fieldName
6941 public function getDataTypeForRealField($fieldName) {
6942 return CRM_Utils_Type
::typeToString($this->getMetadataForRealField($fieldName)['type']);
6946 * If we have a field that is better rendered via the pseudoconstant handled them here.
6948 * Rather than joining in the additional table we render the option value on output.
6950 * @todo - so far this applies to a narrow range of pseudocontants. We are adding them
6951 * carefully with test coverage but aim to extend.
6953 * @param string $name
6955 protected function addPseudoconstantFieldToSelect($name) {
6956 $field = $this->getMetadataForRealField($name);
6957 $realFieldName = $field['name'];
6958 $pseudoFieldName = $field['pseudofield_name'] ??
NULL;
6959 if ($pseudoFieldName) {
6960 // @todo - we don't really need to build this array now we have metadata more available with getMetadataForField fn.
6961 $this->_pseudoConstantsSelect
[$pseudoFieldName] = [
6962 'pseudoField' => $pseudoFieldName,
6963 'idCol' => $realFieldName,
6964 'field_name' => $field['name'],
6965 'bao' => $field['bao'],
6966 'pseudoconstant' => $field['pseudoconstant'],
6970 $this->_tables
[$field['table_name']] = 1;
6971 $this->_element
[$realFieldName] = 1;
6972 $this->_select
[$field['name']] = str_replace('civicrm_contact.', 'contact_a.', "{$field['where']} as `$realFieldName`");
6976 * Is this pseudofield a foreign key constraint.
6978 * We are trying to cautiously expand our pseudoconstant handling. This check allows us
6979 * to extend to a narrowly defined type (and then only if the pseudofield is in the fields
6980 * array which is done for contributions which are mostly handled as pseudoconstants.
6986 protected function isPseudoFieldAnFK($fieldSpec) {
6987 if (empty($fieldSpec['FKClassName'])
6988 || CRM_Utils_Array
::value('keyColumn', $fieldSpec['pseudoconstant']) !== 'id'
6989 || CRM_Utils_Array
::value('labelColumn', $fieldSpec['pseudoconstant']) !== 'name') {
6996 * Is the field a relative date field.
6998 * @param string $fieldName
7002 protected function isARelativeDateField($fieldName) {
7003 if (substr($fieldName, -9, 9) !== '_relative') {
7006 $realField = substr($fieldName, 0, strlen($fieldName) - 9);
7007 return isset($this->_fields
[$realField]);
7011 * Get the specifications for the field, if available.
7013 * @param string $fieldName
7014 * Fieldname as displayed on the form.
7018 public function getFieldSpec($fieldName) {
7019 if (isset($this->_fields
[$fieldName])) {
7020 $fieldSpec = $this->_fields
[$fieldName];
7021 if (!empty($fieldSpec['is_pseudofield_for'])) {
7022 $fieldSpec = array_merge($this->_fields
[$fieldSpec['is_pseudofield_for']], $this->_fields
[$fieldName]);
7026 $lowFieldName = str_replace('_low', '', $fieldName);
7027 if (isset($this->_fields
[$lowFieldName])) {
7028 return array_merge($this->_fields
[$lowFieldName], ['field_name' => $lowFieldName]);
7030 $highFieldName = str_replace('_high', '', $fieldName);
7031 if (isset($this->_fields
[$highFieldName])) {
7032 return array_merge($this->_fields
[$highFieldName], ['field_name' => $highFieldName]);
7037 public function buildWhereForDate() {
7042 * Is the field a relative date field.
7044 * @param string $fieldName
7048 protected function isADateRangeField($fieldName) {
7049 if (substr($fieldName, -4, 4) !== '_low' && substr($fieldName, -5, 5) !== '_high') {
7052 return !empty($this->getFieldSpec($fieldName));
7058 protected function buildRelativeDateQuery(&$values) {
7059 $value = $values[2] ??
NULL;
7060 if (empty($value)) {
7063 $fieldName = substr($values[0], 0, strlen($values[0]) - 9);
7064 $fieldSpec = $this->_fields
[$fieldName];
7065 $tableName = $fieldSpec['table_name'];
7066 $filters = CRM_Core_OptionGroup
::values('relative_date_filters');
7067 $grouping = $values[3] ??
NULL;
7068 // If the table value is already set for a custom field it will be more nuanced than just '1'.
7069 $this->_tables
[$tableName] = $this->_tables
[$tableName] ??
1;
7070 $this->_whereTables
[$tableName] = $this->_whereTables
[$tableName] ??
1;
7072 $dates = CRM_Utils_Date
::getFromTo($value, NULL, NULL);
7073 // Where end would be populated only if we are handling one of the weird ones with different from & to fields.
7074 $secondWhere = $fieldSpec['where_end'] ??
$fieldSpec['where'];
7076 $where = $fieldSpec['where'];
7077 if ($fieldSpec['table_name'] === 'civicrm_contact') {
7078 // Special handling for contact table as it has a known alias in advanced search.
7079 $where = str_replace('civicrm_contact.', 'contact_a.', $where);
7080 $secondWhere = str_replace('civicrm_contact.', 'contact_a.', $secondWhere);
7083 $this->_qill
[$grouping][] = $this->getQillForRelativeDateRange($dates[0], $dates[1], $fieldSpec['title'], $filters[$value]);
7084 if ($fieldName === 'relation_active_period_date') {
7085 // Hack this to fix regression https://lab.civicrm.org/dev/core/issues/1592
7086 // Not sure the 'right' fix.
7087 $this->_where
[$grouping] = [self
::getRelationshipActivePeriodClauses($dates[0], $dates[1], TRUE)];
7091 if (empty($dates[0])) {
7092 // ie. no start date we only have end date
7093 $this->_where
[$grouping][] = $secondWhere . " <= '{$dates[1]}'";
7095 elseif (empty($dates[1])) {
7097 // ie. no end date we only have start date
7098 $this->_where
[$grouping][] = $where . " >= '{$dates[0]}'";
7101 // we have start and end dates.
7102 if ($secondWhere !== $where) {
7103 $this->_where
[$grouping][] = $where . ">= '{$dates[0]}' AND $secondWhere <='{$dates[1]}'";
7106 $this->_where
[$grouping][] = $where . " BETWEEN '{$dates[0]}' AND '{$dates[1]}'";
7112 * Build the query for a date field if it is a _high or _low field.
7117 * @throws \CRM_Core_Exception
7119 public function buildDateRangeQuery($values) {
7120 if ($this->isADateRangeField($values[0])) {
7121 $fieldSpec = $this->getFieldSpec($values[0]);
7122 $title = empty($fieldSpec['unique_title']) ?
$fieldSpec['title'] : $fieldSpec['unique_title'];
7123 $this->dateQueryBuilder($values, $fieldSpec['table_name'], $fieldSpec['field_name'], $fieldSpec['name'], $title);
7130 * Add the address table into the query.
7132 * @param string $tableKey
7133 * @param string $joinCondition
7139 protected function addAddressTable($tableKey, $joinCondition) {
7140 $tName = "$tableKey-address";
7141 $aName = "`$tableKey-address`";
7142 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
7143 $this->_element
["{$tName}_id"] = 1;
7144 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$joinCondition)";
7145 $this->_tables
[$tName] = $addressJoin;
7154 * Get the clause for group status.
7156 * @param int $grouping
7160 protected function getGroupStatusClause($grouping) {
7161 $statuses = $this->getSelectedGroupStatuses($grouping);
7162 return "status IN (" . implode(', ', $statuses) . ")";
7166 * Get an array of the statuses that have been selected.
7168 * @param string $grouping
7172 * @throws \CRM_Core_Exception
7174 protected function getSelectedGroupStatuses($grouping) {
7176 $gcsValues = $this->getWhereValues('group_contact_status', $grouping);
7178 is_array($gcsValues[2])
7180 foreach ($gcsValues[2] as $k => $v) {
7182 $statuses[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
7187 $statuses[] = "'Added'";
7193 * Get the qill value for the field.
7195 * @param string $name
7196 * @param array|int|string $value
7198 * @param array $fieldSpec
7199 * @param string $labelOverride
7200 * Label override, if required.
7204 public function getQillForField($name, $value, $op, $fieldSpec = [], $labelOverride = NULL): string {
7205 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue($fieldSpec['bao'] ??
NULL, $name, $value, $op);
7206 return (string) ts("%1 %2 %3", [
7207 1 => $labelOverride ??
$fieldSpec['title'],
7214 * Where handling for any field with adequately defined metadata.
7216 * @param array $fieldSpec
7217 * @param string $name
7218 * @param string|array|int $value
7220 * @param string|int $grouping
7222 * @throws \CRM_Core_Exception
7224 public function handleWhereFromMetadata($fieldSpec, $name, $value, $op, $grouping = 0) {
7225 $this->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause($fieldSpec['where'], $op, $value, CRM_Utils_Type
::typeToString($fieldSpec['type']));
7226 $this->_qill
[$grouping][] = $this->getQillForField($name, $value, $op, $fieldSpec);
7227 if (!isset($this->_tables
[$fieldSpec['table_name']])) {
7228 $this->_tables
[$fieldSpec['table_name']] = 1;
7230 if (!isset($this->_whereTables
[$fieldSpec['table_name']])) {
7231 $this->_whereTables
[$fieldSpec['table_name']] = 1;
7236 * Get the qill for the relative date range.
7238 * @param string|null $from
7239 * @param string|null $to
7240 * @param string $fieldTitle
7241 * @param string $relativeRange
7245 protected function getQillForRelativeDateRange($from, $to, string $fieldTitle, string $relativeRange): string {
7247 return ts('%1 is ', [$fieldTitle]) . $relativeRange . ' (' . ts('to %1', [CRM_Utils_Date
::customFormat($to)]) . ')';
7250 return ts('%1 is ', [$fieldTitle]) . $relativeRange . ' (' . ts('from %1', [CRM_Utils_Date
::customFormat($from)]) . ')';
7252 return ts('%1 is ', [$fieldTitle]) . $relativeRange . ' (' . ts('between %1 and %2', [
7253 CRM_Utils_Date
::customFormat($from),
7254 CRM_Utils_Date
::customFormat($to),