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 * The cache to translate the option values into labels.
224 * Are we in search mode.
228 public $_search = TRUE;
231 * Should we skip permission checking.
235 public $_skipPermission = FALSE;
238 * Should we skip adding of delete clause.
242 public $_skipDeleteClause = FALSE;
245 * Are we in strict mode (use equality over LIKE)
249 public $_strict = FALSE;
252 * What operator to use to group the clauses.
256 public $_operator = 'AND';
261 * Should we only search on primary location.
265 public $_primaryLocation = TRUE;
268 * Are contact ids part of the query.
272 public $_includeContactIds = FALSE;
275 * Should we use the smart group cache.
279 public $_smartGroupCache = TRUE;
282 * Should we display contacts with a specific relationship type.
286 public $_displayRelationshipType;
289 * Reference to the query object for custom values.
293 public $_customQuery;
296 * Should we enable the distinct clause, used if we are including
297 * more than one group
301 public $_useDistinct = FALSE;
304 * Should we just display one contact record
307 public $_useGroupBy = FALSE;
310 * The relationship type direction
314 public static $_relType;
321 public static $_activityRole;
324 * Consider the component activity type
325 * during activity search.
329 public static $_considerCompActivities;
332 * Consider with contact activities only,
333 * during activity search.
337 public static $_withContactActivitiesOnly;
340 * Use distinct component clause for component searches
344 public $_distinctComponentClause;
346 public $_rowCountClause;
349 * Use groupBy component clause for component searches
353 public $_groupByComponentClause;
356 * Track open panes, useful in advance search
360 public static $_openedPanes = [];
363 * For search builder - which custom fields are location-dependent
366 public $_locationSpecificCustomFields = [];
369 * The tables which have a dependency on location and/or address
373 public static $_dependencies = [
374 'civicrm_state_province' => 1,
375 'civicrm_country' => 1,
376 'civicrm_county' => 1,
377 'civicrm_address' => 1,
378 'civicrm_location_type' => 1,
382 * List of location specific fields.
385 public static $_locationSpecificFields = [
390 'supplemental_address_1',
391 'supplemental_address_2',
392 'supplemental_address_3',
395 'postal_code_suffix',
409 * Remember if we handle either end of a number or date range
410 * so we can skip the other
413 protected $_rangeCache = [];
415 * Set to true when $this->relationship is run to avoid adding twice.
419 protected $_relationshipValuesAdded = FALSE;
422 * Set to the name of the temp table if one has been created.
426 public static $_relationshipTempTable;
428 public $_pseudoConstantsSelect = [];
430 public $_groupUniqueKey;
431 public $_groupKeys = [];
434 * Class constructor which also does all the work.
436 * @param array $params
437 * @param array $returnProperties
438 * @param array $fields
439 * @param bool $includeContactIds
440 * @param bool $strict
441 * @param bool|int $mode - mode the search is operating on
443 * @param bool $skipPermission
444 * @param bool $searchDescendentGroups
445 * @param bool $smartGroupCache
446 * @param null $displayRelationshipType
447 * @param string $operator
448 * @param string $apiEntity
449 * @param bool|null $primaryLocationOnly
451 * @throws \CRM_Core_Exception
453 public function __construct(
454 $params = NULL, $returnProperties = NULL, $fields = NULL,
455 $includeContactIds = FALSE, $strict = FALSE, $mode = 1,
456 $skipPermission = FALSE, $searchDescendentGroups = TRUE,
457 $smartGroupCache = TRUE, $displayRelationshipType = NULL,
460 $primaryLocationOnly = NULL
462 if ($primaryLocationOnly === NULL) {
463 $primaryLocationOnly = Civi
::settings()->get('searchPrimaryDetailsOnly');
465 $this->_primaryLocation
= $primaryLocationOnly;
466 $this->_params
= &$params;
467 if ($this->_params
== NULL) {
471 if ($returnProperties === self
::NO_RETURN_PROPERTIES
) {
472 $this->_returnProperties
= [];
474 elseif (empty($returnProperties)) {
475 $this->_returnProperties
= self
::defaultReturnProperties($mode);
478 $this->_returnProperties
= &$returnProperties;
481 $this->_includeContactIds
= $includeContactIds;
482 $this->_strict
= $strict;
483 $this->_mode
= $mode;
484 $this->_skipPermission
= $skipPermission;
485 $this->_smartGroupCache
= $smartGroupCache;
486 $this->_displayRelationshipType
= $displayRelationshipType;
487 $this->setOperator($operator);
490 $this->_fields
= &$fields;
491 $this->_search
= FALSE;
492 $this->_skipPermission
= TRUE;
495 $this->_fields
= CRM_Contact_BAO_Contact
::exportableFields('All', FALSE, TRUE, TRUE, FALSE, !$skipPermission);
496 // The legacy hacked fields will output as a string rather than their underlying type.
497 foreach (array_keys($this->legacyHackedFields
) as $fieldName) {
498 $this->_fields
[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
500 $relationMetadata = CRM_Contact_BAO_Relationship
::fields();
501 $relationFields = array_intersect_key($relationMetadata, array_fill_keys(['relationship_start_date', 'relationship_end_date'], 1));
502 // No good option other than hard-coding metadata for this 'special' field in.
503 $relationFields['relation_active_period_date'] = [
504 'name' => 'relation_active_period_date',
505 'type' => CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
,
506 'title' => ts('Active Period'),
507 'table_name' => 'civicrm_relationship',
508 'where' => 'civicrm_relationship.start_date',
509 'where_end' => 'civicrm_relationship.end_date',
510 'html' => ['type' => 'SelectDate', 'formatType' => 'activityDateTime'],
512 $this->_fields
= array_merge($relationFields, $this->_fields
);
514 $fields = CRM_Core_Component
::getQueryFields(!$this->_skipPermission
);
515 unset($fields['note']);
516 $this->_fields
= array_merge($this->_fields
, $fields);
518 // add activity fields
519 $this->_fields
= array_merge($this->_fields
, CRM_Activity_BAO_Activity
::exportableFields());
520 $this->_fields
= array_merge($this->_fields
, CRM_Activity_BAO_Activity
::exportableFields('Case'));
521 // Add hack as no unique name is defined for the field but the search form is in denial.
522 $this->_fields
['activity_priority_id'] = $this->_fields
['priority_id'];
524 // add any fields provided by hook implementers
525 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
526 $this->_fields
= array_merge($this->_fields
, $extFields);
529 // basically do all the work once, and then reuse it
530 $this->initialize($apiEntity);
534 * Function which actually does all the work for the constructor.
536 * @param string $apiEntity
537 * The api entity being called.
538 * This sort-of duplicates $mode in a confusing way. Probably not by design.
540 * @throws \CRM_Core_Exception
542 public function initialize($apiEntity = NULL) {
544 $this->_element
= [];
546 $this->_whereTables
= [];
549 $this->_options
= [];
551 $this->_paramLookup
= [];
554 $this->_customQuery
= NULL;
556 // reset cached static variables - CRM-5803
557 self
::$_activityRole = NULL;
558 self
::$_considerCompActivities = NULL;
559 self
::$_withContactActivitiesOnly = NULL;
561 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
562 $this->_element
['contact_id'] = 1;
563 $this->_tables
['civicrm_contact'] = 1;
565 if (!empty($this->_params
)) {
566 $this->buildParamsLookup();
569 $this->_whereTables
= $this->_tables
;
571 $this->selectClause($apiEntity);
572 if (!empty($this->_cfIDs
)) {
573 // @todo This function is the select function but instead of running 'select' it
574 // is running the whole query.
575 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
576 $this->_customQuery
->query();
577 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
578 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
579 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
580 $this->_options
= $this->_customQuery
->_options
;
582 $isForcePrimaryOnly = !empty($apiEntity);
583 $this->_whereClause
= $this->whereClause($isForcePrimaryOnly);
584 if (array_key_exists('civicrm_contribution', $this->_whereTables
)) {
585 $component = 'contribution';
587 if (array_key_exists('civicrm_membership', $this->_whereTables
)) {
588 $component = 'membership';
590 if (isset($component) && !$this->_skipPermission
) {
591 // Unit test coverage in api_v3_FinancialTypeACLTest::testGetACLContribution.
592 CRM_Financial_BAO_FinancialType
::buildPermissionedClause($this->_whereClause
, $component);
595 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
, $apiEntity);
596 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
598 $this->openedSearchPanes(TRUE);
602 * Function for same purpose as convertFormValues.
604 * Like convert form values this function exists to pre-Process parameters from the form.
606 * It is unclear why they are different functions & likely relates to advances search
607 * versus search builder.
609 * The direction we are going is having the form convert values to a standardised format &
610 * moving away from weird & wonderful where clause switches.
612 * Fix and handle contact deletion nicely.
614 * this code is primarily for search builder use case where different clauses can specify if they want deleted.
616 * @see https://issues.civicrm.org/jira/browse/CRM-11971
618 public function buildParamsLookup() {
619 $trashParamExists = FALSE;
621 foreach ($this->_params
as $k => $param) {
622 if (!empty($param[0]) && $param[0] == 'contact_is_deleted') {
623 $trashParamExists = TRUE;
625 if (!empty($param[3])) {
626 $paramByGroup[$param[3]][$k] = $param;
630 if ($trashParamExists) {
631 $this->_skipDeleteClause
= TRUE;
633 //cycle through group sets and explicitly add trash param if not set
634 foreach ($paramByGroup as $setID => $set) {
636 !in_array(['contact_is_deleted', '=', '1', $setID, '0'], $this->_params
) &&
637 !in_array(['contact_is_deleted', '=', '0', $setID, '0'], $this->_params
)
640 'contact_is_deleted',
650 foreach ($this->_params
as $value) {
651 if (empty($value[0])) {
654 $cfID = CRM_Core_BAO_CustomField
::getKeyID(str_replace(['_relative', '_low', '_high', '_to', '_high'], '', $value[0]));
656 if (!array_key_exists($cfID, $this->_cfIDs
)) {
657 $this->_cfIDs
[$cfID] = [];
659 // Set wildcard value based on "and/or" selection
660 foreach ($this->_params
as $key => $param) {
661 if ($param[0] == $value[0] . '_operator') {
662 $value[4] = $param[2] == 'or';
666 $this->_cfIDs
[$cfID][] = $value;
669 if (!array_key_exists($value[0], $this->_paramLookup
)) {
670 $this->_paramLookup
[$value[0]] = [];
672 if ($value[0] !== 'group') {
673 // Just trying to unravel how group interacts here! This whole function is weird.
674 $this->_paramLookup
[$value[0]][] = $value;
680 * Some composite fields do not appear in the fields array hack to make them part of the query.
683 * The api entity being called.
684 * This sort-of duplicates $mode in a confusing way. Probably not by design.
686 public function addSpecialFields($apiEntity) {
687 static $special = ['contact_type', 'contact_sub_type', 'sort_name', 'display_name'];
688 // if get called via Contact.get API having address_id as return parameter
689 if ($apiEntity === 'Contact') {
690 $special[] = 'address_id';
692 foreach ($special as $name) {
693 if (!empty($this->_returnProperties
[$name])) {
694 if ($name === 'address_id') {
695 $this->_tables
['civicrm_address'] = 1;
696 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
697 $this->_element
['address_id'] = 1;
700 $this->_select
[$name] = "contact_a.{$name} as $name";
701 $this->_element
[$name] = 1;
708 * Given a list of conditions in params and a list of desired
709 * return Properties generate the required select and from
710 * clauses. Note that since the where clause introduces new
711 * tables, the initial attempt also retrieves all variables used
714 * @param string $apiEntity
715 * The api entity being called.
716 * This sort-of duplicates $mode in a confusing way. Probably not by design.
718 public function selectClause($apiEntity = NULL) {
720 // @todo Tidy up this. This arises because 1) we are ignoring the $mode & adding a new
721 // param ($apiEntity) instead - presumably an oversight & 2 because
722 // contact is not implemented as a component.
723 $this->addSpecialFields($apiEntity);
725 foreach ($this->_fields
as $name => $field) {
726 // skip component fields
727 // there are done by the alter query below
728 // and need not be done on every field
729 // @todo remove these & handle using metadata - only obscure fields
730 // that are hack-added should need to be excluded from the main loop.
732 (substr($name, 0, 12) === 'participant_') ||
733 (substr($name, 0, 7) === 'pledge_') ||
734 (substr($name, 0, 5) === 'case_')
739 // redirect to activity select clause
741 (substr($name, 0, 9) === 'activity_') ||
742 ($name === 'parent_id')
744 CRM_Activity_BAO_Query
::select($this);
747 // if this is a hierarchical name, we ignore it
748 $names = explode('-', $name);
749 if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) {
753 // make an exception for special cases, to add the field in select clause
754 $makeException = FALSE;
756 //special handling for groups/tags
757 if (in_array($name, ['groups', 'tags', 'notes'])
758 && isset($this->_returnProperties
[substr($name, 0, -1)])
760 // @todo instead of setting make exception to get us into
761 // an if clause that has handling for these fields buried with in it
762 // move the handling to here.
763 $makeException = TRUE;
766 // since note has 3 different options we need special handling
767 // note / note_subject / note_body
768 if ($name === 'notes') {
769 foreach (['note', 'note_subject', 'note_body'] as $noteField) {
770 if (isset($this->_returnProperties
[$noteField])) {
771 $makeException = TRUE;
777 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
779 !empty($this->_paramLookup
[$name])
780 ||
!empty($this->_returnProperties
[$name])
781 ||
$this->pseudoConstantNameIsInReturnProperties($field, $name)
785 // add to cfIDs array if not present
786 if (!array_key_exists($cfID, $this->_cfIDs
)) {
787 $this->_cfIDs
[$cfID] = [];
790 elseif (isset($field['where'])) {
791 list($tableName, $fieldName) = explode('.', $field['where'], 2);
792 if (isset($tableName)) {
793 if (!empty(self
::$_dependencies[$tableName])) {
794 $this->_tables
['civicrm_address'] = 1;
795 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
796 $this->_element
['address_id'] = 1;
799 if ($tableName === 'im_provider' ||
$tableName === 'email_greeting' ||
800 $tableName === 'postal_greeting' ||
$tableName === 'addressee'
802 if ($tableName === 'im_provider') {
803 CRM_Core_OptionValue
::select($this);
806 if (in_array($tableName,
807 ['email_greeting', 'postal_greeting', 'addressee'])) {
808 $this->_element
["{$name}_id"] = 1;
809 $this->_select
["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
810 $this->_pseudoConstantsSelect
[$name] = ['pseudoField' => $tableName, 'idCol' => "{$name}_id"];
811 $this->_pseudoConstantsSelect
[$name]['select'] = "{$name}.{$fieldName} as $name";
812 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
814 if ($tableName === 'email_greeting') {
816 $this->_pseudoConstantsSelect
[$name]['join']
817 = " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
818 $this->_pseudoConstantsSelect
[$name]['join'] .=
819 " 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 ) ";
821 elseif ($tableName === 'postal_greeting') {
823 $this->_pseudoConstantsSelect
[$name]['join']
824 = " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
825 $this->_pseudoConstantsSelect
[$name]['join'] .=
826 " 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 ) ";
828 elseif ($tableName == 'addressee') {
830 $this->_pseudoConstantsSelect
[$name]['join']
831 = " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
832 $this->_pseudoConstantsSelect
[$name]['join'] .=
833 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
835 $this->_pseudoConstantsSelect
[$name]['table'] = $tableName;
838 $greetField = "{$name}_display";
839 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
840 $this->_element
[$greetField] = 1;
842 $greetField = "{$name}_custom";
843 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
844 $this->_element
[$greetField] = 1;
848 if (!in_array($tableName, ['civicrm_state_province', 'civicrm_country', 'civicrm_county'])) {
849 $this->_tables
[$tableName] = 1;
852 // also get the id of the tableName
853 $tName = substr($tableName, 8);
854 if (in_array($tName, ['country', 'state_province', 'county'])) {
855 if ($tName == 'state_province') {
856 $this->_pseudoConstantsSelect
['state_province_name'] = [
857 'pseudoField' => "{$tName}",
858 'idCol' => "{$tName}_id",
859 'bao' => 'CRM_Core_BAO_Address',
860 'table' => "civicrm_{$tName}",
861 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
864 $this->_pseudoConstantsSelect
[$tName] = [
865 'pseudoField' => 'state_province_abbreviation',
866 'idCol' => "{$tName}_id",
867 'table' => "civicrm_{$tName}",
868 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
872 $this->_pseudoConstantsSelect
[$name] = [
873 'pseudoField' => "{$tName}_id",
874 'idCol' => "{$tName}_id",
875 'bao' => 'CRM_Core_BAO_Address',
876 'table' => "civicrm_{$tName}",
877 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
881 $this->_select
["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
882 $this->_element
["{$tName}_id"] = 1;
884 elseif ($tName != 'contact') {
885 $this->_select
["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
886 $this->_element
["{$tName}_id"] = 1;
889 //special case for phone
890 if ($name == 'phone') {
891 $this->_select
['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
892 $this->_element
['phone_type_id'] = 1;
895 // if IM then select provider_id also
896 // to get "IM Service Provider" in a file to be exported, CRM-3140
898 $this->_select
['provider_id'] = "civicrm_im.provider_id as provider_id";
899 $this->_element
['provider_id'] = 1;
902 if ($tName == 'contact' && $fieldName == 'organization_name') {
903 // special case, when current employer is set for Individual contact
904 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
906 elseif ($tName == 'contact' && $fieldName === 'id') {
907 // Handled elsewhere, explicitly ignore. Possibly for all tables...
909 elseif (in_array($tName, ['country', 'county'])) {
910 $this->_pseudoConstantsSelect
[$name]['select'] = "{$field['where']} as `$name`";
911 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
913 elseif ($tName == 'state_province') {
914 $this->_pseudoConstantsSelect
[$tName]['select'] = "{$field['where']} as `$name`";
915 $this->_pseudoConstantsSelect
[$tName]['element'] = $name;
917 elseif (strpos($name, 'contribution_soft_credit') !== FALSE) {
918 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled($this->_params
)) {
919 $this->_select
[$name] = "{$field['where']} as `$name`";
922 elseif ($this->pseudoConstantNameIsInReturnProperties($field, $name)) {
923 $this->addPseudoconstantFieldToSelect($name);
926 $this->_select
[$name] = str_replace('civicrm_contact.', 'contact_a.', "{$field['where']} as `$name`");
928 if (!in_array($tName, ['state_province', 'country', 'county'])) {
929 $this->_element
[$name] = 1;
934 elseif ($name === 'tags') {
935 //@todo move this handling outside the big IF & ditch $makeException
936 $this->_useGroupBy
= TRUE;
937 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
938 $this->_element
[$name] = 1;
939 $this->_tables
['civicrm_tag'] = 1;
940 $this->_tables
['civicrm_entity_tag'] = 1;
942 elseif ($name === 'groups') {
943 //@todo move this handling outside the big IF & ditch $makeException
944 $this->_useGroupBy
= TRUE;
945 // Duplicates will be created here but better to sort them out in php land.
946 $this->_select
[$name] = "
948 GROUP_CONCAT(DISTINCT IF(civicrm_group_contact.status = 'Added', civicrm_group_contact.group_id, '')),
949 GROUP_CONCAT(DISTINCT civicrm_group_contact_cache.group_id)
952 $this->_element
[$name] = 1;
953 $this->_tables
['civicrm_group_contact'] = 1;
954 $this->_tables
['civicrm_group_contact_cache'] = 1;
955 $this->_pseudoConstantsSelect
["{$name}"] = [
956 'pseudoField' => "groups",
960 elseif ($name === 'notes') {
961 //@todo move this handling outside the big IF & ditch $makeException
962 // if note field is subject then return subject else body of the note
963 $noteColumn = 'note';
964 if (isset($noteField) && $noteField === 'note_subject') {
965 $noteColumn = 'subject';
968 $this->_useGroupBy
= TRUE;
969 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
970 $this->_element
[$name] = 1;
971 $this->_tables
['civicrm_note'] = 1;
973 elseif ($name === 'current_employer') {
974 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
975 $this->_element
[$name] = 1;
979 if ($cfID && !empty($field['is_search_range'])) {
980 // this is a custom field with range search enabled, so we better check for two/from values
981 if (!empty($this->_paramLookup
[$name . '_from'])) {
982 if (!array_key_exists($cfID, $this->_cfIDs
)) {
983 $this->_cfIDs
[$cfID] = [];
985 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
986 // search in the cdID array for the same grouping
988 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
989 if ($c[3] == $p[3]) {
990 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
995 $p[2] = ['from' => $p[2]];
996 $this->_cfIDs
[$cfID][] = $p;
1000 if (!empty($this->_paramLookup
[$name . '_to'])) {
1001 if (!array_key_exists($cfID, $this->_cfIDs
)) {
1002 $this->_cfIDs
[$cfID] = [];
1004 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
1005 // search in the cdID array for the same grouping
1007 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
1008 if ($c[4] == $p[4]) {
1009 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
1014 $p[2] = ['to' => $p[2]];
1015 $this->_cfIDs
[$cfID][] = $p;
1022 // add location as hierarchical elements
1023 $this->addHierarchicalElements();
1025 // add multiple field like website
1026 $this->addMultipleElements();
1029 CRM_Core_Component
::alterQuery($this, 'select');
1031 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'select');
1035 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
1037 public function addHierarchicalElements() {
1038 if (empty($this->_returnProperties
['location'])) {
1041 if (!is_array($this->_returnProperties
['location'])) {
1045 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
1049 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
1050 $addressCustomFieldIds = [];
1052 foreach ($this->_returnProperties
['location'] as $name => $elements) {
1053 $lCond = self
::getPrimaryCondition($name);
1054 $locationTypeId = is_numeric($name) ?
NULL : array_search($name, $locationTypes);
1057 if ($locationTypeId === FALSE) {
1060 $lCond = "location_type_id = $locationTypeId";
1061 $this->_useDistinct
= TRUE;
1063 //commented for CRM-3256
1064 $this->_useGroupBy
= TRUE;
1067 $name = str_replace(' ', '_', $name);
1068 $tName = "$name-location_type";
1069 $ltName = "`$name-location_type`";
1070 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1071 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
1072 $this->_element
["{$tName}_id"] = 1;
1073 $this->_element
["{$tName}"] = 1;
1075 $locationTypeName = $tName;
1076 $locationTypeJoin = [];
1079 foreach ($elements as $elementFullName => $dontCare) {
1081 $elementName = $elementCmpName = $elementFullName;
1083 if (substr($elementCmpName, 0, 5) == 'phone') {
1084 $elementCmpName = 'phone';
1087 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
1088 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
1089 $addressCustomFieldIds[$cfID][$name] = 1;
1092 // add address table - doesn't matter if we do it mutliple times - it's the same data
1093 // @todo ditch the double processing of addressJoin
1094 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
1095 && !in_array($elementCmpName, ['email', 'phone', 'im', 'openid'])
1097 list($aName, $addressJoin) = $this->addAddressTable($name, $lCond);
1098 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
1099 $processed[$aName] = 1;
1102 $cond = $elementType = '';
1103 if (strpos($elementName, '-') !== FALSE) {
1104 // this is either phone, email or IM
1105 list($elementName, $elementType) = explode('-', $elementName);
1107 if (($elementName != 'phone') && ($elementName != 'im')) {
1108 $cond = self
::getPrimaryCondition($elementType);
1110 // CRM-13011 : If location type is primary, do not restrict search to the phone
1111 // type id - we want the primary phone, regardless of what type it is.
1112 // Otherwise, restrict to the specified phone type for the given field.
1113 if ((!$cond) && ($elementName == 'phone')) {
1114 $cond = "phone_type_id = '$elementType'";
1116 elseif ((!$cond) && ($elementName == 'im')) {
1117 // IM service provider id, CRM-3140
1118 $cond = "provider_id = '$elementType'";
1120 $elementType = '-' . $elementType;
1123 $field = $this->_fields
[$elementName] ??
NULL;
1125 // hack for profile, add location id
1128 // fix for CRM-882( to handle phone types )
1129 !is_numeric($elementType)
1131 if (is_numeric($name)) {
1132 $field = $this->_fields
[$elementName . "-Primary$elementType"] ??
NULL;
1135 $field = $this->_fields
[$elementName . "-$locationTypeId$elementType"] ??
NULL;
1138 elseif (is_numeric($name)) {
1139 //this for phone type to work
1140 if (in_array($elementName, ['phone', 'phone_ext'])) {
1141 $field = $this->_fields
[$elementName . "-Primary" . $elementType] ??
NULL;
1144 $field = $this->_fields
[$elementName . "-Primary"] ??
NULL;
1148 //this is for phone type to work for profile edit
1149 if (in_array($elementName, ['phone', 'phone_ext'])) {
1150 $field = $this->_fields
[$elementName . "-$locationTypeId$elementType"] ??
NULL;
1153 $field = $this->_fields
[$elementName . "-$locationTypeId"] ??
NULL;
1158 // Check if there is a value, if so also add to where Clause
1160 if ($this->_params
) {
1162 if (isset($locationTypeId)) {
1163 $nm .= "-$locationTypeId";
1165 if (!is_numeric($elementType)) {
1166 $nm .= "$elementType";
1169 foreach ($this->_params
as $id => $values) {
1170 if ((is_array($values) && $values[0] == $nm) ||
1171 (in_array($elementName, ['phone', 'im'])
1172 && (strpos($values[0], $nm) !== FALSE)
1182 if ($field && isset($field['where'])) {
1183 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1184 $pf = substr($tableName, 8);
1185 $tName = $name . '-' . $pf . $elementType;
1186 if (isset($tableName)) {
1187 if ($tableName == 'civicrm_state_province' ||
$tableName == 'civicrm_country' ||
$tableName == 'civicrm_county') {
1188 $this->_select
["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1191 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1194 $this->_element
["{$tName}_id"] = 1;
1195 if (substr($tName, -15) == '-state_province') {
1196 // FIXME: hack to fix CRM-1900
1197 $a = Civi
::settings()->get('address_format');
1199 if (substr_count($a, 'state_province_name') > 0) {
1200 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = [
1201 'pseudoField' => "{$pf}_id",
1202 'idCol' => "{$tName}_id",
1203 'bao' => 'CRM_Core_BAO_Address',
1205 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1208 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = [
1209 'pseudoField' => 'state_province_abbreviation',
1210 'idCol' => "{$tName}_id",
1212 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1216 if (substr($elementFullName, 0, 2) == 'im') {
1217 $provider = "{$name}-{$elementFullName}-provider_id";
1218 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1219 $this->_element
[$provider] = 1;
1221 if ($pf == 'country' ||
$pf == 'county') {
1222 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = [
1223 'pseudoField' => "{$pf}_id",
1224 'idCol' => "{$tName}_id",
1225 'bao' => 'CRM_Core_BAO_Address',
1227 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1230 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1234 if (in_array($pf, ['state_province', 'country', 'county'])) {
1235 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1238 $this->_element
["{$name}-{$elementFullName}"] = 1;
1241 if (empty($processed["`$tName`"])) {
1242 $processed["`$tName`"] = 1;
1243 $newName = $tableName . '_' . $index;
1244 switch ($tableName) {
1245 case 'civicrm_phone':
1246 case 'civicrm_email':
1248 case 'civicrm_openid':
1250 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id";
1251 if ($tableName != 'civicrm_phone') {
1252 $this->_tables
[$tName] .= " AND `$tName`.$lCond";
1254 elseif (is_numeric($name)) {
1255 $this->_select
[$tName] = "IF (`$tName`.is_primary = $name, `$tName`.phone, NULL) as `$tName`";
1258 // this special case to add phone type
1260 $phoneTypeCondition = " AND `$tName`.$cond ";
1261 //gross hack to pickup corrupted data also, CRM-7603
1262 if (strpos($cond, 'phone_type_id') !== FALSE) {
1263 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1264 if (!empty($lCond)) {
1265 $phoneTypeCondition .= " AND ( `$tName`.$lCond ) ";
1268 $this->_tables
[$tName] .= $phoneTypeCondition;
1271 //build locationType join
1272 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1275 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1279 case 'civicrm_state_province':
1280 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1281 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1282 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1284 $this->_whereTables
["{$name}-address"] = $addressJoin;
1288 case 'civicrm_country':
1289 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1290 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1291 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1293 $this->_whereTables
["{$name}-address"] = $addressJoin;
1297 case 'civicrm_county':
1298 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1299 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1300 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1302 $this->_whereTables
["{$name}-address"] = $addressJoin;
1307 if (isset($addressCustomFields[$elementName]['custom_field_id']) && !empty($addressCustomFields[$elementName]['custom_field_id'])) {
1308 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.id";
1311 $this->_whereTables
["{$name}-address"] = $addressJoin;
1320 // add location type join
1321 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1322 $this->_tables
[$locationTypeName] = $ltypeJoin;
1324 // table should be present in $this->_whereTables,
1325 // to add its condition in location type join, CRM-3939.
1326 if ($addWhereCount) {
1328 foreach ($this->_whereTables
as $tableName => $clause) {
1329 if (!empty($locationTypeJoin[$tableName])) {
1330 $locClause[] = $locationTypeJoin[$tableName];
1334 if (!empty($locClause)) {
1335 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1340 if (!empty($addressCustomFieldIds)) {
1341 $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
1342 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1343 foreach ($locTypeName as $name => $dnc) {
1344 $this->_locationSpecificCustomFields
[$cfID] = [$name, array_search($name, $locationTypes)];
1345 $fieldName = "$name-custom_{$cfID}";
1346 $tName = "$name-address-custom-{$cfID}";
1347 $aName = "`$name-address-custom-{$cfID}`";
1348 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1349 $this->_element
["{$tName}_id"] = 1;
1350 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1351 $this->_element
[$fieldName] = 1;
1352 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1359 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
1361 public function addMultipleElements() {
1362 if (empty($this->_returnProperties
['website'])) {
1365 if (!is_array($this->_returnProperties
['website'])) {
1369 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1370 foreach ($elements as $elementFullName => $dontCare) {
1371 $tName = "website-{$key}-{$elementFullName}";
1372 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1373 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1374 $this->_element
["{$tName}_id"] = 1;
1375 $this->_element
["{$tName}"] = 1;
1377 $type = "website-{$key}-website_type_id";
1378 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1379 $this->_element
[$type] = 1;
1380 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id AND `$tName`.website_type_id = $key )";
1386 * Generate the query based on what type of query we need.
1388 * @param bool $count
1389 * @param bool $sortByChar
1390 * @param bool $groupContacts
1391 * @param bool $onlyDeleted
1394 * sql query parts as an array
1396 public function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE, $onlyDeleted = FALSE) {
1397 // build permission clause
1398 $this->generatePermissionClause($onlyDeleted, $count);
1401 if (isset($this->_rowCountClause
)) {
1402 $select = "SELECT {$this->_rowCountClause}";
1404 elseif (isset($this->_distinctComponentClause
)) {
1405 // we add distinct to get the right count for components
1406 // for the more complex result set, we use GROUP BY the same id
1408 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} ) as rowCount";
1411 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1413 $from = $this->_simpleFromClause
;
1414 if ($this->_useDistinct
) {
1415 $this->_useGroupBy
= TRUE;
1418 elseif ($sortByChar) {
1419 // @fixme add the deprecated warning back in (it breaks CRM_Contact_SelectorTest::testSelectorQuery)
1420 // CRM_Core_Error::deprecatedFunctionWarning('sort by char is deprecated - use alphabetQuery method');
1421 $select = 'SELECT DISTINCT LEFT(contact_a.sort_name, 1) as sort_name';
1422 $from = $this->_simpleFromClause
;
1424 elseif ($groupContacts) {
1425 $select = 'SELECT contact_a.id as id';
1426 if ($this->_useDistinct
) {
1427 $this->_useGroupBy
= TRUE;
1429 $from = $this->_simpleFromClause
;
1432 if (!empty($this->_paramLookup
['group'])) {
1434 list($name, $op, $value, $grouping, $wildcard) = $this->_paramLookup
['group'][0];
1436 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
1437 $this->_paramLookup
['group'][0][1] = key($value);
1440 // Presumably the lines below come into manage groups screen.
1441 // make sure there is only one element
1442 // this is used when we are running under smog and need to know
1443 // how the contact was added (CRM-1203)
1444 $groups = (array) CRM_Utils_Array
::value($this->_paramLookup
['group'][0][1], $this->_paramLookup
['group'][0][2], $this->_paramLookup
['group'][0][2]);
1445 if ((count($this->_paramLookup
['group']) == 1) &&
1446 (count($groups) == 1)
1448 $groupId = $groups[0];
1450 //check if group is saved search
1451 $group = new CRM_Contact_BAO_Group();
1452 $group->id
= $groupId;
1455 if (!isset($group->saved_search_id
)) {
1456 $tbName = "civicrm_group_contact";
1457 // CRM-17254 don't retrieve extra fields if contact_id is specifically requested
1458 // as this will add load to an intentionally light query.
1459 // ideally this code would be removed as it appears to be to support CRM-1203
1460 // and passing in the required returnProperties from the url would
1461 // make more sense that globally applying the requirements of one form.
1462 if (($this->_returnProperties
!= ['contact_id'])) {
1463 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1464 $this->_element
['group_contact_id'] = 1;
1465 $this->_select
['status'] = "$tbName.status as status";
1466 $this->_element
['status'] = 1;
1470 $this->_useGroupBy
= TRUE;
1472 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1473 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1475 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1476 $this->_useDistinct
= FALSE;
1477 $this->_useGroupBy
= TRUE;
1481 $select = $this->getSelect();
1482 $from = $this->_fromClause
;
1486 if (!empty($this->_whereClause
)) {
1487 $where = "WHERE {$this->_whereClause}";
1490 if (!empty($this->_permissionWhereClause
) && empty($this->_displayRelationshipType
)) {
1491 if (!empty($this->_permissionFromClause
)) {
1492 $from .= " $this->_permissionFromClause";
1494 if (empty($where)) {
1495 $where = "WHERE $this->_permissionWhereClause";
1498 $where = "$where AND $this->_permissionWhereClause";
1503 if (!empty($this->_having
)) {
1504 foreach ($this->_having
as $havingSets) {
1505 foreach ($havingSets as $havingSet) {
1506 $havingValue[] = $havingSet;
1509 $having = ' HAVING ' . implode(' AND ', $havingValue);
1512 // if we are doing a transform, do it here
1513 // use the $from, $where and $having to get the contact ID
1514 if ($this->_displayRelationshipType
) {
1515 $this->filterRelatedContacts($from, $where, $having);
1518 return [$select, $from, $where, $having];
1522 * Get where values from the parameters.
1524 * @param string $name
1525 * @param mixed $grouping
1529 public function getWhereValues($name, $grouping) {
1531 foreach ($this->_params
as $values) {
1532 if ($values[0] == $name && $values[3] == $grouping) {
1543 * @param bool $relative
1544 * @param string $from
1547 public static function fixDateValues($relative, &$from, &$to) {
1549 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1554 * Convert values from form-appropriate to query-object appropriate.
1556 * The query object is increasingly supporting the sql-filter syntax which is the most flexible syntax.
1557 * So, ideally we would convert all fields to look like
1560 * // Set the operator for legacy reasons, but it is ignored
1562 * // array in sql filter syntax
1563 * 2 => array('BETWEEN' => array(1,60),
1568 * There are some examples of the syntax in
1569 * https://github.com/civicrm/civicrm-core/tree/master/api/v3/examples/Relationship
1571 * More notes at CRM_Core_DAO::createSQLFilter
1573 * and a list of supported operators in CRM_Core_DAO
1575 * @param array $formValues
1576 * @param int $wildcard
1577 * @param bool $useEquals
1579 * @param string $apiEntity
1581 * @param array $entityReferenceFields
1582 * Field names of any entity reference fields (which will need reformatting to IN syntax).
1586 public static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL,
1587 $entityReferenceFields = []) {
1589 if (empty($formValues)) {
1593 self
::filterCountryFromValuesIfStateExists($formValues);
1594 CRM_Core_BAO_CustomValue
::fixCustomFieldValue($formValues);
1596 foreach ($formValues as $id => $values) {
1597 if (self
::isAlreadyProcessedForQueryFormat($values)) {
1598 $params[] = $values;
1602 self
::legacyConvertFormValues($id, $values);
1604 // The form uses 1 field to represent two db fields
1605 if ($id === 'contact_type' && $values && (!is_array($values) ||
!array_intersect(array_keys($values), CRM_Core_DAO
::acceptedSQLOperators()))) {
1608 foreach ((array) $values as $key => $type) {
1609 $types = explode('__', is_numeric($type) ?
$key : $type, 2);
1610 $contactType[$types[0]] = $types[0];
1611 // Add sub-type if specified
1612 if (!empty($types[1])) {
1613 $subType[$types[1]] = $types[1];
1616 $params[] = ['contact_type', 'IN', $contactType, 0, 0];
1618 $params[] = ['contact_sub_type', 'IN', $subType, 0, 0];
1621 elseif ($id === 'privacy') {
1622 if (is_array($formValues['privacy'])) {
1623 $op = !empty($formValues['privacy']['do_not_toggle']) ?
'=' : '!=';
1624 foreach ($formValues['privacy'] as $key => $value) {
1626 $params[] = [$key, $op, $value, 0, 0];
1631 elseif ($id === 'email_on_hold') {
1632 if ($onHoldValue = CRM_Utils_Array
::value('email_on_hold', $formValues)) {
1633 // onHoldValue should be 0 or 1 or an array. Some legacy groups may hold ''
1634 // so in 5.11 we have an extra if that should become redundant over time.
1635 // https://lab.civicrm.org/dev/core/issues/745
1636 // @todo this renaming of email_on_hold to on_hold needs revisiting
1637 // it precedes recent changes but causes the default not to reload.
1638 $onHoldValue = array_filter((array) $onHoldValue, 'is_numeric');
1639 if (!empty($onHoldValue)) {
1640 $params[] = ['on_hold', 'IN', $onHoldValue, 0, 0];
1644 elseif (substr($id, 0, 7) === 'custom_'
1646 substr($id, -5, 5) === '_from'
1647 ||
substr($id, -3, 3) === '_to'
1650 self
::convertCustomRelativeFields($formValues, $params, $values, $id);
1652 elseif (in_array($id, $entityReferenceFields) && !empty($values) && is_string($values) && (strpos($values, ',') !=
1654 $params[] = [$id, 'IN', explode(',', $values), 0, 0];
1657 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals, $apiEntity);
1662 $params[] = $values;
1669 * Function to support legacy format for groups and tags.
1672 * @param array|int $values
1675 public static function legacyConvertFormValues($id, &$values) {
1681 'membership_type_id',
1682 'membership_status_id',
1684 if (in_array($id, $legacyElements) && is_array($values)) {
1685 // prior to 4.7, formValues for some attributes (e.g. group, tag) are stored in array(id1 => 1, id2 => 1),
1686 // as per the recent Search fixes $values need to be in standard array(id1, id2) format
1687 $values = CRM_Utils_Array
::convertCheckboxFormatToArray($values);
1692 * Fix values from query from/to something no-one cared enough to document.
1695 * @param array $values
1696 * @param int $wildcard
1697 * @param bool $useEquals
1699 * @param string $apiEntity
1701 * @return array|null
1703 public static function fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL) {
1704 // skip a few search variables
1705 static $skipWhere = NULL;
1706 static $likeNames = NULL;
1709 // Change camelCase EntityName to lowercase with underscores
1710 $apiEntity = _civicrm_api_get_entity_name_from_camel($apiEntity);
1712 // check if $value is in OK (Operator as Key) format as used by Get API
1713 if (CRM_Utils_System
::isNull($values)) {
1725 'display_relationship_type',
1729 if (in_array($id, $skipWhere) ||
1730 substr($id, 0, 4) == '_qf_' ||
1731 substr($id, 0, 7) == 'hidden_'
1737 (substr($id, 0, strlen($apiEntity)) != $apiEntity) &&
1738 (substr($id, 0, 10) != 'financial_' && substr($id, 0, 8) != 'payment_') &&
1739 (substr($id, 0, 7) != 'custom_')
1741 $id = $apiEntity . '_' . $id;
1745 $likeNames = ['sort_name', 'email', 'note', 'display_name'];
1748 // email comes in via advanced search
1749 // so use wildcard always
1750 if ($id == 'email') {
1754 if (!$useEquals && in_array($id, $likeNames)) {
1755 $result = [$id, 'LIKE', $values, 0, 1];
1757 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1758 $result = [$id, 'LIKE', $values, 0, 0];
1760 elseif ($id == 'contact_type' ||
1761 (!empty($values) && is_array($values) && !in_array(key($values), CRM_Core_DAO
::acceptedSQLOperators(), TRUE))
1763 $result = [$id, 'IN', $values, 0, $wildcard];
1766 $result = [$id, '=', $values, 0, $wildcard];
1773 * Get the where clause for a single field.
1775 * @param array $values
1776 * @param bool $isForcePrimaryOnly
1778 * @throws \CRM_Core_Exception
1780 public function whereClauseSingle(&$values, $isForcePrimaryOnly = FALSE) {
1781 if ($this->isARelativeDateField($values[0])) {
1782 $this->buildRelativeDateQuery($values);
1785 // @todo also handle _low, _high generically here with if ($query->buildDateRangeQuery($values)) {return}
1787 // do not process custom fields or prefixed contact ids or component params
1788 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1789 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1790 (substr($values[0], 0, 13) === 'contribution_') ||
1791 (substr($values[0], 0, 6) === 'event_') ||
1792 (substr($values[0], 0, 12) === 'participant_') ||
1793 (substr($values[0], 0, 7) === 'member_') ||
1794 (substr($values[0], 0, 6) === 'grant_') ||
1795 (substr($values[0], 0, 7) === 'pledge_') ||
1796 (substr($values[0], 0, 5) === 'case_') ||
1797 (substr($values[0], 0, 10) === 'financial_') ||
1798 (substr($values[0], 0, 8) === 'payment_') ||
1799 (substr($values[0], 0, 11) === 'membership_')
1800 // temporary fix for regression https://lab.civicrm.org/dev/core/issues/1551
1801 // ideally the metadata would allow this field to be parsed below & the special handling would not
1803 ||
$values[0] === 'mailing_id'
1808 // skip for hook injected fields / params
1809 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1810 if (array_key_exists($values[0], $extFields)) {
1814 switch ($values[0]) {
1815 case 'deleted_contacts':
1816 $this->deletedContacts($values);
1819 case 'contact_sub_type':
1820 $this->contactSubType($values);
1825 $this->group($values);
1828 // case tag comes from find contacts
1830 $this->tagSearch($values);
1834 case 'contact_tags':
1835 $this->tag($values);
1840 case 'note_subject':
1841 $this->notes($values);
1845 $this->ufUser($values);
1849 case 'display_name':
1850 $this->sortName($values);
1854 case 'postal_greeting':
1855 case 'email_greeting':
1856 $this->greetings($values);
1861 $this->email($values, $isForcePrimaryOnly);
1864 case 'phone_numeric':
1865 $this->phone_numeric($values);
1868 case 'phone_phone_type_id':
1869 case 'phone_location_type_id':
1870 $this->phone_option_group($values);
1873 case 'street_address':
1874 $this->street_address($values);
1877 case 'street_number':
1878 $this->street_number($values);
1881 case 'sortByCharacter':
1882 $this->sortByCharacter($values);
1885 case 'location_type':
1886 $this->locationType($values);
1890 $this->county($values);
1893 case 'state_province':
1894 case 'state_province_id':
1895 case 'state_province_name':
1896 $this->stateProvince($values);
1901 $this->country($values, FALSE);
1905 case 'postal_code_low':
1906 case 'postal_code_high':
1907 $this->postalCode($values);
1910 case 'activity_date':
1911 case 'activity_date_low':
1912 case 'activity_date_high':
1913 case 'activity_date_time_low':
1914 case 'activity_date_time_high':
1915 case 'activity_role':
1916 case 'activity_status_id':
1917 case 'activity_status':
1918 case 'activity_priority':
1919 case 'activity_priority_id':
1920 case 'followup_parent_id':
1922 case 'source_contact_id':
1923 case 'activity_text':
1924 case 'activity_option':
1925 case 'test_activities':
1926 case 'activity_type_id':
1927 case 'activity_type':
1928 case 'activity_survey_id':
1929 case 'activity_tags':
1930 case 'activity_taglist':
1931 case 'activity_test':
1932 case 'activity_campaign_id':
1933 case 'activity_engagement_level':
1935 case 'activity_result':
1936 case 'source_contact':
1937 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1942 case 'birth_date_low':
1943 case 'birth_date_high':
1944 case 'deceased_date_low':
1945 case 'deceased_date_high':
1946 $this->demographics($values);
1949 case 'age_asof_date':
1950 // handled by demographics
1953 case 'log_date_low':
1954 case 'log_date_high':
1955 $this->modifiedDates($values);
1959 $this->changeLog($values);
1962 case 'do_not_phone':
1963 case 'do_not_email':
1966 case 'do_not_trade':
1968 $this->privacy($values);
1971 case 'privacy_options':
1972 $this->privacyOptions($values);
1975 case 'privacy_operator':
1976 case 'privacy_toggle':
1977 // these are handled by privacy options
1980 case 'preferred_communication_method':
1981 $this->preferredCommunication($values);
1984 case 'relation_type_id':
1985 case 'relationship_start_date_high':
1986 case 'relationship_start_date_low':
1987 case 'relationship_end_date_high':
1988 case 'relationship_end_date_low':
1989 case 'relation_active_period_date_high':
1990 case 'relation_active_period_date_low':
1991 case 'relation_target_name':
1992 case 'relation_status':
1993 case 'relation_description':
1994 case 'relation_date_low':
1995 case 'relation_date_high':
1996 $this->relationship($values);
1997 $this->_relationshipValuesAdded
= TRUE;
2000 case 'task_status_id':
2001 $this->task($values);
2005 // since this case is handled with the above
2008 case 'prox_distance':
2009 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
2012 case 'prox_street_address':
2014 case 'prox_postal_code':
2015 case 'prox_state_province_id':
2016 case 'prox_country_id':
2017 case 'prox_geo_code_1':
2018 case 'prox_geo_code_2':
2019 // handled by the proximity_distance clause
2023 $this->restWhere($values);
2029 * Given a list of conditions in params generate the required where clause.
2031 * @param bool $isForcePrimaryEmailOnly
2034 * @throws \CRM_Core_Exception
2036 public function whereClause($isForcePrimaryEmailOnly = NULL) {
2037 $this->_where
[0] = [];
2038 $this->_qill
[0] = [];
2040 $this->includeContactIDs();
2041 if (!empty($this->_params
)) {
2042 foreach (array_keys($this->_params
) as $id) {
2043 if (empty($this->_params
[$id][0])) {
2046 // check for both id and contact_id
2047 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
2048 $this->_where
[0][] = self
::buildClause("contact_a.id", $this->_params
[$id][1], $this->_params
[$id][2]);
2049 $field = $this->_fields
['id'] ??
NULL;
2050 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(
2051 'CRM_Contact_BAO_Contact',
2053 $this->_params
[$id][2],
2054 $this->_params
[$id][1]
2056 $this->_qill
[0][] = ts("%1 %2 %3", [
2057 1 => $field['title'] ??
'',
2063 $this->whereClauseSingle($this->_params
[$id], $isForcePrimaryEmailOnly);
2067 CRM_Core_Component
::alterQuery($this, 'where');
2069 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
2072 if ($this->_customQuery
) {
2073 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
2074 // Added following if condition to avoid the wrong value display for 'my account' / any UF info.
2075 // Hope it wont affect the other part of civicrm.. if it does please remove it.
2076 if (!empty($this->_customQuery
->_where
)) {
2077 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
2079 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
2086 if (!empty($this->_where
)) {
2087 foreach ($this->_where
as $grouping => $values) {
2088 if ($grouping > 0 && !empty($values)) {
2089 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
2094 if (!empty($this->_where
[0])) {
2095 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
2097 if (!empty($clauses)) {
2098 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
2101 if ($validClauses > 1) {
2102 $this->_useDistinct
= TRUE;
2106 return implode(' AND ', $andClauses);
2110 * Generate where clause for any parameters not already handled.
2112 * @param array $values
2116 public function restWhere(&$values) {
2117 $name = $values[0] ??
NULL;
2118 $op = $values[1] ??
NULL;
2119 $value = $values[2] ??
NULL;
2120 $grouping = $values[3] ??
NULL;
2121 $wildcard = $values[4] ??
NULL;
2123 if (isset($grouping) && empty($this->_where
[$grouping])) {
2124 $this->_where
[$grouping] = [];
2127 $multipleFields = ['url'];
2129 //check if the location type exists for fields
2131 $locType = explode('-', $name);
2133 if (!in_array($locType[0], $multipleFields)) {
2134 //add phone type if exists
2135 if (isset($locType[2]) && $locType[2]) {
2136 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
2140 $field = $this->_fields
[$name] ??
NULL;
2143 $field = $this->_fields
[$locType[0]] ??
NULL;
2146 // Strip any trailing _high & _low that might be appended.
2147 $realFieldName = str_replace(['_high', '_low'], '', $name);
2148 if (isset($this->_fields
[$realFieldName])) {
2149 $field = $this->_fields
[str_replace(['_high', '_low'], '', $realFieldName)];
2150 $columnName = $field['column_name'] ??
$field['name'];
2151 $this->dateQueryBuilder($values, $field['table_name'], $realFieldName, $columnName, $field['title']);
2159 $locationType = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
2160 if (isset($locType[1]) && is_numeric($locType[1])) {
2161 $lType = $locationType[$locType[1]];
2164 $field['title'] .= " ($lType)";
2167 if (substr($name, 0, 14) === 'state_province') {
2168 if (isset($locType[1]) && is_numeric($locType[1])) {
2170 $aName = "{$lType}-address";
2171 $where = "`$aName`.state_province_id";
2174 $where = "civicrm_address.state_province_id";
2177 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value);
2178 $this->_tables
[$aName] = $this->_whereTables
[$aName] = 1;
2179 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
2180 $this->_qill
[$grouping][] = ts("%1 %2 %3", [1 => $field['title'], 2 => $qillop, 3 => $qillVal]);
2182 elseif (!empty($field['pseudoconstant'])) {
2183 // For the hacked fields we want to undo the hack to type to avoid missing the index by adding quotes.
2184 $dataType = !empty($this->legacyHackedFields
[$name]) ? CRM_Utils_Type
::T_INT
: $field['type'];
2185 $this->optionValueQuery(
2186 $name, $op, $value, $grouping,
2187 'CRM_Contact_DAO_Contact',
2190 CRM_Utils_Type
::typeToString($dataType)
2192 if ($name === 'gender_id') {
2193 self
::$_openedPanes[ts('Demographics')] = TRUE;
2196 elseif (substr($name, 0, 7) === 'country' ||
substr($name, 0, 6) === 'county') {
2197 $name = (substr($name, 0, 7) === 'country') ?
"country_id" : "county_id";
2198 if (isset($locType[1]) && is_numeric($locType[1])) {
2200 $aName = "{$lType}-address";
2201 $where = "`$aName`.$name";
2204 $where = "civicrm_address.$name";
2207 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2208 $this->_tables
[$aName] = $this->_whereTables
[$aName] = 1;
2210 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
2211 $this->_qill
[$grouping][] = ts("%1 %2 %3", [1 => $field['title'], 2 => $qillop, 3 => $qillVal]);
2213 elseif ($name === 'world_region') {
2214 $this->optionValueQuery(
2215 $name, $op, $value, $grouping,
2222 elseif ($name === 'is_deceased') {
2223 $this->setQillAndWhere($name, $op, $value, $grouping, $field);
2224 self
::$_openedPanes[ts('Demographics')] = TRUE;
2226 elseif ($name === 'created_date' ||
$name === 'modified_date' ||
$name === 'deceased_date' ||
$name === 'birth_date') {
2227 $appendDateTime = TRUE;
2228 if ($name === 'deceased_date' ||
$name === 'birth_date') {
2229 $appendDateTime = FALSE;
2230 self
::$_openedPanes[ts('Demographics')] = TRUE;
2232 $this->dateQueryBuilder($values, 'contact_a', $name, $name, $field['title'], $appendDateTime);
2234 elseif ($name === 'contact_id') {
2235 if (is_int($value)) {
2236 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
2237 $this->_qill
[$grouping][] = "$field[title] $op $value";
2240 elseif ($name === 'name') {
2241 $value = CRM_Core_DAO
::escapeString($value);
2244 $value = self
::getWildCardedValue($wildcard, $op, $value);
2246 CRM_Core_Error
::deprecatedFunctionWarning('Untested code path');
2247 // @todo it's likely this code path is obsolete / never called. It is definitely not
2248 // passed through in our test suite.
2249 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, "'$value'");
2250 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2252 elseif ($name === 'current_employer') {
2255 $value = self
::getWildCardedValue($wildcard, $op, $value);
2257 $ceWhereClause = self
::buildClause("contact_a.organization_name", $op,
2260 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2261 $this->_where
[$grouping][] = $ceWhereClause;
2262 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2264 elseif (substr($name, 0, 4) === 'url-') {
2265 $tName = 'civicrm_website';
2266 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2267 $value = CRM_Core_DAO
::escapeString($value);
2270 $value = self
::getWildCardedValue($wildcard, $op, $value);
2273 $this->_where
[$grouping][] = $d = self
::buildClause('civicrm_website.url', $op, $value);
2274 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2276 elseif ($name === 'contact_is_deleted') {
2277 $this->setQillAndWhere('is_deleted', $op, $value, $grouping, $field);
2279 elseif (!empty($field['where'])) {
2281 if (!empty($field['type'])) {
2282 $type = CRM_Utils_Type
::typeToString($field['type']);
2285 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2287 if (isset($locType[1]) &&
2288 is_numeric($locType[1])
2292 //get the location name
2293 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2294 $fieldName = "`$tName`.$fldName";
2296 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2297 $this->_tables
[$tName] = $this->_whereTables
[$tName] = 1;
2301 if ($tableName == 'civicrm_contact') {
2302 $fieldName = "contact_a.{$fieldName}";
2305 $fieldName = $field['where'];
2309 list($qillop, $qillVal) = self
::buildQillForFieldValue(NULL, $field['title'], $value, $op);
2310 $this->_qill
[$grouping][] = ts("%1 %2 %3", [
2311 1 => $field['title'],
2313 3 => (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) ?
$qillVal : "'$qillVal'",
2316 if (is_array($value)) {
2317 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2318 // for api style operators for functions that hit this point without worrying about regression
2319 // (the previous comments indicated the condition for hitting this point were unknown
2320 // per CRM-14743 we are adding modified_date & created_date operator support
2321 $operations = array_keys($value);
2322 foreach ($operations as $operator) {
2323 if (!in_array($operator, CRM_Core_DAO
::acceptedSQLOperators())) {
2324 //Via Contact get api value is not in array(operator => array(values)) format ONLY for IN/NOT IN operators
2325 //so this condition will satisfy the search for now
2326 if (strpos($op, 'IN') !== FALSE) {
2327 $value = [$op => $value];
2329 // we don't know when this might happen
2331 throw new CRM_Core_Exception(ts("%1 is not a valid operator", [1 => $operator]));
2335 $this->_where
[$grouping][] = CRM_Core_DAO
::createSQLFilter($fieldName, $value, $type);
2340 $value = self
::getWildCardedValue($wildcard, $op, $value);
2343 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2347 if ($setTables && isset($field['where'])) {
2348 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2349 if (isset($tableName)) {
2350 $this->_tables
[$tableName] = 1;
2351 $this->_whereTables
[$tableName] = 1;
2363 public static function getLocationTableName(&$where, &$locType) {
2364 if (isset($locType[1]) && is_numeric($locType[1])) {
2365 list($tbName, $fldName) = explode(".", $where);
2367 //get the location name
2368 $locationType = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
2369 $specialFields = ['email', 'im', 'phone', 'openid', 'phone_ext'];
2370 if (in_array($locType[0], $specialFields)) {
2371 //hack to fix / special handing for phone_ext
2372 if ($locType[0] == 'phone_ext') {
2373 $locType[0] = 'phone';
2375 if (isset($locType[2]) && $locType[2]) {
2376 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2379 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2382 elseif (in_array($locType[0],
2387 'street_number_suffix',
2389 'supplemental_address_1',
2390 'supplemental_address_2',
2391 'supplemental_address_3',
2394 'postal_code_suffix',
2400 //fix for search by profile with address fields.
2401 $tName = "{$locationType[$locType[1]]}-address";
2403 elseif (in_array($locType[0],
2411 $tName = "{$locationType[$locType[1]]}-email";
2413 elseif ($locType[0] == 'provider_id') {
2414 $tName = "{$locationType[$locType[1]]}-im";
2416 elseif ($locType[0] == 'openid') {
2417 $tName = "{$locationType[$locType[1]]}-openid";
2420 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2422 $tName = str_replace(' ', '_', $tName);
2423 return [$tName, $fldName];
2425 throw new CRM_Core_Exception('Cannot determine location table information');
2429 * Given a result dao, extract the values and return that array
2431 * @param CRM_Core_DAO $dao
2434 * values for this query
2436 public function store($dao) {
2439 foreach ($this->_element
as $key => $dontCare) {
2440 if (property_exists($dao, $key)) {
2441 if (strpos($key, '-') !== FALSE) {
2442 $values = explode('-', $key);
2443 $lastElement = array_pop($values);
2445 $cnt = count($values);
2447 foreach ($values as $v) {
2448 if (!array_key_exists($v, $current)) {
2451 //bad hack for im_provider
2452 if ($lastElement == 'provider_id') {
2453 if ($count < $cnt) {
2454 $current = &$current[$v];
2457 $lastElement = "{$v}_{$lastElement}";
2461 $current = &$current[$v];
2466 $current[$lastElement] = $dao->$key;
2469 $value[$key] = $dao->$key;
2477 * Getter for tables array.
2481 public function tables() {
2482 return $this->_tables
;
2486 * Sometimes used to create the from clause, but, not reliably, set
2487 * this AND set tables.
2489 * It's unclear the intent - there is a 'simpleFrom' clause which
2490 * takes whereTables into account & a fromClause which doesn't.
2492 * logic may have eroded?
2496 public function whereTables() {
2497 return $this->_whereTables
;
2501 * Generate the where clause (used in match contacts and permissions)
2503 * @param array $params
2504 * @param array $fields
2505 * @param array $tables
2506 * @param $whereTables
2507 * @param bool $strict
2510 * @throws \CRM_Core_Exception
2512 public static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2513 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2517 $tables = array_merge($query->tables(), $tables);
2518 $whereTables = array_merge($query->whereTables(), $whereTables);
2520 return $query->_whereClause
;
2524 * Create the from clause.
2526 * @param array $tables
2527 * Tables that need to be included in this from clause. If null,
2528 * return mimimal from clause (i.e. civicrm_contact).
2529 * @param array $inner
2530 * Tables that should be inner-joined.
2531 * @param array $right
2532 * Tables that should be right-joined.
2533 * @param bool $primaryLocation
2534 * Search on primary location. See note below.
2536 * Determines search mode based on bitwise MODE_* constants.
2537 * @param string|NULL $apiEntity
2538 * Determines search mode based on entity by string.
2540 * The $primaryLocation flag only seems to be used when
2541 * locationType() has been called. This may be a search option
2542 * exposed, or perhaps it's a "search all details" approach which
2543 * predates decoupling of location types and primary fields?
2545 * @see https://issues.civicrm.org/jira/browse/CRM-19967
2550 public static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1, $apiEntity = NULL) {
2552 $from = ' FROM civicrm_contact contact_a';
2553 if (empty($tables)) {
2557 if (!empty($tables['civicrm_worldregion'])) {
2558 $tables = array_merge(['civicrm_country' => 1], $tables);
2561 if ((!empty($tables['civicrm_state_province']) ||
!empty($tables['civicrm_country']) ||
2562 !empty($tables['civicrm_county'])) && empty($tables['civicrm_address'])) {
2563 $tables = array_merge(['civicrm_address' => 1],
2568 // add group_contact and group table is subscription history is present
2569 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2570 $tables = array_merge([
2571 'civicrm_group' => 1,
2572 'civicrm_group_contact' => 1,
2578 // to handle table dependencies of components
2579 CRM_Core_Component
::tableNames($tables);
2580 // to handle table dependencies of hook injected tables
2581 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2583 //format the table list according to the weight
2584 $info = CRM_Core_TableHierarchy
::info();
2586 foreach ($tables as $key => $value) {
2588 if (strpos($key, '-') !== FALSE) {
2589 $keyArray = explode('-', $key);
2590 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2592 elseif (strpos($key, '_') !== FALSE) {
2593 $keyArray = explode('_', $key);
2594 if (is_numeric(array_pop($keyArray))) {
2595 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2598 $k = CRM_Utils_Array
::value($key, $info, 99);
2602 $k = CRM_Utils_Array
::value($key, $info, 99);
2604 $tempTable[$k . ".$key"] = $key;
2608 foreach ($tempTable as $key) {
2609 $newTables[$key] = $tables[$key];
2612 $tables = $newTables;
2614 foreach ($tables as $name => $value) {
2619 if (!empty($inner[$name])) {
2622 elseif (!empty($right[$name])) {
2630 // if there is already a join statement in value, use value itself
2631 if (strpos($value, 'JOIN')) {
2632 $from .= " $value ";
2635 $from .= " $side JOIN $name ON ( $value ) ";
2640 $from .= ' ' . trim(self
::getEntitySpecificJoins($name, $mode, $side, $primaryLocation)) . ' ';
2646 * Get join statements for the from clause depending on entity type
2648 * @param string $name
2650 * @param string $side
2651 * @param string $primaryLocation
2654 protected static function getEntitySpecificJoins($name, $mode, $side, $primaryLocation) {
2655 $limitToPrimaryClause = $primaryLocation ?
"AND {$name}.is_primary = 1" : '';
2657 case 'civicrm_address':
2658 //CRM-14263 further handling of address joins further down...
2659 return " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id {$limitToPrimaryClause} )";
2661 case 'civicrm_state_province':
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_state_province ON ( civicrm_address.state_province_id = civicrm_state_province.id )";
2667 case 'civicrm_country':
2668 // This is encountered when doing an export after having applied a 'sort' - it pretty much implies primary
2669 // but that will have been implied-in by the calling function.
2670 // test cover in testContactIDQuery
2671 return " $side JOIN civicrm_country ON ( civicrm_address.country_id = civicrm_country.id )";
2673 case 'civicrm_phone':
2674 return " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id {$limitToPrimaryClause}) ";
2676 case 'civicrm_email':
2677 return " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id {$limitToPrimaryClause})";
2680 return " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id {$limitToPrimaryClause}) ";
2683 $from = " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2684 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2685 $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)";
2688 case 'civicrm_openid':
2689 return " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id {$limitToPrimaryClause} )";
2691 case 'civicrm_worldregion':
2692 // We can be sure from the calling function that country will already be joined in.
2693 // we really don't need world_region - we could use a pseudoconstant for it.
2694 return " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2696 case 'civicrm_location_type':
2697 return " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2699 case 'civicrm_group':
2700 return " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2702 case 'civicrm_group_contact':
2703 return " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2705 case 'civicrm_group_contact_cache':
2706 return " $side JOIN civicrm_group_contact_cache ON contact_a.id = civicrm_group_contact_cache.contact_id ";
2708 case 'civicrm_activity':
2709 case 'civicrm_activity_tag':
2710 case 'activity_type':
2711 case 'activity_status':
2713 case 'civicrm_activity_contact':
2714 case 'source_contact':
2715 case 'activity_priority':
2716 return CRM_Activity_BAO_Query
::from($name, $mode, $side);
2718 case 'civicrm_entity_tag':
2719 $from = " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact'";
2720 return "$from AND civicrm_entity_tag.entity_id = contact_a.id ) ";
2722 case 'civicrm_note':
2723 $from = " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact'";
2724 return "$from AND contact_a.id = civicrm_note.entity_id ) ";
2726 case 'civicrm_subscription_history':
2727 $from = " $side JOIN civicrm_subscription_history";
2728 $from .= " ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id";
2729 return "$from AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2731 case 'civicrm_relationship':
2732 if (self
::$_relType == 'reciprocal') {
2733 if (self
::$_relationshipTempTable) {
2734 // we have a temptable to join on
2735 $tbl = self
::$_relationshipTempTable;
2736 return " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2739 $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2740 $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)";
2744 elseif (self
::$_relType == 'b') {
2745 $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2746 return "$from $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2749 $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2750 return "$from $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2754 $from = " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2755 return "$from INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2758 return " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2760 case 'civicrm_grant':
2761 return CRM_Grant_BAO_Query
::from($name, $mode, $side);
2763 case 'civicrm_website':
2764 return " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2766 case 'civicrm_campaign':
2767 //Move to default case if not in either mode.
2768 if ($mode & CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
2769 return CRM_Contribute_BAO_Query
::from($name, $mode, $side);
2771 elseif ($mode & CRM_Contact_BAO_Query
::MODE_MAILING
) {
2772 return CRM_Mailing_BAO_Query
::from($name, $mode, $side);
2774 elseif ($mode & CRM_Contact_BAO_Query
::MODE_CAMPAIGN
) {
2775 return CRM_Campaign_BAO_Query
::from($name, $mode, $side);
2779 $locationTypeName = '';
2780 if (strpos($name, '-address') != 0) {
2781 $locationTypeName = 'address';
2783 elseif (strpos($name, '-phone') != 0) {
2784 $locationTypeName = 'phone';
2786 elseif (strpos($name, '-email') != 0) {
2787 $locationTypeName = 'email';
2789 elseif (strpos($name, '-im') != 0) {
2790 $locationTypeName = 'im';
2792 elseif (strpos($name, '-openid') != 0) {
2793 $locationTypeName = 'openid';
2796 if ($locationTypeName) {
2797 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2798 $parts = explode('-', $name);
2799 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
2800 foreach ($locationTypes as $locationTypeID => $locationType) {
2801 if ($parts[0] == str_replace(' ', '_', $locationType)) {
2802 $locationID = $locationTypeID;
2805 $from = " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2808 $from = CRM_Core_Component
::from($name, $mode, $side);
2810 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2817 * WHERE / QILL clause for deleted_contacts
2819 * @param array $values
2821 public function deletedContacts($values) {
2822 list($_, $_, $value, $grouping, $_) = $values;
2824 // *prepend* to the relevant grouping as this is quite an important factor
2825 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2830 * Where / qill clause for contact_type
2834 * @throws \CRM_Core_Exception
2836 public function contactType(&$values) {
2837 list($name, $op, $value, $grouping, $wildcard) = $values;
2842 // account for search builder mapping multiple values
2843 if (!is_array($value)) {
2844 $values = self
::parseSearchBuilderString($value, 'String');
2845 if (is_array($values)) {
2846 $value = array_flip($values);
2850 if (is_array($value)) {
2851 foreach ($value as $k => $v) {
2856 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2857 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2860 if (!empty($subType)) {
2861 $subTypes[$subType] = 1;
2863 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2868 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2869 $contactType = $contactTypeANDSubType[0];
2870 $subType = $contactTypeANDSubType[1] ??
NULL;
2871 if (!empty($subType)) {
2872 $subTypes[$subType] = 1;
2874 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2878 if (!empty($clause)) {
2880 if ($op == 'IN' ||
$op == 'NOT IN') {
2881 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2884 $type = array_pop($clause);
2885 $this->_where
[$grouping][] = self
::buildClause("contact_a.contact_type", $op, $contactType);
2888 $this->_qill
[$grouping][] = ts('Contact Type') . " $op " . implode(' ' . ts('or') . ' ', $quill);
2890 if (!empty($subTypes)) {
2891 $this->includeContactSubTypes($subTypes, $grouping);
2897 * Where / qill clause for contact_sub_type.
2899 * @param array $values
2901 public function contactSubType(&$values) {
2902 list($name, $op, $value, $grouping, $wildcard) = $values;
2903 $this->includeContactSubTypes($value, $grouping, $op);
2911 * @throws \CRM_Core_Exception
2913 public function includeContactSubTypes($value, $grouping, $op = 'LIKE') {
2915 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2917 $value = $value[$op];
2921 $alias = "contact_a.contact_sub_type";
2922 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
2924 $op = str_replace('IN', 'LIKE', $op);
2925 $op = str_replace('=', 'LIKE', $op);
2926 $op = str_replace('!', 'NOT ', $op);
2928 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2929 $this->_where
[$grouping][] = self
::buildClause($alias, $op, $value, 'String');
2931 elseif (is_array($value)) {
2932 foreach ($value as $k => $v) {
2933 $clause[$k] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($v, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2937 $clause[$value] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2940 if (!empty($clause)) {
2941 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2943 $this->_qill
[$grouping][] = ts('Contact Subtype %1 ', [1 => $qillOperators[$op]]) . implode(' ' . ts('or') . ' ', array_keys($clause));
2947 * Where / qill clause for groups.
2951 * @throws \CRM_Core_Exception
2952 * @throws \Exception
2954 public function group($values) {
2955 list($name, $op, $value, $grouping, $wildcard) = $values;
2957 // If the $value is in OK (operator as key) array format we need to extract the key as operator and value first
2958 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2960 $value = $value[$op];
2962 // Translate EMPTY to NULL as EMPTY is cannot be used in it's intended meaning here
2963 // so has to be 'squashed into' NULL. (ie. group membership cannot be '').
2964 // even one group might equate to multiple when looking at children so IN is simpler.
2965 // @todo - also look at != casting but there are rows below to review.
2967 'IS EMPTY' => 'IS NULL',
2968 'IS NOT EMPTY' => 'IS NOT NULL',
2971 if (isset($opReplacements[$op])) {
2972 $op = $opReplacements[$op];
2975 if (strpos($op, 'NULL')) {
2979 if (is_array($value) && count($value) > 1) {
2980 if (strpos($op, 'IN') === FALSE && strpos($op, 'NULL') === FALSE) {
2981 throw new CRM_Core_Exception(ts("%1 is not a valid operator", [1 => $op]));
2983 $this->_useDistinct
= TRUE;
2986 if (isset($value)) {
2987 $value = CRM_Utils_Array
::value($op, $value, $value);
2990 if ($name === 'group_type') {
2991 $value = array_keys($this->getGroupsFromTypeCriteria($value));
2994 $regularGroupIDs = $smartGroupIDs = [];
2995 foreach ((array) $value as $id) {
2996 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
2997 $smartGroupIDs[] = (int) $id;
3000 $regularGroupIDs[] = (int) trim($id);
3003 $hasNonSmartGroups = count($regularGroupIDs);
3005 $isNotOp = ($op === 'NOT IN' ||
$op === '!=');
3007 $statusJoinClause = $this->getGroupStatusClause($grouping);
3008 // If we are searching for 'Removed' contacts then despite it being a smart group we only care about the group_contact table.
3009 $isGroupStatusSearch = (!empty($this->getSelectedGroupStatuses($grouping)) && $this->getSelectedGroupStatuses($grouping) !== ["'Added'"]);
3011 if ($hasNonSmartGroups ||
empty($value) ||
$isGroupStatusSearch) {
3012 // include child groups IDs if any
3013 $childGroupIds = (array) CRM_Contact_BAO_Group
::getChildGroupIds($regularGroupIDs);
3014 foreach ($childGroupIds as $key => $id) {
3015 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
3016 $smartGroupIDs[] = $id;
3017 unset($childGroupIds[$key]);
3020 if (count($childGroupIds)) {
3021 $regularGroupIDs = array_merge($regularGroupIDs, $childGroupIds);
3024 if (empty($regularGroupIDs)) {
3025 if ($isGroupStatusSearch) {
3026 $regularGroupIDs = $smartGroupIDs;
3028 // If it is still empty we want a filter that blocks all results.
3029 if (empty($regularGroupIDs)) {
3030 $regularGroupIDs = [0];
3034 $gcTable = '`civicrm_group_contact-' . uniqid() . "`";
3035 $joinClause = ["contact_a.id = {$gcTable}.contact_id"];
3037 // @todo consider just casting != to NOT IN & handling both together.
3040 if (!empty($regularGroupIDs)) {
3041 $groupIds = CRM_Utils_Type
::validate(implode(',', (array) $regularGroupIDs), 'CommaSeparatedIntegers');
3043 $clause = "{$gcTable}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact cgc WHERE cgc.group_id = $groupIds )";
3046 $clause = self
::buildClause("{$gcTable}.group_id", $op, $regularGroupIDs);
3048 $groupClause[] = "( {$clause} )";
3050 if ($statusJoinClause) {
3051 $joinClause[] = "{$gcTable}.$statusJoinClause";
3053 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
3056 //CRM-19589: contact(s) removed from a Smart Group, resides in civicrm_group_contact table
3057 // If we are only searching for Removed or Pending contacts we don't need to resolve the smart group
3058 // as that info is in the group_contact table.
3059 if ((count($smartGroupIDs) ||
empty($value)) && !$isGroupStatusSearch) {
3060 $this->_groupUniqueKey
= uniqid();
3061 $this->_groupKeys
[] = $this->_groupUniqueKey
;
3062 $gccTableAlias = "civicrm_group_contact_cache_{$this->_groupUniqueKey}";
3063 $groupContactCacheClause = $this->addGroupContactCache($smartGroupIDs, $gccTableAlias, "contact_a", $op);
3064 if (!empty($groupContactCacheClause)) {
3066 $groupIds = CRM_Utils_Type
::validate(implode(',', (array) $smartGroupIDs), 'CommaSeparatedIntegers');
3067 $gcTable = "civicrm_group_contact_{$this->_groupUniqueKey}";
3068 $joinClause = ["contact_a.id = {$gcTable}.contact_id"];
3069 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
3070 if (strpos($op, 'IN') !== FALSE) {
3071 $groupClause[] = "{$gcTable}.group_id $op ( $groupIds ) AND {$gccTableAlias}.group_id IS NULL";
3074 $groupClause[] = "{$gcTable}.group_id $op $groupIds AND {$gccTableAlias}.group_id IS NULL";
3077 $groupClause[] = " ( {$groupContactCacheClause} ) ";
3081 $and = ($op == 'IS NULL') ?
' AND ' : ' OR ';
3082 if (!empty($groupClause)) {
3083 $this->_where
[$grouping][] = ' ( ' . implode($and, $groupClause) . ' ) ';
3086 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Group', 'id', $value, $op);
3087 $this->_qill
[$grouping][] = ts("Group(s) %1 %2", [1 => $qillop, 2 => $qillVal]);
3088 if (strpos($op, 'NULL') === FALSE) {
3089 $this->_qill
[$grouping][] = ts("Group Status %1", [1 => implode(' ' . ts('or') . ' ', $this->getSelectedGroupStatuses($grouping))]);
3096 public function getGroupCacheTableKeys() {
3097 return $this->_groupKeys
;
3101 * Function translates selection of group type into a list of groups.
3106 public function getGroupsFromTypeCriteria($value) {
3108 foreach ((array) $value as $groupTypeValue) {
3109 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
3110 $groupIds = ($groupIds +
$groupList);
3116 * Prime smart group cache for smart groups in the search, and join
3117 * civicrm_group_contact_cache table into the query.
3119 * @param array $groups IDs of groups specified in search criteria.
3120 * @param string $tableAlias Alias to use for civicrm_group_contact_cache table.
3121 * @param string $joinTable Table on which to join civicrm_group_contact_cache
3122 * @param string $op SQL comparison operator (NULL, IN, !=, IS NULL, etc.)
3123 * @param string $joinColumn Column in $joinTable on which to join civicrm_group_contact_cache.contact_id
3125 * @return string WHERE clause component for smart group criteria.
3126 * @throws \CRM_Core_Exception
3128 public function addGroupContactCache($groups, $tableAlias, $joinTable = "contact_a", $op, $joinColumn = 'id') {
3129 $isNullOp = (strpos($op, 'NULL') !== FALSE);
3130 $groupsIds = $groups;
3132 $operator = ['=' => 'IN', '!=' => 'NOT IN'];
3133 if (!empty($operator[$op]) && is_array($groups)) {
3134 $op = $operator[$op];
3136 if (!$isNullOp && !$groups) {
3139 elseif (strpos($op, 'IN') !== FALSE) {
3140 $groups = [$op => $groups];
3142 elseif (is_array($groups) && count($groups)) {
3143 $groups = ['IN' => $groups];
3146 // Find all the groups that are part of a saved search.
3147 $smartGroupClause = self
::buildClause("id", $op, $groups, 'Int');
3149 SELECT id, cache_date, saved_search_id, children
3151 WHERE $smartGroupClause
3152 AND ( saved_search_id != 0
3153 OR saved_search_id IS NOT NULL
3154 OR children IS NOT NULL )
3157 $group = CRM_Core_DAO
::executeQuery($sql);
3159 while ($group->fetch()) {
3160 $this->_useDistinct
= TRUE;
3161 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
3162 CRM_Contact_BAO_GroupContactCache
::load($group);
3165 if ($group->N
== 0 && $op != 'NOT IN') {
3169 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache {$tableAlias} ON {$joinTable}.{$joinColumn} = {$tableAlias}.contact_id ";
3171 if ($op == 'NOT IN') {
3172 return "{$tableAlias}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact_cache cgcc WHERE cgcc.group_id IN ( " . implode(',', (array) $groupsIds) . " ) )";
3174 return self
::buildClause("{$tableAlias}.group_id", $op, $groups, 'Int');
3178 * Where / qill clause for cms users
3182 public function ufUser(&$values) {
3183 list($name, $op, $value, $grouping, $wildcard) = $values;
3186 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3188 $this->_qill
[$grouping][] = ts('CMS User');
3190 elseif ($value == 0) {
3191 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3193 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
3194 $this->_qill
[$grouping][] = ts('Not a CMS User');
3199 * All tag search specific.
3201 * @param array $values
3203 * @throws \CRM_Core_Exception
3205 public function tagSearch(&$values) {
3206 list($name, $op, $value, $grouping, $wildcard) = $values;
3209 $value = "%{$value}%";
3210 $escapedValue = CRM_Utils_Type
::escape("%{$value}%", 'String');
3212 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3213 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3215 $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
3216 $tTable = "`civicrm_tag-" . uniqid() . "`";
3218 if ($useAllTagTypes[2]) {
3219 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3220 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
3221 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
3223 // search tag in cases
3224 $etCaseTable = "`civicrm_entity_case_tag-" . uniqid() . "`";
3225 $tCaseTable = "`civicrm_case_tag-" . uniqid() . "`";
3226 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3227 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3228 LEFT JOIN civicrm_case
3229 ON (civicrm_case_contact.case_id = civicrm_case.id
3230 AND civicrm_case.is_deleted = 0 )
3231 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
3232 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
3233 // search tag in activities
3234 $etActTable = "`civicrm_entity_act_tag-" . uniqid() . "`";
3235 $tActTable = "`civicrm_act_tag-" . uniqid() . "`";
3236 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
3237 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3239 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3240 = " LEFT JOIN civicrm_activity_contact
3241 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3242 LEFT JOIN civicrm_activity
3243 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3244 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3245 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
3246 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
3248 $this->_where
[$grouping][] = "({$tTable}.name $op '" . $escapedValue . "' OR {$tCaseTable}.name $op '" . $escapedValue . "' OR {$tActTable}.name $op '" . $escapedValue . "')";
3249 $this->_qill
[$grouping][] = ts('Tag %1 %2', [1 => $tagTypesText[2], 2 => $op]) . ' ' . $value;
3252 $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
3253 $tTable = "`civicrm_tag-" . uniqid() . "`";
3254 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
3255 {$etTable}.entity_table = 'civicrm_contact' )
3256 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
3258 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
3259 $this->_qill
[$grouping][] = ts('Tagged %1', [1 => $op]) . ' ' . $value;
3264 * Where / qill clause for tag.
3266 * @param array $values
3268 * @throws \CRM_Core_Exception
3270 public function tag(&$values) {
3271 list($name, $op, $value, $grouping, $wildcard) = $values;
3273 // API/Search Builder format array(operator => array(values))
3274 if (is_array($value)) {
3275 if (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
3277 $value = $value[$op];
3279 if (count($value) > 1) {
3280 $this->_useDistinct
= TRUE;
3284 if (strpos($op, 'NULL') ||
strpos($op, 'EMPTY')) {
3288 $tagTree = CRM_Core_BAO_Tag
::getChildTags();
3289 foreach ((array) $value as $tagID) {
3290 if (!empty($tagTree[$tagID])) {
3291 $value = array_unique(array_merge($value, $tagTree[$tagID]));
3295 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_EntityTag', "tag_id", $value, $op, ['onlyActive' => FALSE]);
3297 // implode array, then remove all spaces
3298 $value = str_replace(' ', '', implode(',', (array) $value));
3299 if (!empty($value)) {
3300 $value = CRM_Utils_Type
::validate($value, 'CommaSeparatedIntegers');
3303 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3304 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3306 $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
3308 if (!empty($useAllTagTypes[2])) {
3309 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3310 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3312 // search tag in cases
3313 $etCaseTable = "`civicrm_entity_case_tag-" . uniqid() . "`";
3314 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
3315 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3317 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3318 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3319 LEFT JOIN civicrm_case
3320 ON (civicrm_case_contact.case_id = civicrm_case.id
3321 AND civicrm_case.is_deleted = 0 )
3322 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3323 // search tag in activities
3324 $etActTable = "`civicrm_entity_act_tag-" . uniqid() . "`";
3325 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3326 = " LEFT JOIN civicrm_activity_contact
3327 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3328 LEFT JOIN civicrm_activity
3329 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3330 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3331 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3334 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
3335 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3338 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (" . $value . ") OR {$etCaseTable}.tag_id $op (" . $value . ") OR {$etActTable}.tag_id $op (" . $value . "))";
3342 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3343 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3346 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
3347 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3348 $op = str_replace('EMPTY', 'NULL', $op);
3349 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
3351 // CRM-16941: for tag tried with != operator we don't show contact who don't have given $value AND also in other tag
3352 elseif ($op == '!=') {
3353 $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') . ")";
3355 elseif ($op == '=' ||
strstr($op, 'IN')) {
3356 $op = ($op == '=') ?
'IN' : $op;
3357 $this->_where
[$grouping][] = "{$etTable}.tag_id $op ( $value )";
3360 $this->_qill
[$grouping][] = ts('Tagged %1 %2', [1 => $qillop, 2 => $qillVal]);
3364 * Where/qill clause for notes
3366 * @param array $values
3368 * @throws \CRM_Core_Exception
3370 public function notes(&$values) {
3371 list($name, $op, $value, $grouping, $wildcard) = $values;
3373 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3374 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
3375 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
3377 $this->_useDistinct
= TRUE;
3379 $this->_tables
['civicrm_note'] = $this->_whereTables
['civicrm_note']
3380 = " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3383 $value = CRM_Core_DAO
::escapeString($n);
3385 if (strpos($value, '%') === FALSE) {
3386 $value = "%$value%";
3390 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
3396 if ($noteOption %
2 == 0) {
3397 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
3398 $label = ts('Note: Body Only');
3400 if ($noteOption %
3 == 0) {
3401 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
3402 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
3404 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3405 list($qillOp, $qillVal) = self
::buildQillForFieldValue(NULL, $name, $n, $op);
3406 $this->_qill
[$grouping][] = ts("%1 %2 %3", [1 => $label, 2 => $qillOp, 3 => $qillVal]);
3410 * @param string $name
3416 public function nameNullOrEmptyOp($name, $op, $grouping) {
3420 $this->_where
[$grouping][] = "contact_a.$name $op";
3421 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3425 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3426 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3429 case 'IS NOT EMPTY':
3430 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3431 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3440 * Where / qill clause for sort_name
3442 * @param array $values
3444 public function sortName(&$values) {
3445 list($fieldName, $op, $value, $grouping, $wildcard) = $values;
3447 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3448 if ($this->nameNullOrEmptyOp($fieldName, $op, $grouping)) {
3452 $input = $value = is_array($value) ?
trim($value['LIKE']) : trim($value);
3454 if (!strlen($value)) {
3458 $config = CRM_Core_Config
::singleton();
3462 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3465 $firstChar = substr($value, 0, 1);
3466 $lastChar = substr($value, -1, 1);
3467 $quotes = ["'", '"'];
3468 // If string is quoted, strip quotes and otherwise don't alter it
3469 if ((strlen($value) > 2) && in_array($firstChar, $quotes) && in_array($lastChar, $quotes)) {
3470 $value = trim($value, implode('', $quotes));
3472 // Replace spaces with wildcards for a LIKE operation
3473 // UNLESS string contains a comma (this exception is a tiny bit questionable)
3474 // Also need to check if there is space in between sort name.
3475 elseif ($op == 'LIKE' && strpos($value, ',') === FALSE && strpos($value, ' ') === TRUE) {
3476 $value = str_replace(' ', '%', $value);
3478 $value = CRM_Core_DAO
::escapeString(trim($value));
3479 if (strlen($value)) {
3481 $value = "'" . self
::getWildCardedValue($wildcard, $op, $value) . "'";
3482 if ($fieldName == 'sort_name') {
3483 $wc = "contact_a.sort_name";
3486 $wc = "contact_a.display_name";
3488 $fieldsub[] = " ( $wc $op $value )";
3489 if ($config->includeNickNameInName
) {
3490 $wc = "contact_a.nick_name";
3491 $fieldsub[] = " ( $wc $op $value )";
3493 if ($config->includeEmailInName
) {
3494 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3496 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3499 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3501 $this->_where
[$grouping][] = $sub;
3502 if ($config->includeEmailInName
) {
3503 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3504 $this->_qill
[$grouping][] = ts('Name or Email') . " $op - '$input'";
3507 $this->_qill
[$grouping][] = ts('Name') . " $op - '$input'";
3512 * Where/qill clause for greeting fields.
3514 * @param array $values
3516 * @throws \CRM_Core_Exception
3518 public function greetings(&$values) {
3519 list($name, $op, $value, $grouping, $wildcard) = $values;
3520 $name .= '_display';
3522 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
3523 $this->_qill
[$grouping][] = ts('Greeting %1 %2', [1 => $qillop, 2 => $qillVal]);
3524 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value, 'String');
3528 * Where / qill clause for email
3530 * @param array $values
3531 * @param string $isForcePrimaryOnly
3533 * @throws \CRM_Core_Exception
3535 protected function email(&$values, $isForcePrimaryOnly) {
3536 list($name, $op, $value, $grouping, $wildcard) = $values;
3537 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3539 // CRM-18147: for Contact's GET API, email fieldname got appended with its entity as in {$apiEntiy}_{$name}
3540 // so following code is use build whereClause for contact's primart email id
3541 if (!empty($isForcePrimaryOnly)) {
3542 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.is_primary', '=', 1, 'Integer');
3544 // @todo - this should come from the $this->_fields array
3545 $dbName = $name === 'email_id' ?
'id' : $name;
3547 if (is_array($value) ||
$name === 'email_id') {
3548 $this->_qill
[$grouping][] = $this->getQillForField($name, $value, $op, [], ts('Email'));
3549 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.' . $dbName, $op, $value, 'String');
3553 // Is this ever hit now? Ideally ensure always an array & handle above.
3556 if (substr($n, 0, 1) == '"' &&
3557 substr($n, -1, 1) == '"'
3559 $n = substr($n, 1, -1);
3560 $value = CRM_Core_DAO
::escapeString($n);
3564 $value = self
::getWildCardedValue($wildcard, $op, $n);
3566 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3567 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3570 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3571 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3576 * Where / qill clause for phone number
3578 * @param array $values
3580 * @throws \CRM_Core_Exception
3582 public function phone_numeric(&$values) {
3583 list($name, $op, $value, $grouping, $wildcard) = $values;
3584 // Strip non-numeric characters; allow wildcards
3585 $number = preg_replace('/[^\d%]/', '', $value);
3587 if (strpos($number, '%') === FALSE) {
3588 $number = "%$number%";
3591 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3592 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3593 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3598 * Where / qill clause for phone type/location
3600 * @param array $values
3602 * @throws \CRM_Core_Exception
3604 public function phone_option_group($values) {
3605 list($name, $op, $value, $grouping, $wildcard) = $values;
3606 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3607 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3608 $optionName = $options[$value];
3609 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3610 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3611 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3615 * Where / qill clause for street_address.
3617 * @param array $values
3619 * @throws \CRM_Core_Exception
3621 public function street_address(&$values) {
3622 list($name, $op, $value, $grouping) = $values;
3631 if (strpos($value, '%') === FALSE) {
3632 // only add wild card if not there
3633 $value = "%{$value}%";
3636 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, $value, 'String');
3637 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3640 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3641 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3644 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3648 * Where / qill clause for street_unit.
3650 * @param array $values
3652 * @throws \CRM_Core_Exception
3654 public function street_number(&$values) {
3655 list($name, $op, $value, $grouping, $wildcard) = $values;
3663 if (strtolower($n) == 'odd') {
3664 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3665 $this->_qill
[$grouping][] = ts('Street Number is odd');
3667 elseif (strtolower($n) == 'even') {
3668 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3669 $this->_qill
[$grouping][] = ts('Street Number is even');
3673 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_number', $op, $value, 'String');
3674 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3677 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3681 * Where / qill clause for sorting by character.
3683 * @param array $values
3685 public function sortByCharacter(&$values) {
3686 list($name, $op, $value, $grouping, $wildcard) = $values;
3688 $name = trim($value);
3689 $cond = " contact_a.sort_name LIKE '" . CRM_Core_DAO
::escapeWildCardString($name) . "%'";
3690 $this->_where
[$grouping][] = $cond;
3691 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', [1 => $name]);
3695 * Where / qill clause for including contact ids.
3697 public function includeContactIDs() {
3698 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3703 foreach ($this->_params
as $id => $values) {
3704 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3705 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3708 CRM_Utils_Type
::validateAll($contactIds, 'Positive');
3709 if (!empty($contactIds)) {
3710 $this->_where
[0][] = ' ( contact_a.id IN (' . implode(',', $contactIds) . " ) ) ";
3715 * Where / qill clause for postal code.
3717 * @param array $values
3719 * @throws \CRM_Core_Exception
3721 public function postalCode(&$values) {
3722 // skip if the fields dont have anything to do with postal_code
3723 if (empty($this->_fields
['postal_code'])) {
3727 list($name, $op, $value, $grouping, $wildcard) = $values;
3729 // Handle numeric postal code range searches properly by casting the column as numeric
3730 if (is_numeric($value)) {
3731 $field = "IF (civicrm_address.postal_code REGEXP '^[0-9]{1,10}$', CAST(civicrm_address.postal_code AS UNSIGNED), 0)";
3732 $val = CRM_Utils_Type
::escape($value, 'Integer');
3735 $field = 'civicrm_address.postal_code';
3736 // Per CRM-17060 we might be looking at an 'IN' syntax so don't case arrays to string.
3737 if (!is_array($value)) {
3738 $val = CRM_Utils_Type
::escape($value, 'String');
3741 // Do we need to escape values here? I would expect buildClause does.
3746 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3748 if ($name == 'postal_code') {
3749 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3750 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3752 elseif ($name == 'postal_code_low') {
3753 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3754 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', [1 => $value]);
3756 elseif ($name == 'postal_code_high') {
3757 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3758 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', [1 => $value]);
3763 * Where / qill clause for location type.
3765 * @param array $values
3766 * @param null $status
3770 public function locationType(&$values, $status = NULL) {
3771 list($name, $op, $value, $grouping, $wildcard) = $values;
3773 if (is_array($value)) {
3774 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')';
3775 $this->_tables
['civicrm_address'] = 1;
3776 $this->_whereTables
['civicrm_address'] = 1;
3778 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3780 foreach ($value as $id) {
3781 $names[] = $locationType[$id];
3784 $this->_primaryLocation
= FALSE;
3787 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3790 return implode(' ' . ts('or') . ' ', $names);
3797 * @param bool $fromStateProvince
3799 * @return array|NULL
3800 * @throws \CRM_Core_Exception
3802 public function country(&$values, $fromStateProvince = TRUE) {
3803 list($name, $op, $value, $grouping, $wildcard) = $values;
3805 if (!$fromStateProvince) {
3806 $stateValues = $this->getWhereValues('state_province', $grouping);
3807 if (!empty($stateValues)) {
3808 // return back to caller if there are state province values
3809 // since that handles this case
3814 $countryClause = $countryQill = NULL;
3815 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY']) ||
($values && !empty($value))) {
3816 $this->_tables
['civicrm_address'] = 1;
3817 $this->_whereTables
['civicrm_address'] = 1;
3819 $countryClause = self
::buildClause('civicrm_address.country_id', $op, $value, 'Positive');
3820 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, 'country_id', $value, $op);
3821 $countryQill = ts("%1 %2 %3", [1 => 'Country', 2 => $qillop, 3 => $qillVal]);
3823 if (!$fromStateProvince) {
3824 $this->_where
[$grouping][] = $countryClause;
3825 $this->_qill
[$grouping][] = $countryQill;
3829 if ($fromStateProvince) {
3830 if (!empty($countryClause)) {
3833 " ...AND... " . $countryQill,
3837 return [NULL, NULL];
3843 * Where / qill clause for county (if present).
3845 * @param array $values
3846 * @param null $status
3850 public function county(&$values, $status = NULL) {
3851 list($name, $op, $value, $grouping, $wildcard) = $values;
3853 if (!is_array($value)) {
3854 // force the county to be an array
3858 // check if the values are ids OR names of the counties
3859 $inputFormat = 'id';
3860 foreach ($value as $v) {
3861 if (!is_numeric($v)) {
3862 $inputFormat = 'name';
3870 elseif ($op == '!=') {
3874 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3875 $op = str_replace('EMPTY', 'NULL', $op);
3878 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
3879 $clause = "civicrm_address.county_id $op";
3881 elseif ($inputFormat == 'id') {
3882 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3884 $county = CRM_Core_PseudoConstant
::county();
3885 foreach ($value as $id) {
3886 $names[] = $county[$id] ??
NULL;
3891 $county = CRM_Core_PseudoConstant
::county();
3892 foreach ($value as $name) {
3893 $name = trim($name);
3894 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3896 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3899 $this->_tables
['civicrm_address'] = 1;
3900 $this->_whereTables
['civicrm_address'] = 1;
3902 $this->_where
[$grouping][] = $clause;
3904 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3907 return implode(' ' . ts('or') . ' ', $names);
3912 * Where / qill clause for state/province AND country (if present).
3914 * @param array $values
3915 * @param null $status
3918 * @throws \CRM_Core_Exception
3920 public function stateProvince(&$values, $status = NULL) {
3921 list($name, $op, $value, $grouping, $wildcard) = $values;
3923 $stateClause = self
::buildClause('civicrm_address.state_province_id', $op, $value, 'Positive');
3924 $this->_tables
['civicrm_address'] = 1;
3925 $this->_whereTables
['civicrm_address'] = 1;
3927 $countryValues = $this->getWhereValues('country', $grouping);
3928 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3929 if ($countryClause) {
3930 $clause = "( $stateClause AND $countryClause )";
3933 $clause = $stateClause;
3936 $this->_where
[$grouping][] = $clause;
3937 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
3939 $this->_qill
[$grouping][] = ts("State/Province %1 %2 %3", [1 => $qillop, 2 => $qillVal, 3 => $countryQill]);
3942 return implode(' ' . ts('or') . ' ', $qillVal) . $countryQill;
3947 * Where / qill clause for change log.
3949 * @param array $values
3951 public function changeLog(&$values) {
3952 list($name, $op, $value, $grouping, $wildcard) = $values;
3954 $targetName = $this->getWhereValues('changed_by', $grouping);
3959 $name = trim($targetName[2]);
3960 $name = CRM_Core_DAO
::escapeString($name);
3961 $name = $targetName[4] ?
"%$name%" : $name;
3962 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3963 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3964 $fieldTitle = ts('Altered By');
3966 list($qillop, $qillVal) = self
::buildQillForFieldValue(NULL, 'changed_by', $name, 'LIKE');
3967 $this->_qill
[$grouping][] = ts("%1 %2 '%3'", [
3977 * @throws \CRM_Core_Exception
3979 public function modifiedDates($values) {
3980 $this->_useDistinct
= TRUE;
3982 // CRM-11281, default to added date if not set
3983 $fieldTitle = ts('Added Date');
3984 $fieldName = 'created_date';
3985 foreach (array_keys($this->_params
) as $id) {
3986 if ($this->_params
[$id][0] == 'log_date') {
3987 if ($this->_params
[$id][2] == 2) {
3988 $fieldTitle = ts('Modified Date');
3989 $fieldName = 'modified_date';
3994 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3996 self
::$_openedPanes[ts('Change Log')] = TRUE;
4002 * @throws \CRM_Core_Exception
4004 public function demographics(&$values) {
4005 list($name, $op, $value, $grouping, $wildcard) = $values;
4007 if (($name == 'age_low') ||
($name == 'age_high')) {
4008 $this->ageRangeQueryBuilder($values,
4009 'contact_a', 'age', 'birth_date', ts('Age')
4012 elseif (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
4014 $this->dateQueryBuilder($values,
4015 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
4018 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
4020 $this->dateQueryBuilder($values,
4021 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
4025 self
::$_openedPanes[ts('Demographics')] = TRUE;
4031 public function privacy(&$values) {
4032 list($name, $op, $value, $grouping) = $values;
4033 if (is_array($value)) {
4034 if (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
4036 $value = $value[$op];
4039 $field = $this->_fields
[$name] ??
NULL;
4040 CRM_Utils_Type
::validate($value, 'Integer');
4041 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
4042 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
4043 $title = $field ?
$field['title'] : $name;
4044 $this->_qill
[$grouping][] = "$title $op $value";
4050 public function privacyOptions($values) {
4051 list($name, $op, $value, $grouping, $wildcard) = $values;
4053 if (empty($value) ||
!is_array($value)) {
4057 // get the operator and toggle values
4058 $opValues = $this->getWhereValues('privacy_operator', $grouping);
4061 strtolower($opValues[2] == 'AND')
4063 // @todo this line is logially unreachable
4067 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
4069 if ($toggleValues &&
4070 $toggleValues[2] == 2
4077 foreach ($value as $dontCare => $pOption) {
4078 $clauses[] = " ( contact_a.{$pOption} = 1 ) ";
4079 $field = $this->_fields
[$pOption] ??
NULL;
4080 $title = $field ?
$field['title'] : $pOption;
4081 $qill[] = " $title = 1 ";
4084 $this->_where
[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )';
4085 $this->_qill
[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )';
4091 * @throws \CRM_Core_Exception
4093 public function preferredCommunication(&$values) {
4094 list($name, $op, $value, $grouping, $wildcard) = $values;
4096 if (!is_array($value)) {
4097 $value = str_replace(['(', ')'], '', explode(",", $value));
4099 elseif (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
4101 $value = $value[$op];
4103 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Contact', $name, $value, $op);
4105 if (self
::caseImportant($op)) {
4106 $value = implode("[[:cntrl:]]|[[:cntrl:]]", (array) $value);
4107 $op = (strstr($op, '!') ||
strstr($op, 'NOT')) ?
'NOT RLIKE' : 'RLIKE';
4108 $value = "[[:cntrl:]]" . $value . "[[:cntrl:]]";
4111 $this->_where
[$grouping][] = self
::buildClause("contact_a.preferred_communication_method", $op, $value);
4112 $this->_qill
[$grouping][] = ts('Preferred Communication Method %1 %2', [1 => $qillop, 2 => $qillVal]);
4116 * Where / qill clause for relationship.
4118 * @param array $values
4120 public function relationship(&$values) {
4121 list($name, $op, $value, $grouping, $wildcard) = $values;
4122 if ($this->_relationshipValuesAdded
) {
4125 // also get values array for relation_target_name
4126 // for relationship search we always do wildcard
4127 $relationType = $this->getWhereValues('relation_type_id', $grouping);
4128 $description = $this->getWhereValues('relation_description', $grouping);
4129 $targetName = $this->getWhereValues('relation_target_name', $grouping);
4130 $relStatus = $this->getWhereValues('relation_status', $grouping);
4131 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
4133 $nameClause = $name = NULL;
4135 $name = trim($targetName[2]);
4136 if (substr($name, 0, 1) == '"' &&
4137 substr($name, -1, 1) == '"'
4139 $name = substr($name, 1, -1);
4140 $name = CRM_Core_DAO
::escapeString($name);
4141 $nameClause = "= '$name'";
4144 $name = CRM_Core_DAO
::escapeString($name);
4145 $nameClause = "LIKE '%{$name}%'";
4149 $relTypes = $relTypesIds = [];
4150 if (!empty($relationType)) {
4151 $relationType[2] = (array) $relationType[2];
4152 foreach ($relationType[2] as $relType) {
4153 $rel = explode('_', $relType);
4154 self
::$_relType = $rel[1];
4155 $params = ['id' => $rel[0]];
4157 $rTypeValue = CRM_Contact_BAO_RelationshipType
::retrieve($params, $typeValues);
4158 if (!empty($rTypeValue)) {
4159 if ($rTypeValue->name_a_b
== $rTypeValue->name_b_a
) {
4160 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4161 self
::$_relType = 'reciprocal';
4163 $relTypesIds[] = $rel[0];
4164 $relTypes[] = $relType;
4169 // if we are creating a temp table we build our own where for the relationship table
4170 $relationshipTempTable = NULL;
4171 if (self
::$_relType == 'reciprocal') {
4173 self
::$_relationshipTempTable = $relationshipTempTable = CRM_Utils_SQL_TempTable
::build()
4174 ->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`)")
4177 $where[$grouping][] = " sort_name $nameClause ";
4179 $groupJoinTable = "civicrm_relationship";
4180 $groupJoinColumn = "contact_id_alt";
4183 $where = &$this->_where
;
4185 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4187 $groupJoinTable = "contact_b";
4188 $groupJoinColumn = "id";
4190 $allRelationshipType = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, NULL, TRUE, 'label', FALSE);
4191 if ($nameClause ||
!$targetGroup) {
4192 if (!empty($relationType)) {
4194 foreach ($relTypes as $rel) {
4195 if (!empty($relQill)) {
4198 $relQill .= $allRelationshipType[$rel];
4200 $this->_qill
[$grouping][] = 'Relationship Type(s) ' . $relQill . " $name";
4203 $this->_qill
[$grouping][] = $name;
4207 //check to see if the target contact is in specified group
4209 //add contacts from static groups
4210 $this->_tables
['civicrm_relationship_group_contact'] = $this->_whereTables
['civicrm_relationship_group_contact']
4211 = " 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'";
4212 $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" .
4213 implode(",", $targetGroup[2]) . ") ) ";
4215 //add contacts from saved searches
4216 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", $groupJoinTable, $op, $groupJoinColumn);
4218 //set the group where clause
4220 $groupWhere[] = "( " . $ssWhere . " )";
4222 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4224 //Get the names of the target groups for the qill
4225 $groupNames = CRM_Core_PseudoConstant
::group();
4227 foreach ($targetGroup[2] as $groupId) {
4228 if (array_key_exists($groupId, $groupNames)) {
4229 $qillNames[] = $groupNames[$groupId];
4232 if (!empty($relationType)) {
4234 foreach ($relTypes as $rel) {
4235 if (!empty($relQill)) {
4238 $relQill .= CRM_Utils_Array
::value($rel, $allRelationshipType);
4240 $this->_qill
[$grouping][] = 'Relationship Type(s) ' . $relQill . " ( " . implode(", ", $qillNames) . " )";
4243 $this->_qill
[$grouping][] = implode(", ", $qillNames);
4248 if (!empty($description[2]) && trim($description[2])) {
4249 $this->_qill
[$grouping][] = ts('Relationship description - ' . $description[2]);
4250 $description = CRM_Core_DAO
::escapeString(trim($description[2]));
4251 $where[$grouping][] = "civicrm_relationship.description LIKE '%{$description}%'";
4254 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4255 $today = date('Ymd');
4256 //check for active, inactive and all relation status
4257 if (empty($relStatus[2])) {
4258 $where[$grouping][] = "(
4259 civicrm_relationship.is_active = 1 AND
4260 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4261 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4263 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
4265 elseif ($relStatus[2] == 1) {
4266 $where[$grouping][] = "(
4267 civicrm_relationship.is_active = 0 OR
4268 civicrm_relationship.end_date < {$today} OR
4269 civicrm_relationship.start_date > {$today}
4271 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
4275 if (in_array(['deleted_contacts', '=', '1', '0', '0'], $this->_params
)) {
4278 $where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})";
4280 $this->addRelationshipPermissionClauses($grouping, $where);
4281 $this->addRelationshipDateClauses($grouping, $where);
4282 $this->addRelationshipActivePeriodClauses($grouping, $where);
4283 if (!empty($relTypes)) {
4284 $where[$grouping][] = 'civicrm_relationship.relationship_type_id IN (' . implode(',', $relTypesIds) . ')';
4286 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
4287 $this->_useDistinct
= TRUE;
4288 $this->_relationshipValuesAdded
= TRUE;
4289 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4291 if ($relationshipTempTable) {
4293 if (!empty($where[$grouping])) {
4294 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4295 $whereClause = str_replace('contact_b', 'c', $whereClause);
4298 INSERT INTO {$relationshipTempTable} (contact_id, contact_id_alt, id)
4299 (SELECT contact_id_b as contact_id, contact_id_a as contact_id_alt, civicrm_relationship.id
4300 FROM civicrm_relationship
4301 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4304 (SELECT contact_id_a as contact_id, contact_id_b as contact_id_alt, civicrm_relationship.id
4305 FROM civicrm_relationship
4306 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4309 CRM_Core_DAO
::executeQuery($sql);
4314 * Add relationship permission criteria to where clause.
4316 * @param string $grouping
4317 * @param array $where Array to add "where" criteria to, in case you are generating a temp table.
4318 * Not the main query.
4320 public function addRelationshipPermissionClauses($grouping, &$where) {
4321 $relPermission = $this->getWhereValues('relation_permission', $grouping);
4322 if ($relPermission) {
4323 if (!is_array($relPermission[2])) {
4324 // this form value was scalar in previous versions of Civi
4325 $relPermission[2] = [$relPermission[2]];
4327 $where[$grouping][] = "(civicrm_relationship.is_permission_a_b IN (" . implode(",", $relPermission[2]) . "))";
4329 $allRelationshipPermissions = CRM_Contact_BAO_Relationship
::buildOptions('is_permission_a_b');
4331 $relPermNames = array_intersect_key($allRelationshipPermissions, array_flip($relPermission[2]));
4332 $this->_qill
[$grouping][] = ts('Permissioned Relationships') . ' - ' . implode(' OR ', $relPermNames);
4337 * Add start & end date criteria in
4338 * @param string $grouping
4339 * @param array $where
4340 * = array to add where clauses to, in case you are generating a temp table.
4341 * not the main query.
4343 public function addRelationshipDateClauses($grouping, &$where) {
4344 foreach (['start_date', 'end_date'] as $dateField) {
4345 $dateValueLow = $this->getWhereValues('relationship_' . $dateField . '_low', $grouping);
4346 $dateValueHigh = $this->getWhereValues('relationship_' . $dateField . '_high', $grouping);
4347 if (!empty($dateValueLow)) {
4348 $date = date('Ymd', strtotime($dateValueLow[2]));
4349 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4350 $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);
4352 if (!empty($dateValueHigh)) {
4353 $date = date('Ymd', strtotime($dateValueHigh[2]));
4354 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4355 $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);
4361 * Add start & end active period criteria in
4362 * @param string $grouping
4363 * @param array $where
4364 * = array to add where clauses to, in case you are generating a temp table.
4365 * not the main query.
4367 public function addRelationshipActivePeriodClauses($grouping, &$where) {
4369 $dateField = 'active_period_date';
4371 $dateValueLow = $this->getWhereValues('relation_active_period_date_low', $grouping);
4372 $dateValueHigh = $this->getWhereValues('relation_active_period_date_high', $grouping);
4373 $dateValueLowFormated = $dateValueHighFormated = NULL;
4374 if (!empty($dateValueLow) && !empty($dateValueHigh)) {
4375 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4376 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
4377 $this->_qill
[$grouping][] = (ts('Relationship was active between')) . " " . CRM_Utils_Date
::customFormat($dateValueLowFormated) . " and " . CRM_Utils_Date
::customFormat($dateValueHighFormated);
4379 elseif (!empty($dateValueLow)) {
4380 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4381 $this->_qill
[$grouping][] = (ts('Relationship was active after')) . " " . CRM_Utils_Date
::customFormat($dateValueLowFormated);
4383 elseif (!empty($dateValueHigh)) {
4384 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
4385 $this->_qill
[$grouping][] = (ts('Relationship was active before')) . " " . CRM_Utils_Date
::customFormat($dateValueHighFormated);
4388 if ($activePeriodClauses = self
::getRelationshipActivePeriodClauses($dateValueLowFormated, $dateValueHighFormated, TRUE)) {
4389 $where[$grouping][] = $activePeriodClauses;
4394 * Get start & end active period criteria
4398 * @param $forceTableName
4402 public static function getRelationshipActivePeriodClauses($from, $to, $forceTableName) {
4403 $tableName = $forceTableName ?
'civicrm_relationship.' : '';
4404 if (!is_null($from) && !is_null($to)) {
4405 return '(((' . $tableName . 'start_date >= ' . $from . ' AND ' . $tableName . 'start_date <= ' . $to . ') OR
4406 (' . $tableName . 'end_date >= ' . $from . ' AND ' . $tableName . 'end_date <= ' . $to . ') OR
4407 (' . $tableName . 'start_date <= ' . $from . ' AND ' . $tableName . 'end_date >= ' . $to . ' )) 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 . ') OR
4410 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4412 elseif (!is_null($from)) {
4413 return '((' . $tableName . 'start_date >= ' . $from . ') OR
4414 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4415 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . '))';
4417 elseif (!is_null($to)) {
4418 return '((' . $tableName . 'start_date <= ' . $to . ') OR
4419 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4420 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4425 * Default set of return properties.
4430 * derault return properties
4432 public static function &defaultReturnProperties($mode = 1) {
4433 if (!isset(self
::$_defaultReturnProperties)) {
4434 self
::$_defaultReturnProperties = [];
4437 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4438 // add activity return properties
4439 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4440 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4443 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4446 if (empty(self
::$_defaultReturnProperties[$mode])) {
4447 self
::$_defaultReturnProperties[$mode] = [
4450 'legal_identifier' => 1,
4451 'external_identifier' => 1,
4452 'contact_type' => 1,
4453 'contact_sub_type' => 1,
4455 'display_name' => 1,
4456 'preferred_mail_format' => 1,
4463 'formal_title' => 1,
4464 'communication_style_id' => 1,
4467 'street_address' => 1,
4468 'supplemental_address_1' => 1,
4469 'supplemental_address_2' => 1,
4470 'supplemental_address_3' => 1,
4473 'postal_code_suffix' => 1,
4474 'state_province' => 1,
4476 'world_region' => 1,
4483 'household_name' => 1,
4484 'organization_name' => 1,
4485 'deceased_date' => 1,
4490 'current_employer' => 1,
4491 // FIXME: should we use defaultHierReturnProperties() for the below?
4492 'do_not_email' => 1,
4495 'do_not_phone' => 1,
4496 'do_not_trade' => 1,
4498 'contact_is_deleted' => 1,
4499 'preferred_communication_method' => 1,
4500 'preferred_language' => 1,
4504 return self
::$_defaultReturnProperties[$mode];
4508 * Get primary condition for a sql clause.
4512 * @return string|NULL
4514 public static function getPrimaryCondition($value) {
4515 if (is_numeric($value)) {
4516 $value = (int ) $value;
4517 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4523 * Wrapper for a simple search query.
4525 * @param array $params
4526 * @param array $returnProperties
4527 * @param bool $count
4530 * @throws \CRM_Core_Exception
4532 public static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4533 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4534 list($select, $from, $where, $having) = $query->query();
4535 $groupBy = ($query->_useGroupBy
) ?
'GROUP BY contact_a.id' : '';
4537 $query = "$select $from $where $groupBy $having";
4542 * These are stub comments as this function needs more explanation - particularly in terms of how it
4543 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4545 * This function was originally written as a wrapper for the api query but is called from multiple places
4546 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4547 * but it is unclear as to whehter that is historical or there is a reason
4548 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4550 * @param array $params
4551 * @param array $returnProperties
4552 * @param null $fields
4553 * @param string $sort
4554 * @param int $offset
4555 * @param int $row_count
4556 * @param bool $smartGroupCache
4557 * ?? update smart group cache?.
4558 * @param bool $count
4559 * Return count obnly.
4560 * @param bool $skipPermissions
4561 * Should permissions be ignored or should the logged in user's permissions be applied.
4563 * This basically correlates to the component.
4564 * @param string $apiEntity
4565 * The api entity being called.
4566 * This sort-of duplicates $mode in a confusing way. Probably not by design.
4568 * @param bool|null $primaryLocationOnly
4571 * @throws \CRM_Core_Exception
4573 public static function apiQuery(
4575 $returnProperties = NULL,
4580 $smartGroupCache = TRUE,
4582 $skipPermissions = TRUE,
4583 $mode = CRM_Contact_BAO_Query
::MODE_CONTACTS
,
4585 $primaryLocationOnly = NULL
4588 $query = new CRM_Contact_BAO_Query(
4589 $params, $returnProperties,
4590 NULL, TRUE, FALSE, $mode,
4592 TRUE, $smartGroupCache,
4594 $apiEntity, $primaryLocationOnly
4597 //this should add a check for view deleted if permissions are enabled
4598 if ($skipPermissions) {
4599 $query->_skipDeleteClause
= TRUE;
4601 $query->generatePermissionClause(FALSE, $count);
4603 // note : this modifies _fromClause and _simpleFromClause
4604 $query->includePseudoFieldsJoin($sort);
4606 list($select, $from, $where, $having) = $query->query($count);
4608 $options = $query->_options
;
4609 if (!empty($query->_permissionWhereClause
)) {
4610 if (!empty($query->_permissionFromClause
) && !stripos($from, 'aclContactCache')) {
4611 $from .= " $query->_permissionFromClause";
4613 if (empty($where)) {
4614 $where = "WHERE $query->_permissionWhereClause";
4617 $where = "$where AND $query->_permissionWhereClause";
4621 $sql = "$select $from $where $having";
4623 // add group by only when API action is not getcount
4624 // otherwise query fetches incorrect count
4625 if ($query->_useGroupBy
&& !$count) {
4626 $sql .= self
::getGroupByFromSelectColumns($query->_select
, 'contact_a.id');
4628 if (!empty($sort)) {
4629 $sort = CRM_Utils_Type
::escape($sort, 'String');
4630 $sql .= " ORDER BY $sort ";
4632 if ($row_count > 0 && $offset >= 0) {
4633 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4634 $row_count = CRM_Utils_Type
::escape($row_count, 'Int');
4635 $sql .= " LIMIT $offset, $row_count ";
4638 $dao = CRM_Core_DAO
::executeQuery($sql);
4640 // @todo derive this from the component class rather than hard-code two options.
4641 $entityIDField = ($mode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) ?
'contribution_id' : 'contact_id';
4644 while ($dao->fetch()) {
4646 $noRows = $dao->rowCount
;
4647 return [$noRows, NULL];
4649 $val = $query->store($dao);
4650 $convertedVals = $query->convertToPseudoNames($dao, TRUE, TRUE);
4652 if (!empty($convertedVals)) {
4653 $val = array_replace_recursive($val, $convertedVals);
4655 $values[$dao->$entityIDField] = $val;
4657 return [$values, $options];
4661 * Get the actual custom field name by stripping off the appended string.
4663 * The string could be _relative, _from, or _to
4665 * @todo use metadata rather than convention to do this.
4667 * @param string $parameterName
4668 * The name of the parameter submitted to the form.
4675 public static function getCustomFieldName($parameterName) {
4676 if (substr($parameterName, -5, 5) == '_from') {
4677 return substr($parameterName, 0, strpos($parameterName, '_from'));
4679 if (substr($parameterName, -9, 9) == '_relative') {
4680 return substr($parameterName, 0, strpos($parameterName, '_relative'));
4682 if (substr($parameterName, -3, 3) == '_to') {
4683 return substr($parameterName, 0, strpos($parameterName, '_to'));
4688 * Convert submitted values for relative custom fields to query object format.
4690 * The query will support the sqlOperator format so convert to that format.
4692 * @param array $formValues
4694 * @param array $params
4695 * Converted parameters for the query object.
4696 * @param string $values
4698 * @param string $fieldName
4699 * Submitted field name. (Matches form field not DB field.)
4701 protected static function convertCustomRelativeFields(&$formValues, &$params, $values, $fieldName) {
4702 if (empty($values)) {
4703 // e.g we might have relative set & from & to empty. The form flow is a bit funky &
4704 // this function gets called again after they fields have been converted which can get ugly.
4707 $customFieldName = self
::getCustomFieldName($fieldName);
4709 if (substr($fieldName, -9, 9) == '_relative') {
4710 list($from, $to) = CRM_Utils_Date
::getFromTo($values, NULL, NULL);
4713 if ($fieldName == $customFieldName . '_to' && !empty($formValues[$customFieldName . '_from'])) {
4714 // Both to & from are set. We only need to acton one, choosing from.
4718 $from = $formValues[$customFieldName . '_from'] ??
NULL;
4719 $to = $formValues[$customFieldName . '_to'] ??
NULL;
4721 if (self
::isCustomDateField($customFieldName)) {
4722 list($from, $to) = CRM_Utils_Date
::getFromTo(NULL, $from, $to);
4728 $relativeFunction = ['BETWEEN' => [$from, $to]];
4731 $relativeFunction = ['>=' => $from];
4735 $relativeFunction = ['<=' => $to];
4747 * Are we dealing with custom field of type date.
4752 * @throws \CiviCRM_API3_Exception
4754 public static function isCustomDateField($fieldName) {
4755 if (($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($fieldName)) == FALSE) {
4759 $customFieldDataType = civicrm_api3('CustomField', 'getvalue', ['id' => $customFieldID, 'return' => 'data_type']);
4760 if ('Date' == $customFieldDataType) {
4764 catch (CiviCRM_API3_Exception
$e) {
4770 * Has this field already been reformatting to Query object syntax.
4772 * The form layer passed formValues to this function in preProcess & postProcess. Reason unknown. This seems
4773 * to come with associated double queries & is possibly damaging performance.
4775 * However, here we add a tested function to ensure convertFormValues identifies pre-processed fields & returns
4778 * @param mixed $values
4779 * Value in formValues for the field.
4783 public static function isAlreadyProcessedForQueryFormat($values) {
4784 if (!is_array($values)) {
4787 if (($operator = CRM_Utils_Array
::value(1, $values)) == FALSE) {
4790 return in_array($operator, CRM_Core_DAO
::acceptedSQLOperators());
4794 * If the state and country are passed remove state.
4796 * Country is implicit from the state, but including both results in
4797 * a poor query as there is no combined index on state AND country.
4799 * @see https://issues.civicrm.org/jira/browse/CRM-18125
4801 * @param array $formValues
4803 public static function filterCountryFromValuesIfStateExists(&$formValues) {
4804 if (!empty($formValues['country']) && !empty($formValues['state_province'])) {
4805 // The use of array map sanitises the data by ensuring we are dealing with integers.
4806 $states = implode(', ', array_map('intval', $formValues['state_province']));
4807 $countryList = CRM_Core_DAO
::singleValueQuery(
4808 "SELECT GROUP_CONCAT(country_id) FROM civicrm_state_province WHERE id IN ($states)"
4810 if ($countryList == $formValues['country']) {
4811 unset($formValues['country']);
4817 * For some special cases, grouping by subset of select fields becomes mandatory.
4818 * Hence, full_group_by mode is handled by appending any_value
4819 * keyword to select fields not present in groupBy
4821 * @param array $selectClauses
4822 * @param array $groupBy - Columns already included in GROUP By clause.
4823 * @param string $aggregateFunction
4827 public static function appendAnyValueToSelect($selectClauses, $groupBy, $aggregateFunction = 'ANY_VALUE') {
4828 if (!CRM_Utils_SQL
::disableFullGroupByMode()) {
4829 $groupBy = array_map('trim', (array) $groupBy);
4830 $aggregateFunctions = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN|IF)[[:blank:]]*\(/i';
4831 foreach ($selectClauses as $key => &$val) {
4832 list($selectColumn, $alias) = array_pad(preg_split('/ as /i', $val), 2, NULL);
4833 // append ANY_VALUE() keyword
4834 if (!in_array($selectColumn, $groupBy) && preg_match($aggregateFunctions, trim($selectColumn)) !== 1) {
4835 $val = ($aggregateFunction == 'GROUP_CONCAT') ?
4836 str_replace($selectColumn, "$aggregateFunction(DISTINCT {$selectColumn})", $val) :
4837 str_replace($selectColumn, "$aggregateFunction({$selectColumn})", $val);
4842 return "SELECT " . implode(', ', $selectClauses) . " ";
4846 * For some special cases, where if non-aggregate ORDER BY columns are not present in GROUP BY
4847 * on full_group_by mode, then append the those missing columns to GROUP BY clause
4848 * keyword to select fields not present in groupBy
4850 * @param string $groupBy - GROUP BY clause where missing ORDER BY columns will be appended if not present
4851 * @param array $orderBys - ORDER BY sub-clauses
4854 public static function getGroupByFromOrderBy(&$groupBy, $orderBys) {
4855 if (!CRM_Utils_SQL
::disableFullGroupByMode()) {
4856 foreach ($orderBys as $orderBy) {
4857 // remove sort syntax from ORDER BY clauses if present
4858 $orderBy = str_ireplace([' DESC', ' ASC', '`'], '', $orderBy);
4859 // if ORDER BY column is not present in GROUP BY then append it to end
4860 if (preg_match('/(MAX|MIN)\(/i', trim($orderBy)) !== 1 && !strstr($groupBy, $orderBy)) {
4861 $groupBy .= ", {$orderBy}";
4868 * Include Select columns in groupBy clause.
4870 * @param array $selectClauses
4871 * @param array $groupBy - Columns already included in GROUP By clause.
4875 public static function getGroupByFromSelectColumns($selectClauses, $groupBy = NULL) {
4876 $groupBy = (array) $groupBy;
4877 $mysqlVersion = CRM_Core_DAO
::singleValueQuery('SELECT VERSION()');
4878 $sqlMode = CRM_Core_DAO
::singleValueQuery('SELECT @@sql_mode');
4880 //return if ONLY_FULL_GROUP_BY is not enabled.
4881 if (CRM_Utils_SQL
::supportsFullGroupBy() && !empty($sqlMode) && in_array('ONLY_FULL_GROUP_BY', explode(',', $sqlMode))) {
4882 $regexToExclude = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN|IF)[[:blank:]]*\(/i';
4883 foreach ($selectClauses as $key => $val) {
4884 $aliasArray = preg_split('/ as /i', $val);
4885 // if more than 1 alias we need to split by ','.
4886 if (count($aliasArray) > 2) {
4887 $aliasArray = preg_split('/,/', $val);
4888 foreach ($aliasArray as $key => $value) {
4889 $alias = current(preg_split('/ as /i', $value));
4890 if (!in_array($alias, $groupBy) && preg_match($regexToExclude, trim($alias)) !== 1) {
4891 $groupBy[] = $alias;
4896 list($selectColumn, $alias) = array_pad($aliasArray, 2, NULL);
4897 $dateRegex = '/^(DATE_FORMAT|DATE_ADD|CASE)/i';
4898 $tableName = current(explode('.', $selectColumn));
4899 $primaryKey = "{$tableName}.id";
4900 // exclude columns which are already included in groupBy and aggregate functions from select
4901 // CRM-18439 - Also exclude the columns which are functionally dependent on columns in $groupBy (MySQL 5.7+)
4902 if (!in_array($selectColumn, $groupBy) && !in_array($primaryKey, $groupBy) && preg_match($regexToExclude, trim($selectColumn)) !== 1) {
4903 if (!empty($alias) && preg_match($dateRegex, trim($selectColumn))) {
4904 $groupBy[] = $alias;
4907 $groupBy[] = $selectColumn;
4914 if (!empty($groupBy)) {
4915 return " GROUP BY " . implode(', ', $groupBy);
4921 * Create and query the db for an contact search.
4923 * @param int $offset
4924 * The offset for the query.
4925 * @param int $rowCount
4926 * The number of rows to return.
4927 * @param string|CRM_Utils_Sort $sort
4928 * The order by string.
4929 * @param bool $count
4930 * Is this a count only query ?.
4931 * @param bool $includeContactIds
4932 * Should we include contact ids?.
4933 * @param bool $sortByChar
4934 * If true returns the distinct array of first characters for search results.
4935 * @param bool $groupContacts
4936 * If true, return only the contact ids.
4937 * @param bool $returnQuery
4938 * Should we return the query as a string.
4939 * @param string $additionalWhereClause
4940 * If the caller wants to further restrict the search (used for components).
4941 * @param null $sortOrder
4942 * @param string $additionalFromClause
4943 * Should be clause with proper joins, effective to reduce where clause load.
4945 * @param bool $skipOrderAndLimit
4947 * @return CRM_Core_DAO
4949 public function searchQuery(
4950 $offset = 0, $rowCount = 0, $sort = NULL,
4951 $count = FALSE, $includeContactIds = FALSE,
4952 $sortByChar = FALSE, $groupContacts = FALSE,
4953 $returnQuery = FALSE,
4954 $additionalWhereClause = NULL, $sortOrder = NULL,
4955 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4958 $query = $this->getSearchSQL($offset, $rowCount, $sort, $count, $includeContactIds, $sortByChar, $groupContacts, $additionalWhereClause, $sortOrder, $additionalFromClause, $skipOrderAndLimit);
4964 return CRM_Core_DAO
::singleValueQuery($query);
4967 $dao = CRM_Core_DAO
::executeQuery($query);
4969 // We can always call this - it will only re-enable if it was originally enabled.
4970 CRM_Core_DAO
::reenableFullGroupByMode();
4972 if ($groupContacts) {
4974 while ($dao->fetch()) {
4977 return implode(',', $ids);
4984 * Create and query the db for the list of all first letters used by contacts
4986 * @return CRM_Core_DAO
4988 public function alphabetQuery() {
4989 $sqlParts = $this->getSearchSQLParts(NULL, NULL, NULL, FALSE, FALSE, TRUE);
4990 $query = "SELECT DISTINCT LEFT(contact_a.sort_name, 1) as sort_name
4992 {$sqlParts['where']}
4993 {$sqlParts['having']}
4995 ORDER BY sort_name asc";
4996 $dao = CRM_Core_DAO
::executeQuery($query);
5001 * Fetch a list of contacts for displaying a search results page
5003 * @param array $cids
5004 * List of contact IDs
5005 * @param bool $includeContactIds
5006 * @return CRM_Core_DAO
5008 public function getCachedContacts($cids, $includeContactIds) {
5009 CRM_Core_DAO
::disableFullGroupByMode();
5010 CRM_Utils_Type
::validateAll($cids, 'Positive');
5011 $this->_includeContactIds
= $includeContactIds;
5012 $onlyDeleted = in_array(['deleted_contacts', '=', '1', '0', '0'], $this->_params
);
5013 list($select, $from, $where) = $this->query(FALSE, FALSE, FALSE, $onlyDeleted);
5014 $select .= sprintf(", (%s) AS _wgt", $this->createSqlCase('contact_a.id', $cids));
5015 $where .= sprintf(' AND contact_a.id IN (%s)', implode(',', $cids));
5016 $order = 'ORDER BY _wgt';
5017 $groupBy = $this->_useGroupBy ?
' GROUP BY contact_a.id' : '';
5019 $query = "$select $from $where $groupBy $order $limit";
5021 $result = CRM_Core_DAO
::executeQuery($query);
5022 CRM_Core_DAO
::reenableFullGroupByMode();
5027 * Construct a SQL CASE expression.
5029 * @param string $idCol
5030 * The name of a column with ID's (eg 'contact_a.id').
5031 * @param array $cids
5032 * Array(int $weight => int $id).
5034 * CASE WHEN id=123 THEN 1 WHEN id=456 THEN 2 END
5036 private function createSqlCase($idCol, $cids) {
5038 foreach ($cids as $weight => $cid) {
5039 $buf .= " WHEN $idCol = $cid THEN $weight \n";
5046 * Populate $this->_permissionWhereClause with permission related clause and update other
5047 * query related properties.
5049 * Function calls ACL permission class and hooks to filter the query appropriately
5051 * Note that these 2 params were in the code when extracted from another function
5052 * and a second round extraction would be to make them properties of the class
5054 * @param bool $onlyDeleted
5055 * Only get deleted contacts.
5056 * @param bool $count
5057 * Return Count only.
5059 public function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
5060 if (!$this->_skipPermission
) {
5061 $permissionClauses = CRM_Contact_BAO_Contact_Permission
::cacheClause();
5062 $this->_permissionWhereClause
= $permissionClauses[1];
5063 $this->_permissionFromClause
= $permissionClauses[0];
5065 if (CRM_Core_Permission
::check('access deleted contacts')) {
5066 if (!$onlyDeleted) {
5067 $this->_permissionWhereClause
= str_replace('( 1 )', '(contact_a.is_deleted = 0)', $this->_permissionWhereClause
);
5070 if ($this->_permissionWhereClause
=== '( 1 )') {
5071 $this->_permissionWhereClause
= str_replace('( 1 )', '(contact_a.is_deleted)', $this->_permissionWhereClause
);
5074 $this->_permissionWhereClause
.= " AND (contact_a.is_deleted) ";
5079 if (isset($this->_tables
['civicrm_activity'])) {
5080 $bao = new CRM_Activity_BAO_Activity();
5081 $clauses = $subclauses = [];
5082 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
5083 if ($vals && $field !== 'id') {
5084 $clauses[] = $bao->tableName() . ".$field " . $vals;
5087 $subclauses[] = "$field " . implode(" AND $field ", (array) $vals);
5091 $clauses[] = $bao->tableName() . '.`id` IN (SELECT `id` FROM `' . $bao->tableName() . '` WHERE ' . implode(' AND ', $subclauses) . ')';
5093 if (!empty($clauses) && $this->_permissionWhereClause
) {
5094 $this->_permissionWhereClause
.= ' AND (' . implode(' AND ', $clauses) . ')';
5096 elseif (!empty($clauses)) {
5097 $this->_permissionWhereClause
.= '(' . implode(' AND ', $clauses) . ')';
5102 // add delete clause if needed even if we are skipping permission
5104 if (!$this->_skipDeleteClause
) {
5105 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
5106 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
5110 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
5119 public function setSkipPermission($val) {
5120 $this->_skipPermission
= $val;
5124 * @param null $context
5127 * @throws \CRM_Core_Exception
5129 public function summaryContribution($context = NULL) {
5130 list($innerselect, $from, $where, $having) = $this->query(TRUE);
5131 if (!empty($this->_permissionFromClause
) && !stripos($from, 'aclContactCache')) {
5132 $from .= " $this->_permissionFromClause";
5134 if ($this->_permissionWhereClause
) {
5135 $where .= " AND " . $this->_permissionWhereClause
;
5137 if ($context == 'search') {
5138 $where .= " AND contact_a.is_deleted = 0 ";
5141 $this->appendFinancialTypeWhereAndFromToQueryStrings($where, $from);
5143 $summary = ['total' => []];
5144 $this->addBasicStatsToSummary($summary, $where, $from);
5146 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
5147 $this->addBasicSoftCreditStatsToStats($summary, $where, $from);
5150 $this->addBasicCancelStatsToSummary($summary, $where, $from);
5156 * Append financial ACL limits to the query from & where clauses, if applicable.
5158 * @param string $where
5159 * @param string $from
5161 public function appendFinancialTypeWhereAndFromToQueryStrings(&$where, &$from) {
5162 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
5165 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
5166 if (!empty($financialTypes)) {
5167 $where .= " AND civicrm_contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND li.id IS NULL";
5168 $from .= " LEFT JOIN civicrm_line_item li
5169 ON civicrm_contribution.id = li.contribution_id AND
5170 li.entity_table = 'civicrm_contribution' AND li.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ") ";
5173 $where .= " AND civicrm_contribution.financial_type_id IN (0)";
5178 * Getter for the qill object.
5182 public function qill() {
5183 return $this->_qill
;
5187 * Default set of return default hier return properties.
5191 public static function &defaultHierReturnProperties() {
5192 if (!isset(self
::$_defaultHierReturnProperties)) {
5193 self
::$_defaultHierReturnProperties = [
5196 'legal_identifier' => 1,
5197 'external_identifier' => 1,
5198 'contact_type' => 1,
5199 'contact_sub_type' => 1,
5201 'display_name' => 1,
5208 'formal_title' => 1,
5209 'communication_style_id' => 1,
5210 'email_greeting' => 1,
5211 'postal_greeting' => 1,
5215 'preferred_communication_method' => 1,
5216 'do_not_phone' => 1,
5217 'do_not_email' => 1,
5220 'do_not_trade' => 1,
5223 'location_type' => 1,
5224 'street_address' => 1,
5226 'state_province' => 1,
5228 'postal_code_suffix' => 1,
5231 'phone-Mobile' => 1,
5244 'location_type' => 1,
5245 'street_address' => 1,
5247 'state_province' => 1,
5249 'postal_code_suffix' => 1,
5252 'phone-Mobile' => 1,
5266 return self
::$_defaultHierReturnProperties;
5270 * Build query for a date field.
5272 * @param array $values
5273 * @param string $tableName
5274 * @param string $fieldName
5275 * @param string $dbFieldName
5276 * @param string $fieldTitle
5277 * @param bool $appendTimeStamp
5278 * @param string $dateFormat
5279 * @param string|null $highDBFieldName
5280 * Optional field name for when the 'high' part of the calculation uses a different field than the 'low' part.
5281 * This is an obscure situation & one we don't want to do more of but supporting them here is the only way for now.
5282 * Examples are event date & relationship active date -in both cases we are looking for things greater than the start
5283 * date & less than the end date.
5285 * @throws \CRM_Core_Exception
5287 public function dateQueryBuilder(
5288 $values, $tableName, $fieldName,
5289 $dbFieldName, $fieldTitle,
5290 $appendTimeStamp = TRUE,
5291 $dateFormat = 'YmdHis',
5292 $highDBFieldName = NULL
5294 // @todo - remove dateFormat - pretty sure it's never passed in...
5295 list($name, $op, $value, $grouping, $wildcard) = $values;
5296 if ($name !== $fieldName && $name !== "{$fieldName}_low" && $name !== "{$fieldName}_high") {
5297 CRM_Core_Error
::deprecatedFunctionWarning('Date query builder called unexpectedly');
5300 if ($tableName === 'civicrm_contact') {
5301 // Special handling for contact table as it has a known alias in advanced search.
5302 $tableName = 'contact_a';
5304 if ($name === "{$fieldName}_low" ||
5305 $name === "{$fieldName}_high"
5307 if (isset($this->_rangeCache
[$fieldName]) ||
!$value) {
5310 $this->_rangeCache
[$fieldName] = 1;
5312 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
5314 if ($name == $fieldName . '_low') {
5316 $firstPhrase = ts('greater than or equal to');
5317 $firstDate = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5319 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5320 if (!empty($secondValues) && $secondValues[2]) {
5322 $secondPhrase = ts('less than or equal to');
5323 $secondValue = $secondValues[2];
5325 if ($appendTimeStamp && strlen($secondValue) == 10) {
5326 $secondValue .= ' 23:59:59';
5328 $secondDate = CRM_Utils_Date
::processDate($secondValue, NULL, FALSE, $dateFormat);
5331 elseif ($name == $fieldName . '_high') {
5333 $firstPhrase = ts('less than or equal to');
5335 if ($appendTimeStamp && strlen($value) == 10) {
5336 $value .= ' 23:59:59';
5338 $firstDate = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5340 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5341 if (!empty($secondValues) && $secondValues[2]) {
5343 $secondPhrase = ts('greater than or equal to');
5344 $secondValue = $secondValues[2];
5345 $secondDate = CRM_Utils_Date
::processDate($secondValue, NULL, FALSE, $dateFormat);
5349 if (!$appendTimeStamp) {
5350 $firstDate = substr($firstDate, 0, 8);
5352 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
5355 if (!$appendTimeStamp) {
5356 $secondDate = substr($secondDate, 0, 8);
5358 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
5362 $highDBFieldName = $highDBFieldName ??
$dbFieldName;
5363 $this->_where
[$grouping][] = "
5364 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5365 ( {$tableName}.{$highDBFieldName} $secondOP '$secondDate' )
5367 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
5370 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5371 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5375 if ($name == $fieldName) {
5376 //In Get API, for operators other then '=' the $value is in array(op => value) format
5377 if (is_array($value) && !empty($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
5379 $value = $value[$op];
5382 $date = $format = NULL;
5383 if (strstr($op, 'IN')) {
5385 foreach ($value as &$date) {
5386 $date = CRM_Utils_Date
::processDate($date, NULL, FALSE, $dateFormat);
5387 if (!$appendTimeStamp) {
5388 $date = substr($date, 0, 8);
5390 $format[] = CRM_Utils_Date
::customFormat($date);
5392 $date = "('" . implode("','", $value) . "')";
5393 $format = implode(', ', $format);
5395 elseif ($value && (!strstr($op, 'NULL') && !strstr($op, 'EMPTY'))) {
5396 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5397 if (!$appendTimeStamp) {
5398 $date = substr($date, 0, 8);
5400 $format = CRM_Utils_Date
::customFormat($date);
5405 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op $date";
5408 $this->_where
[$grouping][] = self
::buildClause("{$tableName}.{$dbFieldName}", $op);
5411 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
5412 $this->_qill
[$grouping][] = "$fieldTitle $op $format";
5415 // Ensure the tables are set, but don't whomp anything.
5416 $this->_tables
[$tableName] = $this->_tables
[$tableName] ??
1;
5417 $this->_whereTables
[$tableName] = $this->_whereTables
[$tableName] ??
1;
5422 * @param string $tableName
5423 * @param string $fieldName
5424 * @param string $dbFieldName
5425 * @param $fieldTitle
5426 * @param null $options
5428 public function numberRangeBuilder(
5430 $tableName, $fieldName,
5431 $dbFieldName, $fieldTitle,
5434 list($name, $op, $value, $grouping, $wildcard) = $values;
5436 if ($name == "{$fieldName}_low" ||
5437 $name == "{$fieldName}_high"
5439 if (isset($this->_rangeCache
[$fieldName])) {
5442 $this->_rangeCache
[$fieldName] = 1;
5444 $secondOP = $secondPhrase = $secondValue = NULL;
5446 if ($name == "{$fieldName}_low") {
5448 $firstPhrase = ts('greater than');
5450 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5451 if (!empty($secondValues)) {
5453 $secondPhrase = ts('less than');
5454 $secondValue = $secondValues[2];
5459 $firstPhrase = ts('less than');
5461 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5462 if (!empty($secondValues)) {
5464 $secondPhrase = ts('greater than');
5465 $secondValue = $secondValues[2];
5470 $this->_where
[$grouping][] = "
5471 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5472 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5474 $displayValue = $options ?
$options[$value] : $value;
5475 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5477 $this->_qill
[$grouping][]
5478 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5481 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5482 $displayValue = $options ?
$options[$value] : $value;
5483 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5485 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5490 if ($name == $fieldName) {
5494 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5496 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5497 $displayValue = $options ?
$options[$value] : $value;
5498 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5504 * @param string $tableName
5505 * @param string $fieldName
5506 * @param string $dbFieldName
5507 * @param $fieldTitle
5508 * @param null $options
5510 public function ageRangeQueryBuilder(
5512 $tableName, $fieldName,
5513 $dbFieldName, $fieldTitle,
5516 list($name, $op, $value, $grouping, $wildcard) = $values;
5518 $asofDateValues = $this->getWhereValues("{$fieldName}_asof_date", $grouping);
5519 // will be treated as current day
5521 if ($asofDateValues) {
5522 $asofDate = CRM_Utils_Date
::processDate($asofDateValues[2]);
5523 $asofDateFormat = CRM_Utils_Date
::customFormat(substr($asofDate, 0, 8));
5524 $fieldTitle .= ' ' . ts('as of') . ' ' . $asofDateFormat;
5527 if ($name == "{$fieldName}_low" ||
5528 $name == "{$fieldName}_high"
5530 if (isset($this->_rangeCache
[$fieldName])) {
5533 $this->_rangeCache
[$fieldName] = 1;
5535 $secondOP = $secondPhrase = $secondValue = NULL;
5537 if ($name == "{$fieldName}_low") {
5538 $firstPhrase = ts('greater than or equal to');
5539 // NB: age > X means date of birth < Y
5541 $firstDate = self
::calcDateFromAge($asofDate, $value, 'min');
5543 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5544 if (!empty($secondValues)) {
5546 $secondPhrase = ts('less than or equal to');
5547 $secondValue = $secondValues[2];
5548 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'max');
5553 $firstPhrase = ts('less than or equal to');
5554 $firstDate = self
::calcDateFromAge($asofDate, $value, 'max');
5556 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5557 if (!empty($secondValues)) {
5559 $secondPhrase = ts('greater than or equal to');
5560 $secondValue = $secondValues[2];
5561 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'min');
5566 $this->_where
[$grouping][] = "
5567 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5568 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5570 $displayValue = $options ?
$options[$value] : $value;
5571 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5573 $this->_qill
[$grouping][]
5574 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5577 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5578 $displayValue = $options ?
$options[$value] : $value;
5579 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5581 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5587 * Calculate date from age.
5589 * @param string $asofDate
5591 * @param string $type
5594 * @throws \Exception
5596 public static function calcDateFromAge($asofDate, $age, $type) {
5597 $date = new DateTime($asofDate);
5598 if ($type == "min") {
5599 // minimum age is $age: dob <= date - age "235959"
5600 $date->sub(new DateInterval("P" . $age . "Y"));
5601 return $date->format('Ymd') . "235959";
5604 // max age is $age: dob >= date - (age + 1y) + 1d "000000"
5605 $date->sub(new DateInterval("P" . ($age +
1) . "Y"))->add(new DateInterval("P1D"));
5606 return $date->format('Ymd') . "000000";
5611 * Given the field name, operator, value & its data type
5612 * builds the where Clause for the query
5613 * used for handling 'IS NULL'/'IS NOT NULL' operators
5615 * @param string $field
5619 * @param string $value
5621 * @param string $dataType
5622 * Data type of the field.
5625 * Where clause for the query.
5626 * @throws \CRM_Core_Exception
5628 public static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5630 $clause = "$field $op";
5638 $clause = ($dataType == 'Date') ?
" $field IS NULL " : " (NULLIF($field, '') IS NULL) ";
5641 case 'IS NOT EMPTY':
5642 $clause = ($dataType == 'Date') ?
" $field IS NOT NULL " : " (NULLIF($field, '') IS NOT NULL) ";
5646 return " {$clause} BINARY '{$value}' ";
5650 // I feel like this would be escaped properly if passed through $queryString = CRM_Core_DAO::createSqlFilter.
5651 if (!empty($value) && (!is_array($value) ||
!array_key_exists($op, $value))) {
5652 $value = [$op => (array) $value];
5656 if (empty($dataType) ||
$dataType == 'Date') {
5657 $dataType = 'String';
5659 if (is_array($value)) {
5660 //this could have come from the api - as in the restWhere section we potentially use the api operator syntax which is becoming more
5661 // widely used and consistent across the codebase
5662 // adding this here won't accept the search functions which don't submit an array
5663 if (($queryString = CRM_Core_DAO
::createSQLFilter($field, $value, $dataType)) != FALSE) {
5665 return $queryString;
5667 if (!empty($value[0]) && $op === 'BETWEEN') {
5668 CRM_Core_Error
::deprecatedFunctionWarning('Fix search input params');
5669 if (($queryString = CRM_Core_DAO
::createSQLFilter($field, [$op => $value], $dataType)) != FALSE) {
5670 return $queryString;
5673 throw new CRM_Core_Exception(ts('Failed to interpret input for search'));
5676 $value = CRM_Utils_Type
::escape($value, $dataType);
5677 // if we don't have a dataType we should assume
5678 if ($dataType == 'String' ||
$dataType == 'Text') {
5679 $value = "'" . $value . "'";
5681 return "$clause $value";
5686 * @param bool $reset
5690 public function openedSearchPanes($reset = FALSE) {
5691 if (!$reset ||
empty($this->_whereTables
)) {
5692 return self
::$_openedPanes;
5695 // pane name to table mapper
5697 ts('Contributions') => 'civicrm_contribution',
5698 ts('Memberships') => 'civicrm_membership',
5699 ts('Events') => 'civicrm_participant',
5700 ts('Relationships') => 'civicrm_relationship',
5701 ts('Activities') => 'civicrm_activity',
5702 ts('Pledges') => 'civicrm_pledge',
5703 ts('Cases') => 'civicrm_case',
5704 ts('Grants') => 'civicrm_grant',
5705 ts('Address Fields') => 'civicrm_address',
5706 ts('Notes') => 'civicrm_note',
5707 ts('Change Log') => 'civicrm_log',
5708 ts('Mailings') => 'civicrm_mailing',
5710 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
5712 foreach (array_keys($this->_whereTables
) as $table) {
5713 if ($panName = array_search($table, $panesMapper)) {
5714 self
::$_openedPanes[$panName] = TRUE;
5718 return self
::$_openedPanes;
5724 public function setOperator($operator) {
5725 $validOperators = ['AND', 'OR'];
5726 if (!in_array($operator, $validOperators)) {
5729 $this->_operator
= $operator;
5735 public function getOperator() {
5736 return $this->_operator
;
5744 public function filterRelatedContacts(&$from, &$where, &$having) {
5745 if (!isset(Civi
::$statics[__CLASS__
]['related_contacts_filter'])) {
5746 Civi
::$statics[__CLASS__
]['related_contacts_filter'] = [];
5748 $_rTempCache =& Civi
::$statics[__CLASS__
]['related_contacts_filter'];
5749 // since there only can be one instance of this filter in every query
5750 // skip if filter has already applied
5751 foreach ($_rTempCache as $acache) {
5752 foreach ($acache['queries'] as $aqcache) {
5753 if (strpos($from, $aqcache['from']) !== FALSE) {
5759 $arg_sig = sha1("$from $where $having");
5760 if (isset($_rTempCache[$arg_sig])) {
5761 $cache = $_rTempCache[$arg_sig];
5764 // create temp table with contact ids
5766 $tableName = CRM_Utils_SQL_TempTable
::build()->createWithColumns('contact_id int primary key')->setMemory(TRUE)->getName();
5769 REPLACE INTO $tableName ( contact_id )
5775 CRM_Core_DAO
::executeQuery($sql);
5777 $cache = ['tableName' => $tableName, 'queries' => []];
5778 $_rTempCache[$arg_sig] = $cache;
5780 // upsert the query depending on relationship type
5781 if (isset($cache['queries'][$this->_displayRelationshipType
])) {
5782 $qcache = $cache['queries'][$this->_displayRelationshipType
];
5785 $tableName = $cache['tableName'];
5790 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5791 if (is_numeric($this->_displayRelationshipType
)) {
5792 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5794 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5795 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5797 $qcache['where'] = "
5798 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5799 AND displayRelType.is_active = 1
5803 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5804 if ($dirOne == 'a') {
5805 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5806 $qcache['from'] .= "
5807 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5808 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5812 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5813 $qcache['from'] .= "
5814 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5815 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5818 $qcache['where'] = "
5819 WHERE displayRelType.relationship_type_id = $relType
5820 AND displayRelType.is_active = 1
5823 $qcache['relTypeLabel'] = $relationshipTypeLabel;
5824 $_rTempCache[$arg_sig]['queries'][$this->_displayRelationshipType
] = $qcache;
5826 $qillMessage = ts('Contacts with a Relationship Type of: ');
5827 $iqill = $qillMessage . "'" . $qcache['relTypeLabel'] . "'";
5828 if (!is_array($this->_qill
[0]) ||
!in_array($iqill, $this->_qill
[0])) {
5829 $this->_qill
[0][] = $iqill;
5831 if (strpos($from, $qcache['from']) === FALSE) {
5832 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5833 // this happens when we have an event_type in the quert (CRM-7969)
5834 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5835 $from .= $qcache['from'];
5836 $where = $qcache['where'];
5837 if (!empty($this->_permissionFromClause
) && !stripos($from, 'aclContactCache')) {
5838 $from .= " $this->_permissionFromClause";
5840 if (!empty($this->_permissionWhereClause
)) {
5841 $where .= "AND $this->_permissionWhereClause";
5849 * See CRM-19811 for why this is database hurty without apparent benefit.
5855 public static function caseImportant($op) {
5856 return !in_array($op, ['LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY']);
5860 * @param $returnProperties
5865 public static function componentPresent(&$returnProperties, $prefix) {
5866 foreach ($returnProperties as $name => $dontCare) {
5867 if (substr($name, 0, strlen($prefix)) == $prefix) {
5875 * Builds the necessary structures for all fields that are similar to option value look-ups.
5877 * @param string $name
5878 * the name of the field.
5880 * the sql operator, this function should handle ALL SQL operators.
5881 * @param string $value
5882 * depends on the operator and who's calling the query builder.
5883 * @param int $grouping
5884 * the index where to place the where clause.
5885 * @param string $daoName
5887 * @param array $field
5888 * an array that contains various properties of the field identified by $name.
5889 * @param string $label
5890 * The label for this field element.
5891 * @param string $dataType
5893 * @throws \CRM_Core_Exception
5895 public function optionValueQuery(
5903 $dataType = 'String'
5912 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5913 if ($tableName == 'civicrm_contact') {
5914 $wc = "contact_a.$fieldName";
5917 // Special handling for on_hold, so that we actually use the 'where'
5918 // property in order to limit the query by the on_hold status of the email,
5919 // instead of using email.id which would be nonsensical.
5920 if ($field['name'] === 'on_hold') {
5921 $wc = $field['where'];
5924 $wc = "$tableName.id";
5928 if (in_array($name, $pseudoFields)) {
5929 $wc = "contact_a.{$name}_id";
5930 $dataType = 'Positive';
5931 $value = (!$value) ?
0 : $value;
5933 if ($name == "world_region") {
5934 $field['name'] = $name;
5937 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue($daoName, $field['name'], $value, $op);
5938 $this->_qill
[$grouping][] = ts("%1 %2 %3", [1 => $label, 2 => $qillop, 3 => $qillVal]);
5939 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5943 * Check and explode a user defined numeric string into an array
5944 * this was the protocol used by search builder in the old old days before we had
5945 * super nice js widgets to do the hard work
5947 * @param string $string
5948 * @param string $dataType
5949 * The dataType we should check for the values, default integer.
5951 * @return bool|array
5952 * false if string does not match the pattern
5953 * array of numeric values if string does match the pattern
5955 public static function parseSearchBuilderString($string, $dataType = 'Integer') {
5956 $string = trim($string);
5957 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5961 $string = substr($string, 1, -1);
5962 $values = explode(',', $string);
5963 if (empty($values)) {
5968 foreach ($values as $v) {
5969 if ($dataType == 'Integer' && !is_numeric($v)) {
5972 elseif ($dataType == 'String' && !is_string($v)) {
5975 $returnValues[] = trim($v);
5978 if (empty($returnValues)) {
5982 return $returnValues;
5986 * Convert the pseudo constants id's to their names
5988 * @param CRM_Core_DAO $dao
5989 * @param bool $return
5990 * @param bool $usedForAPI
5992 * @return array|NULL
5994 public function convertToPseudoNames(&$dao, $return = FALSE, $usedForAPI = FALSE) {
5995 if (empty($this->_pseudoConstantsSelect
)) {
5999 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
6000 if (!empty($this->_pseudoConstantsSelect
[$key]['sorting'])) {
6004 if (is_object($dao) && property_exists($dao, $value['idCol'])) {
6005 $val = $dao->{$value['idCol']};
6006 if ($key == 'groups') {
6007 $dao->groups
= $this->convertGroupIDStringToLabelString($dao, $val);
6011 if (CRM_Utils_System
::isNull($val)) {
6014 elseif (!empty($value['pseudoconstant'])) {
6015 // If pseudoconstant is set that is kind of defacto for 'we have a bit more info about this'
6016 // and we can use the metadata to figure it out.
6017 // ideally this bit of IF will absorb & replace all the rest in time as we move to
6018 // more metadata based choices.
6019 if (strpos($val, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
6020 $dbValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($val, CRM_Core_DAO
::VALUE_SEPARATOR
));
6021 foreach ($dbValues as $pseudoValue) {
6022 $convertedValues[] = CRM_Core_PseudoConstant
::getLabel($value['bao'], $value['idCol'], $pseudoValue);
6025 $dao->$key = ($usedForAPI) ?
$convertedValues : implode(', ', $convertedValues);
6026 $realFieldName = $this->_pseudoConstantsSelect
[$key]['field_name'] ??
NULL;
6027 if ($usedForAPI && $realFieldName) {
6028 // normally we would see 2 fields returned for pseudoConstants. An exception is
6029 // preferred_communication_method where there is no id-variant.
6030 // For the api we prioritise getting the real data returned.
6031 // over the resolved version
6032 $dao->$realFieldName = $dbValues;
6037 // This is basically the same as the default but since we have the bao we can use
6038 // a cached function.
6039 $dao->$key = CRM_Core_PseudoConstant
::getLabel($value['bao'], $value['idCol'], $val);
6042 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
6044 $idColumn = "{$key}_id";
6045 $dao->$idColumn = $val;
6047 if ($key == 'state_province_name') {
6048 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::stateProvince($val);
6051 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
6054 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
6055 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
6057 // @todo handle this in the section above for pseudoconstants.
6058 elseif (in_array($value['pseudoField'], ['participant_role_id', 'participant_role'])) {
6059 // @todo define bao on this & merge into the above condition.
6060 $viewValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $val);
6062 if ($value['pseudoField'] == 'participant_role') {
6063 $pseudoOptions = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'role_id');
6064 foreach ($viewValues as $k => $v) {
6065 $viewValues[$k] = $pseudoOptions[$v];
6068 $dao->$key = ($usedForAPI && count($viewValues) > 1) ?
$viewValues : implode(', ', $viewValues);
6071 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
6072 $dao->$key = $labels[$val];
6075 // return converted values in array format
6077 if (strpos($key, '-') !== FALSE) {
6078 $keyVal = explode('-', $key);
6079 $current = &$values;
6080 $lastElement = array_pop($keyVal);
6081 foreach ($keyVal as $v) {
6082 if (!array_key_exists($v, $current)) {
6085 $current = &$current[$v];
6087 $current[$lastElement] = $dao->$key;
6090 $values[$key] = $dao->$key;
6096 foreach ($this->legacyHackedFields
as $realField => $labelField) {
6097 // This is a temporary routine for handling these fields while
6098 // we figure out how to handled them based on metadata in
6099 /// export and search builder. CRM-19815, CRM-19830.
6100 if (isset($dao->$realField) && is_numeric($dao->$realField) && isset($dao->$labelField)) {
6101 $dao->$realField = $dao->$labelField;
6109 * Include pseudo fields LEFT JOIN.
6110 * @param string|array $sort can be a object or string
6112 * @return array|NULL
6114 public function includePseudoFieldsJoin($sort) {
6115 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
6118 $sort = is_string($sort) ?
$sort : $sort->orderBy();
6121 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
6122 if (!empty($value['table'])) {
6123 $regex = "/({$value['table']}\.|{$name})/";
6124 if (preg_match($regex, $sort)) {
6125 $this->_elemnt
[$value['element']] = 1;
6126 $this->_select
[$value['element']] = $value['select'];
6127 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
6128 $present[$value['table']] = $value['join'];
6132 $presentSimpleFrom = $present;
6134 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
6135 array_key_exists('civicrm_country', $presentSimpleFrom)
6137 unset($presentSimpleFrom['civicrm_country']);
6139 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
6140 array_key_exists('civicrm_country', $present)
6142 unset($present['civicrm_country']);
6145 $presentClause = $presentSimpleFromClause = NULL;
6146 if (!empty($present)) {
6147 $presentClause = implode(' ', $present);
6149 if (!empty($presentSimpleFrom)) {
6150 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
6153 $this->_fromClause
= $this->_fromClause
. $presentClause;
6154 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
6156 return [$presentClause, $presentSimpleFromClause];
6160 * Build qill for field.
6162 * Qill refers to the query detail visible on the UI.
6164 * @param string $daoName
6165 * @param string $fieldName
6166 * @param mixed $fieldValue
6168 * @param array $pseudoExtraParam
6170 * Type of the field per CRM_Utils_Type
6174 public static function buildQillForFieldValue(
6179 $pseudoExtraParam = [],
6180 $type = CRM_Utils_Type
::T_STRING
6182 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
6184 //API usually have fieldValue format as array(operator => array(values)),
6185 //so we need to separate operator out of fieldValue param
6186 if (is_array($fieldValue) && in_array(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
6187 $op = key($fieldValue);
6188 $fieldValue = $fieldValue[$op];
6191 // if Operator chosen is NULL/EMPTY then
6192 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
6193 return [CRM_Utils_Array
::value($op, $qillOperators, $op), ''];
6196 // @todo - if the right BAO is passed in special handling for the below
6197 // fields should not be required. testQillOptions.
6198 if ($fieldName == 'country_id') {
6199 $pseudoOptions = CRM_Core_PseudoConstant
::country();
6201 elseif ($fieldName == 'county_id') {
6202 $pseudoOptions = CRM_Core_PseudoConstant
::county();
6204 elseif ($fieldName == 'world_region') {
6205 $pseudoOptions = CRM_Core_PseudoConstant
::worldRegion();
6207 elseif ($daoName == 'CRM_Event_DAO_Event' && $fieldName == 'id') {
6208 $checkPermission = CRM_Utils_Array
::value('check_permission', $pseudoExtraParam, TRUE);
6209 $pseudoOptions = CRM_Event_BAO_Event
::getEvents(0, $fieldValue, TRUE, $checkPermission, TRUE);
6211 elseif ($fieldName == 'contribution_product_id') {
6212 $pseudoOptions = CRM_Contribute_PseudoConstant
::products();
6214 elseif ($daoName == 'CRM_Contact_DAO_Group' && $fieldName == 'id') {
6215 $pseudoOptions = CRM_Core_PseudoConstant
::group();
6217 elseif ($daoName == 'CRM_Batch_BAO_EntityBatch' && $fieldName == 'batch_id') {
6218 $pseudoOptions = CRM_Contribute_PseudoConstant
::batch();
6221 $pseudoOptions = CRM_Core_PseudoConstant
::get($daoName, $fieldName, $pseudoExtraParam);
6224 if (is_array($fieldValue)) {
6226 if (!empty($pseudoOptions)) {
6227 foreach ((array) $fieldValue as $val) {
6228 $qillString[] = CRM_Utils_Array
::value($val, $pseudoOptions, $val);
6230 $fieldValue = implode(', ', $qillString);
6233 if ($type == CRM_Utils_Type
::T_DATE
) {
6234 foreach ($fieldValue as $index => $value) {
6235 $fieldValue[$index] = CRM_Utils_Date
::customFormat($value);
6239 // @todo - this is a bit specific (one operator).
6240 // However it is covered by a unit test so can be altered later with
6242 if ($op === 'BETWEEN') {
6243 $separator = ' AND ';
6245 $fieldValue = implode($separator, $fieldValue);
6248 elseif (!empty($pseudoOptions) && array_key_exists($fieldValue, $pseudoOptions)) {
6249 $fieldValue = $pseudoOptions[$fieldValue];
6251 elseif ($type === CRM_Utils_Type
::T_DATE
) {
6252 $fieldValue = CRM_Utils_Date
::customFormat($fieldValue);
6255 return [CRM_Utils_Array
::value($op, $qillOperators, $op), $fieldValue];
6259 * Get the qill (search description for field) for the specified field.
6261 * @param string $daoName
6262 * @param string $name
6263 * @param string $value
6264 * @param string|array $op
6265 * @param string $label
6269 public static function getQillValue($daoName, string $name, $value, $op, string $label) {
6270 list($op, $value) = self
::buildQillForFieldValue($daoName, $name, $value, $op);
6271 return ts('%1 %2 %3', [1 => $label, 2 => $op, 3 => $value]);
6275 * Alter value to reflect wildcard settings.
6277 * The form will have tried to guess whether this is a good field to wildcard but there is
6278 * also a site-wide setting that specifies whether it is OK to append the wild card to the beginning
6279 * or only the end of the string
6281 * @param bool $wildcard
6282 * This is a bool made on an assessment 'elsewhere' on whether this is a good field to wildcard.
6284 * Generally '=' or 'LIKE'.
6285 * @param string $value
6286 * The search string.
6290 public static function getWildCardedValue($wildcard, $op, $value) {
6291 if ($wildcard && $op === 'LIKE') {
6292 if (CRM_Core_Config
::singleton()->includeWildCardInName
&& (substr($value, 0, 1) != '%')) {
6305 * Process special fields of Search Form in OK (Operator in Key) format
6307 * @param array $formValues
6308 * @param array $specialFields
6309 * Special params to be processed
6310 * @param array $changeNames
6311 * Array of fields whose name should be changed
6313 public static function processSpecialFormValue(&$formValues, $specialFields, $changeNames = []) {
6314 // Array of special fields whose value are considered only for NULL or EMPTY operators
6315 $nullableFields = ['contribution_batch_id'];
6317 foreach ($specialFields as $element) {
6318 $value = $formValues[$element] ??
NULL;
6320 if (is_array($value)) {
6321 if (in_array($element, array_keys($changeNames))) {
6322 unset($formValues[$element]);
6323 $element = $changeNames[$element];
6325 $formValues[$element] = ['IN' => $value];
6327 elseif (in_array($value, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
6328 $formValues[$element] = [$value => 1];
6330 elseif (!in_array($element, $nullableFields)) {
6331 // if wildcard is already present return searchString as it is OR append and/or prepend with wildcard
6332 $isWilcard = strstr($value, '%') ?
FALSE : CRM_Core_Config
::singleton()->includeWildCardInName
;
6333 $formValues[$element] = ['LIKE' => self
::getWildCardedValue($isWilcard, 'LIKE', $value)];
6340 * Parse and assimilate the various sort options.
6342 * Side-effect: if sorting on a common column from a related table (`city`, `postal_code`,
6343 * `email`), the related table may be joined automatically.
6345 * At time of writing, this code is deeply flawed and should be rewritten. For the moment,
6346 * it's been extracted to a standalone function.
6348 * @param string|CRM_Utils_Sort $sort
6349 * The order by string.
6350 * @param null $sortOrder
6351 * Who knows? Hu knows. He who knows Hu knows who.
6354 * list(string $orderByClause, string $additionalFromClause).
6356 * @throws \CRM_Core_Exception
6358 protected function prepareOrderBy($sort, $sortOrder) {
6362 if (CRM_Core_Config
::singleton()->includeOrderByClause ||
6363 isset($this->_distinctComponentClause
)
6366 if (is_string($sort)) {
6370 $orderBy = trim($sort->orderBy());
6372 // Deliberately remove the backticks again, as they mess up the evil
6373 // string munging below. This balanced by re-escaping before use.
6374 $orderBy = str_replace('`', '', $orderBy);
6376 if (!empty($orderBy)) {
6377 // this is special case while searching for
6378 // change log CRM-1718
6379 if (preg_match('/sort_name/i', $orderBy)) {
6380 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
6384 $orderBy .= " $sortOrder";
6387 // always add contact_a.id to the ORDER clause
6388 // so the order is deterministic
6389 if (strpos('contact_a.id', $orderBy) === FALSE) {
6390 $orderBy .= ", contact_a.id";
6395 $orderBy = " contact_a.sort_name ASC, contact_a.id";
6401 // Remove this here & add it at the end for simplicity.
6402 $order = trim($orderBy);
6403 $orderByArray = explode(',', $order);
6405 foreach ($orderByArray as $orderByClause) {
6406 $orderByClauseParts = explode(' ', trim($orderByClause));
6407 $field = $orderByClauseParts[0];
6408 $direction = $orderByClauseParts[1] ??
'asc';
6409 $fieldSpec = $this->getMetadataForRealField($field);
6411 // This is a hacky add-in for primary address joins. Feel free to iterate as it is unit tested.
6412 // @todo much more cleanup on location handling in addHierarchical elements. Potentially
6413 // add keys to $this->fields to represent the actual keys for locations.
6414 if (empty($fieldSpec) && substr($field, 0, 2) === '1-') {
6415 $fieldSpec = $this->getMetadataForField(substr($field, 2));
6416 $this->addAddressTable('1-' . str_replace('civicrm_', '', $fieldSpec['table_name']), 'is_primary = 1');
6419 if ($this->_returnProperties
=== []) {
6420 if (!empty($fieldSpec['table_name']) && !isset($this->_tables
[$fieldSpec['table_name']])) {
6421 $this->_tables
[$fieldSpec['table_name']] = 1;
6422 $order = $fieldSpec['where'] . ' ' . $direction;
6426 $cfID = CRM_Core_BAO_CustomField
::getKeyID($field);
6427 // add to cfIDs array if not present
6428 if (!empty($cfID) && !array_key_exists($cfID, $this->_cfIDs
)) {
6429 $this->_cfIDs
[$cfID] = [];
6430 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
6431 $this->_customQuery
->query();
6432 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
6433 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
6436 // By replacing the join to the option value table with the mysql construct
6437 // ORDER BY field('contribution_status_id', 2,1,4)
6438 // we can remove a join. In the case of the option value join it is
6439 /// a join known to cause slow queries.
6440 // @todo cover other pseudoconstant types. Limited to option group ones & Foreign keys
6441 // matching an id+name parrern in the
6442 // first instance for scope reasons. They require slightly different handling as the column (label)
6443 // is not declared for them.
6444 // @todo so far only integer fields are being handled. If we add string fields we need to look at
6446 $pseudoConstantMetadata = CRM_Utils_Array
::value('pseudoconstant', $fieldSpec, FALSE);
6447 if (!empty($pseudoConstantMetadata)
6449 if (!empty($pseudoConstantMetadata['optionGroupName'])
6450 ||
$this->isPseudoFieldAnFK($fieldSpec)
6452 // dev/core#1305 @todo this is not the right thing to do but for now avoid fatal error
6453 if (empty($fieldSpec['bao'])) {
6456 $sortedOptions = $fieldSpec['bao']::buildOptions($fieldSpec['name']);
6457 natcasesort($sortedOptions);
6458 $fieldIDsInOrder = implode(',', array_keys($sortedOptions));
6459 // Pretty sure this validation ALSO happens in the order clause & this can't be reached but...
6460 // this might give some early warning.
6461 CRM_Utils_Type
::validate($fieldIDsInOrder, 'CommaSeparatedIntegers');
6462 // use where if it's set to fully qualify ambiguous column names
6463 // i.e. civicrm_contribution.contribution_status_id instead of contribution_status_id
6464 $pseudoColumnName = $fieldSpec['where'] ??
$fieldSpec['name'];
6465 $order = str_replace("$field", "field($pseudoColumnName,$fieldIDsInOrder)", $order);
6467 //CRM-12565 add "`" around $field if it is a pseudo constant
6468 // This appears to be for 'special' fields like locations with appended numbers or hyphens .. maybe.
6469 if (!empty($pseudoConstantMetadata['element']) && $pseudoConstantMetadata['element'] == $field) {
6470 $order = str_replace($field, "`{$field}`", $order);
6475 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6476 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6478 // The above code relies on crazy brittle string manipulation of a peculiarly-encoded ORDER BY
6479 // clause. But this magic helper which forgivingly reescapes ORDER BY.
6481 $order = CRM_Utils_Type
::escape($order, 'MysqlOrderBy');
6482 return ' ORDER BY ' . $order;
6487 * Convert a string of group IDs to a string of group labels.
6489 * The original string may include duplicates and groups the user does not have
6490 * permission to see.
6492 * @param CRM_Core_DAO $dao
6493 * @param string $val
6497 public function convertGroupIDStringToLabelString(&$dao, $val) {
6498 $groupIDs = explode(',', $val);
6499 // Note that groups that the user does not have permission to will be excluded (good).
6500 $groups = array_intersect_key(CRM_Core_PseudoConstant
::group(), array_flip($groupIDs));
6501 return implode(', ', $groups);
6506 * Set the qill and where properties for a field.
6508 * This function is intended as a short-term function to encourage refactoring
6509 * & re-use - but really we should just have less special-casing.
6511 * @param string $name
6513 * @param string|array $value
6514 * @param string $grouping
6515 * @param array $field
6517 * @throws \CRM_Core_Exception
6519 public function setQillAndWhere($name, $op, $value, $grouping, $field) {
6520 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
6521 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
6522 $this->_qill
[$grouping][] = ts("%1 %2 %3", [
6523 1 => $field['title'],
6530 * Has the pseudoconstant of the field been requested.
6532 * For example if the field is payment_instrument_id then it
6533 * has been requested if either payment_instrument_id or payment_instrument
6534 * have been requested. Payment_instrument is the option groun name field value.
6536 * @param array $field
6537 * @param string $fieldName
6538 * The unique name of the field - ie. the one it will be aliased to in the query.
6542 private function pseudoConstantNameIsInReturnProperties($field, $fieldName = NULL) {
6543 $realField = $this->getMetadataForRealField($fieldName);
6544 if (!isset($realField['pseudoconstant'])) {
6547 $pseudoConstant = $realField['pseudoconstant'];
6548 if (empty($pseudoConstant['optionGroupName']) &&
6549 CRM_Utils_Array
::value('labelColumn', $pseudoConstant) !== 'name') {
6550 // We are increasing our pseudoconstant handling - but still very cautiously,
6551 // hence the check for labelColumn === name
6555 if (!empty($pseudoConstant['optionGroupName']) && !empty($this->_returnProperties
[$pseudoConstant['optionGroupName']])) {
6558 if (!empty($this->_returnProperties
[$fieldName])) {
6561 // Is this still required - the above goes off the unique name. Test with things like
6562 // communication_preferences & prefix_id.
6563 if (!empty($this->_returnProperties
[$field['name']])) {
6570 * Get Select Clause.
6574 public function getSelect() {
6575 $select = 'SELECT ';
6576 if (isset($this->_distinctComponentClause
)) {
6577 $select .= "{$this->_distinctComponentClause}, ";
6579 $select .= implode(', ', $this->_select
);
6584 * Add basic statistics to the summary.
6586 * @param array $summary
6587 * @param string $where
6588 * @param string $from
6591 * @throws \CRM_Core_Exception
6593 protected function addBasicStatsToSummary(&$summary, $where, $from) {
6594 $summary['total']['count'] = 0;
6595 $summary['total']['amount'] = $summary['total']['avg'] = [];
6598 SELECT COUNT( conts.total_amount ) as total_count,
6599 SUM( conts.total_amount ) as total_amount,
6600 AVG( conts.total_amount ) as total_avg,
6601 conts.currency as currency
6603 SELECT civicrm_contribution.total_amount, COUNT(civicrm_contribution.total_amount) as civicrm_contribution_total_amount_count,
6604 civicrm_contribution.currency
6606 $where AND civicrm_contribution.contribution_status_id = 1
6607 GROUP BY civicrm_contribution.id
6611 $dao = CRM_Core_DAO
::executeQuery($query);
6613 while ($dao->fetch()) {
6614 $summary['total']['count'] +
= $dao->total_count
;
6615 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
6616 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
6619 if (!empty($summary['total']['amount'])) {
6620 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
6621 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
6624 $summary['total']['amount'] = $summary['total']['avg'] = 0;
6630 * Add basic soft credit statistics to summary array.
6632 * @param array $summary
6633 * @param string $where
6634 * @param string $from
6636 * @throws \CRM_Core_Exception
6638 protected function addBasicSoftCreditStatsToStats(&$summary, $where, $from) {
6640 SELECT COUNT( conts.total_amount ) as total_count,
6641 SUM( conts.total_amount ) as total_amount,
6642 AVG( conts.total_amount ) as total_avg,
6643 conts.currency as currency
6645 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency
6647 $where AND civicrm_contribution.contribution_status_id = 1 AND civicrm_contribution_soft.id IS NOT NULL
6648 GROUP BY civicrm_contribution_soft.id
6652 $dao = CRM_Core_DAO
::executeQuery($query);
6653 $summary['soft_credit']['count'] = 0;
6654 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = [];
6655 while ($dao->fetch()) {
6656 $summary['soft_credit']['count'] +
= $dao->total_count
;
6657 $summary['soft_credit']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
6658 $summary['soft_credit']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
6660 if (!empty($summary['soft_credit']['amount'])) {
6661 $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
6662 $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
6665 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
6670 * Add basic stats about cancelled contributions to the summary.
6672 * @param array $summary
6673 * @param string $where
6674 * @param string $from
6676 * @throws \CRM_Core_Exception
6678 protected function addBasicCancelStatsToSummary(&$summary, $where, $from) {
6680 SELECT COUNT( conts.total_amount ) as cancel_count,
6681 SUM( conts.total_amount ) as cancel_amount,
6682 AVG( conts.total_amount ) as cancel_avg,
6683 conts.currency as currency
6685 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency
6687 $where AND civicrm_contribution.cancel_date IS NOT NULL
6688 GROUP BY civicrm_contribution.id
6692 $dao = CRM_Core_DAO
::executeQuery($query);
6695 if ($dao->fetch()) {
6696 $summary['cancel']['count'] = $dao->cancel_count
;
6697 $summary['cancel']['amount'] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
6698 $summary['cancel']['avg'] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
6702 $summary['cancel']['count'] = 0;
6703 $summary['cancel']['amount'] = $summary['cancel']['avg'] = [];
6704 while ($dao->fetch()) {
6705 $summary['cancel']['count'] +
= $dao->cancel_count
;
6706 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
6707 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
6709 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
6710 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
6715 * Create the sql query for an contact search.
6717 * @param int $offset
6718 * The offset for the query.
6719 * @param int $rowCount
6720 * The number of rows to return.
6721 * @param string|CRM_Utils_Sort $sort
6722 * The order by string.
6723 * @param bool $count
6724 * Is this a count only query ?.
6725 * @param bool $includeContactIds
6726 * Should we include contact ids?.
6727 * @param bool $sortByChar
6728 * If true returns the distinct array of first characters for search results.
6729 * @param bool $groupContacts
6730 * If true, return only the contact ids.
6731 * @param string $additionalWhereClause
6732 * If the caller wants to further restrict the search (used for components).
6733 * @param null $sortOrder
6734 * @param string $additionalFromClause
6735 * Should be clause with proper joins, effective to reduce where clause load.
6737 * @param bool $skipOrderAndLimit
6741 * @throws \CRM_Core_Exception
6743 public function getSearchSQL(
6744 $offset = 0, $rowCount = 0, $sort = NULL,
6745 $count = FALSE, $includeContactIds = FALSE,
6746 $sortByChar = FALSE, $groupContacts = FALSE,
6747 $additionalWhereClause = NULL, $sortOrder = NULL,
6748 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE) {
6750 $sqlParts = $this->getSearchSQLParts($offset, $rowCount, $sort, $count, $includeContactIds, $sortByChar, $groupContacts, $additionalWhereClause, $sortOrder, $additionalFromClause);
6753 CRM_Core_Error
::deprecatedFunctionWarning('sort by char is deprecated - use alphabetQuery method');
6754 $sqlParts['order_by'] = 'ORDER BY sort_name asc';
6757 if ($skipOrderAndLimit) {
6758 CRM_Core_Error
::deprecatedFunctionWarning('skipOrderAndLimit is deprected - call getSearchSQLParts & construct it in the calling function');
6759 $query = "{$sqlParts['select']} {$sqlParts['from']} {$sqlParts['where']} {$sqlParts['having']} {$sqlParts['group_by']}";
6762 $query = "{$sqlParts['select']} {$sqlParts['from']} {$sqlParts['where']} {$sqlParts['having']} {$sqlParts['group_by']} {$sqlParts['order_by']} {$sqlParts['limit']}";
6768 * Get the component parts of the search query as an array.
6770 * @param int $offset
6771 * The offset for the query.
6772 * @param int $rowCount
6773 * The number of rows to return.
6774 * @param string|CRM_Utils_Sort $sort
6775 * The order by string.
6776 * @param bool $count
6777 * Is this a count only query ?.
6778 * @param bool $includeContactIds
6779 * Should we include contact ids?.
6780 * @param bool $sortByChar
6781 * If true returns the distinct array of first characters for search results.
6782 * @param bool $groupContacts
6783 * If true, return only the contact ids.
6784 * @param string $additionalWhereClause
6785 * If the caller wants to further restrict the search (used for components).
6786 * @param null $sortOrder
6787 * @param string $additionalFromClause
6788 * Should be clause with proper joins, effective to reduce where clause load.
6791 * @throws \CRM_Core_Exception
6793 public function getSearchSQLParts($offset = 0, $rowCount = 0, $sort = NULL,
6794 $count = FALSE, $includeContactIds = FALSE,
6795 $sortByChar = FALSE, $groupContacts = FALSE,
6796 $additionalWhereClause = NULL, $sortOrder = NULL,
6797 $additionalFromClause = NULL) {
6798 if ($includeContactIds) {
6799 $this->_includeContactIds
= TRUE;
6800 $this->_whereClause
= $this->whereClause();
6802 $onlyDeleted = in_array([
6810 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
6811 // and that contact happens to be deleted, set $onlyDeleted to true
6812 foreach ($this->_params
as $values) {
6813 $name = $values[0] ??
NULL;
6814 $op = $values[1] ??
NULL;
6815 $value = $values[2] ??
NULL;
6816 if ($name === 'contact_id' and $op === '=') {
6817 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
6818 $onlyDeleted = TRUE;
6824 // building the query string
6825 $groupBy = $groupByCols = NULL;
6827 if (isset($this->_groupByComponentClause
)) {
6828 $groupByCols = preg_replace('/^GROUP BY /', '', trim($this->_groupByComponentClause
));
6829 $groupByCols = explode(', ', $groupByCols);
6831 elseif ($this->_useGroupBy
) {
6832 $groupByCols = ['contact_a.id'];
6835 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
6836 $groupByCols = ['civicrm_activity.id'];
6838 if (!empty($groupByCols)) {
6839 $groupBy = " GROUP BY " . implode(', ', $groupByCols);
6842 $order = $orderBy = '';
6845 $order = $this->prepareOrderBy($sort, $sortOrder);
6848 // Cases where we are disabling FGB (FULL_GROUP_BY_MODE):
6849 // 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
6850 // clause. This will impact the search query output.
6851 $disableFullGroupByMode = (!empty($groupBy) ||
$groupContacts);
6853 if ($disableFullGroupByMode) {
6854 CRM_Core_DAO
::disableFullGroupByMode();
6858 $this->_sort
= $sort;
6861 $this->includePseudoFieldsJoin($sort);
6863 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
6865 if ($additionalWhereClause) {
6866 $where = $where . ' AND ' . $additionalWhereClause;
6869 //additional from clause should be w/ proper joins.
6870 if ($additionalFromClause) {
6871 $from .= "\n" . $additionalFromClause;
6874 // if we are doing a transform, do it here
6875 // use the $from, $where and $having to get the contact ID
6876 if ($this->_displayRelationshipType
) {
6877 $this->filterRelatedContacts($from, $where, $having);
6879 $limit = (!$count && $rowCount) ?
" LIMIT " . CRM_Utils_Type
::escape($offset, 'Int') . ", " . CRM_Utils_Type
::escape($rowCount, 'Int') : '';
6882 'select' => $select,
6885 'order_by' => $order,
6886 'group_by' => $groupBy,
6887 'having' => $having,
6893 * Get the metadata for a given field.
6895 * @param string $fieldName
6899 protected function getMetadataForField($fieldName) {
6900 if ($fieldName === 'contact_a.id') {
6901 // This seems to be the only anomaly.
6904 $pseudoField = $this->_pseudoConstantsSelect
[$fieldName] ??
[];
6905 $field = $this->_fields
[$fieldName] ??
$pseudoField;
6906 $field = array_merge($field, $pseudoField);
6907 if (!empty($field) && empty($field['name'])) {
6908 // standardising field formatting here - over time we can phase out variants.
6909 // all paths using this currently unit tested
6910 $field['name'] = CRM_Utils_Array
::value('field_name', $field, CRM_Utils_Array
::value('idCol', $field, $fieldName));
6916 * Get the metadata for a given field, returning the 'real field' if it is a pseudofield.
6918 * @param string $fieldName
6922 public function getMetadataForRealField($fieldName) {
6923 $field = $this->getMetadataForField($fieldName);
6924 if (!empty($field['is_pseudofield_for'])) {
6925 $field = $this->getMetadataForField($field['is_pseudofield_for']);
6926 $field['pseudofield_name'] = $fieldName;
6928 elseif (!empty($field['pseudoconstant'])) {
6929 if (!empty($field['pseudoconstant']['optionGroupName'])) {
6930 $field['pseudofield_name'] = $field['pseudoconstant']['optionGroupName'];
6931 if (empty($field['table_name'])) {
6932 if (!empty($field['where'])) {
6933 $field['table_name'] = explode('.', $field['where'])[0];
6936 $field['table_name'] = 'civicrm_contact';
6945 * If we have a field that is better rendered via the pseudoconstant handled them here.
6947 * Rather than joining in the additional table we render the option value on output.
6949 * @todo - so far this applies to a narrow range of pseudocontants. We are adding them
6950 * carefully with test coverage but aim to extend.
6952 * @param string $name
6954 protected function addPseudoconstantFieldToSelect($name) {
6955 $field = $this->getMetadataForRealField($name);
6956 $realFieldName = $field['name'];
6957 $pseudoFieldName = $field['pseudofield_name'] ??
NULL;
6958 if ($pseudoFieldName) {
6959 // @todo - we don't really need to build this array now we have metadata more available with getMetadataForField fn.
6960 $this->_pseudoConstantsSelect
[$pseudoFieldName] = [
6961 'pseudoField' => $pseudoFieldName,
6962 'idCol' => $realFieldName,
6963 'field_name' => $field['name'],
6964 'bao' => $field['bao'],
6965 'pseudoconstant' => $field['pseudoconstant'],
6969 $this->_tables
[$field['table_name']] = 1;
6970 $this->_element
[$realFieldName] = 1;
6971 $this->_select
[$field['name']] = str_replace('civicrm_contact.', 'contact_a.', "{$field['where']} as `$realFieldName`");
6975 * Is this pseudofield a foreign key constraint.
6977 * We are trying to cautiously expand our pseudoconstant handling. This check allows us
6978 * to extend to a narrowly defined type (and then only if the pseudofield is in the fields
6979 * array which is done for contributions which are mostly handled as pseudoconstants.
6985 protected function isPseudoFieldAnFK($fieldSpec) {
6986 if (empty($fieldSpec['FKClassName'])
6987 || CRM_Utils_Array
::value('keyColumn', $fieldSpec['pseudoconstant']) !== 'id'
6988 || CRM_Utils_Array
::value('labelColumn', $fieldSpec['pseudoconstant']) !== 'name') {
6995 * Is the field a relative date field.
6997 * @param string $fieldName
7001 protected function isARelativeDateField($fieldName) {
7002 if (substr($fieldName, -9, 9) !== '_relative') {
7005 $realField = substr($fieldName, 0, strlen($fieldName) - 9);
7006 return isset($this->_fields
[$realField]);
7010 * Get the specifications for the field, if available.
7012 * @param string $fieldName
7013 * Fieldname as displayed on the form.
7017 public function getFieldSpec($fieldName) {
7018 if (isset($this->_fields
[$fieldName])) {
7019 $fieldSpec = $this->_fields
[$fieldName];
7020 if (!empty($fieldSpec['is_pseudofield_for'])) {
7021 $fieldSpec = array_merge($this->_fields
[$fieldSpec['is_pseudofield_for']], $this->_fields
[$fieldName]);
7025 $lowFieldName = str_replace('_low', '', $fieldName);
7026 if (isset($this->_fields
[$lowFieldName])) {
7027 return array_merge($this->_fields
[$lowFieldName], ['field_name' => $lowFieldName]);
7029 $highFieldName = str_replace('_high', '', $fieldName);
7030 if (isset($this->_fields
[$highFieldName])) {
7031 return array_merge($this->_fields
[$highFieldName], ['field_name' => $highFieldName]);
7036 public function buildWhereForDate() {
7041 * Is the field a relative date field.
7043 * @param string $fieldName
7047 protected function isADateRangeField($fieldName) {
7048 if (substr($fieldName, -4, 4) !== '_low' && substr($fieldName, -5, 5) !== '_high') {
7051 return !empty($this->getFieldSpec($fieldName));
7057 protected function buildRelativeDateQuery(&$values) {
7058 $value = $values[2] ??
NULL;
7059 if (empty($value)) {
7062 $fieldName = substr($values[0], 0, strlen($values[0]) - 9);
7063 $fieldSpec = $this->_fields
[$fieldName];
7064 $tableName = $fieldSpec['table_name'];
7065 $filters = CRM_Core_OptionGroup
::values('relative_date_filters');
7066 $grouping = $values[3] ??
NULL;
7067 // If the table value is already set for a custom field it will be more nuanced than just '1'.
7068 $this->_tables
[$tableName] = $this->_tables
[$tableName] ??
1;
7069 $this->_whereTables
[$tableName] = $this->_whereTables
[$tableName] ??
1;
7071 $dates = CRM_Utils_Date
::getFromTo($value, NULL, NULL);
7072 // Where end would be populated only if we are handling one of the weird ones with different from & to fields.
7073 $secondWhere = $fieldSpec['where_end'] ??
$fieldSpec['where'];
7075 $where = $fieldSpec['where'];
7076 if ($fieldSpec['table_name'] === 'civicrm_contact') {
7077 // Special handling for contact table as it has a known alias in advanced search.
7078 $where = str_replace('civicrm_contact.', 'contact_a.', $where);
7079 $secondWhere = str_replace('civicrm_contact.', 'contact_a.', $secondWhere);
7082 $this->_qill
[$grouping][] = $this->getQillForRelativeDateRange($dates[0], $dates[1], $fieldSpec['title'], $filters[$value]);
7083 if ($fieldName === 'relation_active_period_date') {
7084 // Hack this to fix regression https://lab.civicrm.org/dev/core/issues/1592
7085 // Not sure the 'right' fix.
7086 $this->_where
[$grouping] = [self
::getRelationshipActivePeriodClauses($dates[0], $dates[1], TRUE)];
7090 if (empty($dates[0])) {
7091 // ie. no start date we only have end date
7092 $this->_where
[$grouping][] = $secondWhere . " <= '{$dates[1]}'";
7094 elseif (empty($dates[1])) {
7096 // ie. no end date we only have start date
7097 $this->_where
[$grouping][] = $where . " >= '{$dates[0]}'";
7100 // we have start and end dates.
7101 if ($secondWhere !== $where) {
7102 $this->_where
[$grouping][] = $where . ">= '{$dates[0]}' AND $secondWhere <='{$dates[1]}'";
7105 $this->_where
[$grouping][] = $where . " BETWEEN '{$dates[0]}' AND '{$dates[1]}'";
7111 * Build the query for a date field if it is a _high or _low field.
7116 * @throws \CRM_Core_Exception
7118 public function buildDateRangeQuery($values) {
7119 if ($this->isADateRangeField($values[0])) {
7120 $fieldSpec = $this->getFieldSpec($values[0]);
7121 $title = empty($fieldSpec['unique_title']) ?
$fieldSpec['title'] : $fieldSpec['unique_title'];
7122 $this->dateQueryBuilder($values, $fieldSpec['table_name'], $fieldSpec['field_name'], $fieldSpec['name'], $title);
7129 * Add the address table into the query.
7131 * @param string $tableKey
7132 * @param string $joinCondition
7138 protected function addAddressTable($tableKey, $joinCondition) {
7139 $tName = "$tableKey-address";
7140 $aName = "`$tableKey-address`";
7141 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
7142 $this->_element
["{$tName}_id"] = 1;
7143 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$joinCondition)";
7144 $this->_tables
[$tName] = $addressJoin;
7153 * Get the clause for group status.
7155 * @param int $grouping
7159 protected function getGroupStatusClause($grouping) {
7160 $statuses = $this->getSelectedGroupStatuses($grouping);
7161 return "status IN (" . implode(', ', $statuses) . ")";
7165 * Get an array of the statuses that have been selected.
7167 * @param string $grouping
7171 * @throws \CRM_Core_Exception
7173 protected function getSelectedGroupStatuses($grouping) {
7175 $gcsValues = $this->getWhereValues('group_contact_status', $grouping);
7177 is_array($gcsValues[2])
7179 foreach ($gcsValues[2] as $k => $v) {
7181 $statuses[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
7186 $statuses[] = "'Added'";
7192 * Get the qill value for the field.
7194 * @param string $name
7195 * @param array|int|string $value
7197 * @param array $fieldSpec
7198 * @param string $labelOverride
7199 * Label override, if required.
7203 public function getQillForField($name, $value, $op, $fieldSpec = [], $labelOverride = NULL): string {
7204 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue($fieldSpec['bao'] ??
NULL, $name, $value, $op);
7205 return (string) ts("%1 %2 %3", [
7206 1 => $labelOverride ??
$fieldSpec['title'],
7213 * Where handling for any field with adequately defined metadata.
7215 * @param array $fieldSpec
7216 * @param string $name
7217 * @param string|array|int $value
7219 * @param string|int $grouping
7221 * @throws \CRM_Core_Exception
7223 public function handleWhereFromMetadata($fieldSpec, $name, $value, $op, $grouping = 0) {
7224 $this->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause($fieldSpec['where'], $op, $value, CRM_Utils_Type
::typeToString($fieldSpec['type']));
7225 $this->_qill
[$grouping][] = $this->getQillForField($name, $value, $op, $fieldSpec);
7226 if (!isset($this->_tables
[$fieldSpec['table_name']])) {
7227 $this->_tables
[$fieldSpec['table_name']] = 1;
7229 if (!isset($this->_whereTables
[$fieldSpec['table_name']])) {
7230 $this->_whereTables
[$fieldSpec['table_name']] = 1;
7235 * Get the qill for the relative date range.
7237 * @param string|null $from
7238 * @param string|null $to
7239 * @param string $fieldTitle
7240 * @param string $relativeRange
7244 protected function getQillForRelativeDateRange($from, $to, string $fieldTitle, string $relativeRange): string {
7246 return ts('%1 is ', [$fieldTitle]) . $relativeRange . ' (' . ts('to %1', [CRM_Utils_Date
::customFormat($to)]) . ')';
7249 return ts('%1 is ', [$fieldTitle]) . $relativeRange . ' (' . ts('from %1', [CRM_Utils_Date
::customFormat($from)]) . ')';
7251 return ts('%1 is ', [$fieldTitle]) . $relativeRange . ' (' . ts('between %1 and %2', [
7252 CRM_Utils_Date
::customFormat($from),
7253 CRM_Utils_Date
::customFormat($to),