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 // Add hack as no unique name is defined for the field but the search form is in denial.
521 $this->_fields
['activity_priority_id'] = $this->_fields
['priority_id'];
523 // add any fields provided by hook implementers
524 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
525 $this->_fields
= array_merge($this->_fields
, $extFields);
528 // basically do all the work once, and then reuse it
529 $this->initialize($apiEntity);
533 * Function which actually does all the work for the constructor.
535 * @param string $apiEntity
536 * The api entity being called.
537 * This sort-of duplicates $mode in a confusing way. Probably not by design.
539 * @throws \CRM_Core_Exception
541 public function initialize($apiEntity = NULL) {
543 $this->_element
= [];
545 $this->_whereTables
= [];
548 $this->_options
= [];
550 $this->_paramLookup
= [];
553 $this->_customQuery
= NULL;
555 // reset cached static variables - CRM-5803
556 self
::$_activityRole = NULL;
557 self
::$_considerCompActivities = NULL;
558 self
::$_withContactActivitiesOnly = NULL;
560 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
561 $this->_element
['contact_id'] = 1;
562 $this->_tables
['civicrm_contact'] = 1;
564 if (!empty($this->_params
)) {
565 $this->buildParamsLookup();
568 $this->_whereTables
= $this->_tables
;
570 $this->selectClause($apiEntity);
571 if (!empty($this->_cfIDs
)) {
572 // @todo This function is the select function but instead of running 'select' it
573 // is running the whole query.
574 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
575 $this->_customQuery
->query();
576 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
577 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
578 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
579 $this->_options
= $this->_customQuery
->_options
;
581 $isForcePrimaryOnly = !empty($apiEntity);
582 $this->_whereClause
= $this->whereClause($isForcePrimaryOnly);
583 if (array_key_exists('civicrm_contribution', $this->_whereTables
)) {
584 $component = 'contribution';
586 if (array_key_exists('civicrm_membership', $this->_whereTables
)) {
587 $component = 'membership';
589 if (isset($component) && !$this->_skipPermission
) {
590 // Unit test coverage in api_v3_FinancialTypeACLTest::testGetACLContribution.
591 CRM_Financial_BAO_FinancialType
::buildPermissionedClause($this->_whereClause
, $component);
594 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
, $apiEntity);
595 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
597 $this->openedSearchPanes(TRUE);
601 * Function for same purpose as convertFormValues.
603 * Like convert form values this function exists to pre-Process parameters from the form.
605 * It is unclear why they are different functions & likely relates to advances search
606 * versus search builder.
608 * The direction we are going is having the form convert values to a standardised format &
609 * moving away from weird & wonderful where clause switches.
611 * Fix and handle contact deletion nicely.
613 * this code is primarily for search builder use case where different clauses can specify if they want deleted.
617 public function buildParamsLookup() {
618 $trashParamExists = FALSE;
620 foreach ($this->_params
as $k => $param) {
621 if (!empty($param[0]) && $param[0] == 'contact_is_deleted') {
622 $trashParamExists = TRUE;
624 if (!empty($param[3])) {
625 $paramByGroup[$param[3]][$k] = $param;
629 if ($trashParamExists) {
630 $this->_skipDeleteClause
= TRUE;
632 //cycle through group sets and explicitly add trash param if not set
633 foreach ($paramByGroup as $setID => $set) {
635 !in_array(['contact_is_deleted', '=', '1', $setID, '0'], $this->_params
) &&
636 !in_array(['contact_is_deleted', '=', '0', $setID, '0'], $this->_params
)
639 'contact_is_deleted',
649 foreach ($this->_params
as $value) {
650 if (empty($value[0])) {
653 $cfID = CRM_Core_BAO_CustomField
::getKeyID(str_replace(['_relative', '_low', '_high', '_to', '_high'], '', $value[0]));
655 if (!array_key_exists($cfID, $this->_cfIDs
)) {
656 $this->_cfIDs
[$cfID] = [];
658 // Set wildcard value based on "and/or" selection
659 foreach ($this->_params
as $key => $param) {
660 if ($param[0] == $value[0] . '_operator') {
661 $value[4] = $param[2] == 'or';
665 $this->_cfIDs
[$cfID][] = $value;
668 if (!array_key_exists($value[0], $this->_paramLookup
)) {
669 $this->_paramLookup
[$value[0]] = [];
671 if ($value[0] !== 'group') {
672 // Just trying to unravel how group interacts here! This whole function is weird.
673 $this->_paramLookup
[$value[0]][] = $value;
679 * Some composite fields do not appear in the fields array hack to make them part of the query.
682 * The api entity being called.
683 * This sort-of duplicates $mode in a confusing way. Probably not by design.
685 public function addSpecialFields($apiEntity) {
686 static $special = ['contact_type', 'contact_sub_type', 'sort_name', 'display_name'];
687 // if get called via Contact.get API having address_id as return parameter
688 if ($apiEntity === 'Contact') {
689 $special[] = 'address_id';
691 foreach ($special as $name) {
692 if (!empty($this->_returnProperties
[$name])) {
693 if ($name === 'address_id') {
694 $this->_tables
['civicrm_address'] = 1;
695 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
696 $this->_element
['address_id'] = 1;
699 $this->_select
[$name] = "contact_a.{$name} as $name";
700 $this->_element
[$name] = 1;
707 * Given a list of conditions in params and a list of desired
708 * return Properties generate the required select and from
709 * clauses. Note that since the where clause introduces new
710 * tables, the initial attempt also retrieves all variables used
713 * @param string $apiEntity
714 * The api entity being called.
715 * This sort-of duplicates $mode in a confusing way. Probably not by design.
717 public function selectClause($apiEntity = NULL) {
719 // @todo Tidy up this. This arises because 1) we are ignoring the $mode & adding a new
720 // param ($apiEntity) instead - presumably an oversight & 2 because
721 // contact is not implemented as a component.
722 $this->addSpecialFields($apiEntity);
724 foreach ($this->_fields
as $name => $field) {
725 // skip component fields
726 // there are done by the alter query below
727 // and need not be done on every field
728 // @todo remove these & handle using metadata - only obscure fields
729 // that are hack-added should need to be excluded from the main loop.
731 (substr($name, 0, 12) === 'participant_') ||
732 (substr($name, 0, 7) === 'pledge_') ||
733 (substr($name, 0, 5) === 'case_')
738 // redirect to activity select clause
740 (substr($name, 0, 9) === 'activity_') ||
741 ($name === 'parent_id')
743 CRM_Activity_BAO_Query
::select($this);
746 // if this is a hierarchical name, we ignore it
747 $names = explode('-', $name);
748 if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) {
752 // make an exception for special cases, to add the field in select clause
753 $makeException = FALSE;
755 //special handling for groups/tags
756 if (in_array($name, ['groups', 'tags', 'notes'])
757 && isset($this->_returnProperties
[substr($name, 0, -1)])
759 // @todo instead of setting make exception to get us into
760 // an if clause that has handling for these fields buried with in it
761 // move the handling to here.
762 $makeException = TRUE;
765 // since note has 3 different options we need special handling
766 // note / note_subject / note_body
767 if ($name === 'notes') {
768 foreach (['note', 'note_subject', 'note_body'] as $noteField) {
769 if (isset($this->_returnProperties
[$noteField])) {
770 $makeException = TRUE;
776 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
778 !empty($this->_paramLookup
[$name])
779 ||
!empty($this->_returnProperties
[$name])
780 ||
$this->pseudoConstantNameIsInReturnProperties($field, $name)
784 // add to cfIDs array if not present
785 if (!array_key_exists($cfID, $this->_cfIDs
)) {
786 $this->_cfIDs
[$cfID] = [];
789 elseif (isset($field['where'])) {
790 list($tableName, $fieldName) = explode('.', $field['where'], 2);
791 if (isset($tableName)) {
792 if (!empty(self
::$_dependencies[$tableName])) {
793 $this->_tables
['civicrm_address'] = 1;
794 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
795 $this->_element
['address_id'] = 1;
798 if ($tableName === 'im_provider' ||
$tableName === 'email_greeting' ||
799 $tableName === 'postal_greeting' ||
$tableName === 'addressee'
801 if ($tableName === 'im_provider') {
802 CRM_Core_OptionValue
::select($this);
805 if (in_array($tableName,
806 ['email_greeting', 'postal_greeting', 'addressee'])) {
807 $this->_element
["{$name}_id"] = 1;
808 $this->_select
["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
809 $this->_pseudoConstantsSelect
[$name] = ['pseudoField' => $tableName, 'idCol' => "{$name}_id"];
810 $this->_pseudoConstantsSelect
[$name]['select'] = "{$name}.{$fieldName} as $name";
811 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
813 if ($tableName === 'email_greeting') {
815 $this->_pseudoConstantsSelect
[$name]['join']
816 = " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
817 $this->_pseudoConstantsSelect
[$name]['join'] .=
818 " 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 ) ";
820 elseif ($tableName === 'postal_greeting') {
822 $this->_pseudoConstantsSelect
[$name]['join']
823 = " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
824 $this->_pseudoConstantsSelect
[$name]['join'] .=
825 " 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 ) ";
827 elseif ($tableName == 'addressee') {
829 $this->_pseudoConstantsSelect
[$name]['join']
830 = " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
831 $this->_pseudoConstantsSelect
[$name]['join'] .=
832 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
834 $this->_pseudoConstantsSelect
[$name]['table'] = $tableName;
837 $greetField = "{$name}_display";
838 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
839 $this->_element
[$greetField] = 1;
841 $greetField = "{$name}_custom";
842 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
843 $this->_element
[$greetField] = 1;
847 if (!in_array($tableName, ['civicrm_state_province', 'civicrm_country', 'civicrm_county'])) {
848 $this->_tables
[$tableName] = 1;
851 // also get the id of the tableName
852 $tName = substr($tableName, 8);
853 if (in_array($tName, ['country', 'state_province', 'county'])) {
854 if ($tName == 'state_province') {
855 $this->_pseudoConstantsSelect
['state_province_name'] = [
856 'pseudoField' => "{$tName}",
857 'idCol' => "{$tName}_id",
858 'bao' => 'CRM_Core_BAO_Address',
859 'table' => "civicrm_{$tName}",
860 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
863 $this->_pseudoConstantsSelect
[$tName] = [
864 'pseudoField' => 'state_province_abbreviation',
865 'idCol' => "{$tName}_id",
866 'table' => "civicrm_{$tName}",
867 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
871 $this->_pseudoConstantsSelect
[$name] = [
872 'pseudoField' => "{$tName}_id",
873 'idCol' => "{$tName}_id",
874 'bao' => 'CRM_Core_BAO_Address',
875 'table' => "civicrm_{$tName}",
876 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
880 $this->_select
["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
881 $this->_element
["{$tName}_id"] = 1;
883 elseif ($tName != 'contact') {
884 $this->_select
["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
885 $this->_element
["{$tName}_id"] = 1;
888 //special case for phone
889 if ($name == 'phone') {
890 $this->_select
['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
891 $this->_element
['phone_type_id'] = 1;
894 // if IM then select provider_id also
895 // to get "IM Service Provider" in a file to be exported, CRM-3140
897 $this->_select
['provider_id'] = "civicrm_im.provider_id as provider_id";
898 $this->_element
['provider_id'] = 1;
901 if ($tName == 'contact' && $fieldName == 'organization_name') {
902 // special case, when current employer is set for Individual contact
903 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
905 elseif ($tName == 'contact' && $fieldName === 'id') {
906 // Handled elsewhere, explicitly ignore. Possibly for all tables...
908 elseif (in_array($tName, ['country', 'county'])) {
909 $this->_pseudoConstantsSelect
[$name]['select'] = "{$field['where']} as `$name`";
910 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
912 elseif ($tName == 'state_province') {
913 $this->_pseudoConstantsSelect
[$tName]['select'] = "{$field['where']} as `$name`";
914 $this->_pseudoConstantsSelect
[$tName]['element'] = $name;
916 elseif (strpos($name, 'contribution_soft_credit') !== FALSE) {
917 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled($this->_params
)) {
918 $this->_select
[$name] = "{$field['where']} as `$name`";
921 elseif ($this->pseudoConstantNameIsInReturnProperties($field, $name)) {
922 $this->addPseudoconstantFieldToSelect($name);
925 $this->_select
[$name] = str_replace('civicrm_contact.', 'contact_a.', "{$field['where']} as `$name`");
927 if (!in_array($tName, ['state_province', 'country', 'county'])) {
928 $this->_element
[$name] = 1;
933 elseif ($name === 'tags') {
934 //@todo move this handling outside the big IF & ditch $makeException
935 $this->_useGroupBy
= TRUE;
936 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
937 $this->_element
[$name] = 1;
938 $this->_tables
['civicrm_tag'] = 1;
939 $this->_tables
['civicrm_entity_tag'] = 1;
941 elseif ($name === 'groups') {
942 //@todo move this handling outside the big IF & ditch $makeException
943 $this->_useGroupBy
= TRUE;
944 // Duplicates will be created here but better to sort them out in php land.
945 $this->_select
[$name] = "
947 GROUP_CONCAT(DISTINCT IF(civicrm_group_contact.status = 'Added', civicrm_group_contact.group_id, '')),
948 GROUP_CONCAT(DISTINCT civicrm_group_contact_cache.group_id)
951 $this->_element
[$name] = 1;
952 $this->_tables
['civicrm_group_contact'] = 1;
953 $this->_tables
['civicrm_group_contact_cache'] = 1;
954 $this->_pseudoConstantsSelect
["{$name}"] = [
955 'pseudoField' => "groups",
959 elseif ($name === 'notes') {
960 //@todo move this handling outside the big IF & ditch $makeException
961 // if note field is subject then return subject else body of the note
962 $noteColumn = 'note';
963 if (isset($noteField) && $noteField === 'note_subject') {
964 $noteColumn = 'subject';
967 $this->_useGroupBy
= TRUE;
968 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
969 $this->_element
[$name] = 1;
970 $this->_tables
['civicrm_note'] = 1;
972 elseif ($name === 'current_employer') {
973 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
974 $this->_element
[$name] = 1;
978 if ($cfID && !empty($field['is_search_range'])) {
979 // this is a custom field with range search enabled, so we better check for two/from values
980 if (!empty($this->_paramLookup
[$name . '_from'])) {
981 if (!array_key_exists($cfID, $this->_cfIDs
)) {
982 $this->_cfIDs
[$cfID] = [];
984 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
985 // search in the cdID array for the same grouping
987 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
988 if ($c[3] == $p[3]) {
989 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
994 $p[2] = ['from' => $p[2]];
995 $this->_cfIDs
[$cfID][] = $p;
999 if (!empty($this->_paramLookup
[$name . '_to'])) {
1000 if (!array_key_exists($cfID, $this->_cfIDs
)) {
1001 $this->_cfIDs
[$cfID] = [];
1003 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
1004 // search in the cdID array for the same grouping
1006 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
1007 if ($c[4] == $p[4]) {
1008 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
1013 $p[2] = ['to' => $p[2]];
1014 $this->_cfIDs
[$cfID][] = $p;
1021 // add location as hierarchical elements
1022 $this->addHierarchicalElements();
1024 // add multiple field like website
1025 $this->addMultipleElements();
1028 CRM_Core_Component
::alterQuery($this, 'select');
1030 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'select');
1034 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
1036 public function addHierarchicalElements() {
1037 if (empty($this->_returnProperties
['location'])) {
1040 if (!is_array($this->_returnProperties
['location'])) {
1044 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
1048 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
1049 $addressCustomFieldIds = [];
1051 foreach ($this->_returnProperties
['location'] as $name => $elements) {
1052 $lCond = self
::getPrimaryCondition($name);
1053 $locationTypeId = is_numeric($name) ?
NULL : array_search($name, $locationTypes);
1056 if ($locationTypeId === FALSE) {
1059 $lCond = "location_type_id = $locationTypeId";
1060 $this->_useDistinct
= TRUE;
1062 //commented for CRM-3256
1063 $this->_useGroupBy
= TRUE;
1066 $name = str_replace(' ', '_', $name);
1067 $tName = "$name-location_type";
1068 $ltName = "`$name-location_type`";
1069 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1070 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
1071 $this->_element
["{$tName}_id"] = 1;
1072 $this->_element
["{$tName}"] = 1;
1074 $locationTypeName = $tName;
1075 $locationTypeJoin = [];
1078 foreach ($elements as $elementFullName => $dontCare) {
1080 $elementName = $elementCmpName = $elementFullName;
1082 if (substr($elementCmpName, 0, 5) == 'phone') {
1083 $elementCmpName = 'phone';
1086 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
1087 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
1088 $addressCustomFieldIds[$cfID][$name] = 1;
1091 // add address table - doesn't matter if we do it mutliple times - it's the same data
1092 // @todo ditch the double processing of addressJoin
1093 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
1094 && !in_array($elementCmpName, ['email', 'phone', 'im', 'openid'])
1096 list($aName, $addressJoin) = $this->addAddressTable($name, $lCond);
1097 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
1098 $processed[$aName] = 1;
1101 $cond = $elementType = '';
1102 if (strpos($elementName, '-') !== FALSE) {
1103 // this is either phone, email or IM
1104 list($elementName, $elementType) = explode('-', $elementName);
1106 if (($elementName != 'phone') && ($elementName != 'im')) {
1107 $cond = self
::getPrimaryCondition($elementType);
1109 // CRM-13011 : If location type is primary, do not restrict search to the phone
1110 // type id - we want the primary phone, regardless of what type it is.
1111 // Otherwise, restrict to the specified phone type for the given field.
1112 if ((!$cond) && ($elementName == 'phone')) {
1113 $cond = "phone_type_id = '$elementType'";
1115 elseif ((!$cond) && ($elementName == 'im')) {
1116 // IM service provider id, CRM-3140
1117 $cond = "provider_id = '$elementType'";
1119 $elementType = '-' . $elementType;
1122 $field = $this->_fields
[$elementName] ??
NULL;
1124 // hack for profile, add location id
1127 // fix for CRM-882( to handle phone types )
1128 !is_numeric($elementType)
1130 if (is_numeric($name)) {
1131 $field = $this->_fields
[$elementName . "-Primary$elementType"] ??
NULL;
1134 $field = $this->_fields
[$elementName . "-$locationTypeId$elementType"] ??
NULL;
1137 elseif (is_numeric($name)) {
1138 //this for phone type to work
1139 if (in_array($elementName, ['phone', 'phone_ext'])) {
1140 $field = $this->_fields
[$elementName . "-Primary" . $elementType] ??
NULL;
1143 $field = $this->_fields
[$elementName . "-Primary"] ??
NULL;
1147 //this is for phone type to work for profile edit
1148 if (in_array($elementName, ['phone', 'phone_ext'])) {
1149 $field = $this->_fields
[$elementName . "-$locationTypeId$elementType"] ??
NULL;
1152 $field = $this->_fields
[$elementName . "-$locationTypeId"] ??
NULL;
1157 // Check if there is a value, if so also add to where Clause
1159 if ($this->_params
) {
1161 if (isset($locationTypeId)) {
1162 $nm .= "-$locationTypeId";
1164 if (!is_numeric($elementType)) {
1165 $nm .= "$elementType";
1168 foreach ($this->_params
as $id => $values) {
1169 if ((is_array($values) && $values[0] == $nm) ||
1170 (in_array($elementName, ['phone', 'im'])
1171 && (strpos($values[0], $nm) !== FALSE)
1181 if ($field && isset($field['where'])) {
1182 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1183 $pf = substr($tableName, 8);
1184 $tName = $name . '-' . $pf . $elementType;
1185 if (isset($tableName)) {
1186 if ($tableName == 'civicrm_state_province' ||
$tableName == 'civicrm_country' ||
$tableName == 'civicrm_county') {
1187 $this->_select
["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1190 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1193 $this->_element
["{$tName}_id"] = 1;
1194 if (substr($tName, -15) == '-state_province') {
1195 // FIXME: hack to fix CRM-1900
1196 $a = Civi
::settings()->get('address_format');
1198 if (substr_count($a, 'state_province_name') > 0) {
1199 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = [
1200 'pseudoField' => "{$pf}_id",
1201 'idCol' => "{$tName}_id",
1202 'bao' => 'CRM_Core_BAO_Address',
1204 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1207 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = [
1208 'pseudoField' => 'state_province_abbreviation',
1209 'idCol' => "{$tName}_id",
1211 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1215 if (substr($elementFullName, 0, 2) == 'im') {
1216 $provider = "{$name}-{$elementFullName}-provider_id";
1217 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1218 $this->_element
[$provider] = 1;
1220 if ($pf == 'country' ||
$pf == 'county') {
1221 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = [
1222 'pseudoField' => "{$pf}_id",
1223 'idCol' => "{$tName}_id",
1224 'bao' => 'CRM_Core_BAO_Address',
1226 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1229 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1233 if (in_array($pf, ['state_province', 'country', 'county'])) {
1234 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1237 $this->_element
["{$name}-{$elementFullName}"] = 1;
1240 if (empty($processed["`$tName`"])) {
1241 $processed["`$tName`"] = 1;
1242 $newName = $tableName . '_' . $index;
1243 switch ($tableName) {
1244 case 'civicrm_phone':
1245 case 'civicrm_email':
1247 case 'civicrm_openid':
1249 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id";
1250 if ($tableName != 'civicrm_phone') {
1251 $this->_tables
[$tName] .= " AND `$tName`.$lCond";
1253 elseif (is_numeric($name)) {
1254 $this->_select
[$tName] = "IF (`$tName`.is_primary = $name, `$tName`.phone, NULL) as `$tName`";
1257 // this special case to add phone type
1259 $phoneTypeCondition = " AND `$tName`.$cond ";
1260 //gross hack to pickup corrupted data also, CRM-7603
1261 if (strpos($cond, 'phone_type_id') !== FALSE) {
1262 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1263 if (!empty($lCond)) {
1264 $phoneTypeCondition .= " AND ( `$tName`.$lCond ) ";
1267 $this->_tables
[$tName] .= $phoneTypeCondition;
1270 //build locationType join
1271 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1274 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1278 case 'civicrm_state_province':
1279 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1280 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1281 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1283 $this->_whereTables
["{$name}-address"] = $addressJoin;
1287 case 'civicrm_country':
1288 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1289 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1290 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1292 $this->_whereTables
["{$name}-address"] = $addressJoin;
1296 case 'civicrm_county':
1297 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1298 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1299 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1301 $this->_whereTables
["{$name}-address"] = $addressJoin;
1306 if (isset($addressCustomFields[$elementName]['custom_field_id']) && !empty($addressCustomFields[$elementName]['custom_field_id'])) {
1307 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.id";
1310 $this->_whereTables
["{$name}-address"] = $addressJoin;
1319 // add location type join
1320 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1321 $this->_tables
[$locationTypeName] = $ltypeJoin;
1323 // table should be present in $this->_whereTables,
1324 // to add its condition in location type join, CRM-3939.
1325 if ($addWhereCount) {
1327 foreach ($this->_whereTables
as $tableName => $clause) {
1328 if (!empty($locationTypeJoin[$tableName])) {
1329 $locClause[] = $locationTypeJoin[$tableName];
1333 if (!empty($locClause)) {
1334 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1339 if (!empty($addressCustomFieldIds)) {
1340 $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
1341 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1342 foreach ($locTypeName as $name => $dnc) {
1343 $this->_locationSpecificCustomFields
[$cfID] = [$name, array_search($name, $locationTypes)];
1344 $fieldName = "$name-custom_{$cfID}";
1345 $tName = "$name-address-custom-{$cfID}";
1346 $aName = "`$name-address-custom-{$cfID}`";
1347 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1348 $this->_element
["{$tName}_id"] = 1;
1349 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1350 $this->_element
[$fieldName] = 1;
1351 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1358 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
1360 public function addMultipleElements() {
1361 if (empty($this->_returnProperties
['website'])) {
1364 if (!is_array($this->_returnProperties
['website'])) {
1368 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1369 foreach ($elements as $elementFullName => $dontCare) {
1370 $tName = "website-{$key}-{$elementFullName}";
1371 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1372 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1373 $this->_element
["{$tName}_id"] = 1;
1374 $this->_element
["{$tName}"] = 1;
1376 $type = "website-{$key}-website_type_id";
1377 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1378 $this->_element
[$type] = 1;
1379 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id AND `$tName`.website_type_id = $key )";
1385 * Generate the query based on what type of query we need.
1387 * @param bool $count
1388 * @param bool $sortByChar
1389 * @param bool $groupContacts
1390 * @param bool $onlyDeleted
1393 * sql query parts as an array
1395 public function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE, $onlyDeleted = FALSE) {
1396 // build permission clause
1397 $this->generatePermissionClause($onlyDeleted, $count);
1400 if (isset($this->_rowCountClause
)) {
1401 $select = "SELECT {$this->_rowCountClause}";
1403 elseif (isset($this->_distinctComponentClause
)) {
1404 // we add distinct to get the right count for components
1405 // for the more complex result set, we use GROUP BY the same id
1407 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} ) as rowCount";
1410 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1412 $from = $this->_simpleFromClause
;
1413 if ($this->_useDistinct
) {
1414 $this->_useGroupBy
= TRUE;
1417 elseif ($sortByChar) {
1418 // @fixme add the deprecated warning back in (it breaks CRM_Contact_SelectorTest::testSelectorQuery)
1419 // CRM_Core_Error::deprecatedFunctionWarning('sort by char is deprecated - use alphabetQuery method');
1420 $select = 'SELECT DISTINCT LEFT(contact_a.sort_name, 1) as sort_name';
1421 $from = $this->_simpleFromClause
;
1423 elseif ($groupContacts) {
1424 $select = 'SELECT contact_a.id as id';
1425 if ($this->_useDistinct
) {
1426 $this->_useGroupBy
= TRUE;
1428 $from = $this->_simpleFromClause
;
1431 if (!empty($this->_paramLookup
['group'])) {
1433 list($name, $op, $value, $grouping, $wildcard) = $this->_paramLookup
['group'][0];
1435 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
1436 $this->_paramLookup
['group'][0][1] = key($value);
1439 // Presumably the lines below come into manage groups screen.
1440 // make sure there is only one element
1441 // this is used when we are running under smog and need to know
1442 // how the contact was added (CRM-1203)
1443 $groups = (array) CRM_Utils_Array
::value($this->_paramLookup
['group'][0][1], $this->_paramLookup
['group'][0][2], $this->_paramLookup
['group'][0][2]);
1444 if ((count($this->_paramLookup
['group']) == 1) &&
1445 (count($groups) == 1)
1447 $groupId = $groups[0];
1449 //check if group is saved search
1450 $group = new CRM_Contact_BAO_Group();
1451 $group->id
= $groupId;
1454 if (!isset($group->saved_search_id
)) {
1455 $tbName = "civicrm_group_contact";
1456 // CRM-17254 don't retrieve extra fields if contact_id is specifically requested
1457 // as this will add load to an intentionally light query.
1458 // ideally this code would be removed as it appears to be to support CRM-1203
1459 // and passing in the required returnProperties from the url would
1460 // make more sense that globally applying the requirements of one form.
1461 if (($this->_returnProperties
!= ['contact_id'])) {
1462 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1463 $this->_element
['group_contact_id'] = 1;
1464 $this->_select
['status'] = "$tbName.status as status";
1465 $this->_element
['status'] = 1;
1469 $this->_useGroupBy
= TRUE;
1471 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1472 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1474 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1475 $this->_useDistinct
= FALSE;
1476 $this->_useGroupBy
= TRUE;
1480 $select = $this->getSelect();
1481 $from = $this->_fromClause
;
1485 if (!empty($this->_whereClause
)) {
1486 $where = "WHERE {$this->_whereClause}";
1489 if (!empty($this->_permissionWhereClause
) && empty($this->_displayRelationshipType
)) {
1490 if (empty($where)) {
1491 $where = "WHERE $this->_permissionWhereClause";
1494 $where = "$where AND $this->_permissionWhereClause";
1499 if (!empty($this->_having
)) {
1500 foreach ($this->_having
as $havingSets) {
1501 foreach ($havingSets as $havingSet) {
1502 $havingValue[] = $havingSet;
1505 $having = ' HAVING ' . implode(' AND ', $havingValue);
1508 // if we are doing a transform, do it here
1509 // use the $from, $where and $having to get the contact ID
1510 if ($this->_displayRelationshipType
) {
1511 $this->filterRelatedContacts($from, $where, $having);
1514 return [$select, $from, $where, $having];
1518 * Get where values from the parameters.
1520 * @param string $name
1521 * @param mixed $grouping
1525 public function getWhereValues($name, $grouping) {
1527 foreach ($this->_params
as $values) {
1528 if ($values[0] == $name && $values[3] == $grouping) {
1539 * @param bool $relative
1540 * @param string $from
1543 public static function fixDateValues($relative, &$from, &$to) {
1545 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1550 * Convert values from form-appropriate to query-object appropriate.
1552 * The query object is increasingly supporting the sql-filter syntax which is the most flexible syntax.
1553 * So, ideally we would convert all fields to look like
1556 * // Set the operator for legacy reasons, but it is ignored
1558 * // array in sql filter syntax
1559 * 2 => array('BETWEEN' => array(1,60),
1564 * There are some examples of the syntax in
1565 * https://github.com/civicrm/civicrm-core/tree/master/api/v3/examples/Relationship
1567 * More notes at CRM_Core_DAO::createSQLFilter
1569 * and a list of supported operators in CRM_Core_DAO
1571 * @param array $formValues
1572 * @param int $wildcard
1573 * @param bool $useEquals
1575 * @param string $apiEntity
1577 * @param array $entityReferenceFields
1578 * Field names of any entity reference fields (which will need reformatting to IN syntax).
1582 public static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL,
1583 $entityReferenceFields = []) {
1585 if (empty($formValues)) {
1589 self
::filterCountryFromValuesIfStateExists($formValues);
1591 foreach ($formValues as $id => $values) {
1592 if (self
::isAlreadyProcessedForQueryFormat($values)) {
1593 $params[] = $values;
1597 self
::legacyConvertFormValues($id, $values);
1599 // The form uses 1 field to represent two db fields
1600 if ($id === 'contact_type' && $values && (!is_array($values) ||
!array_intersect(array_keys($values), CRM_Core_DAO
::acceptedSQLOperators()))) {
1603 foreach ((array) $values as $key => $type) {
1604 $types = explode('__', is_numeric($type) ?
$key : $type, 2);
1605 $contactType[$types[0]] = $types[0];
1606 // Add sub-type if specified
1607 if (!empty($types[1])) {
1608 $subType[$types[1]] = $types[1];
1611 $params[] = ['contact_type', 'IN', $contactType, 0, 0];
1613 $params[] = ['contact_sub_type', 'IN', $subType, 0, 0];
1616 elseif ($id === 'privacy') {
1617 if (is_array($formValues['privacy'])) {
1618 $op = !empty($formValues['privacy']['do_not_toggle']) ?
'=' : '!=';
1619 foreach ($formValues['privacy'] as $key => $value) {
1621 $params[] = [$key, $op, $value, 0, 0];
1626 elseif ($id === 'email_on_hold') {
1627 if ($onHoldValue = CRM_Utils_Array
::value('email_on_hold', $formValues)) {
1628 // onHoldValue should be 0 or 1 or an array. Some legacy groups may hold ''
1629 // so in 5.11 we have an extra if that should become redundant over time.
1630 // https://lab.civicrm.org/dev/core/issues/745
1631 // @todo this renaming of email_on_hold to on_hold needs revisiting
1632 // it precedes recent changes but causes the default not to reload.
1633 $onHoldValue = array_filter((array) $onHoldValue, 'is_numeric');
1634 if (!empty($onHoldValue)) {
1635 $params[] = ['on_hold', 'IN', $onHoldValue, 0, 0];
1639 elseif (substr($id, 0, 7) === 'custom_'
1641 substr($id, -5, 5) === '_from'
1642 ||
substr($id, -3, 3) === '_to'
1645 self
::convertCustomRelativeFields($formValues, $params, $values, $id);
1647 elseif (in_array($id, $entityReferenceFields) && !empty($values) && is_string($values) && (strpos($values, ',') !=
1649 $params[] = [$id, 'IN', explode(',', $values), 0, 0];
1652 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals, $apiEntity);
1657 $params[] = $values;
1664 * Function to support legacy format for groups and tags.
1667 * @param array|int $values
1670 public static function legacyConvertFormValues($id, &$values) {
1676 'membership_type_id',
1677 'membership_status_id',
1679 if (in_array($id, $legacyElements) && is_array($values)) {
1680 // prior to 4.7, formValues for some attributes (e.g. group, tag) are stored in array(id1 => 1, id2 => 1),
1681 // as per the recent Search fixes $values need to be in standard array(id1, id2) format
1682 $values = CRM_Utils_Array
::convertCheckboxFormatToArray($values);
1687 * Fix values from query from/to something no-one cared enough to document.
1690 * @param array $values
1691 * @param int $wildcard
1692 * @param bool $useEquals
1694 * @param string $apiEntity
1696 * @return array|null
1698 public static function fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL) {
1699 // skip a few search variables
1700 static $skipWhere = NULL;
1701 static $likeNames = NULL;
1704 // Change camelCase EntityName to lowercase with underscores
1705 $apiEntity = _civicrm_api_get_entity_name_from_camel($apiEntity);
1707 // check if $value is in OK (Operator as Key) format as used by Get API
1708 if (CRM_Utils_System
::isNull($values)) {
1720 'display_relationship_type',
1724 if (in_array($id, $skipWhere) ||
1725 substr($id, 0, 4) == '_qf_' ||
1726 substr($id, 0, 7) == 'hidden_'
1732 (substr($id, 0, strlen($apiEntity)) != $apiEntity) &&
1733 (substr($id, 0, 10) != 'financial_' && substr($id, 0, 8) != 'payment_') &&
1734 (substr($id, 0, 7) != 'custom_')
1736 $id = $apiEntity . '_' . $id;
1740 $likeNames = ['sort_name', 'email', 'note', 'display_name'];
1743 // email comes in via advanced search
1744 // so use wildcard always
1745 if ($id == 'email') {
1749 if (!$useEquals && in_array($id, $likeNames)) {
1750 $result = [$id, 'LIKE', $values, 0, 1];
1752 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1753 $result = [$id, 'LIKE', $values, 0, 0];
1755 elseif ($id == 'contact_type' ||
1756 (!empty($values) && is_array($values) && !in_array(key($values), CRM_Core_DAO
::acceptedSQLOperators(), TRUE))
1758 $result = [$id, 'IN', $values, 0, $wildcard];
1761 $result = [$id, '=', $values, 0, $wildcard];
1768 * Get the where clause for a single field.
1770 * @param array $values
1771 * @param bool $isForcePrimaryOnly
1773 * @throws \CRM_Core_Exception
1775 public function whereClauseSingle(&$values, $isForcePrimaryOnly = FALSE) {
1776 if ($this->isARelativeDateField($values[0])) {
1777 $this->buildRelativeDateQuery($values);
1780 // @todo also handle _low, _high generically here with if ($query->buildDateRangeQuery($values)) {return}
1782 // do not process custom fields or prefixed contact ids or component params
1783 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1784 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1785 (substr($values[0], 0, 13) === 'contribution_') ||
1786 (substr($values[0], 0, 6) === 'event_') ||
1787 (substr($values[0], 0, 12) === 'participant_') ||
1788 (substr($values[0], 0, 7) === 'member_') ||
1789 (substr($values[0], 0, 6) === 'grant_') ||
1790 (substr($values[0], 0, 7) === 'pledge_') ||
1791 (substr($values[0], 0, 5) === 'case_') ||
1792 (substr($values[0], 0, 10) === 'financial_') ||
1793 (substr($values[0], 0, 8) === 'payment_') ||
1794 (substr($values[0], 0, 11) === 'membership_')
1795 // temporary fix for regression https://lab.civicrm.org/dev/core/issues/1551
1796 // ideally the metadata would allow this field to be parsed below & the special handling would not
1798 ||
$values[0] === 'mailing_id'
1803 // skip for hook injected fields / params
1804 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1805 if (array_key_exists($values[0], $extFields)) {
1809 switch ($values[0]) {
1810 case 'deleted_contacts':
1811 $this->deletedContacts($values);
1814 case 'contact_sub_type':
1815 $this->contactSubType($values);
1820 $this->group($values);
1823 // case tag comes from find contacts
1825 $this->tagSearch($values);
1829 case 'contact_tags':
1830 $this->tag($values);
1835 case 'note_subject':
1836 $this->notes($values);
1840 $this->ufUser($values);
1844 case 'display_name':
1845 $this->sortName($values);
1849 case 'postal_greeting':
1850 case 'email_greeting':
1851 $this->greetings($values);
1856 $this->email($values, $isForcePrimaryOnly);
1859 case 'phone_numeric':
1860 $this->phone_numeric($values);
1863 case 'phone_phone_type_id':
1864 case 'phone_location_type_id':
1865 $this->phone_option_group($values);
1868 case 'street_address':
1869 $this->street_address($values);
1872 case 'street_number':
1873 $this->street_number($values);
1876 case 'sortByCharacter':
1877 $this->sortByCharacter($values);
1880 case 'location_type':
1881 $this->locationType($values);
1885 $this->county($values);
1888 case 'state_province':
1889 case 'state_province_id':
1890 case 'state_province_name':
1891 $this->stateProvince($values);
1896 $this->country($values, FALSE);
1900 case 'postal_code_low':
1901 case 'postal_code_high':
1902 $this->postalCode($values);
1905 case 'activity_date':
1906 case 'activity_date_low':
1907 case 'activity_date_high':
1908 case 'activity_date_time_low':
1909 case 'activity_date_time_high':
1910 case 'activity_role':
1911 case 'activity_status_id':
1912 case 'activity_status':
1913 case 'activity_priority':
1914 case 'activity_priority_id':
1915 case 'followup_parent_id':
1917 case 'source_contact_id':
1918 case 'activity_text':
1919 case 'activity_option':
1920 case 'test_activities':
1921 case 'activity_type_id':
1922 case 'activity_type':
1923 case 'activity_survey_id':
1924 case 'activity_tags':
1925 case 'activity_taglist':
1926 case 'activity_test':
1927 case 'activity_campaign_id':
1928 case 'activity_engagement_level':
1930 case 'activity_result':
1931 case 'source_contact':
1932 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1937 case 'birth_date_low':
1938 case 'birth_date_high':
1939 case 'deceased_date_low':
1940 case 'deceased_date_high':
1941 $this->demographics($values);
1944 case 'age_asof_date':
1945 // handled by demographics
1948 case 'log_date_low':
1949 case 'log_date_high':
1950 $this->modifiedDates($values);
1954 $this->changeLog($values);
1957 case 'do_not_phone':
1958 case 'do_not_email':
1961 case 'do_not_trade':
1963 $this->privacy($values);
1966 case 'privacy_options':
1967 $this->privacyOptions($values);
1970 case 'privacy_operator':
1971 case 'privacy_toggle':
1972 // these are handled by privacy options
1975 case 'preferred_communication_method':
1976 $this->preferredCommunication($values);
1979 case 'relation_type_id':
1980 case 'relationship_start_date_high':
1981 case 'relationship_start_date_low':
1982 case 'relationship_end_date_high':
1983 case 'relationship_end_date_low':
1984 case 'relation_active_period_date_high':
1985 case 'relation_active_period_date_low':
1986 case 'relation_target_name':
1987 case 'relation_status':
1988 case 'relation_description':
1989 case 'relation_date_low':
1990 case 'relation_date_high':
1991 $this->relationship($values);
1992 $this->_relationshipValuesAdded
= TRUE;
1995 case 'task_status_id':
1996 $this->task($values);
2000 // since this case is handled with the above
2003 case 'prox_distance':
2004 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
2007 case 'prox_street_address':
2009 case 'prox_postal_code':
2010 case 'prox_state_province_id':
2011 case 'prox_country_id':
2012 case 'prox_geo_code_1':
2013 case 'prox_geo_code_2':
2014 // handled by the proximity_distance clause
2018 $this->restWhere($values);
2024 * Given a list of conditions in params generate the required where clause.
2026 * @param bool $isForcePrimaryEmailOnly
2029 * @throws \CRM_Core_Exception
2031 public function whereClause($isForcePrimaryEmailOnly = NULL) {
2032 $this->_where
[0] = [];
2033 $this->_qill
[0] = [];
2035 $this->includeContactIDs();
2036 if (!empty($this->_params
)) {
2037 foreach (array_keys($this->_params
) as $id) {
2038 if (empty($this->_params
[$id][0])) {
2041 // check for both id and contact_id
2042 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
2043 $this->_where
[0][] = self
::buildClause("contact_a.id", $this->_params
[$id][1], $this->_params
[$id][2]);
2044 $field = $this->_fields
['id'] ??
NULL;
2045 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(
2046 'CRM_Contact_BAO_Contact',
2048 $this->_params
[$id][2],
2049 $this->_params
[$id][1]
2051 $this->_qill
[0][] = ts("%1 %2 %3", [
2052 1 => $field['title'],
2058 $this->whereClauseSingle($this->_params
[$id], $isForcePrimaryEmailOnly);
2062 CRM_Core_Component
::alterQuery($this, 'where');
2064 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
2067 if ($this->_customQuery
) {
2068 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
2069 // Added following if condition to avoid the wrong value display for 'my account' / any UF info.
2070 // Hope it wont affect the other part of civicrm.. if it does please remove it.
2071 if (!empty($this->_customQuery
->_where
)) {
2072 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
2074 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
2081 if (!empty($this->_where
)) {
2082 foreach ($this->_where
as $grouping => $values) {
2083 if ($grouping > 0 && !empty($values)) {
2084 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
2089 if (!empty($this->_where
[0])) {
2090 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
2092 if (!empty($clauses)) {
2093 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
2096 if ($validClauses > 1) {
2097 $this->_useDistinct
= TRUE;
2101 return implode(' AND ', $andClauses);
2105 * Generate where clause for any parameters not already handled.
2107 * @param array $values
2111 public function restWhere(&$values) {
2112 $name = $values[0] ??
NULL;
2113 $op = $values[1] ??
NULL;
2114 $value = $values[2] ??
NULL;
2115 $grouping = $values[3] ??
NULL;
2116 $wildcard = $values[4] ??
NULL;
2118 if (isset($grouping) && empty($this->_where
[$grouping])) {
2119 $this->_where
[$grouping] = [];
2122 $multipleFields = ['url'];
2124 //check if the location type exists for fields
2126 $locType = explode('-', $name);
2128 if (!in_array($locType[0], $multipleFields)) {
2129 //add phone type if exists
2130 if (isset($locType[2]) && $locType[2]) {
2131 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
2135 $field = $this->_fields
[$name] ??
NULL;
2138 $field = $this->_fields
[$locType[0]] ??
NULL;
2141 // Strip any trailing _high & _low that might be appended.
2142 $realFieldName = str_replace(['_high', '_low'], '', $name);
2143 if (isset($this->_fields
[$realFieldName])) {
2144 $field = $this->_fields
[str_replace(['_high', '_low'], '', $realFieldName)];
2145 $columnName = $field['column_name'] ??
$field['name'];
2146 $this->dateQueryBuilder($values, $field['table_name'], $realFieldName, $columnName, $field['title']);
2154 $locationType = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
2155 if (isset($locType[1]) && is_numeric($locType[1])) {
2156 $lType = $locationType[$locType[1]];
2159 $field['title'] .= " ($lType)";
2162 if (substr($name, 0, 14) === 'state_province') {
2163 if (isset($locType[1]) && is_numeric($locType[1])) {
2165 $aName = "{$lType}-address";
2166 $where = "`$aName`.state_province_id";
2169 $where = "civicrm_address.state_province_id";
2172 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value);
2173 $this->_tables
[$aName] = $this->_whereTables
[$aName] = 1;
2174 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
2175 $this->_qill
[$grouping][] = ts("%1 %2 %3", [1 => $field['title'], 2 => $qillop, 3 => $qillVal]);
2177 elseif (!empty($field['pseudoconstant'])) {
2178 // For the hacked fields we want to undo the hack to type to avoid missing the index by adding quotes.
2179 $dataType = !empty($this->legacyHackedFields
[$name]) ? CRM_Utils_Type
::T_INT
: $field['type'];
2180 $this->optionValueQuery(
2181 $name, $op, $value, $grouping,
2182 'CRM_Contact_DAO_Contact',
2185 CRM_Utils_Type
::typeToString($dataType)
2187 if ($name === 'gender_id') {
2188 self
::$_openedPanes[ts('Demographics')] = TRUE;
2191 elseif (substr($name, 0, 7) === 'country' ||
substr($name, 0, 6) === 'county') {
2192 $name = (substr($name, 0, 7) === 'country') ?
"country_id" : "county_id";
2193 if (isset($locType[1]) && is_numeric($locType[1])) {
2195 $aName = "{$lType}-address";
2196 $where = "`$aName`.$name";
2199 $where = "civicrm_address.$name";
2202 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2203 $this->_tables
[$aName] = $this->_whereTables
[$aName] = 1;
2205 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
2206 $this->_qill
[$grouping][] = ts("%1 %2 %3", [1 => $field['title'], 2 => $qillop, 3 => $qillVal]);
2208 elseif ($name === 'world_region') {
2209 $this->optionValueQuery(
2210 $name, $op, $value, $grouping,
2217 elseif ($name === 'is_deceased') {
2218 $this->setQillAndWhere($name, $op, $value, $grouping, $field);
2219 self
::$_openedPanes[ts('Demographics')] = TRUE;
2221 elseif ($name === 'created_date' ||
$name === 'modified_date' ||
$name === 'deceased_date' ||
$name === 'birth_date') {
2222 $appendDateTime = TRUE;
2223 if ($name === 'deceased_date' ||
$name === 'birth_date') {
2224 $appendDateTime = FALSE;
2225 self
::$_openedPanes[ts('Demographics')] = TRUE;
2227 $this->dateQueryBuilder($values, 'contact_a', $name, $name, $field['title'], $appendDateTime);
2229 elseif ($name === 'contact_id') {
2230 if (is_int($value)) {
2231 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
2232 $this->_qill
[$grouping][] = "$field[title] $op $value";
2235 elseif ($name === 'name') {
2236 $value = CRM_Core_DAO
::escapeString($value);
2239 $value = self
::getWildCardedValue($wildcard, $op, $value);
2241 CRM_Core_Error
::deprecatedFunctionWarning('Untested code path');
2242 // @todo it's likely this code path is obsolete / never called. It is definitely not
2243 // passed through in our test suite.
2244 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, "'$value'");
2245 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2247 elseif ($name === 'current_employer') {
2250 $value = self
::getWildCardedValue($wildcard, $op, $value);
2252 $ceWhereClause = self
::buildClause("contact_a.organization_name", $op,
2255 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2256 $this->_where
[$grouping][] = $ceWhereClause;
2257 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2259 elseif (substr($name, 0, 4) === 'url-') {
2260 $tName = 'civicrm_website';
2261 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2262 $value = CRM_Core_DAO
::escapeString($value);
2265 $value = self
::getWildCardedValue($wildcard, $op, $value);
2268 $this->_where
[$grouping][] = $d = self
::buildClause('civicrm_website.url', $op, $value);
2269 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2271 elseif ($name === 'contact_is_deleted') {
2272 $this->setQillAndWhere('is_deleted', $op, $value, $grouping, $field);
2274 elseif (!empty($field['where'])) {
2276 if (!empty($field['type'])) {
2277 $type = CRM_Utils_Type
::typeToString($field['type']);
2280 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2282 if (isset($locType[1]) &&
2283 is_numeric($locType[1])
2287 //get the location name
2288 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2289 $fieldName = "`$tName`.$fldName";
2291 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2292 $this->_tables
[$tName] = $this->_whereTables
[$tName] = 1;
2296 if ($tableName == 'civicrm_contact') {
2297 $fieldName = "contact_a.{$fieldName}";
2300 $fieldName = $field['where'];
2304 list($qillop, $qillVal) = self
::buildQillForFieldValue(NULL, $field['title'], $value, $op);
2305 $this->_qill
[$grouping][] = ts("%1 %2 %3", [
2306 1 => $field['title'],
2308 3 => (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) ?
$qillVal : "'$qillVal'",
2311 if (is_array($value)) {
2312 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2313 // for api style operators for functions that hit this point without worrying about regression
2314 // (the previous comments indicated the condition for hitting this point were unknown
2315 // per CRM-14743 we are adding modified_date & created_date operator support
2316 $operations = array_keys($value);
2317 foreach ($operations as $operator) {
2318 if (!in_array($operator, CRM_Core_DAO
::acceptedSQLOperators())) {
2319 //Via Contact get api value is not in array(operator => array(values)) format ONLY for IN/NOT IN operators
2320 //so this condition will satisfy the search for now
2321 if (strpos($op, 'IN') !== FALSE) {
2322 $value = [$op => $value];
2324 // we don't know when this might happen
2326 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", [1 => $operator]));
2330 $this->_where
[$grouping][] = CRM_Core_DAO
::createSQLFilter($fieldName, $value, $type);
2335 $value = self
::getWildCardedValue($wildcard, $op, $value);
2338 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2342 if ($setTables && isset($field['where'])) {
2343 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2344 if (isset($tableName)) {
2345 $this->_tables
[$tableName] = 1;
2346 $this->_whereTables
[$tableName] = 1;
2358 public static function getLocationTableName(&$where, &$locType) {
2359 if (isset($locType[1]) && is_numeric($locType[1])) {
2360 list($tbName, $fldName) = explode(".", $where);
2362 //get the location name
2363 $locationType = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
2364 $specialFields = ['email', 'im', 'phone', 'openid', 'phone_ext'];
2365 if (in_array($locType[0], $specialFields)) {
2366 //hack to fix / special handing for phone_ext
2367 if ($locType[0] == 'phone_ext') {
2368 $locType[0] = 'phone';
2370 if (isset($locType[2]) && $locType[2]) {
2371 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2374 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2377 elseif (in_array($locType[0],
2382 'street_number_suffix',
2384 'supplemental_address_1',
2385 'supplemental_address_2',
2386 'supplemental_address_3',
2389 'postal_code_suffix',
2395 //fix for search by profile with address fields.
2396 $tName = "{$locationType[$locType[1]]}-address";
2398 elseif (in_array($locType[0],
2406 $tName = "{$locationType[$locType[1]]}-email";
2408 elseif ($locType[0] == 'provider_id') {
2409 $tName = "{$locationType[$locType[1]]}-im";
2411 elseif ($locType[0] == 'openid') {
2412 $tName = "{$locationType[$locType[1]]}-openid";
2415 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2417 $tName = str_replace(' ', '_', $tName);
2418 return [$tName, $fldName];
2420 CRM_Core_Error
::fatal();
2424 * Given a result dao, extract the values and return that array
2426 * @param CRM_Core_DAO $dao
2429 * values for this query
2431 public function store($dao) {
2434 foreach ($this->_element
as $key => $dontCare) {
2435 if (property_exists($dao, $key)) {
2436 if (strpos($key, '-') !== FALSE) {
2437 $values = explode('-', $key);
2438 $lastElement = array_pop($values);
2440 $cnt = count($values);
2442 foreach ($values as $v) {
2443 if (!array_key_exists($v, $current)) {
2446 //bad hack for im_provider
2447 if ($lastElement == 'provider_id') {
2448 if ($count < $cnt) {
2449 $current = &$current[$v];
2452 $lastElement = "{$v}_{$lastElement}";
2456 $current = &$current[$v];
2461 $current[$lastElement] = $dao->$key;
2464 $value[$key] = $dao->$key;
2472 * Getter for tables array.
2476 public function tables() {
2477 return $this->_tables
;
2481 * Sometimes used to create the from clause, but, not reliably, set
2482 * this AND set tables.
2484 * It's unclear the intent - there is a 'simpleFrom' clause which
2485 * takes whereTables into account & a fromClause which doesn't.
2487 * logic may have eroded?
2491 public function whereTables() {
2492 return $this->_whereTables
;
2496 * Generate the where clause (used in match contacts and permissions)
2498 * @param array $params
2499 * @param array $fields
2500 * @param array $tables
2501 * @param $whereTables
2502 * @param bool $strict
2505 * @throws \CRM_Core_Exception
2507 public static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2508 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2512 $tables = array_merge($query->tables(), $tables);
2513 $whereTables = array_merge($query->whereTables(), $whereTables);
2515 return $query->_whereClause
;
2519 * Create the from clause.
2521 * @param array $tables
2522 * Tables that need to be included in this from clause. If null,
2523 * return mimimal from clause (i.e. civicrm_contact).
2524 * @param array $inner
2525 * Tables that should be inner-joined.
2526 * @param array $right
2527 * Tables that should be right-joined.
2528 * @param bool $primaryLocation
2529 * Search on primary location. See note below.
2531 * Determines search mode based on bitwise MODE_* constants.
2532 * @param string|NULL $apiEntity
2533 * Determines search mode based on entity by string.
2535 * The $primaryLocation flag only seems to be used when
2536 * locationType() has been called. This may be a search option
2537 * exposed, or perhaps it's a "search all details" approach which
2538 * predates decoupling of location types and primary fields?
2540 * @see https://issues.civicrm.org/jira/browse/CRM-19967
2545 public static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1, $apiEntity = NULL) {
2547 $from = ' FROM civicrm_contact contact_a';
2548 if (empty($tables)) {
2552 if (!empty($tables['civicrm_worldregion'])) {
2553 $tables = array_merge(['civicrm_country' => 1], $tables);
2556 if ((!empty($tables['civicrm_state_province']) ||
!empty($tables['civicrm_country']) ||
2557 !empty($tables['civicrm_county'])) && empty($tables['civicrm_address'])) {
2558 $tables = array_merge(['civicrm_address' => 1],
2563 // add group_contact and group table is subscription history is present
2564 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2565 $tables = array_merge([
2566 'civicrm_group' => 1,
2567 'civicrm_group_contact' => 1,
2573 // to handle table dependencies of components
2574 CRM_Core_Component
::tableNames($tables);
2575 // to handle table dependencies of hook injected tables
2576 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2578 //format the table list according to the weight
2579 $info = CRM_Core_TableHierarchy
::info();
2581 foreach ($tables as $key => $value) {
2583 if (strpos($key, '-') !== FALSE) {
2584 $keyArray = explode('-', $key);
2585 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2587 elseif (strpos($key, '_') !== FALSE) {
2588 $keyArray = explode('_', $key);
2589 if (is_numeric(array_pop($keyArray))) {
2590 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2593 $k = CRM_Utils_Array
::value($key, $info, 99);
2597 $k = CRM_Utils_Array
::value($key, $info, 99);
2599 $tempTable[$k . ".$key"] = $key;
2603 foreach ($tempTable as $key) {
2604 $newTables[$key] = $tables[$key];
2607 $tables = $newTables;
2609 foreach ($tables as $name => $value) {
2614 if (!empty($inner[$name])) {
2617 elseif (!empty($right[$name])) {
2625 // if there is already a join statement in value, use value itself
2626 if (strpos($value, 'JOIN')) {
2627 $from .= " $value ";
2630 $from .= " $side JOIN $name ON ( $value ) ";
2635 $from .= ' ' . trim(self
::getEntitySpecificJoins($name, $mode, $side, $primaryLocation)) . ' ';
2641 * Get join statements for the from clause depending on entity type
2643 * @param string $name
2645 * @param string $side
2646 * @param string $primaryLocation
2649 protected static function getEntitySpecificJoins($name, $mode, $side, $primaryLocation) {
2650 $limitToPrimaryClause = $primaryLocation ?
"AND {$name}.is_primary = 1" : '';
2652 case 'civicrm_address':
2653 //CRM-14263 further handling of address joins further down...
2654 return " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id {$limitToPrimaryClause} )";
2656 case 'civicrm_state_province':
2657 // This is encountered when doing an export after having applied a 'sort' - it pretty much implies primary
2658 // but that will have been implied-in by the calling function.
2659 // test cover in testContactIDQuery
2660 return " $side JOIN civicrm_state_province ON ( civicrm_address.state_province_id = civicrm_state_province.id )";
2662 case 'civicrm_country':
2663 // This is encountered when doing an export after having applied a 'sort' - it pretty much implies primary
2664 // but that will have been implied-in by the calling function.
2665 // test cover in testContactIDQuery
2666 return " $side JOIN civicrm_country ON ( civicrm_address.country_id = civicrm_country.id )";
2668 case 'civicrm_phone':
2669 return " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id {$limitToPrimaryClause}) ";
2671 case 'civicrm_email':
2672 return " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id {$limitToPrimaryClause})";
2675 return " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id {$limitToPrimaryClause}) ";
2678 $from = " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2679 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2680 $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)";
2683 case 'civicrm_openid':
2684 return " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id {$limitToPrimaryClause} )";
2686 case 'civicrm_worldregion':
2687 // We can be sure from the calling function that country will already be joined in.
2688 // we really don't need world_region - we could use a pseudoconstant for it.
2689 return " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2691 case 'civicrm_location_type':
2692 return " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2694 case 'civicrm_group':
2695 return " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2697 case 'civicrm_group_contact':
2698 return " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2700 case 'civicrm_group_contact_cache':
2701 return " $side JOIN civicrm_group_contact_cache ON contact_a.id = civicrm_group_contact_cache.contact_id ";
2703 case 'civicrm_activity':
2704 case 'civicrm_activity_tag':
2705 case 'activity_type':
2706 case 'activity_status':
2708 case 'civicrm_activity_contact':
2709 case 'source_contact':
2710 case 'activity_priority':
2711 return CRM_Activity_BAO_Query
::from($name, $mode, $side);
2713 case 'civicrm_entity_tag':
2714 $from = " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact'";
2715 return "$from AND civicrm_entity_tag.entity_id = contact_a.id ) ";
2717 case 'civicrm_note':
2718 $from = " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact'";
2719 return "$from AND contact_a.id = civicrm_note.entity_id ) ";
2721 case 'civicrm_subscription_history':
2722 $from = " $side JOIN civicrm_subscription_history";
2723 $from .= " ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id";
2724 return "$from AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2726 case 'civicrm_relationship':
2727 if (self
::$_relType == 'reciprocal') {
2728 if (self
::$_relationshipTempTable) {
2729 // we have a temptable to join on
2730 $tbl = self
::$_relationshipTempTable;
2731 return " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2734 $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2735 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id OR civicrm_relationship.contact_id_b = contact_b.id)";
2739 elseif (self
::$_relType == 'b') {
2740 $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2741 return "$from $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2744 $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2745 return "$from $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2749 $from = " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2750 return "$from INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2753 return " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2755 case 'civicrm_grant':
2756 return CRM_Grant_BAO_Query
::from($name, $mode, $side);
2758 case 'civicrm_website':
2759 return " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2761 case 'civicrm_campaign':
2762 //Move to default case if not in either mode.
2763 if ($mode & CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
2764 return CRM_Contribute_BAO_Query
::from($name, $mode, $side);
2766 elseif ($mode & CRM_Contact_BAO_Query
::MODE_MAILING
) {
2767 return CRM_Mailing_BAO_Query
::from($name, $mode, $side);
2769 elseif ($mode & CRM_Contact_BAO_Query
::MODE_CAMPAIGN
) {
2770 return CRM_Campaign_BAO_Query
::from($name, $mode, $side);
2774 $locationTypeName = '';
2775 if (strpos($name, '-address') != 0) {
2776 $locationTypeName = 'address';
2778 elseif (strpos($name, '-phone') != 0) {
2779 $locationTypeName = 'phone';
2781 elseif (strpos($name, '-email') != 0) {
2782 $locationTypeName = 'email';
2784 elseif (strpos($name, '-im') != 0) {
2785 $locationTypeName = 'im';
2787 elseif (strpos($name, '-openid') != 0) {
2788 $locationTypeName = 'openid';
2791 if ($locationTypeName) {
2792 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2793 $parts = explode('-', $name);
2794 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
2795 foreach ($locationTypes as $locationTypeID => $locationType) {
2796 if ($parts[0] == str_replace(' ', '_', $locationType)) {
2797 $locationID = $locationTypeID;
2800 $from = " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2803 $from = CRM_Core_Component
::from($name, $mode, $side);
2805 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2812 * WHERE / QILL clause for deleted_contacts
2814 * @param array $values
2816 public function deletedContacts($values) {
2817 list($_, $_, $value, $grouping, $_) = $values;
2819 // *prepend* to the relevant grouping as this is quite an important factor
2820 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2825 * Where / qill clause for contact_type
2829 * @throws \CRM_Core_Exception
2831 public function contactType(&$values) {
2832 list($name, $op, $value, $grouping, $wildcard) = $values;
2837 // account for search builder mapping multiple values
2838 if (!is_array($value)) {
2839 $values = self
::parseSearchBuilderString($value, 'String');
2840 if (is_array($values)) {
2841 $value = array_flip($values);
2845 if (is_array($value)) {
2846 foreach ($value as $k => $v) {
2851 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2852 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2855 if (!empty($subType)) {
2856 $subTypes[$subType] = 1;
2858 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2863 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2864 $contactType = $contactTypeANDSubType[0];
2865 $subType = $contactTypeANDSubType[1] ??
NULL;
2866 if (!empty($subType)) {
2867 $subTypes[$subType] = 1;
2869 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2873 if (!empty($clause)) {
2875 if ($op == 'IN' ||
$op == 'NOT IN') {
2876 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2879 $type = array_pop($clause);
2880 $this->_where
[$grouping][] = self
::buildClause("contact_a.contact_type", $op, $contactType);
2883 $this->_qill
[$grouping][] = ts('Contact Type') . " $op " . implode(' ' . ts('or') . ' ', $quill);
2885 if (!empty($subTypes)) {
2886 $this->includeContactSubTypes($subTypes, $grouping);
2892 * Where / qill clause for contact_sub_type.
2894 * @param array $values
2896 public function contactSubType(&$values) {
2897 list($name, $op, $value, $grouping, $wildcard) = $values;
2898 $this->includeContactSubTypes($value, $grouping, $op);
2906 * @throws \CRM_Core_Exception
2908 public function includeContactSubTypes($value, $grouping, $op = 'LIKE') {
2910 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2912 $value = $value[$op];
2916 $alias = "contact_a.contact_sub_type";
2917 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
2919 $op = str_replace('IN', 'LIKE', $op);
2920 $op = str_replace('=', 'LIKE', $op);
2921 $op = str_replace('!', 'NOT ', $op);
2923 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2924 $this->_where
[$grouping][] = self
::buildClause($alias, $op, $value, 'String');
2926 elseif (is_array($value)) {
2927 foreach ($value as $k => $v) {
2928 $clause[$k] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($v, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2932 $clause[$value] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2935 if (!empty($clause)) {
2936 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2938 $this->_qill
[$grouping][] = ts('Contact Subtype %1 ', [1 => $qillOperators[$op]]) . implode(' ' . ts('or') . ' ', array_keys($clause));
2942 * Where / qill clause for groups.
2946 * @throws \CRM_Core_Exception
2947 * @throws \Exception
2949 public function group($values) {
2950 list($name, $op, $value, $grouping, $wildcard) = $values;
2952 // If the $value is in OK (operator as key) array format we need to extract the key as operator and value first
2953 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2955 $value = $value[$op];
2957 // Translate EMPTY to NULL as EMPTY is cannot be used in it's intended meaning here
2958 // so has to be 'squashed into' NULL. (ie. group membership cannot be '').
2959 // even one group might equate to multiple when looking at children so IN is simpler.
2960 // @todo - also look at != casting but there are rows below to review.
2962 'IS EMPTY' => 'IS NULL',
2963 'IS NOT EMPTY' => 'IS NOT NULL',
2966 if (isset($opReplacements[$op])) {
2967 $op = $opReplacements[$op];
2970 if (strpos($op, 'NULL')) {
2974 if (is_array($value) && count($value) > 1) {
2975 if (strpos($op, 'IN') === FALSE && strpos($op, 'NULL') === FALSE) {
2976 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", [1 => $op]));
2978 $this->_useDistinct
= TRUE;
2981 if (isset($value)) {
2982 $value = CRM_Utils_Array
::value($op, $value, $value);
2985 if ($name === 'group_type') {
2986 $value = array_keys($this->getGroupsFromTypeCriteria($value));
2989 $regularGroupIDs = $smartGroupIDs = [];
2990 foreach ((array) $value as $id) {
2991 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
2992 $smartGroupIDs[] = (int) $id;
2995 $regularGroupIDs[] = (int) trim($id);
2998 $hasNonSmartGroups = count($regularGroupIDs);
3000 $isNotOp = ($op === 'NOT IN' ||
$op === '!=');
3002 $statusJoinClause = $this->getGroupStatusClause($grouping);
3003 // If we are searching for 'Removed' contacts then despite it being a smart group we only care about the group_contact table.
3004 $isGroupStatusSearch = (!empty($this->getSelectedGroupStatuses($grouping)) && $this->getSelectedGroupStatuses($grouping) !== ["'Added'"]);
3006 if ($hasNonSmartGroups ||
empty($value) ||
$isGroupStatusSearch) {
3007 // include child groups IDs if any
3008 $childGroupIds = (array) CRM_Contact_BAO_Group
::getChildGroupIds($regularGroupIDs);
3009 foreach ($childGroupIds as $key => $id) {
3010 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
3011 $smartGroupIDs[] = $id;
3012 unset($childGroupIds[$key]);
3015 if (count($childGroupIds)) {
3016 $regularGroupIDs = array_merge($regularGroupIDs, $childGroupIds);
3019 if (empty($regularGroupIDs)) {
3020 if ($isGroupStatusSearch) {
3021 $regularGroupIDs = $smartGroupIDs;
3023 // If it is still empty we want a filter that blocks all results.
3024 if (empty($regularGroupIDs)) {
3025 $regularGroupIDs = [0];
3029 $gcTable = '`civicrm_group_contact-' . uniqid() . "`";
3030 $joinClause = ["contact_a.id = {$gcTable}.contact_id"];
3032 // @todo consider just casting != to NOT IN & handling both together.
3035 if (!empty($regularGroupIDs)) {
3036 $groupIds = CRM_Utils_Type
::validate(
3037 implode(',', (array) $regularGroupIDs),
3038 'CommaSeparatedIntegers'
3041 $clause = "{$gcTable}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact cgc WHERE cgc.group_id = $groupIds )";
3044 $clause = self
::buildClause("{$gcTable}.group_id", $op, $regularGroupIDs);
3046 $groupClause[] = "( {$clause} )";
3048 if ($statusJoinClause) {
3049 $joinClause[] = "{$gcTable}.$statusJoinClause";
3051 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
3054 //CRM-19589: contact(s) removed from a Smart Group, resides in civicrm_group_contact table
3055 // If we are only searching for Removed or Pending contacts we don't need to resolve the smart group
3056 // as that info is in the group_contact table.
3057 if ((count($smartGroupIDs) ||
empty($value)) && !$isGroupStatusSearch) {
3058 $this->_groupUniqueKey
= uniqid();
3059 $this->_groupKeys
[] = $this->_groupUniqueKey
;
3060 $gccTableAlias = "civicrm_group_contact_cache_{$this->_groupUniqueKey}";
3061 $groupContactCacheClause = $this->addGroupContactCache($smartGroupIDs, $gccTableAlias, "contact_a", $op);
3062 if (!empty($groupContactCacheClause)) {
3064 $groupIds = CRM_Utils_Type
::validate(implode(',', (array) $smartGroupIDs), 'CommaSeparatedIntegers');
3065 $gcTable = "civicrm_group_contact_{$this->_groupUniqueKey}";
3066 $joinClause = ["contact_a.id = {$gcTable}.contact_id"];
3067 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
3068 if (strpos($op, 'IN') !== FALSE) {
3069 $groupClause[] = "{$gcTable}.group_id $op ( $groupIds ) AND {$gccTableAlias}.group_id IS NULL";
3072 $groupClause[] = "{$gcTable}.group_id $op $groupIds AND {$gccTableAlias}.group_id IS NULL";
3075 $groupClause[] = " ( {$groupContactCacheClause} ) ";
3079 $and = ($op == 'IS NULL') ?
' AND ' : ' OR ';
3080 if (!empty($groupClause)) {
3081 $this->_where
[$grouping][] = ' ( ' . implode($and, $groupClause) . ' ) ';
3084 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Group', 'id', $value, $op);
3085 $this->_qill
[$grouping][] = ts("Group(s) %1 %2", [1 => $qillop, 2 => $qillVal]);
3086 if (strpos($op, 'NULL') === FALSE) {
3087 $this->_qill
[$grouping][] = ts("Group Status %1", [1 => implode(' ' . ts('or') . ' ', $this->getSelectedGroupStatuses($grouping))]);
3094 public function getGroupCacheTableKeys() {
3095 return $this->_groupKeys
;
3099 * Function translates selection of group type into a list of groups.
3104 public function getGroupsFromTypeCriteria($value) {
3106 foreach ((array) $value as $groupTypeValue) {
3107 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
3108 $groupIds = ($groupIds +
$groupList);
3114 * Prime smart group cache for smart groups in the search, and join
3115 * civicrm_group_contact_cache table into the query.
3117 * @param array $groups IDs of groups specified in search criteria.
3118 * @param string $tableAlias Alias to use for civicrm_group_contact_cache table.
3119 * @param string $joinTable Table on which to join civicrm_group_contact_cache
3120 * @param string $op SQL comparison operator (NULL, IN, !=, IS NULL, etc.)
3121 * @param string $joinColumn Column in $joinTable on which to join civicrm_group_contact_cache.contact_id
3123 * @return string WHERE clause component for smart group criteria.
3124 * @throws \CRM_Core_Exception
3126 public function addGroupContactCache($groups, $tableAlias, $joinTable = "contact_a", $op, $joinColumn = 'id') {
3127 $isNullOp = (strpos($op, 'NULL') !== FALSE);
3128 $groupsIds = $groups;
3130 $operator = ['=' => 'IN', '!=' => 'NOT IN'];
3131 if (!empty($operator[$op]) && is_array($groups)) {
3132 $op = $operator[$op];
3134 if (!$isNullOp && !$groups) {
3137 elseif (strpos($op, 'IN') !== FALSE) {
3138 $groups = [$op => $groups];
3140 elseif (is_array($groups) && count($groups)) {
3141 $groups = ['IN' => $groups];
3144 // Find all the groups that are part of a saved search.
3145 $smartGroupClause = self
::buildClause("id", $op, $groups, 'Int');
3147 SELECT id, cache_date, saved_search_id, children
3149 WHERE $smartGroupClause
3150 AND ( saved_search_id != 0
3151 OR saved_search_id IS NOT NULL
3152 OR children IS NOT NULL )
3155 $group = CRM_Core_DAO
::executeQuery($sql);
3157 while ($group->fetch()) {
3158 $this->_useDistinct
= TRUE;
3159 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
3160 CRM_Contact_BAO_GroupContactCache
::load($group);
3163 if ($group->N
== 0 && $op != 'NOT IN') {
3167 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache {$tableAlias} ON {$joinTable}.{$joinColumn} = {$tableAlias}.contact_id ";
3169 if ($op == 'NOT IN') {
3170 return "{$tableAlias}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact_cache cgcc WHERE cgcc.group_id IN ( " . implode(',', (array) $groupsIds) . " ) )";
3172 return self
::buildClause("{$tableAlias}.group_id", $op, $groups, 'Int');
3176 * Where / qill clause for cms users
3180 public function ufUser(&$values) {
3181 list($name, $op, $value, $grouping, $wildcard) = $values;
3184 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3186 $this->_qill
[$grouping][] = ts('CMS User');
3188 elseif ($value == 0) {
3189 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3191 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
3192 $this->_qill
[$grouping][] = ts('Not a CMS User');
3197 * All tag search specific.
3199 * @param array $values
3201 * @throws \CRM_Core_Exception
3203 public function tagSearch(&$values) {
3204 list($name, $op, $value, $grouping, $wildcard) = $values;
3207 $value = "%{$value}%";
3208 $escapedValue = CRM_Utils_Type
::escape("%{$value}%", 'String');
3210 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3211 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3213 $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
3214 $tTable = "`civicrm_tag-" . uniqid() . "`";
3216 if ($useAllTagTypes[2]) {
3217 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3218 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
3219 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
3221 // search tag in cases
3222 $etCaseTable = "`civicrm_entity_case_tag-" . uniqid() . "`";
3223 $tCaseTable = "`civicrm_case_tag-" . uniqid() . "`";
3224 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3225 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3226 LEFT JOIN civicrm_case
3227 ON (civicrm_case_contact.case_id = civicrm_case.id
3228 AND civicrm_case.is_deleted = 0 )
3229 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
3230 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
3231 // search tag in activities
3232 $etActTable = "`civicrm_entity_act_tag-" . uniqid() . "`";
3233 $tActTable = "`civicrm_act_tag-" . uniqid() . "`";
3234 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
3235 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3237 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3238 = " LEFT JOIN civicrm_activity_contact
3239 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3240 LEFT JOIN civicrm_activity
3241 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3242 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3243 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
3244 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
3246 $this->_where
[$grouping][] = "({$tTable}.name $op '" . $escapedValue . "' OR {$tCaseTable}.name $op '" . $escapedValue . "' OR {$tActTable}.name $op '" . $escapedValue . "')";
3247 $this->_qill
[$grouping][] = ts('Tag %1 %2', [1 => $tagTypesText[2], 2 => $op]) . ' ' . $value;
3250 $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
3251 $tTable = "`civicrm_tag-" . uniqid() . "`";
3252 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
3253 {$etTable}.entity_table = 'civicrm_contact' )
3254 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
3256 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
3257 $this->_qill
[$grouping][] = ts('Tagged %1', [1 => $op]) . ' ' . $value;
3262 * Where / qill clause for tag.
3264 * @param array $values
3266 * @throws \CRM_Core_Exception
3268 public function tag(&$values) {
3269 list($name, $op, $value, $grouping, $wildcard) = $values;
3271 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_EntityTag', "tag_id", $value, $op, ['onlyActive' => FALSE]);
3272 // API/Search Builder format array(operator => array(values))
3273 if (is_array($value)) {
3274 if (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
3276 $value = $value[$op];
3278 if (count($value) > 1) {
3279 $this->_useDistinct
= TRUE;
3283 // implode array, then remove all spaces
3284 $value = str_replace(' ', '', implode(',', (array) $value));
3285 if (!empty($value)) {
3286 $value = CRM_Utils_Type
::validate(
3288 'CommaSeparatedIntegers'
3292 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3293 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3295 $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
3297 if ($useAllTagTypes[2]) {
3298 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3299 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3301 // search tag in cases
3302 $etCaseTable = "`civicrm_entity_case_tag-" . uniqid() . "`";
3303 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
3304 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3306 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3307 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3308 LEFT JOIN civicrm_case
3309 ON (civicrm_case_contact.case_id = civicrm_case.id
3310 AND civicrm_case.is_deleted = 0 )
3311 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3312 // search tag in activities
3313 $etActTable = "`civicrm_entity_act_tag-" . uniqid() . "`";
3314 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3315 = " LEFT JOIN civicrm_activity_contact
3316 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3317 LEFT JOIN civicrm_activity
3318 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3319 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3320 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3323 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
3324 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3327 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (" . $value . ") OR {$etCaseTable}.tag_id $op (" . $value . ") OR {$etActTable}.tag_id $op (" . $value . "))";
3331 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3332 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3335 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
3336 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3337 $op = str_replace('EMPTY', 'NULL', $op);
3338 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
3340 // CRM-16941: for tag tried with != operator we don't show contact who don't have given $value AND also in other tag
3341 elseif ($op == '!=') {
3342 $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') . ")";
3344 elseif ($op == '=' ||
strstr($op, 'IN')) {
3345 $op = ($op == '=') ?
'IN' : $op;
3346 $this->_where
[$grouping][] = "{$etTable}.tag_id $op ( $value )";
3349 $this->_qill
[$grouping][] = ts('Tagged %1 %2', [1 => $qillop, 2 => $qillVal]);
3353 * Where/qill clause for notes
3355 * @param array $values
3357 * @throws \CRM_Core_Exception
3359 public function notes(&$values) {
3360 list($name, $op, $value, $grouping, $wildcard) = $values;
3362 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3363 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
3364 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
3366 $this->_useDistinct
= TRUE;
3368 $this->_tables
['civicrm_note'] = $this->_whereTables
['civicrm_note']
3369 = " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3372 $value = CRM_Core_DAO
::escapeString($n);
3374 if (strpos($value, '%') === FALSE) {
3375 $value = "%$value%";
3379 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
3385 if ($noteOption %
2 == 0) {
3386 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
3387 $label = ts('Note: Body Only');
3389 if ($noteOption %
3 == 0) {
3390 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
3391 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
3393 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3394 list($qillOp, $qillVal) = self
::buildQillForFieldValue(NULL, $name, $n, $op);
3395 $this->_qill
[$grouping][] = ts("%1 %2 %3", [1 => $label, 2 => $qillOp, 3 => $qillVal]);
3399 * @param string $name
3405 public function nameNullOrEmptyOp($name, $op, $grouping) {
3409 $this->_where
[$grouping][] = "contact_a.$name $op";
3410 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3414 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3415 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3418 case 'IS NOT EMPTY':
3419 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3420 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3429 * Where / qill clause for sort_name
3431 * @param array $values
3433 public function sortName(&$values) {
3434 list($fieldName, $op, $value, $grouping, $wildcard) = $values;
3436 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3437 if ($this->nameNullOrEmptyOp($fieldName, $op, $grouping)) {
3441 $input = $value = is_array($value) ?
trim($value['LIKE']) : trim($value);
3443 if (!strlen($value)) {
3447 $config = CRM_Core_Config
::singleton();
3451 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3454 $firstChar = substr($value, 0, 1);
3455 $lastChar = substr($value, -1, 1);
3456 $quotes = ["'", '"'];
3457 // If string is quoted, strip quotes and otherwise don't alter it
3458 if ((strlen($value) > 2) && in_array($firstChar, $quotes) && in_array($lastChar, $quotes)) {
3459 $value = trim($value, implode('', $quotes));
3461 // Replace spaces with wildcards for a LIKE operation
3462 // UNLESS string contains a comma (this exception is a tiny bit questionable)
3463 // Also need to check if there is space in between sort name.
3464 elseif ($op == 'LIKE' && strpos($value, ',') === FALSE && strpos($value, ' ') === TRUE) {
3465 $value = str_replace(' ', '%', $value);
3467 $value = CRM_Core_DAO
::escapeString(trim($value));
3468 if (strlen($value)) {
3470 $value = "'" . self
::getWildCardedValue($wildcard, $op, $value) . "'";
3471 if ($fieldName == 'sort_name') {
3472 $wc = "contact_a.sort_name";
3475 $wc = "contact_a.display_name";
3477 $fieldsub[] = " ( $wc $op $value )";
3478 if ($config->includeNickNameInName
) {
3479 $wc = "contact_a.nick_name";
3480 $fieldsub[] = " ( $wc $op $value )";
3482 if ($config->includeEmailInName
) {
3483 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3485 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3488 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3490 $this->_where
[$grouping][] = $sub;
3491 if ($config->includeEmailInName
) {
3492 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3493 $this->_qill
[$grouping][] = ts('Name or Email') . " $op - '$input'";
3496 $this->_qill
[$grouping][] = ts('Name') . " $op - '$input'";
3501 * Where/qill clause for greeting fields.
3503 * @param array $values
3505 * @throws \CRM_Core_Exception
3507 public function greetings(&$values) {
3508 list($name, $op, $value, $grouping, $wildcard) = $values;
3509 $name .= '_display';
3511 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
3512 $this->_qill
[$grouping][] = ts('Greeting %1 %2', [1 => $qillop, 2 => $qillVal]);
3513 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value, 'String');
3517 * Where / qill clause for email
3519 * @param array $values
3520 * @param string $isForcePrimaryOnly
3522 * @throws \CRM_Core_Exception
3524 protected function email(&$values, $isForcePrimaryOnly) {
3525 list($name, $op, $value, $grouping, $wildcard) = $values;
3526 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3528 // CRM-18147: for Contact's GET API, email fieldname got appended with its entity as in {$apiEntiy}_{$name}
3529 // so following code is use build whereClause for contact's primart email id
3530 if (!empty($isForcePrimaryOnly)) {
3531 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.is_primary', '=', 1, 'Integer');
3533 // @todo - this should come from the $this->_fields array
3534 $dbName = $name === 'email_id' ?
'id' : $name;
3536 if (is_array($value) ||
$name === 'email_id') {
3537 $this->_qill
[$grouping][] = $this->getQillForField($name, $value, $op, [], ts('Email'));
3538 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.' . $dbName, $op, $value, 'String');
3542 // Is this ever hit now? Ideally ensure always an array & handle above.
3545 if (substr($n, 0, 1) == '"' &&
3546 substr($n, -1, 1) == '"'
3548 $n = substr($n, 1, -1);
3549 $value = CRM_Core_DAO
::escapeString($n);
3553 $value = self
::getWildCardedValue($wildcard, $op, $n);
3555 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3556 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3559 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3560 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3565 * Where / qill clause for phone number
3567 * @param array $values
3569 * @throws \CRM_Core_Exception
3571 public function phone_numeric(&$values) {
3572 list($name, $op, $value, $grouping, $wildcard) = $values;
3573 // Strip non-numeric characters; allow wildcards
3574 $number = preg_replace('/[^\d%]/', '', $value);
3576 if (strpos($number, '%') === FALSE) {
3577 $number = "%$number%";
3580 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3581 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3582 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3587 * Where / qill clause for phone type/location
3589 * @param array $values
3591 * @throws \CRM_Core_Exception
3593 public function phone_option_group($values) {
3594 list($name, $op, $value, $grouping, $wildcard) = $values;
3595 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3596 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3597 $optionName = $options[$value];
3598 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3599 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3600 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3604 * Where / qill clause for street_address.
3606 * @param array $values
3608 * @throws \CRM_Core_Exception
3610 public function street_address(&$values) {
3611 list($name, $op, $value, $grouping) = $values;
3620 if (strpos($value, '%') === FALSE) {
3621 // only add wild card if not there
3622 $value = "%{$value}%";
3625 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, $value, 'String');
3626 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3629 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3630 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3633 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3637 * Where / qill clause for street_unit.
3639 * @param array $values
3641 * @throws \CRM_Core_Exception
3643 public function street_number(&$values) {
3644 list($name, $op, $value, $grouping, $wildcard) = $values;
3652 if (strtolower($n) == 'odd') {
3653 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3654 $this->_qill
[$grouping][] = ts('Street Number is odd');
3656 elseif (strtolower($n) == 'even') {
3657 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3658 $this->_qill
[$grouping][] = ts('Street Number is even');
3662 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_number', $op, $value, 'String');
3663 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3666 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3670 * Where / qill clause for sorting by character.
3672 * @param array $values
3674 public function sortByCharacter(&$values) {
3675 list($name, $op, $value, $grouping, $wildcard) = $values;
3677 $name = trim($value);
3678 $cond = " contact_a.sort_name LIKE '" . CRM_Core_DAO
::escapeWildCardString($name) . "%'";
3679 $this->_where
[$grouping][] = $cond;
3680 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', [1 => $name]);
3684 * Where / qill clause for including contact ids.
3686 public function includeContactIDs() {
3687 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3692 foreach ($this->_params
as $id => $values) {
3693 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3694 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3697 CRM_Utils_Type
::validateAll($contactIds, 'Positive');
3698 if (!empty($contactIds)) {
3699 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3704 * Where / qill clause for postal code.
3706 * @param array $values
3708 * @throws \CRM_Core_Exception
3710 public function postalCode(&$values) {
3711 // skip if the fields dont have anything to do with postal_code
3712 if (empty($this->_fields
['postal_code'])) {
3716 list($name, $op, $value, $grouping, $wildcard) = $values;
3718 // Handle numeric postal code range searches properly by casting the column as numeric
3719 if (is_numeric($value)) {
3720 $field = "IF (civicrm_address.postal_code REGEXP '^[0-9]{1,10}$', CAST(civicrm_address.postal_code AS UNSIGNED), 0)";
3721 $val = CRM_Utils_Type
::escape($value, 'Integer');
3724 $field = 'civicrm_address.postal_code';
3725 // Per CRM-17060 we might be looking at an 'IN' syntax so don't case arrays to string.
3726 if (!is_array($value)) {
3727 $val = CRM_Utils_Type
::escape($value, 'String');
3730 // Do we need to escape values here? I would expect buildClause does.
3735 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3737 if ($name == 'postal_code') {
3738 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3739 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3741 elseif ($name == 'postal_code_low') {
3742 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3743 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', [1 => $value]);
3745 elseif ($name == 'postal_code_high') {
3746 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3747 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', [1 => $value]);
3752 * Where / qill clause for location type.
3754 * @param array $values
3755 * @param null $status
3759 public function locationType(&$values, $status = NULL) {
3760 list($name, $op, $value, $grouping, $wildcard) = $values;
3762 if (is_array($value)) {
3763 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')';
3764 $this->_tables
['civicrm_address'] = 1;
3765 $this->_whereTables
['civicrm_address'] = 1;
3767 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3769 foreach ($value as $id) {
3770 $names[] = $locationType[$id];
3773 $this->_primaryLocation
= FALSE;
3776 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3779 return implode(' ' . ts('or') . ' ', $names);
3786 * @param bool $fromStateProvince
3788 * @return array|NULL
3789 * @throws \CRM_Core_Exception
3791 public function country(&$values, $fromStateProvince = TRUE) {
3792 list($name, $op, $value, $grouping, $wildcard) = $values;
3794 if (!$fromStateProvince) {
3795 $stateValues = $this->getWhereValues('state_province', $grouping);
3796 if (!empty($stateValues)) {
3797 // return back to caller if there are state province values
3798 // since that handles this case
3803 $countryClause = $countryQill = NULL;
3804 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY']) ||
($values && !empty($value))) {
3805 $this->_tables
['civicrm_address'] = 1;
3806 $this->_whereTables
['civicrm_address'] = 1;
3808 $countryClause = self
::buildClause('civicrm_address.country_id', $op, $value, 'Positive');
3809 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, 'country_id', $value, $op);
3810 $countryQill = ts("%1 %2 %3", [1 => 'Country', 2 => $qillop, 3 => $qillVal]);
3812 if (!$fromStateProvince) {
3813 $this->_where
[$grouping][] = $countryClause;
3814 $this->_qill
[$grouping][] = $countryQill;
3818 if ($fromStateProvince) {
3819 if (!empty($countryClause)) {
3822 " ...AND... " . $countryQill,
3826 return [NULL, NULL];
3832 * Where / qill clause for county (if present).
3834 * @param array $values
3835 * @param null $status
3839 public function county(&$values, $status = NULL) {
3840 list($name, $op, $value, $grouping, $wildcard) = $values;
3842 if (!is_array($value)) {
3843 // force the county to be an array
3847 // check if the values are ids OR names of the counties
3848 $inputFormat = 'id';
3849 foreach ($value as $v) {
3850 if (!is_numeric($v)) {
3851 $inputFormat = 'name';
3859 elseif ($op == '!=') {
3863 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3864 $op = str_replace('EMPTY', 'NULL', $op);
3867 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
3868 $clause = "civicrm_address.county_id $op";
3870 elseif ($inputFormat == 'id') {
3871 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3873 $county = CRM_Core_PseudoConstant
::county();
3874 foreach ($value as $id) {
3875 $names[] = $county[$id] ??
NULL;
3880 $county = CRM_Core_PseudoConstant
::county();
3881 foreach ($value as $name) {
3882 $name = trim($name);
3883 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3885 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3888 $this->_tables
['civicrm_address'] = 1;
3889 $this->_whereTables
['civicrm_address'] = 1;
3891 $this->_where
[$grouping][] = $clause;
3893 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3896 return implode(' ' . ts('or') . ' ', $names);
3901 * Where / qill clause for state/province AND country (if present).
3903 * @param array $values
3904 * @param null $status
3907 * @throws \CRM_Core_Exception
3909 public function stateProvince(&$values, $status = NULL) {
3910 list($name, $op, $value, $grouping, $wildcard) = $values;
3912 $stateClause = self
::buildClause('civicrm_address.state_province_id', $op, $value, 'Positive');
3913 $this->_tables
['civicrm_address'] = 1;
3914 $this->_whereTables
['civicrm_address'] = 1;
3916 $countryValues = $this->getWhereValues('country', $grouping);
3917 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3918 if ($countryClause) {
3919 $clause = "( $stateClause AND $countryClause )";
3922 $clause = $stateClause;
3925 $this->_where
[$grouping][] = $clause;
3926 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
3928 $this->_qill
[$grouping][] = ts("State/Province %1 %2 %3", [1 => $qillop, 2 => $qillVal, 3 => $countryQill]);
3931 return implode(' ' . ts('or') . ' ', $qillVal) . $countryQill;
3936 * Where / qill clause for change log.
3938 * @param array $values
3940 public function changeLog(&$values) {
3941 list($name, $op, $value, $grouping, $wildcard) = $values;
3943 $targetName = $this->getWhereValues('changed_by', $grouping);
3948 $name = trim($targetName[2]);
3949 $name = CRM_Core_DAO
::escapeString($name);
3950 $name = $targetName[4] ?
"%$name%" : $name;
3951 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3952 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3953 $fieldTitle = ts('Altered By');
3955 list($qillop, $qillVal) = self
::buildQillForFieldValue(NULL, 'changed_by', $name, 'LIKE');
3956 $this->_qill
[$grouping][] = ts("%1 %2 '%3'", [
3966 * @throws \CRM_Core_Exception
3968 public function modifiedDates($values) {
3969 $this->_useDistinct
= TRUE;
3971 // CRM-11281, default to added date if not set
3972 $fieldTitle = ts('Added Date');
3973 $fieldName = 'created_date';
3974 foreach (array_keys($this->_params
) as $id) {
3975 if ($this->_params
[$id][0] == 'log_date') {
3976 if ($this->_params
[$id][2] == 2) {
3977 $fieldTitle = ts('Modified Date');
3978 $fieldName = 'modified_date';
3983 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3985 self
::$_openedPanes[ts('Change Log')] = TRUE;
3991 * @throws \CRM_Core_Exception
3993 public function demographics(&$values) {
3994 list($name, $op, $value, $grouping, $wildcard) = $values;
3996 if (($name == 'age_low') ||
($name == 'age_high')) {
3997 $this->ageRangeQueryBuilder($values,
3998 'contact_a', 'age', 'birth_date', ts('Age')
4001 elseif (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
4003 $this->dateQueryBuilder($values,
4004 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
4007 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
4009 $this->dateQueryBuilder($values,
4010 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
4014 self
::$_openedPanes[ts('Demographics')] = TRUE;
4020 public function privacy(&$values) {
4021 list($name, $op, $value, $grouping) = $values;
4022 if (is_array($value)) {
4023 if (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
4025 $value = $value[$op];
4028 $field = $this->_fields
[$name] ??
NULL;
4029 CRM_Utils_Type
::validate($value, 'Integer');
4030 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
4031 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
4032 $title = $field ?
$field['title'] : $name;
4033 $this->_qill
[$grouping][] = "$title $op $value";
4039 public function privacyOptions($values) {
4040 list($name, $op, $value, $grouping, $wildcard) = $values;
4042 if (empty($value) ||
!is_array($value)) {
4046 // get the operator and toggle values
4047 $opValues = $this->getWhereValues('privacy_operator', $grouping);
4050 strtolower($opValues[2] == 'AND')
4052 // @todo this line is logially unreachable
4056 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
4058 if ($toggleValues &&
4059 $toggleValues[2] == 2
4066 foreach ($value as $dontCare => $pOption) {
4067 $clauses[] = " ( contact_a.{$pOption} = 1 ) ";
4068 $field = $this->_fields
[$pOption] ??
NULL;
4069 $title = $field ?
$field['title'] : $pOption;
4070 $qill[] = " $title = 1 ";
4073 $this->_where
[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )';
4074 $this->_qill
[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )';
4080 * @throws \CRM_Core_Exception
4082 public function preferredCommunication(&$values) {
4083 list($name, $op, $value, $grouping, $wildcard) = $values;
4085 if (!is_array($value)) {
4086 $value = str_replace(['(', ')'], '', explode(",", $value));
4088 elseif (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
4090 $value = $value[$op];
4092 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Contact', $name, $value, $op);
4094 if (self
::caseImportant($op)) {
4095 $value = implode("[[:cntrl:]]|[[:cntrl:]]", (array) $value);
4096 $op = (strstr($op, '!') ||
strstr($op, 'NOT')) ?
'NOT RLIKE' : 'RLIKE';
4097 $value = "[[:cntrl:]]" . $value . "[[:cntrl:]]";
4100 $this->_where
[$grouping][] = self
::buildClause("contact_a.preferred_communication_method", $op, $value);
4101 $this->_qill
[$grouping][] = ts('Preferred Communication Method %1 %2', [1 => $qillop, 2 => $qillVal]);
4105 * Where / qill clause for relationship.
4107 * @param array $values
4109 public function relationship(&$values) {
4110 list($name, $op, $value, $grouping, $wildcard) = $values;
4111 if ($this->_relationshipValuesAdded
) {
4114 // also get values array for relation_target_name
4115 // for relationship search we always do wildcard
4116 $relationType = $this->getWhereValues('relation_type_id', $grouping);
4117 $description = $this->getWhereValues('relation_description', $grouping);
4118 $targetName = $this->getWhereValues('relation_target_name', $grouping);
4119 $relStatus = $this->getWhereValues('relation_status', $grouping);
4120 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
4122 $nameClause = $name = NULL;
4124 $name = trim($targetName[2]);
4125 if (substr($name, 0, 1) == '"' &&
4126 substr($name, -1, 1) == '"'
4128 $name = substr($name, 1, -1);
4129 $name = CRM_Core_DAO
::escapeString($name);
4130 $nameClause = "= '$name'";
4133 $name = CRM_Core_DAO
::escapeString($name);
4134 $nameClause = "LIKE '%{$name}%'";
4138 $relTypes = $relTypesIds = [];
4139 if (!empty($relationType)) {
4140 $relationType[2] = (array) $relationType[2];
4141 foreach ($relationType[2] as $relType) {
4142 $rel = explode('_', $relType);
4143 self
::$_relType = $rel[1];
4144 $params = ['id' => $rel[0]];
4146 $rTypeValue = CRM_Contact_BAO_RelationshipType
::retrieve($params, $typeValues);
4147 if (!empty($rTypeValue)) {
4148 if ($rTypeValue->name_a_b
== $rTypeValue->name_b_a
) {
4149 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4150 self
::$_relType = 'reciprocal';
4152 $relTypesIds[] = $rel[0];
4153 $relTypes[] = $relType;
4158 // if we are creating a temp table we build our own where for the relationship table
4159 $relationshipTempTable = NULL;
4160 if (self
::$_relType == 'reciprocal') {
4162 self
::$_relationshipTempTable = $relationshipTempTable = CRM_Utils_SQL_TempTable
::build()
4163 ->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`)")
4166 $where[$grouping][] = " sort_name $nameClause ";
4168 $groupJoinTable = "civicrm_relationship";
4169 $groupJoinColumn = "contact_id_alt";
4172 $where = &$this->_where
;
4174 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4176 $groupJoinTable = "contact_b";
4177 $groupJoinColumn = "id";
4179 $allRelationshipType = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, NULL, TRUE, 'label', FALSE);
4180 if ($nameClause ||
!$targetGroup) {
4181 if (!empty($relationType)) {
4183 foreach ($relTypes as $rel) {
4184 if (!empty($relQill)) {
4187 $relQill .= $allRelationshipType[$rel];
4189 $this->_qill
[$grouping][] = 'Relationship Type(s) ' . $relQill . " $name";
4192 $this->_qill
[$grouping][] = $name;
4196 //check to see if the target contact is in specified group
4198 //add contacts from static groups
4199 $this->_tables
['civicrm_relationship_group_contact'] = $this->_whereTables
['civicrm_relationship_group_contact']
4200 = " 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'";
4201 $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" .
4202 implode(",", $targetGroup[2]) . ") ) ";
4204 //add contacts from saved searches
4205 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", $groupJoinTable, $op, $groupJoinColumn);
4207 //set the group where clause
4209 $groupWhere[] = "( " . $ssWhere . " )";
4211 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4213 //Get the names of the target groups for the qill
4214 $groupNames = CRM_Core_PseudoConstant
::group();
4216 foreach ($targetGroup[2] as $groupId) {
4217 if (array_key_exists($groupId, $groupNames)) {
4218 $qillNames[] = $groupNames[$groupId];
4221 if (!empty($relationType)) {
4223 foreach ($relTypes as $rel) {
4224 if (!empty($relQill)) {
4227 $relQill .= CRM_Utils_Array
::value($rel, $allRelationshipType);
4229 $this->_qill
[$grouping][] = 'Relationship Type(s) ' . $relQill . " ( " . implode(", ", $qillNames) . " )";
4232 $this->_qill
[$grouping][] = implode(", ", $qillNames);
4237 if (!empty($description[2]) && trim($description[2])) {
4238 $this->_qill
[$grouping][] = ts('Relationship description - ' . $description[2]);
4239 $description = CRM_Core_DAO
::escapeString(trim($description[2]));
4240 $where[$grouping][] = "civicrm_relationship.description LIKE '%{$description}%'";
4243 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4244 $today = date('Ymd');
4245 //check for active, inactive and all relation status
4246 if ($relStatus[2] == 0) {
4247 $where[$grouping][] = "(
4248 civicrm_relationship.is_active = 1 AND
4249 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4250 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4252 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
4254 elseif ($relStatus[2] == 1) {
4255 $where[$grouping][] = "(
4256 civicrm_relationship.is_active = 0 OR
4257 civicrm_relationship.end_date < {$today} OR
4258 civicrm_relationship.start_date > {$today}
4260 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
4264 if (in_array(['deleted_contacts', '=', '1', '0', '0'], $this->_params
)) {
4267 $where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})";
4269 $this->addRelationshipPermissionClauses($grouping, $where);
4270 $this->addRelationshipDateClauses($grouping, $where);
4271 $this->addRelationshipActivePeriodClauses($grouping, $where);
4272 if (!empty($relTypes)) {
4273 $where[$grouping][] = 'civicrm_relationship.relationship_type_id IN (' . implode(',', $relTypesIds) . ')';
4275 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
4276 $this->_useDistinct
= TRUE;
4277 $this->_relationshipValuesAdded
= TRUE;
4278 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4280 if ($relationshipTempTable) {
4282 if (!empty($where[$grouping])) {
4283 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4284 $whereClause = str_replace('contact_b', 'c', $whereClause);
4287 INSERT INTO {$relationshipTempTable} (contact_id, contact_id_alt, id)
4288 (SELECT contact_id_b as contact_id, contact_id_a as contact_id_alt, civicrm_relationship.id
4289 FROM civicrm_relationship
4290 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4293 (SELECT contact_id_a as contact_id, contact_id_b as contact_id_alt, civicrm_relationship.id
4294 FROM civicrm_relationship
4295 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4298 CRM_Core_DAO
::executeQuery($sql);
4303 * Add relationship permission criteria to where clause.
4305 * @param string $grouping
4306 * @param array $where Array to add "where" criteria to, in case you are generating a temp table.
4307 * Not the main query.
4309 public function addRelationshipPermissionClauses($grouping, &$where) {
4310 $relPermission = $this->getWhereValues('relation_permission', $grouping);
4311 if ($relPermission) {
4312 if (!is_array($relPermission[2])) {
4313 // this form value was scalar in previous versions of Civi
4314 $relPermission[2] = [$relPermission[2]];
4316 $where[$grouping][] = "(civicrm_relationship.is_permission_a_b IN (" . implode(",", $relPermission[2]) . "))";
4318 $allRelationshipPermissions = CRM_Contact_BAO_Relationship
::buildOptions('is_permission_a_b');
4320 $relPermNames = array_intersect_key($allRelationshipPermissions, array_flip($relPermission[2]));
4321 $this->_qill
[$grouping][] = ts('Permissioned Relationships') . ' - ' . implode(' OR ', $relPermNames);
4326 * Add start & end date criteria in
4327 * @param string $grouping
4328 * @param array $where
4329 * = array to add where clauses to, in case you are generating a temp table.
4330 * not the main query.
4332 public function addRelationshipDateClauses($grouping, &$where) {
4333 foreach (['start_date', 'end_date'] as $dateField) {
4334 $dateValueLow = $this->getWhereValues('relationship_' . $dateField . '_low', $grouping);
4335 $dateValueHigh = $this->getWhereValues('relationship_' . $dateField . '_high', $grouping);
4336 if (!empty($dateValueLow)) {
4337 $date = date('Ymd', strtotime($dateValueLow[2]));
4338 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4339 $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);
4341 if (!empty($dateValueHigh)) {
4342 $date = date('Ymd', strtotime($dateValueHigh[2]));
4343 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4344 $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);
4350 * Add start & end active period criteria in
4351 * @param string $grouping
4352 * @param array $where
4353 * = array to add where clauses to, in case you are generating a temp table.
4354 * not the main query.
4356 public function addRelationshipActivePeriodClauses($grouping, &$where) {
4358 $dateField = 'active_period_date';
4360 $dateValueLow = $this->getWhereValues('relation_active_period_date_low', $grouping);
4361 $dateValueHigh = $this->getWhereValues('relation_active_period_date_high', $grouping);
4362 $dateValueLowFormated = $dateValueHighFormated = NULL;
4363 if (!empty($dateValueLow) && !empty($dateValueHigh)) {
4364 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4365 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
4366 $this->_qill
[$grouping][] = (ts('Relationship was active between')) . " " . CRM_Utils_Date
::customFormat($dateValueLowFormated) . " and " . CRM_Utils_Date
::customFormat($dateValueHighFormated);
4368 elseif (!empty($dateValueLow)) {
4369 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4370 $this->_qill
[$grouping][] = (ts('Relationship was active after')) . " " . CRM_Utils_Date
::customFormat($dateValueLowFormated);
4372 elseif (!empty($dateValueHigh)) {
4373 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
4374 $this->_qill
[$grouping][] = (ts('Relationship was active before')) . " " . CRM_Utils_Date
::customFormat($dateValueHighFormated);
4377 if ($activePeriodClauses = self
::getRelationshipActivePeriodClauses($dateValueLowFormated, $dateValueHighFormated, TRUE)) {
4378 $where[$grouping][] = $activePeriodClauses;
4383 * Get start & end active period criteria
4387 * @param $forceTableName
4391 public static function getRelationshipActivePeriodClauses($from, $to, $forceTableName) {
4392 $tableName = $forceTableName ?
'civicrm_relationship.' : '';
4393 if (!is_null($from) && !is_null($to)) {
4394 return '(((' . $tableName . 'start_date >= ' . $from . ' AND ' . $tableName . 'start_date <= ' . $to . ') OR
4395 (' . $tableName . 'end_date >= ' . $from . ' AND ' . $tableName . 'end_date <= ' . $to . ') OR
4396 (' . $tableName . 'start_date <= ' . $from . ' AND ' . $tableName . 'end_date >= ' . $to . ' )) OR
4397 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4398 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . ') OR
4399 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4401 elseif (!is_null($from)) {
4402 return '((' . $tableName . 'start_date >= ' . $from . ') OR
4403 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4404 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . '))';
4406 elseif (!is_null($to)) {
4407 return '((' . $tableName . 'start_date <= ' . $to . ') OR
4408 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4409 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4414 * Default set of return properties.
4419 * derault return properties
4421 public static function &defaultReturnProperties($mode = 1) {
4422 if (!isset(self
::$_defaultReturnProperties)) {
4423 self
::$_defaultReturnProperties = [];
4426 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4427 // add activity return properties
4428 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4429 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4432 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4435 if (empty(self
::$_defaultReturnProperties[$mode])) {
4436 self
::$_defaultReturnProperties[$mode] = [
4439 'legal_identifier' => 1,
4440 'external_identifier' => 1,
4441 'contact_type' => 1,
4442 'contact_sub_type' => 1,
4444 'display_name' => 1,
4445 'preferred_mail_format' => 1,
4452 'formal_title' => 1,
4453 'communication_style_id' => 1,
4456 'street_address' => 1,
4457 'supplemental_address_1' => 1,
4458 'supplemental_address_2' => 1,
4459 'supplemental_address_3' => 1,
4462 'postal_code_suffix' => 1,
4463 'state_province' => 1,
4465 'world_region' => 1,
4472 'household_name' => 1,
4473 'organization_name' => 1,
4474 'deceased_date' => 1,
4479 'current_employer' => 1,
4480 // FIXME: should we use defaultHierReturnProperties() for the below?
4481 'do_not_email' => 1,
4484 'do_not_phone' => 1,
4485 'do_not_trade' => 1,
4487 'contact_is_deleted' => 1,
4488 'preferred_communication_method' => 1,
4489 'preferred_language' => 1,
4493 return self
::$_defaultReturnProperties[$mode];
4497 * Get primary condition for a sql clause.
4501 * @return string|NULL
4503 public static function getPrimaryCondition($value) {
4504 if (is_numeric($value)) {
4505 $value = (int ) $value;
4506 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4512 * Wrapper for a simple search query.
4514 * @param array $params
4515 * @param array $returnProperties
4516 * @param bool $count
4519 * @throws \CRM_Core_Exception
4521 public static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4522 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4523 list($select, $from, $where, $having) = $query->query();
4524 $groupBy = ($query->_useGroupBy
) ?
'GROUP BY contact_a.id' : '';
4526 $query = "$select $from $where $groupBy $having";
4531 * These are stub comments as this function needs more explanation - particularly in terms of how it
4532 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4534 * This function was originally written as a wrapper for the api query but is called from multiple places
4535 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4536 * but it is unclear as to whehter that is historical or there is a reason
4537 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4539 * @param array $params
4540 * @param array $returnProperties
4541 * @param null $fields
4542 * @param string $sort
4543 * @param int $offset
4544 * @param int $row_count
4545 * @param bool $smartGroupCache
4546 * ?? update smart group cache?.
4547 * @param bool $count
4548 * Return count obnly.
4549 * @param bool $skipPermissions
4550 * Should permissions be ignored or should the logged in user's permissions be applied.
4552 * This basically correlates to the component.
4553 * @param string $apiEntity
4554 * The api entity being called.
4555 * This sort-of duplicates $mode in a confusing way. Probably not by design.
4557 * @param bool|null $primaryLocationOnly
4560 * @throws \CRM_Core_Exception
4562 public static function apiQuery(
4564 $returnProperties = NULL,
4569 $smartGroupCache = TRUE,
4571 $skipPermissions = TRUE,
4572 $mode = CRM_Contact_BAO_Query
::MODE_CONTACTS
,
4574 $primaryLocationOnly = NULL
4577 $query = new CRM_Contact_BAO_Query(
4578 $params, $returnProperties,
4579 NULL, TRUE, FALSE, $mode,
4581 TRUE, $smartGroupCache,
4583 $apiEntity, $primaryLocationOnly
4586 //this should add a check for view deleted if permissions are enabled
4587 if ($skipPermissions) {
4588 $query->_skipDeleteClause
= TRUE;
4590 $query->generatePermissionClause(FALSE, $count);
4592 // note : this modifies _fromClause and _simpleFromClause
4593 $query->includePseudoFieldsJoin($sort);
4595 list($select, $from, $where, $having) = $query->query($count);
4597 $options = $query->_options
;
4598 if (!empty($query->_permissionWhereClause
)) {
4599 if (empty($where)) {
4600 $where = "WHERE $query->_permissionWhereClause";
4603 $where = "$where AND $query->_permissionWhereClause";
4607 $sql = "$select $from $where $having";
4609 // add group by only when API action is not getcount
4610 // otherwise query fetches incorrect count
4611 if ($query->_useGroupBy
&& !$count) {
4612 $sql .= self
::getGroupByFromSelectColumns($query->_select
, 'contact_a.id');
4614 if (!empty($sort)) {
4615 $sort = CRM_Utils_Type
::escape($sort, 'String');
4616 $sql .= " ORDER BY $sort ";
4618 if ($row_count > 0 && $offset >= 0) {
4619 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4620 $row_count = CRM_Utils_Type
::escape($row_count, 'Int');
4621 $sql .= " LIMIT $offset, $row_count ";
4624 $dao = CRM_Core_DAO
::executeQuery($sql);
4626 // @todo derive this from the component class rather than hard-code two options.
4627 $entityIDField = ($mode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) ?
'contribution_id' : 'contact_id';
4630 while ($dao->fetch()) {
4632 $noRows = $dao->rowCount
;
4633 return [$noRows, NULL];
4635 $val = $query->store($dao);
4636 $convertedVals = $query->convertToPseudoNames($dao, TRUE, TRUE);
4638 if (!empty($convertedVals)) {
4639 $val = array_replace_recursive($val, $convertedVals);
4641 $values[$dao->$entityIDField] = $val;
4643 return [$values, $options];
4647 * Get the actual custom field name by stripping off the appended string.
4649 * The string could be _relative, _from, or _to
4651 * @todo use metadata rather than convention to do this.
4653 * @param string $parameterName
4654 * The name of the parameter submitted to the form.
4661 public static function getCustomFieldName($parameterName) {
4662 if (substr($parameterName, -5, 5) == '_from') {
4663 return substr($parameterName, 0, strpos($parameterName, '_from'));
4665 if (substr($parameterName, -9, 9) == '_relative') {
4666 return substr($parameterName, 0, strpos($parameterName, '_relative'));
4668 if (substr($parameterName, -3, 3) == '_to') {
4669 return substr($parameterName, 0, strpos($parameterName, '_to'));
4674 * Convert submitted values for relative custom fields to query object format.
4676 * The query will support the sqlOperator format so convert to that format.
4678 * @param array $formValues
4680 * @param array $params
4681 * Converted parameters for the query object.
4682 * @param string $values
4684 * @param string $fieldName
4685 * Submitted field name. (Matches form field not DB field.)
4687 protected static function convertCustomRelativeFields(&$formValues, &$params, $values, $fieldName) {
4688 if (empty($values)) {
4689 // e.g we might have relative set & from & to empty. The form flow is a bit funky &
4690 // this function gets called again after they fields have been converted which can get ugly.
4693 $customFieldName = self
::getCustomFieldName($fieldName);
4695 if (substr($fieldName, -9, 9) == '_relative') {
4696 list($from, $to) = CRM_Utils_Date
::getFromTo($values, NULL, NULL);
4699 if ($fieldName == $customFieldName . '_to' && !empty($formValues[$customFieldName . '_from'])) {
4700 // Both to & from are set. We only need to acton one, choosing from.
4704 $from = $formValues[$customFieldName . '_from'] ??
NULL;
4705 $to = $formValues[$customFieldName . '_to'] ??
NULL;
4707 if (self
::isCustomDateField($customFieldName)) {
4708 list($from, $to) = CRM_Utils_Date
::getFromTo(NULL, $from, $to);
4714 $relativeFunction = ['BETWEEN' => [$from, $to]];
4717 $relativeFunction = ['>=' => $from];
4721 $relativeFunction = ['<=' => $to];
4733 * Are we dealing with custom field of type date.
4738 * @throws \CiviCRM_API3_Exception
4740 public static function isCustomDateField($fieldName) {
4741 if (($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($fieldName)) == FALSE) {
4745 $customFieldDataType = civicrm_api3('CustomField', 'getvalue', ['id' => $customFieldID, 'return' => 'data_type']);
4746 if ('Date' == $customFieldDataType) {
4750 catch (CiviCRM_API3_Exception
$e) {
4756 * Has this field already been reformatting to Query object syntax.
4758 * The form layer passed formValues to this function in preProcess & postProcess. Reason unknown. This seems
4759 * to come with associated double queries & is possibly damaging performance.
4761 * However, here we add a tested function to ensure convertFormValues identifies pre-processed fields & returns
4764 * @param mixed $values
4765 * Value in formValues for the field.
4769 public static function isAlreadyProcessedForQueryFormat($values) {
4770 if (!is_array($values)) {
4773 if (($operator = CRM_Utils_Array
::value(1, $values)) == FALSE) {
4776 return in_array($operator, CRM_Core_DAO
::acceptedSQLOperators());
4780 * If the state and country are passed remove state.
4782 * Country is implicit from the state, but including both results in
4783 * a poor query as there is no combined index on state AND country.
4787 * @param array $formValues
4789 public static function filterCountryFromValuesIfStateExists(&$formValues) {
4790 if (!empty($formValues['country']) && !empty($formValues['state_province'])) {
4791 // The use of array map sanitises the data by ensuring we are dealing with integers.
4792 $states = implode(', ', array_map('intval', $formValues['state_province']));
4793 $countryList = CRM_Core_DAO
::singleValueQuery(
4794 "SELECT GROUP_CONCAT(country_id) FROM civicrm_state_province WHERE id IN ($states)"
4796 if ($countryList == $formValues['country']) {
4797 unset($formValues['country']);
4803 * For some special cases, grouping by subset of select fields becomes mandatory.
4804 * Hence, full_group_by mode is handled by appending any_value
4805 * keyword to select fields not present in groupBy
4807 * @param array $selectClauses
4808 * @param array $groupBy - Columns already included in GROUP By clause.
4809 * @param string $aggregateFunction
4813 public static function appendAnyValueToSelect($selectClauses, $groupBy, $aggregateFunction = 'ANY_VALUE') {
4814 if (!CRM_Utils_SQL
::disableFullGroupByMode()) {
4815 $groupBy = array_map('trim', (array) $groupBy);
4816 $aggregateFunctions = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN|IF)[[:blank:]]*\(/i';
4817 foreach ($selectClauses as $key => &$val) {
4818 list($selectColumn, $alias) = array_pad(preg_split('/ as /i', $val), 2, NULL);
4819 // append ANY_VALUE() keyword
4820 if (!in_array($selectColumn, $groupBy) && preg_match($aggregateFunctions, trim($selectColumn)) !== 1) {
4821 $val = ($aggregateFunction == 'GROUP_CONCAT') ?
4822 str_replace($selectColumn, "$aggregateFunction(DISTINCT {$selectColumn})", $val) :
4823 str_replace($selectColumn, "$aggregateFunction({$selectColumn})", $val);
4828 return "SELECT " . implode(', ', $selectClauses) . " ";
4832 * For some special cases, where if non-aggregate ORDER BY columns are not present in GROUP BY
4833 * on full_group_by mode, then append the those missing columns to GROUP BY clause
4834 * keyword to select fields not present in groupBy
4836 * @param string $groupBy - GROUP BY clause where missing ORDER BY columns will be appended if not present
4837 * @param array $orderBys - ORDER BY sub-clauses
4840 public static function getGroupByFromOrderBy(&$groupBy, $orderBys) {
4841 if (!CRM_Utils_SQL
::disableFullGroupByMode()) {
4842 foreach ($orderBys as $orderBy) {
4843 // remove sort syntax from ORDER BY clauses if present
4844 $orderBy = str_ireplace([' DESC', ' ASC', '`'], '', $orderBy);
4845 // if ORDER BY column is not present in GROUP BY then append it to end
4846 if (preg_match('/(MAX|MIN)\(/i', trim($orderBy)) !== 1 && !strstr($groupBy, $orderBy)) {
4847 $groupBy .= ", {$orderBy}";
4854 * Include Select columns in groupBy clause.
4856 * @param array $selectClauses
4857 * @param array $groupBy - Columns already included in GROUP By clause.
4861 public static function getGroupByFromSelectColumns($selectClauses, $groupBy = NULL) {
4862 $groupBy = (array) $groupBy;
4863 $mysqlVersion = CRM_Core_DAO
::singleValueQuery('SELECT VERSION()');
4864 $sqlMode = CRM_Core_DAO
::singleValueQuery('SELECT @@sql_mode');
4866 //return if ONLY_FULL_GROUP_BY is not enabled.
4867 if (CRM_Utils_SQL
::supportsFullGroupBy() && !empty($sqlMode) && in_array('ONLY_FULL_GROUP_BY', explode(',', $sqlMode))) {
4868 $regexToExclude = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN|IF)[[:blank:]]*\(/i';
4869 foreach ($selectClauses as $key => $val) {
4870 $aliasArray = preg_split('/ as /i', $val);
4871 // if more than 1 alias we need to split by ','.
4872 if (count($aliasArray) > 2) {
4873 $aliasArray = preg_split('/,/', $val);
4874 foreach ($aliasArray as $key => $value) {
4875 $alias = current(preg_split('/ as /i', $value));
4876 if (!in_array($alias, $groupBy) && preg_match($regexToExclude, trim($alias)) !== 1) {
4877 $groupBy[] = $alias;
4882 list($selectColumn, $alias) = array_pad($aliasArray, 2, NULL);
4883 $dateRegex = '/^(DATE_FORMAT|DATE_ADD|CASE)/i';
4884 $tableName = current(explode('.', $selectColumn));
4885 $primaryKey = "{$tableName}.id";
4886 // exclude columns which are already included in groupBy and aggregate functions from select
4887 // CRM-18439 - Also exclude the columns which are functionally dependent on columns in $groupBy (MySQL 5.7+)
4888 if (!in_array($selectColumn, $groupBy) && !in_array($primaryKey, $groupBy) && preg_match($regexToExclude, trim($selectColumn)) !== 1) {
4889 if (!empty($alias) && preg_match($dateRegex, trim($selectColumn))) {
4890 $groupBy[] = $alias;
4893 $groupBy[] = $selectColumn;
4900 if (!empty($groupBy)) {
4901 return " GROUP BY " . implode(', ', $groupBy);
4907 * Create and query the db for an contact search.
4909 * @param int $offset
4910 * The offset for the query.
4911 * @param int $rowCount
4912 * The number of rows to return.
4913 * @param string|CRM_Utils_Sort $sort
4914 * The order by string.
4915 * @param bool $count
4916 * Is this a count only query ?.
4917 * @param bool $includeContactIds
4918 * Should we include contact ids?.
4919 * @param bool $sortByChar
4920 * If true returns the distinct array of first characters for search results.
4921 * @param bool $groupContacts
4922 * If true, return only the contact ids.
4923 * @param bool $returnQuery
4924 * Should we return the query as a string.
4925 * @param string $additionalWhereClause
4926 * If the caller wants to further restrict the search (used for components).
4927 * @param null $sortOrder
4928 * @param string $additionalFromClause
4929 * Should be clause with proper joins, effective to reduce where clause load.
4931 * @param bool $skipOrderAndLimit
4933 * @return CRM_Core_DAO
4935 public function searchQuery(
4936 $offset = 0, $rowCount = 0, $sort = NULL,
4937 $count = FALSE, $includeContactIds = FALSE,
4938 $sortByChar = FALSE, $groupContacts = FALSE,
4939 $returnQuery = FALSE,
4940 $additionalWhereClause = NULL, $sortOrder = NULL,
4941 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4944 $query = $this->getSearchSQL($offset, $rowCount, $sort, $count, $includeContactIds, $sortByChar, $groupContacts, $additionalWhereClause, $sortOrder, $additionalFromClause, $skipOrderAndLimit);
4950 return CRM_Core_DAO
::singleValueQuery($query);
4953 $dao = CRM_Core_DAO
::executeQuery($query);
4955 // We can always call this - it will only re-enable if it was originally enabled.
4956 CRM_Core_DAO
::reenableFullGroupByMode();
4958 if ($groupContacts) {
4960 while ($dao->fetch()) {
4963 return implode(',', $ids);
4970 * Create and query the db for the list of all first letters used by contacts
4972 * @return CRM_Core_DAO
4974 public function alphabetQuery() {
4975 $sqlParts = $this->getSearchSQLParts(NULL, NULL, NULL, FALSE, FALSE, TRUE);
4976 $query = "SELECT DISTINCT LEFT(contact_a.sort_name, 1) as sort_name
4978 {$sqlParts['where']}
4979 {$sqlParts['having']}
4981 ORDER BY sort_name asc";
4982 $dao = CRM_Core_DAO
::executeQuery($query);
4987 * Fetch a list of contacts for displaying a search results page
4989 * @param array $cids
4990 * List of contact IDs
4991 * @param bool $includeContactIds
4992 * @return CRM_Core_DAO
4994 public function getCachedContacts($cids, $includeContactIds) {
4995 CRM_Core_DAO
::disableFullGroupByMode();
4996 CRM_Utils_Type
::validateAll($cids, 'Positive');
4997 $this->_includeContactIds
= $includeContactIds;
4998 $onlyDeleted = in_array(['deleted_contacts', '=', '1', '0', '0'], $this->_params
);
4999 list($select, $from, $where) = $this->query(FALSE, FALSE, FALSE, $onlyDeleted);
5000 $select .= sprintf(", (%s) AS _wgt", $this->createSqlCase('contact_a.id', $cids));
5001 $where .= sprintf(' AND contact_a.id IN (%s)', implode(',', $cids));
5002 $order = 'ORDER BY _wgt';
5003 $groupBy = $this->_useGroupBy ?
' GROUP BY contact_a.id' : '';
5005 $query = "$select $from $where $groupBy $order $limit";
5007 $result = CRM_Core_DAO
::executeQuery($query);
5008 CRM_Core_DAO
::reenableFullGroupByMode();
5013 * Construct a SQL CASE expression.
5015 * @param string $idCol
5016 * The name of a column with ID's (eg 'contact_a.id').
5017 * @param array $cids
5018 * Array(int $weight => int $id).
5020 * CASE WHEN id=123 THEN 1 WHEN id=456 THEN 2 END
5022 private function createSqlCase($idCol, $cids) {
5024 foreach ($cids as $weight => $cid) {
5025 $buf .= " WHEN $idCol = $cid THEN $weight \n";
5032 * Populate $this->_permissionWhereClause with permission related clause and update other
5033 * query related properties.
5035 * Function calls ACL permission class and hooks to filter the query appropriately
5037 * Note that these 2 params were in the code when extracted from another function
5038 * and a second round extraction would be to make them properties of the class
5040 * @param bool $onlyDeleted
5041 * Only get deleted contacts.
5042 * @param bool $count
5043 * Return Count only.
5045 public function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
5046 if (!$this->_skipPermission
) {
5047 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
5048 CRM_Core_Permission
::VIEW
,
5050 $this->_whereTables
,
5053 $this->_skipDeleteClause
5056 // regenerate fromClause since permission might have added tables
5057 if ($this->_permissionWhereClause
) {
5058 //fix for row count in qill (in contribute/membership find)
5060 $this->_useDistinct
= TRUE;
5063 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
5064 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
5065 // note : this modifies _fromClause and _simpleFromClause
5066 $this->includePseudoFieldsJoin($this->_sort
);
5070 // add delete clause if needed even if we are skipping permission
5072 if (!$this->_skipDeleteClause
) {
5073 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
5074 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
5078 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
5087 public function setSkipPermission($val) {
5088 $this->_skipPermission
= $val;
5092 * @param null $context
5095 * @throws \CRM_Core_Exception
5097 public function summaryContribution($context = NULL) {
5098 list($innerselect, $from, $where, $having) = $this->query(TRUE);
5099 if ($this->_permissionWhereClause
) {
5100 $where .= " AND " . $this->_permissionWhereClause
;
5102 if ($context == 'search') {
5103 $where .= " AND contact_a.is_deleted = 0 ";
5106 $this->appendFinancialTypeWhereAndFromToQueryStrings($where, $from);
5108 $summary = ['total' => []];
5109 $this->addBasicStatsToSummary($summary, $where, $from);
5111 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
5112 $this->addBasicSoftCreditStatsToStats($summary, $where, $from);
5115 $this->addBasicCancelStatsToSummary($summary, $where, $from);
5121 * Append financial ACL limits to the query from & where clauses, if applicable.
5123 * @param string $where
5124 * @param string $from
5126 public function appendFinancialTypeWhereAndFromToQueryStrings(&$where, &$from) {
5127 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
5130 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
5131 if (!empty($financialTypes)) {
5132 $where .= " AND civicrm_contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND li.id IS NULL";
5133 $from .= " LEFT JOIN civicrm_line_item li
5134 ON civicrm_contribution.id = li.contribution_id AND
5135 li.entity_table = 'civicrm_contribution' AND li.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ") ";
5138 $where .= " AND civicrm_contribution.financial_type_id IN (0)";
5143 * Getter for the qill object.
5147 public function qill() {
5148 return $this->_qill
;
5152 * Default set of return default hier return properties.
5156 public static function &defaultHierReturnProperties() {
5157 if (!isset(self
::$_defaultHierReturnProperties)) {
5158 self
::$_defaultHierReturnProperties = [
5161 'legal_identifier' => 1,
5162 'external_identifier' => 1,
5163 'contact_type' => 1,
5164 'contact_sub_type' => 1,
5166 'display_name' => 1,
5173 'formal_title' => 1,
5174 'communication_style_id' => 1,
5175 'email_greeting' => 1,
5176 'postal_greeting' => 1,
5180 'preferred_communication_method' => 1,
5181 'do_not_phone' => 1,
5182 'do_not_email' => 1,
5185 'do_not_trade' => 1,
5188 'location_type' => 1,
5189 'street_address' => 1,
5191 'state_province' => 1,
5193 'postal_code_suffix' => 1,
5196 'phone-Mobile' => 1,
5209 'location_type' => 1,
5210 'street_address' => 1,
5212 'state_province' => 1,
5214 'postal_code_suffix' => 1,
5217 'phone-Mobile' => 1,
5231 return self
::$_defaultHierReturnProperties;
5235 * Build query for a date field.
5237 * @param array $values
5238 * @param string $tableName
5239 * @param string $fieldName
5240 * @param string $dbFieldName
5241 * @param string $fieldTitle
5242 * @param bool $appendTimeStamp
5243 * @param string $dateFormat
5244 * @param string|null $highDBFieldName
5245 * Optional field name for when the 'high' part of the calculation uses a different field than the 'low' part.
5246 * This is an obscure situation & one we don't want to do more of but supporting them here is the only way for now.
5247 * Examples are event date & relationship active date -in both cases we are looking for things greater than the start
5248 * date & less than the end date.
5250 * @throws \CRM_Core_Exception
5252 public function dateQueryBuilder(
5253 $values, $tableName, $fieldName,
5254 $dbFieldName, $fieldTitle,
5255 $appendTimeStamp = TRUE,
5256 $dateFormat = 'YmdHis',
5257 $highDBFieldName = NULL
5259 // @todo - remove dateFormat - pretty sure it's never passed in...
5260 list($name, $op, $value, $grouping, $wildcard) = $values;
5261 if ($name !== $fieldName && $name !== "{$fieldName}_low" && $name !== "{$fieldName}_high") {
5262 CRM_Core_Error
::deprecatedFunctionWarning('Date query builder called unexpectedly');
5265 if ($tableName === 'civicrm_contact') {
5266 // Special handling for contact table as it has a known alias in advanced search.
5267 $tableName = 'contact_a';
5269 if ($name === "{$fieldName}_low" ||
5270 $name === "{$fieldName}_high"
5272 if (isset($this->_rangeCache
[$fieldName]) ||
!$value) {
5275 $this->_rangeCache
[$fieldName] = 1;
5277 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
5279 if ($name == $fieldName . '_low') {
5281 $firstPhrase = ts('greater than or equal to');
5282 $firstDate = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5284 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5285 if (!empty($secondValues) && $secondValues[2]) {
5287 $secondPhrase = ts('less than or equal to');
5288 $secondValue = $secondValues[2];
5290 if ($appendTimeStamp && strlen($secondValue) == 10) {
5291 $secondValue .= ' 23:59:59';
5293 $secondDate = CRM_Utils_Date
::processDate($secondValue, NULL, FALSE, $dateFormat);
5296 elseif ($name == $fieldName . '_high') {
5298 $firstPhrase = ts('less than or equal to');
5300 if ($appendTimeStamp && strlen($value) == 10) {
5301 $value .= ' 23:59:59';
5303 $firstDate = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5305 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5306 if (!empty($secondValues) && $secondValues[2]) {
5308 $secondPhrase = ts('greater than or equal to');
5309 $secondValue = $secondValues[2];
5310 $secondDate = CRM_Utils_Date
::processDate($secondValue, NULL, FALSE, $dateFormat);
5314 if (!$appendTimeStamp) {
5315 $firstDate = substr($firstDate, 0, 8);
5317 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
5320 if (!$appendTimeStamp) {
5321 $secondDate = substr($secondDate, 0, 8);
5323 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
5327 $highDBFieldName = $highDBFieldName ??
$dbFieldName;
5328 $this->_where
[$grouping][] = "
5329 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5330 ( {$tableName}.{$highDBFieldName} $secondOP '$secondDate' )
5332 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
5335 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5336 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5340 if ($name == $fieldName) {
5341 //In Get API, for operators other then '=' the $value is in array(op => value) format
5342 if (is_array($value) && !empty($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
5344 $value = $value[$op];
5347 $date = $format = NULL;
5348 if (strstr($op, 'IN')) {
5350 foreach ($value as &$date) {
5351 $date = CRM_Utils_Date
::processDate($date, NULL, FALSE, $dateFormat);
5352 if (!$appendTimeStamp) {
5353 $date = substr($date, 0, 8);
5355 $format[] = CRM_Utils_Date
::customFormat($date);
5357 $date = "('" . implode("','", $value) . "')";
5358 $format = implode(', ', $format);
5360 elseif ($value && (!strstr($op, 'NULL') && !strstr($op, 'EMPTY'))) {
5361 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5362 if (!$appendTimeStamp) {
5363 $date = substr($date, 0, 8);
5365 $format = CRM_Utils_Date
::customFormat($date);
5370 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op $date";
5373 $this->_where
[$grouping][] = self
::buildClause("{$tableName}.{$dbFieldName}", $op);
5376 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
5377 $this->_qill
[$grouping][] = "$fieldTitle $op $format";
5380 // Ensure the tables are set, but don't whomp anything.
5381 $this->_tables
[$tableName] = $this->_tables
[$tableName] ??
1;
5382 $this->_whereTables
[$tableName] = $this->_whereTables
[$tableName] ??
1;
5387 * @param string $tableName
5388 * @param string $fieldName
5389 * @param string $dbFieldName
5390 * @param $fieldTitle
5391 * @param null $options
5393 public function numberRangeBuilder(
5395 $tableName, $fieldName,
5396 $dbFieldName, $fieldTitle,
5399 list($name, $op, $value, $grouping, $wildcard) = $values;
5401 if ($name == "{$fieldName}_low" ||
5402 $name == "{$fieldName}_high"
5404 if (isset($this->_rangeCache
[$fieldName])) {
5407 $this->_rangeCache
[$fieldName] = 1;
5409 $secondOP = $secondPhrase = $secondValue = NULL;
5411 if ($name == "{$fieldName}_low") {
5413 $firstPhrase = ts('greater than');
5415 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5416 if (!empty($secondValues)) {
5418 $secondPhrase = ts('less than');
5419 $secondValue = $secondValues[2];
5424 $firstPhrase = ts('less than');
5426 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5427 if (!empty($secondValues)) {
5429 $secondPhrase = ts('greater than');
5430 $secondValue = $secondValues[2];
5435 $this->_where
[$grouping][] = "
5436 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5437 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5439 $displayValue = $options ?
$options[$value] : $value;
5440 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5442 $this->_qill
[$grouping][]
5443 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5446 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5447 $displayValue = $options ?
$options[$value] : $value;
5448 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5450 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5455 if ($name == $fieldName) {
5459 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5461 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5462 $displayValue = $options ?
$options[$value] : $value;
5463 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5469 * @param string $tableName
5470 * @param string $fieldName
5471 * @param string $dbFieldName
5472 * @param $fieldTitle
5473 * @param null $options
5475 public function ageRangeQueryBuilder(
5477 $tableName, $fieldName,
5478 $dbFieldName, $fieldTitle,
5481 list($name, $op, $value, $grouping, $wildcard) = $values;
5483 $asofDateValues = $this->getWhereValues("{$fieldName}_asof_date", $grouping);
5484 // will be treated as current day
5486 if ($asofDateValues) {
5487 $asofDate = CRM_Utils_Date
::processDate($asofDateValues[2]);
5488 $asofDateFormat = CRM_Utils_Date
::customFormat(substr($asofDate, 0, 8));
5489 $fieldTitle .= ' ' . ts('as of') . ' ' . $asofDateFormat;
5492 if ($name == "{$fieldName}_low" ||
5493 $name == "{$fieldName}_high"
5495 if (isset($this->_rangeCache
[$fieldName])) {
5498 $this->_rangeCache
[$fieldName] = 1;
5500 $secondOP = $secondPhrase = $secondValue = NULL;
5502 if ($name == "{$fieldName}_low") {
5503 $firstPhrase = ts('greater than or equal to');
5504 // NB: age > X means date of birth < Y
5506 $firstDate = self
::calcDateFromAge($asofDate, $value, 'min');
5508 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5509 if (!empty($secondValues)) {
5511 $secondPhrase = ts('less than or equal to');
5512 $secondValue = $secondValues[2];
5513 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'max');
5518 $firstPhrase = ts('less than or equal to');
5519 $firstDate = self
::calcDateFromAge($asofDate, $value, 'max');
5521 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5522 if (!empty($secondValues)) {
5524 $secondPhrase = ts('greater than or equal to');
5525 $secondValue = $secondValues[2];
5526 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'min');
5531 $this->_where
[$grouping][] = "
5532 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5533 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5535 $displayValue = $options ?
$options[$value] : $value;
5536 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5538 $this->_qill
[$grouping][]
5539 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5542 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5543 $displayValue = $options ?
$options[$value] : $value;
5544 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5546 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5552 * Calculate date from age.
5554 * @param string $asofDate
5556 * @param string $type
5559 * @throws \Exception
5561 public static function calcDateFromAge($asofDate, $age, $type) {
5562 $date = new DateTime($asofDate);
5563 if ($type == "min") {
5564 // minimum age is $age: dob <= date - age "235959"
5565 $date->sub(new DateInterval("P" . $age . "Y"));
5566 return $date->format('Ymd') . "235959";
5569 // max age is $age: dob >= date - (age + 1y) + 1d "000000"
5570 $date->sub(new DateInterval("P" . ($age +
1) . "Y"))->add(new DateInterval("P1D"));
5571 return $date->format('Ymd') . "000000";
5576 * Given the field name, operator, value & its data type
5577 * builds the where Clause for the query
5578 * used for handling 'IS NULL'/'IS NOT NULL' operators
5580 * @param string $field
5584 * @param string $value
5586 * @param string $dataType
5587 * Data type of the field.
5590 * Where clause for the query.
5591 * @throws \CRM_Core_Exception
5593 public static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5595 $clause = "$field $op";
5603 $clause = ($dataType == 'Date') ?
" $field IS NULL " : " (NULLIF($field, '') IS NULL) ";
5606 case 'IS NOT EMPTY':
5607 $clause = ($dataType == 'Date') ?
" $field IS NOT NULL " : " (NULLIF($field, '') IS NOT NULL) ";
5611 return " {$clause} BINARY '{$value}' ";
5615 // I feel like this would be escaped properly if passed through $queryString = CRM_Core_DAO::createSqlFilter.
5616 if (!empty($value) && (!is_array($value) ||
!array_key_exists($op, $value))) {
5617 $value = [$op => (array) $value];
5621 if (empty($dataType) ||
$dataType == 'Date') {
5622 $dataType = 'String';
5624 if (is_array($value)) {
5625 //this could have come from the api - as in the restWhere section we potentially use the api operator syntax which is becoming more
5626 // widely used and consistent across the codebase
5627 // adding this here won't accept the search functions which don't submit an array
5628 if (($queryString = CRM_Core_DAO
::createSQLFilter($field, $value, $dataType)) != FALSE) {
5630 return $queryString;
5632 if (!empty($value[0]) && $op === 'BETWEEN') {
5633 CRM_Core_Error
::deprecatedFunctionWarning('Fix search input params');
5634 if (($queryString = CRM_Core_DAO
::createSQLFilter($field, [$op => $value], $dataType)) != FALSE) {
5635 return $queryString;
5638 throw new CRM_Core_Exception(ts('Failed to interpret input for search'));
5641 $value = CRM_Utils_Type
::escape($value, $dataType);
5642 // if we don't have a dataType we should assume
5643 if ($dataType == 'String' ||
$dataType == 'Text') {
5644 $value = "'" . $value . "'";
5646 return "$clause $value";
5651 * @param bool $reset
5655 public function openedSearchPanes($reset = FALSE) {
5656 if (!$reset ||
empty($this->_whereTables
)) {
5657 return self
::$_openedPanes;
5660 // pane name to table mapper
5662 ts('Contributions') => 'civicrm_contribution',
5663 ts('Memberships') => 'civicrm_membership',
5664 ts('Events') => 'civicrm_participant',
5665 ts('Relationships') => 'civicrm_relationship',
5666 ts('Activities') => 'civicrm_activity',
5667 ts('Pledges') => 'civicrm_pledge',
5668 ts('Cases') => 'civicrm_case',
5669 ts('Grants') => 'civicrm_grant',
5670 ts('Address Fields') => 'civicrm_address',
5671 ts('Notes') => 'civicrm_note',
5672 ts('Change Log') => 'civicrm_log',
5673 ts('Mailings') => 'civicrm_mailing',
5675 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
5677 foreach (array_keys($this->_whereTables
) as $table) {
5678 if ($panName = array_search($table, $panesMapper)) {
5679 self
::$_openedPanes[$panName] = TRUE;
5683 return self
::$_openedPanes;
5689 public function setOperator($operator) {
5690 $validOperators = ['AND', 'OR'];
5691 if (!in_array($operator, $validOperators)) {
5694 $this->_operator
= $operator;
5700 public function getOperator() {
5701 return $this->_operator
;
5709 public function filterRelatedContacts(&$from, &$where, &$having) {
5710 if (!isset(Civi
::$statics[__CLASS__
]['related_contacts_filter'])) {
5711 Civi
::$statics[__CLASS__
]['related_contacts_filter'] = [];
5713 $_rTempCache =& Civi
::$statics[__CLASS__
]['related_contacts_filter'];
5714 // since there only can be one instance of this filter in every query
5715 // skip if filter has already applied
5716 foreach ($_rTempCache as $acache) {
5717 foreach ($acache['queries'] as $aqcache) {
5718 if (strpos($from, $aqcache['from']) !== FALSE) {
5724 $arg_sig = sha1("$from $where $having");
5725 if (isset($_rTempCache[$arg_sig])) {
5726 $cache = $_rTempCache[$arg_sig];
5729 // create temp table with contact ids
5731 $tableName = CRM_Utils_SQL_TempTable
::build()->createWithColumns('contact_id int primary key')->setMemory(TRUE)->getName();
5734 REPLACE INTO $tableName ( contact_id )
5740 CRM_Core_DAO
::executeQuery($sql);
5742 $cache = ['tableName' => $tableName, 'queries' => []];
5743 $_rTempCache[$arg_sig] = $cache;
5745 // upsert the query depending on relationship type
5746 if (isset($cache['queries'][$this->_displayRelationshipType
])) {
5747 $qcache = $cache['queries'][$this->_displayRelationshipType
];
5750 $tableName = $cache['tableName'];
5755 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5756 if (is_numeric($this->_displayRelationshipType
)) {
5757 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5759 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5760 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5762 $qcache['where'] = "
5763 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5764 AND displayRelType.is_active = 1
5768 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5769 if ($dirOne == 'a') {
5770 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5771 $qcache['from'] .= "
5772 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5773 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5777 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5778 $qcache['from'] .= "
5779 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5780 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5783 $qcache['where'] = "
5784 WHERE displayRelType.relationship_type_id = $relType
5785 AND displayRelType.is_active = 1
5788 $qcache['relTypeLabel'] = $relationshipTypeLabel;
5789 $_rTempCache[$arg_sig]['queries'][$this->_displayRelationshipType
] = $qcache;
5791 $qillMessage = ts('Contacts with a Relationship Type of: ');
5792 $iqill = $qillMessage . "'" . $qcache['relTypeLabel'] . "'";
5793 if (!is_array($this->_qill
[0]) ||
!in_array($iqill, $this->_qill
[0])) {
5794 $this->_qill
[0][] = $iqill;
5796 if (strpos($from, $qcache['from']) === FALSE) {
5797 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5798 // this happens when we have an event_type in the quert (CRM-7969)
5799 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5800 $from .= $qcache['from'];
5801 $where = $qcache['where'];
5802 if (!empty($this->_permissionWhereClause
)) {
5803 $where .= "AND $this->_permissionWhereClause";
5811 * See CRM-19811 for why this is database hurty without apparent benefit.
5817 public static function caseImportant($op) {
5818 return !in_array($op, ['LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY']);
5822 * @param $returnProperties
5827 public static function componentPresent(&$returnProperties, $prefix) {
5828 foreach ($returnProperties as $name => $dontCare) {
5829 if (substr($name, 0, strlen($prefix)) == $prefix) {
5837 * Builds the necessary structures for all fields that are similar to option value look-ups.
5839 * @param string $name
5840 * the name of the field.
5842 * the sql operator, this function should handle ALL SQL operators.
5843 * @param string $value
5844 * depends on the operator and who's calling the query builder.
5845 * @param int $grouping
5846 * the index where to place the where clause.
5847 * @param string $daoName
5849 * @param array $field
5850 * an array that contains various properties of the field identified by $name.
5851 * @param string $label
5852 * The label for this field element.
5853 * @param string $dataType
5855 * @throws \CRM_Core_Exception
5857 public function optionValueQuery(
5865 $dataType = 'String'
5874 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5875 if ($tableName == 'civicrm_contact') {
5876 $wc = "contact_a.$fieldName";
5879 // Special handling for on_hold, so that we actually use the 'where'
5880 // property in order to limit the query by the on_hold status of the email,
5881 // instead of using email.id which would be nonsensical.
5882 if ($field['name'] === 'on_hold') {
5883 $wc = $field['where'];
5886 $wc = "$tableName.id";
5890 if (in_array($name, $pseudoFields)) {
5891 $wc = "contact_a.{$name}_id";
5892 $dataType = 'Positive';
5893 $value = (!$value) ?
0 : $value;
5895 if ($name == "world_region") {
5896 $field['name'] = $name;
5899 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue($daoName, $field['name'], $value, $op);
5900 $this->_qill
[$grouping][] = ts("%1 %2 %3", [1 => $label, 2 => $qillop, 3 => $qillVal]);
5901 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5905 * Check and explode a user defined numeric string into an array
5906 * this was the protocol used by search builder in the old old days before we had
5907 * super nice js widgets to do the hard work
5909 * @param string $string
5910 * @param string $dataType
5911 * The dataType we should check for the values, default integer.
5913 * @return bool|array
5914 * false if string does not match the pattern
5915 * array of numeric values if string does match the pattern
5917 public static function parseSearchBuilderString($string, $dataType = 'Integer') {
5918 $string = trim($string);
5919 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5923 $string = substr($string, 1, -1);
5924 $values = explode(',', $string);
5925 if (empty($values)) {
5930 foreach ($values as $v) {
5931 if ($dataType == 'Integer' && !is_numeric($v)) {
5934 elseif ($dataType == 'String' && !is_string($v)) {
5937 $returnValues[] = trim($v);
5940 if (empty($returnValues)) {
5944 return $returnValues;
5948 * Convert the pseudo constants id's to their names
5950 * @param CRM_Core_DAO $dao
5951 * @param bool $return
5952 * @param bool $usedForAPI
5954 * @return array|NULL
5956 public function convertToPseudoNames(&$dao, $return = FALSE, $usedForAPI = FALSE) {
5957 if (empty($this->_pseudoConstantsSelect
)) {
5961 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5962 if (!empty($this->_pseudoConstantsSelect
[$key]['sorting'])) {
5966 if (is_object($dao) && property_exists($dao, $value['idCol'])) {
5967 $val = $dao->{$value['idCol']};
5968 if ($key == 'groups') {
5969 $dao->groups
= $this->convertGroupIDStringToLabelString($dao, $val);
5973 if (CRM_Utils_System
::isNull($val)) {
5976 elseif (!empty($value['pseudoconstant'])) {
5977 // If pseudoconstant is set that is kind of defacto for 'we have a bit more info about this'
5978 // and we can use the metadata to figure it out.
5979 // ideally this bit of IF will absorb & replace all the rest in time as we move to
5980 // more metadata based choices.
5981 if (strpos($val, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
5982 $dbValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($val, CRM_Core_DAO
::VALUE_SEPARATOR
));
5983 foreach ($dbValues as $pseudoValue) {
5984 $convertedValues[] = CRM_Core_PseudoConstant
::getLabel($value['bao'], $value['idCol'], $pseudoValue);
5987 $dao->$key = ($usedForAPI) ?
$convertedValues : implode(', ', $convertedValues);
5988 $realFieldName = $this->_pseudoConstantsSelect
[$key]['field_name'] ??
NULL;
5989 if ($usedForAPI && $realFieldName) {
5990 // normally we would see 2 fields returned for pseudoConstants. An exception is
5991 // preferred_communication_method where there is no id-variant.
5992 // For the api we prioritise getting the real data returned.
5993 // over the resolved version
5994 $dao->$realFieldName = $dbValues;
5999 // This is basically the same as the default but since we have the bao we can use
6000 // a cached function.
6001 $dao->$key = CRM_Core_PseudoConstant
::getLabel($value['bao'], $value['idCol'], $val);
6004 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
6006 $idColumn = "{$key}_id";
6007 $dao->$idColumn = $val;
6009 if ($key == 'state_province_name') {
6010 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::stateProvince($val);
6013 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
6016 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
6017 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
6019 // @todo handle this in the section above for pseudoconstants.
6020 elseif (in_array($value['pseudoField'], ['participant_role_id', 'participant_role'])) {
6021 // @todo define bao on this & merge into the above condition.
6022 $viewValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $val);
6024 if ($value['pseudoField'] == 'participant_role') {
6025 $pseudoOptions = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'role_id');
6026 foreach ($viewValues as $k => $v) {
6027 $viewValues[$k] = $pseudoOptions[$v];
6030 $dao->$key = ($usedForAPI && count($viewValues) > 1) ?
$viewValues : implode(', ', $viewValues);
6033 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
6034 $dao->$key = $labels[$val];
6037 // return converted values in array format
6039 if (strpos($key, '-') !== FALSE) {
6040 $keyVal = explode('-', $key);
6041 $current = &$values;
6042 $lastElement = array_pop($keyVal);
6043 foreach ($keyVal as $v) {
6044 if (!array_key_exists($v, $current)) {
6047 $current = &$current[$v];
6049 $current[$lastElement] = $dao->$key;
6052 $values[$key] = $dao->$key;
6058 foreach ($this->legacyHackedFields
as $realField => $labelField) {
6059 // This is a temporary routine for handling these fields while
6060 // we figure out how to handled them based on metadata in
6061 /// export and search builder. CRM-19815, CRM-19830.
6062 if (isset($dao->$realField) && is_numeric($dao->$realField) && isset($dao->$labelField)) {
6063 $dao->$realField = $dao->$labelField;
6071 * Include pseudo fields LEFT JOIN.
6072 * @param string|array $sort can be a object or string
6074 * @return array|NULL
6076 public function includePseudoFieldsJoin($sort) {
6077 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
6080 $sort = is_string($sort) ?
$sort : $sort->orderBy();
6083 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
6084 if (!empty($value['table'])) {
6085 $regex = "/({$value['table']}\.|{$name})/";
6086 if (preg_match($regex, $sort)) {
6087 $this->_elemnt
[$value['element']] = 1;
6088 $this->_select
[$value['element']] = $value['select'];
6089 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
6090 $present[$value['table']] = $value['join'];
6094 $presentSimpleFrom = $present;
6096 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
6097 array_key_exists('civicrm_country', $presentSimpleFrom)
6099 unset($presentSimpleFrom['civicrm_country']);
6101 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
6102 array_key_exists('civicrm_country', $present)
6104 unset($present['civicrm_country']);
6107 $presentClause = $presentSimpleFromClause = NULL;
6108 if (!empty($present)) {
6109 $presentClause = implode(' ', $present);
6111 if (!empty($presentSimpleFrom)) {
6112 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
6115 $this->_fromClause
= $this->_fromClause
. $presentClause;
6116 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
6118 return [$presentClause, $presentSimpleFromClause];
6122 * Build qill for field.
6124 * Qill refers to the query detail visible on the UI.
6126 * @param string $daoName
6127 * @param string $fieldName
6128 * @param mixed $fieldValue
6130 * @param array $pseudoExtraParam
6132 * Type of the field per CRM_Utils_Type
6136 public static function buildQillForFieldValue(
6141 $pseudoExtraParam = [],
6142 $type = CRM_Utils_Type
::T_STRING
6144 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
6146 //API usually have fieldValue format as array(operator => array(values)),
6147 //so we need to separate operator out of fieldValue param
6148 if (is_array($fieldValue) && in_array(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
6149 $op = key($fieldValue);
6150 $fieldValue = $fieldValue[$op];
6153 // if Operator chosen is NULL/EMPTY then
6154 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
6155 return [CRM_Utils_Array
::value($op, $qillOperators, $op), ''];
6158 // @todo - if the right BAO is passed in special handling for the below
6159 // fields should not be required. testQillOptions.
6160 if ($fieldName == 'country_id') {
6161 $pseudoOptions = CRM_Core_PseudoConstant
::country();
6163 elseif ($fieldName == 'county_id') {
6164 $pseudoOptions = CRM_Core_PseudoConstant
::county();
6166 elseif ($fieldName == 'world_region') {
6167 $pseudoOptions = CRM_Core_PseudoConstant
::worldRegion();
6169 elseif ($daoName == 'CRM_Event_DAO_Event' && $fieldName == 'id') {
6170 $checkPermission = CRM_Utils_Array
::value('check_permission', $pseudoExtraParam, TRUE);
6171 $pseudoOptions = CRM_Event_BAO_Event
::getEvents(0, $fieldValue, TRUE, $checkPermission, TRUE);
6173 elseif ($fieldName == 'contribution_product_id') {
6174 $pseudoOptions = CRM_Contribute_PseudoConstant
::products();
6176 elseif ($daoName == 'CRM_Contact_DAO_Group' && $fieldName == 'id') {
6177 $pseudoOptions = CRM_Core_PseudoConstant
::group();
6179 elseif ($daoName == 'CRM_Batch_BAO_EntityBatch' && $fieldName == 'batch_id') {
6180 $pseudoOptions = CRM_Contribute_PseudoConstant
::batch();
6183 $pseudoOptions = CRM_Core_PseudoConstant
::get($daoName, $fieldName, $pseudoExtraParam);
6186 if (is_array($fieldValue)) {
6188 if (!empty($pseudoOptions)) {
6189 foreach ((array) $fieldValue as $val) {
6190 $qillString[] = CRM_Utils_Array
::value($val, $pseudoOptions, $val);
6192 $fieldValue = implode(', ', $qillString);
6195 if ($type == CRM_Utils_Type
::T_DATE
) {
6196 foreach ($fieldValue as $index => $value) {
6197 $fieldValue[$index] = CRM_Utils_Date
::customFormat($value);
6201 // @todo - this is a bit specific (one operator).
6202 // However it is covered by a unit test so can be altered later with
6204 if ($op === 'BETWEEN') {
6205 $separator = ' AND ';
6207 $fieldValue = implode($separator, $fieldValue);
6210 elseif (!empty($pseudoOptions) && array_key_exists($fieldValue, $pseudoOptions)) {
6211 $fieldValue = $pseudoOptions[$fieldValue];
6213 elseif ($type === CRM_Utils_Type
::T_DATE
) {
6214 $fieldValue = CRM_Utils_Date
::customFormat($fieldValue);
6217 return [CRM_Utils_Array
::value($op, $qillOperators, $op), $fieldValue];
6221 * Get the qill (search description for field) for the specified field.
6223 * @param string $daoName
6224 * @param string $name
6225 * @param string $value
6226 * @param string|array $op
6227 * @param string $label
6231 public static function getQillValue($daoName, string $name, $value, $op, string $label) {
6232 list($op, $value) = self
::buildQillForFieldValue($daoName, $name, $value, $op);
6233 return ts('%1 %2 %3', [1 => $label, 2 => $op, 3 => $value]);
6237 * Alter value to reflect wildcard settings.
6239 * The form will have tried to guess whether this is a good field to wildcard but there is
6240 * also a site-wide setting that specifies whether it is OK to append the wild card to the beginning
6241 * or only the end of the string
6243 * @param bool $wildcard
6244 * This is a bool made on an assessment 'elsewhere' on whether this is a good field to wildcard.
6246 * Generally '=' or 'LIKE'.
6247 * @param string $value
6248 * The search string.
6252 public static function getWildCardedValue($wildcard, $op, $value) {
6253 if ($wildcard && $op === 'LIKE') {
6254 if (CRM_Core_Config
::singleton()->includeWildCardInName
&& (substr($value, 0, 1) != '%')) {
6267 * Process special fields of Search Form in OK (Operator in Key) format
6269 * @param array $formValues
6270 * @param array $specialFields
6271 * Special params to be processed
6272 * @param array $changeNames
6273 * Array of fields whose name should be changed
6275 public static function processSpecialFormValue(&$formValues, $specialFields, $changeNames = []) {
6276 // Array of special fields whose value are considered only for NULL or EMPTY operators
6277 $nullableFields = ['contribution_batch_id'];
6279 foreach ($specialFields as $element) {
6280 $value = $formValues[$element] ??
NULL;
6282 if (is_array($value)) {
6283 if (in_array($element, array_keys($changeNames))) {
6284 unset($formValues[$element]);
6285 $element = $changeNames[$element];
6287 $formValues[$element] = ['IN' => $value];
6289 elseif (in_array($value, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
6290 $formValues[$element] = [$value => 1];
6292 elseif (!in_array($element, $nullableFields)) {
6293 // if wildcard is already present return searchString as it is OR append and/or prepend with wildcard
6294 $isWilcard = strstr($value, '%') ?
FALSE : CRM_Core_Config
::singleton()->includeWildCardInName
;
6295 $formValues[$element] = ['LIKE' => self
::getWildCardedValue($isWilcard, 'LIKE', $value)];
6302 * Parse and assimilate the various sort options.
6304 * Side-effect: if sorting on a common column from a related table (`city`, `postal_code`,
6305 * `email`), the related table may be joined automatically.
6307 * At time of writing, this code is deeply flawed and should be rewritten. For the moment,
6308 * it's been extracted to a standalone function.
6310 * @param string|CRM_Utils_Sort $sort
6311 * The order by string.
6312 * @param null $sortOrder
6313 * Who knows? Hu knows. He who knows Hu knows who.
6316 * list(string $orderByClause, string $additionalFromClause).
6318 * @throws \CRM_Core_Exception
6320 protected function prepareOrderBy($sort, $sortOrder) {
6324 if (CRM_Core_Config
::singleton()->includeOrderByClause ||
6325 isset($this->_distinctComponentClause
)
6328 if (is_string($sort)) {
6332 $orderBy = trim($sort->orderBy());
6334 // Deliberately remove the backticks again, as they mess up the evil
6335 // string munging below. This balanced by re-escaping before use.
6336 $orderBy = str_replace('`', '', $orderBy);
6338 if (!empty($orderBy)) {
6339 // this is special case while searching for
6340 // change log CRM-1718
6341 if (preg_match('/sort_name/i', $orderBy)) {
6342 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
6346 $orderBy .= " $sortOrder";
6349 // always add contact_a.id to the ORDER clause
6350 // so the order is deterministic
6351 if (strpos('contact_a.id', $orderBy) === FALSE) {
6352 $orderBy .= ", contact_a.id";
6357 $orderBy = " contact_a.sort_name ASC, contact_a.id";
6363 // Remove this here & add it at the end for simplicity.
6364 $order = trim($orderBy);
6365 $orderByArray = explode(',', $order);
6367 foreach ($orderByArray as $orderByClause) {
6368 $orderByClauseParts = explode(' ', trim($orderByClause));
6369 $field = $orderByClauseParts[0];
6370 $direction = $orderByClauseParts[1] ??
'asc';
6371 $fieldSpec = $this->getMetadataForRealField($field);
6373 // This is a hacky add-in for primary address joins. Feel free to iterate as it is unit tested.
6374 // @todo much more cleanup on location handling in addHierarchical elements. Potentially
6375 // add keys to $this->fields to represent the actual keys for locations.
6376 if (empty($fieldSpec) && substr($field, 0, 2) === '1-') {
6377 $fieldSpec = $this->getMetadataForField(substr($field, 2));
6378 $this->addAddressTable('1-' . str_replace('civicrm_', '', $fieldSpec['table_name']), 'is_primary = 1');
6381 if ($this->_returnProperties
=== []) {
6382 if (!empty($fieldSpec['table_name']) && !isset($this->_tables
[$fieldSpec['table_name']])) {
6383 $this->_tables
[$fieldSpec['table_name']] = 1;
6384 $order = $fieldSpec['where'] . ' ' . $direction;
6388 $cfID = CRM_Core_BAO_CustomField
::getKeyID($field);
6389 // add to cfIDs array if not present
6390 if (!empty($cfID) && !array_key_exists($cfID, $this->_cfIDs
)) {
6391 $this->_cfIDs
[$cfID] = [];
6392 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
6393 $this->_customQuery
->query();
6394 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
6395 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
6398 // By replacing the join to the option value table with the mysql construct
6399 // ORDER BY field('contribution_status_id', 2,1,4)
6400 // we can remove a join. In the case of the option value join it is
6401 /// a join known to cause slow queries.
6402 // @todo cover other pseudoconstant types. Limited to option group ones & Foreign keys
6403 // matching an id+name parrern in the
6404 // first instance for scope reasons. They require slightly different handling as the column (label)
6405 // is not declared for them.
6406 // @todo so far only integer fields are being handled. If we add string fields we need to look at
6408 $pseudoConstantMetadata = CRM_Utils_Array
::value('pseudoconstant', $fieldSpec, FALSE);
6409 if (!empty($pseudoConstantMetadata)
6411 if (!empty($pseudoConstantMetadata['optionGroupName'])
6412 ||
$this->isPseudoFieldAnFK($fieldSpec)
6414 // dev/core#1305 @todo this is not the right thing to do but for now avoid fatal error
6415 if (empty($fieldSpec['bao'])) {
6418 $sortedOptions = $fieldSpec['bao']::buildOptions($fieldSpec['name'], NULL, [
6419 'orderColumn' => CRM_Utils_Array
::value('labelColumn', $pseudoConstantMetadata, 'label'),
6421 $fieldIDsInOrder = implode(',', array_keys($sortedOptions));
6422 // Pretty sure this validation ALSO happens in the order clause & this can't be reached but...
6423 // this might give some early warning.
6424 CRM_Utils_Type
::validate($fieldIDsInOrder, 'CommaSeparatedIntegers');
6425 // use where if it's set to fully qualify ambiguous column names
6426 // i.e. civicrm_contribution.contribution_status_id instead of contribution_status_id
6427 $pseudoColumnName = $fieldSpec['where'] ??
$fieldSpec['name'];
6428 $order = str_replace("$field", "field($pseudoColumnName,$fieldIDsInOrder)", $order);
6430 //CRM-12565 add "`" around $field if it is a pseudo constant
6431 // This appears to be for 'special' fields like locations with appended numbers or hyphens .. maybe.
6432 if (!empty($pseudoConstantMetadata['element']) && $pseudoConstantMetadata['element'] == $field) {
6433 $order = str_replace($field, "`{$field}`", $order);
6438 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6439 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6441 // The above code relies on crazy brittle string manipulation of a peculiarly-encoded ORDER BY
6442 // clause. But this magic helper which forgivingly reescapes ORDER BY.
6444 $order = CRM_Utils_Type
::escape($order, 'MysqlOrderBy');
6445 return ' ORDER BY ' . $order;
6450 * Convert a string of group IDs to a string of group labels.
6452 * The original string may include duplicates and groups the user does not have
6453 * permission to see.
6455 * @param CRM_Core_DAO $dao
6456 * @param string $val
6460 public function convertGroupIDStringToLabelString(&$dao, $val) {
6461 $groupIDs = explode(',', $val);
6462 // Note that groups that the user does not have permission to will be excluded (good).
6463 $groups = array_intersect_key(CRM_Core_PseudoConstant
::group(), array_flip($groupIDs));
6464 return implode(', ', $groups);
6469 * Set the qill and where properties for a field.
6471 * This function is intended as a short-term function to encourage refactoring
6472 * & re-use - but really we should just have less special-casing.
6474 * @param string $name
6476 * @param string|array $value
6477 * @param string $grouping
6478 * @param array $field
6480 * @throws \CRM_Core_Exception
6482 public function setQillAndWhere($name, $op, $value, $grouping, $field) {
6483 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
6484 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
6485 $this->_qill
[$grouping][] = ts("%1 %2 %3", [
6486 1 => $field['title'],
6493 * Has the pseudoconstant of the field been requested.
6495 * For example if the field is payment_instrument_id then it
6496 * has been requested if either payment_instrument_id or payment_instrument
6497 * have been requested. Payment_instrument is the option groun name field value.
6499 * @param array $field
6500 * @param string $fieldName
6501 * The unique name of the field - ie. the one it will be aliased to in the query.
6505 private function pseudoConstantNameIsInReturnProperties($field, $fieldName = NULL) {
6506 $realField = $this->getMetadataForRealField($fieldName);
6507 if (!isset($realField['pseudoconstant'])) {
6510 $pseudoConstant = $realField['pseudoconstant'];
6511 if (empty($pseudoConstant['optionGroupName']) &&
6512 CRM_Utils_Array
::value('labelColumn', $pseudoConstant) !== 'name') {
6513 // We are increasing our pseudoconstant handling - but still very cautiously,
6514 // hence the check for labelColumn === name
6518 if (!empty($pseudoConstant['optionGroupName']) && !empty($this->_returnProperties
[$pseudoConstant['optionGroupName']])) {
6521 if (!empty($this->_returnProperties
[$fieldName])) {
6524 // Is this still required - the above goes off the unique name. Test with things like
6525 // communication_preferences & prefix_id.
6526 if (!empty($this->_returnProperties
[$field['name']])) {
6533 * Get Select Clause.
6537 public function getSelect() {
6538 $select = 'SELECT ';
6539 if (isset($this->_distinctComponentClause
)) {
6540 $select .= "{$this->_distinctComponentClause}, ";
6542 $select .= implode(', ', $this->_select
);
6547 * Add basic statistics to the summary.
6549 * @param array $summary
6550 * @param string $where
6551 * @param string $from
6554 * @throws \CRM_Core_Exception
6556 protected function addBasicStatsToSummary(&$summary, $where, $from) {
6557 $summary['total']['count'] = 0;
6558 $summary['total']['amount'] = $summary['total']['avg'] = [];
6561 SELECT COUNT( conts.total_amount ) as total_count,
6562 SUM( conts.total_amount ) as total_amount,
6563 AVG( conts.total_amount ) as total_avg,
6564 conts.currency as currency
6566 SELECT civicrm_contribution.total_amount, COUNT(civicrm_contribution.total_amount) as civicrm_contribution_total_amount_count,
6567 civicrm_contribution.currency
6569 $where AND civicrm_contribution.contribution_status_id = 1
6570 GROUP BY civicrm_contribution.id
6574 $dao = CRM_Core_DAO
::executeQuery($query);
6576 while ($dao->fetch()) {
6577 $summary['total']['count'] +
= $dao->total_count
;
6578 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
6579 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
6582 if (!empty($summary['total']['amount'])) {
6583 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
6584 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
6587 $summary['total']['amount'] = $summary['total']['avg'] = 0;
6593 * Add basic soft credit statistics to summary array.
6595 * @param array $summary
6596 * @param string $where
6597 * @param string $from
6599 * @throws \CRM_Core_Exception
6601 protected function addBasicSoftCreditStatsToStats(&$summary, $where, $from) {
6603 SELECT COUNT( conts.total_amount ) as total_count,
6604 SUM( conts.total_amount ) as total_amount,
6605 AVG( conts.total_amount ) as total_avg,
6606 conts.currency as currency
6608 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency
6610 $where AND civicrm_contribution.contribution_status_id = 1 AND civicrm_contribution_soft.id IS NOT NULL
6611 GROUP BY civicrm_contribution_soft.id
6615 $dao = CRM_Core_DAO
::executeQuery($query);
6616 $summary['soft_credit']['count'] = 0;
6617 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = [];
6618 while ($dao->fetch()) {
6619 $summary['soft_credit']['count'] +
= $dao->total_count
;
6620 $summary['soft_credit']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
6621 $summary['soft_credit']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
6623 if (!empty($summary['soft_credit']['amount'])) {
6624 $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
6625 $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
6628 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
6633 * Add basic stats about cancelled contributions to the summary.
6635 * @param array $summary
6636 * @param string $where
6637 * @param string $from
6639 * @throws \CRM_Core_Exception
6641 protected function addBasicCancelStatsToSummary(&$summary, $where, $from) {
6643 SELECT COUNT( conts.total_amount ) as cancel_count,
6644 SUM( conts.total_amount ) as cancel_amount,
6645 AVG( conts.total_amount ) as cancel_avg,
6646 conts.currency as currency
6648 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency
6650 $where AND civicrm_contribution.cancel_date IS NOT NULL
6651 GROUP BY civicrm_contribution.id
6655 $dao = CRM_Core_DAO
::executeQuery($query);
6658 if ($dao->fetch()) {
6659 $summary['cancel']['count'] = $dao->cancel_count
;
6660 $summary['cancel']['amount'] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
6661 $summary['cancel']['avg'] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
6665 $summary['cancel']['count'] = 0;
6666 $summary['cancel']['amount'] = $summary['cancel']['avg'] = [];
6667 while ($dao->fetch()) {
6668 $summary['cancel']['count'] +
= $dao->cancel_count
;
6669 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
6670 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
6672 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
6673 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
6678 * Create the sql query for an contact search.
6680 * @param int $offset
6681 * The offset for the query.
6682 * @param int $rowCount
6683 * The number of rows to return.
6684 * @param string|CRM_Utils_Sort $sort
6685 * The order by string.
6686 * @param bool $count
6687 * Is this a count only query ?.
6688 * @param bool $includeContactIds
6689 * Should we include contact ids?.
6690 * @param bool $sortByChar
6691 * If true returns the distinct array of first characters for search results.
6692 * @param bool $groupContacts
6693 * If true, return only the contact ids.
6694 * @param string $additionalWhereClause
6695 * If the caller wants to further restrict the search (used for components).
6696 * @param null $sortOrder
6697 * @param string $additionalFromClause
6698 * Should be clause with proper joins, effective to reduce where clause load.
6700 * @param bool $skipOrderAndLimit
6704 * @throws \CRM_Core_Exception
6706 public function getSearchSQL(
6707 $offset = 0, $rowCount = 0, $sort = NULL,
6708 $count = FALSE, $includeContactIds = FALSE,
6709 $sortByChar = FALSE, $groupContacts = FALSE,
6710 $additionalWhereClause = NULL, $sortOrder = NULL,
6711 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE) {
6713 $sqlParts = $this->getSearchSQLParts($offset, $rowCount, $sort, $count, $includeContactIds, $sortByChar, $groupContacts, $additionalWhereClause, $sortOrder, $additionalFromClause);
6716 CRM_Core_Error
::deprecatedFunctionWarning('sort by char is deprecated - use alphabetQuery method');
6717 $sqlParts['order_by'] = 'ORDER BY sort_name asc';
6720 if ($skipOrderAndLimit) {
6721 CRM_Core_Error
::deprecatedFunctionWarning('skipOrderAndLimit is deprected - call getSearchSQLParts & construct it in the calling function');
6722 $query = "{$sqlParts['select']} {$sqlParts['from']} {$sqlParts['where']} {$sqlParts['having']} {$sqlParts['group_by']}";
6725 $query = "{$sqlParts['select']} {$sqlParts['from']} {$sqlParts['where']} {$sqlParts['having']} {$sqlParts['group_by']} {$sqlParts['order_by']} {$sqlParts['limit']}";
6731 * Get the component parts of the search query as an array.
6733 * @param int $offset
6734 * The offset for the query.
6735 * @param int $rowCount
6736 * The number of rows to return.
6737 * @param string|CRM_Utils_Sort $sort
6738 * The order by string.
6739 * @param bool $count
6740 * Is this a count only query ?.
6741 * @param bool $includeContactIds
6742 * Should we include contact ids?.
6743 * @param bool $sortByChar
6744 * If true returns the distinct array of first characters for search results.
6745 * @param bool $groupContacts
6746 * If true, return only the contact ids.
6747 * @param string $additionalWhereClause
6748 * If the caller wants to further restrict the search (used for components).
6749 * @param null $sortOrder
6750 * @param string $additionalFromClause
6751 * Should be clause with proper joins, effective to reduce where clause load.
6754 * @throws \CRM_Core_Exception
6756 public function getSearchSQLParts($offset = 0, $rowCount = 0, $sort = NULL,
6757 $count = FALSE, $includeContactIds = FALSE,
6758 $sortByChar = FALSE, $groupContacts = FALSE,
6759 $additionalWhereClause = NULL, $sortOrder = NULL,
6760 $additionalFromClause = NULL) {
6761 if ($includeContactIds) {
6762 $this->_includeContactIds
= TRUE;
6763 $this->_whereClause
= $this->whereClause();
6765 $onlyDeleted = in_array([
6773 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
6774 // and that contact happens to be deleted, set $onlyDeleted to true
6775 foreach ($this->_params
as $values) {
6776 $name = $values[0] ??
NULL;
6777 $op = $values[1] ??
NULL;
6778 $value = $values[2] ??
NULL;
6779 if ($name === 'contact_id' and $op === '=') {
6780 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
6781 $onlyDeleted = TRUE;
6787 // building the query string
6788 $groupBy = $groupByCols = NULL;
6790 if (isset($this->_groupByComponentClause
)) {
6791 $groupByCols = preg_replace('/^GROUP BY /', '', trim($this->_groupByComponentClause
));
6792 $groupByCols = explode(', ', $groupByCols);
6794 elseif ($this->_useGroupBy
) {
6795 $groupByCols = ['contact_a.id'];
6798 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
6799 $groupByCols = ['civicrm_activity.id'];
6801 if (!empty($groupByCols)) {
6802 $groupBy = " GROUP BY " . implode(', ', $groupByCols);
6805 $order = $orderBy = '';
6808 $order = $this->prepareOrderBy($sort, $sortOrder);
6811 // Cases where we are disabling FGB (FULL_GROUP_BY_MODE):
6812 // 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
6813 // clause. This will impact the search query output.
6814 $disableFullGroupByMode = (!empty($groupBy) ||
$groupContacts);
6816 if ($disableFullGroupByMode) {
6817 CRM_Core_DAO
::disableFullGroupByMode();
6821 $this->_sort
= $sort;
6824 $this->includePseudoFieldsJoin($sort);
6826 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
6828 if ($additionalWhereClause) {
6829 $where = $where . ' AND ' . $additionalWhereClause;
6832 //additional from clause should be w/ proper joins.
6833 if ($additionalFromClause) {
6834 $from .= "\n" . $additionalFromClause;
6837 // if we are doing a transform, do it here
6838 // use the $from, $where and $having to get the contact ID
6839 if ($this->_displayRelationshipType
) {
6840 $this->filterRelatedContacts($from, $where, $having);
6842 $limit = (!$count && $rowCount) ?
" LIMIT " . CRM_Utils_Type
::escape($offset, 'Int') . ", " . CRM_Utils_Type
::escape($rowCount, 'Int') : '';
6845 'select' => $select,
6848 'order_by' => $order,
6849 'group_by' => $groupBy,
6850 'having' => $having,
6856 * Get the metadata for a given field.
6858 * @param string $fieldName
6862 protected function getMetadataForField($fieldName) {
6863 if ($fieldName === 'contact_a.id') {
6864 // This seems to be the only anomaly.
6867 $pseudoField = $this->_pseudoConstantsSelect
[$fieldName] ??
[];
6868 $field = $this->_fields
[$fieldName] ??
$pseudoField;
6869 $field = array_merge($field, $pseudoField);
6870 if (!empty($field) && empty($field['name'])) {
6871 // standardising field formatting here - over time we can phase out variants.
6872 // all paths using this currently unit tested
6873 $field['name'] = CRM_Utils_Array
::value('field_name', $field, CRM_Utils_Array
::value('idCol', $field, $fieldName));
6879 * Get the metadata for a given field, returning the 'real field' if it is a pseudofield.
6881 * @param string $fieldName
6885 public function getMetadataForRealField($fieldName) {
6886 $field = $this->getMetadataForField($fieldName);
6887 if (!empty($field['is_pseudofield_for'])) {
6888 $field = $this->getMetadataForField($field['is_pseudofield_for']);
6889 $field['pseudofield_name'] = $fieldName;
6891 elseif (!empty($field['pseudoconstant'])) {
6892 if (!empty($field['pseudoconstant']['optionGroupName'])) {
6893 $field['pseudofield_name'] = $field['pseudoconstant']['optionGroupName'];
6894 if (empty($field['table_name'])) {
6895 if (!empty($field['where'])) {
6896 $field['table_name'] = explode('.', $field['where'])[0];
6899 $field['table_name'] = 'civicrm_contact';
6908 * If we have a field that is better rendered via the pseudoconstant handled them here.
6910 * Rather than joining in the additional table we render the option value on output.
6912 * @todo - so far this applies to a narrow range of pseudocontants. We are adding them
6913 * carefully with test coverage but aim to extend.
6915 * @param string $name
6917 protected function addPseudoconstantFieldToSelect($name) {
6918 $field = $this->getMetadataForRealField($name);
6919 $realFieldName = $field['name'];
6920 $pseudoFieldName = $field['pseudofield_name'] ??
NULL;
6921 if ($pseudoFieldName) {
6922 // @todo - we don't really need to build this array now we have metadata more available with getMetadataForField fn.
6923 $this->_pseudoConstantsSelect
[$pseudoFieldName] = [
6924 'pseudoField' => $pseudoFieldName,
6925 'idCol' => $realFieldName,
6926 'field_name' => $field['name'],
6927 'bao' => $field['bao'],
6928 'pseudoconstant' => $field['pseudoconstant'],
6932 $this->_tables
[$field['table_name']] = 1;
6933 $this->_element
[$realFieldName] = 1;
6934 $this->_select
[$field['name']] = str_replace('civicrm_contact.', 'contact_a.', "{$field['where']} as `$realFieldName`");
6938 * Is this pseudofield a foreign key constraint.
6940 * We are trying to cautiously expand our pseudoconstant handling. This check allows us
6941 * to extend to a narrowly defined type (and then only if the pseudofield is in the fields
6942 * array which is done for contributions which are mostly handled as pseudoconstants.
6948 protected function isPseudoFieldAnFK($fieldSpec) {
6949 if (empty($fieldSpec['FKClassName'])
6950 || CRM_Utils_Array
::value('keyColumn', $fieldSpec['pseudoconstant']) !== 'id'
6951 || CRM_Utils_Array
::value('labelColumn', $fieldSpec['pseudoconstant']) !== 'name') {
6958 * Is the field a relative date field.
6960 * @param string $fieldName
6964 protected function isARelativeDateField($fieldName) {
6965 if (substr($fieldName, -9, 9) !== '_relative') {
6968 $realField = substr($fieldName, 0, strlen($fieldName) - 9);
6969 return isset($this->_fields
[$realField]);
6973 * Get the specifications for the field, if available.
6975 * @param string $fieldName
6976 * Fieldname as displayed on the form.
6980 public function getFieldSpec($fieldName) {
6981 if (isset($this->_fields
[$fieldName])) {
6982 $fieldSpec = $this->_fields
[$fieldName];
6983 if (!empty($fieldSpec['is_pseudofield_for'])) {
6984 $fieldSpec = array_merge($this->_fields
[$fieldSpec['is_pseudofield_for']], $this->_fields
[$fieldName]);
6988 $lowFieldName = str_replace('_low', '', $fieldName);
6989 if (isset($this->_fields
[$lowFieldName])) {
6990 return array_merge($this->_fields
[$lowFieldName], ['field_name' => $lowFieldName]);
6992 $highFieldName = str_replace('_high', '', $fieldName);
6993 if (isset($this->_fields
[$highFieldName])) {
6994 return array_merge($this->_fields
[$highFieldName], ['field_name' => $highFieldName]);
6999 public function buildWhereForDate() {
7004 * Is the field a relative date field.
7006 * @param string $fieldName
7010 protected function isADateRangeField($fieldName) {
7011 if (substr($fieldName, -4, 4) !== '_low' && substr($fieldName, -5, 5) !== '_high') {
7014 return !empty($this->getFieldSpec($fieldName));
7020 protected function buildRelativeDateQuery(&$values) {
7021 $value = $values[2] ??
NULL;
7022 if (empty($value)) {
7025 $fieldName = substr($values[0], 0, strlen($values[0]) - 9);
7026 $fieldSpec = $this->_fields
[$fieldName];
7027 $tableName = $fieldSpec['table_name'];
7028 $filters = CRM_Core_OptionGroup
::values('relative_date_filters');
7029 $grouping = $values[3] ??
NULL;
7030 // If the table value is already set for a custom field it will be more nuanced than just '1'.
7031 $this->_tables
[$tableName] = $this->_tables
[$tableName] ??
1;
7032 $this->_whereTables
[$tableName] = $this->_whereTables
[$tableName] ??
1;
7034 $dates = CRM_Utils_Date
::getFromTo($value, NULL, NULL);
7035 // Where end would be populated only if we are handling one of the weird ones with different from & to fields.
7036 $secondWhere = $fieldSpec['where_end'] ??
$fieldSpec['where'];
7038 $where = $fieldSpec['where'];
7039 if ($fieldSpec['table_name'] === 'civicrm_contact') {
7040 // Special handling for contact table as it has a known alias in advanced search.
7041 $where = str_replace('civicrm_contact.', 'contact_a.', $where);
7042 $secondWhere = str_replace('civicrm_contact.', 'contact_a.', $secondWhere);
7045 $this->_qill
[$grouping][] = $this->getQillForRelativeDateRange($dates[0], $dates[1], $fieldSpec['title'], $filters[$value]);
7046 if ($fieldName === 'relation_active_period_date') {
7047 // Hack this to fix regression https://lab.civicrm.org/dev/core/issues/1592
7048 // Not sure the 'right' fix.
7049 $this->_where
[$grouping] = [self
::getRelationshipActivePeriodClauses($dates[0], $dates[1], TRUE)];
7053 if (empty($dates[0])) {
7054 // ie. no start date we only have end date
7055 $this->_where
[$grouping][] = $secondWhere . " <= '{$dates[1]}'";
7057 elseif (empty($dates[1])) {
7059 // ie. no end date we only have start date
7060 $this->_where
[$grouping][] = $where . " >= '{$dates[0]}'";
7063 // we have start and end dates.
7064 if ($secondWhere !== $where) {
7065 $this->_where
[$grouping][] = $where . ">= '{$dates[0]}' AND $secondWhere <='{$dates[1]}'";
7068 $this->_where
[$grouping][] = $where . " BETWEEN '{$dates[0]}' AND '{$dates[1]}'";
7074 * Build the query for a date field if it is a _high or _low field.
7079 * @throws \CRM_Core_Exception
7081 public function buildDateRangeQuery($values) {
7082 if ($this->isADateRangeField($values[0])) {
7083 $fieldSpec = $this->getFieldSpec($values[0]);
7084 $title = empty($fieldSpec['unique_title']) ?
$fieldSpec['title'] : $fieldSpec['unique_title'];
7085 $this->dateQueryBuilder($values, $fieldSpec['table_name'], $fieldSpec['field_name'], $fieldSpec['name'], $title);
7092 * Add the address table into the query.
7094 * @param string $tableKey
7095 * @param string $joinCondition
7101 protected function addAddressTable($tableKey, $joinCondition) {
7102 $tName = "$tableKey-address";
7103 $aName = "`$tableKey-address`";
7104 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
7105 $this->_element
["{$tName}_id"] = 1;
7106 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$joinCondition)";
7107 $this->_tables
[$tName] = $addressJoin;
7116 * Get the clause for group status.
7118 * @param int $grouping
7122 protected function getGroupStatusClause($grouping) {
7123 $statuses = $this->getSelectedGroupStatuses($grouping);
7124 return "status IN (" . implode(', ', $statuses) . ")";
7128 * Get an array of the statuses that have been selected.
7130 * @param string $grouping
7134 * @throws \CRM_Core_Exception
7136 protected function getSelectedGroupStatuses($grouping) {
7138 $gcsValues = $this->getWhereValues('group_contact_status', $grouping);
7140 is_array($gcsValues[2])
7142 foreach ($gcsValues[2] as $k => $v) {
7144 $statuses[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
7149 $statuses[] = "'Added'";
7155 * Get the qill value for the field.
7157 * @param string $name
7158 * @param array|int|string $value
7160 * @param array $fieldSpec
7161 * @param string $labelOverride
7162 * Label override, if required.
7166 public function getQillForField($name, $value, $op, $fieldSpec = [], $labelOverride = NULL): string {
7167 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue($fieldSpec['bao'] ??
NULL, $name, $value, $op);
7168 return (string) ts("%1 %2 %3", [
7169 1 => $labelOverride ??
$fieldSpec['title'],
7176 * Where handling for any field with adequately defined metadata.
7178 * @param array $fieldSpec
7179 * @param string $name
7180 * @param string|array|int $value
7182 * @param string|int $grouping
7184 * @throws \CRM_Core_Exception
7186 public function handleWhereFromMetadata($fieldSpec, $name, $value, $op, $grouping = 0) {
7187 $this->_where
[$grouping][] = CRM_Contact_BAO_Query
::buildClause($fieldSpec['where'], $op, $value, CRM_Utils_Type
::typeToString($fieldSpec['type']));
7188 $this->_qill
[$grouping][] = $this->getQillForField($name, $value, $op, $fieldSpec);
7189 if (!isset($this->_tables
[$fieldSpec['table_name']])) {
7190 $this->_tables
[$fieldSpec['table_name']] = 1;
7192 if (!isset($this->_whereTables
[$fieldSpec['table_name']])) {
7193 $this->_whereTables
[$fieldSpec['table_name']] = 1;
7198 * Get the qill for the relative date range.
7200 * @param string|null $from
7201 * @param string|null $to
7202 * @param string $fieldTitle
7203 * @param string $relativeRange
7207 protected function getQillForRelativeDateRange($from, $to, string $fieldTitle, string $relativeRange): string {
7209 return ts('%1 is ', [$fieldTitle]) . $relativeRange . ' (' . ts('to %1', [CRM_Utils_Date
::customFormat($to)]) . ')';
7212 return ts('%1 is ', [$fieldTitle]) . $relativeRange . ' (' . ts('from %1', [CRM_Utils_Date
::customFormat($from)]) . ')';
7214 return ts('%1 is ', [$fieldTitle]) . $relativeRange . ' (' . ts('between %1 and %2', [
7215 CRM_Utils_Date
::customFormat($from),
7216 CRM_Utils_Date
::customFormat($to),