3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * This is the heart of the search query building mechanism.
37 class CRM_Contact_BAO_Query
{
40 * The various search modes.
42 * As of February 2017, entries not present for 4, 32, 64, 1024.
44 * MODE_ALL seems to be out of sync with the available constants;
45 * if this is intentionally excluding MODE_MAILING then that may
48 * Likewise if there's reason for the missing modes (4, 32, 64 etc).
53 NO_RETURN_PROPERTIES
= 'CRM_Contact_BAO_Query::NO_RETURN_PROPERTIES',
59 MODE_CONTACTSRELATED
= 32,
62 MODE_PLEDGEBANK
= 256,
72 * Constants for search operators
75 SEARCH_OPERATOR_AND
= 'AND',
76 SEARCH_OPERATOR_OR
= 'OR';
79 * The default set of return properties.
83 public static $_defaultReturnProperties = NULL;
86 * The default set of hier return properties.
90 public static $_defaultHierReturnProperties;
93 * The set of input params.
101 public $_paramLookup;
106 * The set of output params
110 public $_returnProperties;
120 * The name of the elements that are in the select clause
121 * used to extract the values.
128 * The tables involved in the query.
135 * The table involved in the where clause.
139 public $_whereTables;
142 * Array of WHERE clause components.
149 * The WHERE clause as a string.
153 public $_whereClause;
156 * Additional WHERE clause for permissions.
160 public $_permissionWhereClause;
170 * Additional permission from clause
174 public $_permissionFromClause;
177 * The from clause for the simple select and alphabetical
182 public $_simpleFromClause;
192 * The english language version of the query
199 * All the fields that could potentially be involved in
207 * Fields hacked for legacy reasons.
209 * Generally where a field has a option group defining it's options we add them to
210 * the fields array as pseudofields - eg for gender we would add the key 'gender' to fields
211 * using CRM_Core_DAO::appendPseudoConstantsToFields($fields);
213 * The rendered results would hold an id in the gender_id field and the label in the pseudo 'Gender'
214 * field. The heading for the pseudofield would come form the the option group name & for the id field
217 * These fields are handled in a more legacy way - ie overwriting 'gender_id' with the label on output
218 * via the convertToPseudoNames function. Ideally we would convert them but they would then need to be fixed
219 * in some other places & there are also some issues around the name (ie. Gender currently has the label in the
220 * schema 'Gender' so adding a second 'Gender' field to search builder & export would be confusing and the standard is
221 * not fully agreed here.
225 protected $legacyHackedFields = [
226 'gender_id' => 'gender',
227 'prefix_id' => 'individual_prefix',
228 'suffix_id' => 'individual_suffix',
229 'communication_style_id' => 'communication_style',
233 * The cache to translate the option values into labels.
240 * Are we in search mode.
244 public $_search = TRUE;
247 * Should we skip permission checking.
251 public $_skipPermission = FALSE;
254 * Should we skip adding of delete clause.
258 public $_skipDeleteClause = FALSE;
261 * Are we in strict mode (use equality over LIKE)
265 public $_strict = FALSE;
268 * What operator to use to group the clauses.
272 public $_operator = 'AND';
277 * Should we only search on primary location.
281 public $_primaryLocation = TRUE;
284 * Are contact ids part of the query.
288 public $_includeContactIds = FALSE;
291 * Should we use the smart group cache.
295 public $_smartGroupCache = TRUE;
298 * Should we display contacts with a specific relationship type.
302 public $_displayRelationshipType = NULL;
305 * Reference to the query object for custom values.
309 public $_customQuery;
312 * Should we enable the distinct clause, used if we are including
313 * more than one group
317 public $_useDistinct = FALSE;
320 * Should we just display one contact record
323 public $_useGroupBy = FALSE;
326 * The relationship type direction
330 public static $_relType;
337 public static $_activityRole;
340 * Consider the component activity type
341 * during activity search.
345 public static $_considerCompActivities;
348 * Consider with contact activities only,
349 * during activity search.
353 public static $_withContactActivitiesOnly;
356 * Use distinct component clause for component searches
360 public $_distinctComponentClause;
362 public $_rowCountClause;
365 * Use groupBy component clause for component searches
369 public $_groupByComponentClause;
372 * Track open panes, useful in advance search
376 public static $_openedPanes = [];
379 * For search builder - which custom fields are location-dependent
382 public $_locationSpecificCustomFields = [];
385 * The tables which have a dependency on location and/or address
389 public static $_dependencies = [
390 'civicrm_state_province' => 1,
391 'civicrm_country' => 1,
392 'civicrm_county' => 1,
393 'civicrm_address' => 1,
394 'civicrm_location_type' => 1,
398 * List of location specific fields.
401 public static $_locationSpecificFields = [
406 'supplemental_address_1',
407 'supplemental_address_2',
408 'supplemental_address_3',
411 'postal_code_suffix',
425 * Remember if we handle either end of a number or date range
426 * so we can skip the other
429 protected $_rangeCache = [];
431 * Set to true when $this->relationship is run to avoid adding twice.
435 protected $_relationshipValuesAdded = FALSE;
438 * Set to the name of the temp table if one has been created.
442 public static $_relationshipTempTable = NULL;
444 public $_pseudoConstantsSelect = [];
446 public $_groupUniqueKey = NULL;
447 public $_groupKeys = [];
450 * Class constructor which also does all the work.
452 * @param array $params
453 * @param array $returnProperties
454 * @param array $fields
455 * @param bool $includeContactIds
456 * @param bool $strict
457 * @param bool|int $mode - mode the search is operating on
459 * @param bool $skipPermission
460 * @param bool $searchDescendentGroups
461 * @param bool $smartGroupCache
462 * @param null $displayRelationshipType
463 * @param string $operator
464 * @param string $apiEntity
465 * @param bool|null $primaryLocationOnly
467 public function __construct(
468 $params = NULL, $returnProperties = NULL, $fields = NULL,
469 $includeContactIds = FALSE, $strict = FALSE, $mode = 1,
470 $skipPermission = FALSE, $searchDescendentGroups = TRUE,
471 $smartGroupCache = TRUE, $displayRelationshipType = NULL,
474 $primaryLocationOnly = NULL
476 if ($primaryLocationOnly === NULL) {
477 $primaryLocationOnly = Civi
::settings()->get('searchPrimaryDetailsOnly');
479 $this->_primaryLocation
= $primaryLocationOnly;
480 $this->_params
= &$params;
481 if ($this->_params
== NULL) {
485 if ($returnProperties === self
::NO_RETURN_PROPERTIES
) {
486 $this->_returnProperties
= [];
488 elseif (empty($returnProperties)) {
489 $this->_returnProperties
= self
::defaultReturnProperties($mode);
492 $this->_returnProperties
= &$returnProperties;
495 $this->_includeContactIds
= $includeContactIds;
496 $this->_strict
= $strict;
497 $this->_mode
= $mode;
498 $this->_skipPermission
= $skipPermission;
499 $this->_smartGroupCache
= $smartGroupCache;
500 $this->_displayRelationshipType
= $displayRelationshipType;
501 $this->setOperator($operator);
504 $this->_fields
= &$fields;
505 $this->_search
= FALSE;
506 $this->_skipPermission
= TRUE;
509 $this->_fields
= CRM_Contact_BAO_Contact
::exportableFields('All', FALSE, TRUE, TRUE, FALSE, !$skipPermission);
510 // The legacy hacked fields will output as a string rather than their underlying type.
511 foreach (array_keys($this->legacyHackedFields
) as $fieldName) {
512 $this->_fields
[$fieldName]['type'] = CRM_Utils_Type
::T_STRING
;
514 $relationMetadata = CRM_Contact_BAO_Relationship
::fields();
515 $relationFields = array_intersect_key($relationMetadata, array_fill_keys(['relationship_start_date', 'relationship_end_date'], 1));
516 // No good option other than hard-coding metadata for this 'special' field in.
517 $relationFields['relation_active_period_date'] = [
518 'name' => 'relation_active_period_date',
519 'type' => CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
,
520 'title' => ts('Active Period'),
521 'table_name' => 'civicrm_relationship',
522 'where' => 'civicrm_relationship.start_date',
523 'where_end' => 'civicrm_relationship.end_date',
524 'html' => ['type' => 'SelectDate', 'formatType' => 'activityDateTime'],
526 $this->_fields
= array_merge($relationFields, $this->_fields
);
528 $fields = CRM_Core_Component
::getQueryFields(!$this->_skipPermission
);
529 unset($fields['note']);
530 $this->_fields
= array_merge($this->_fields
, $fields);
532 // add activity fields
533 $fields = CRM_Activity_BAO_Activity
::exportableFields();
534 $this->_fields
= array_merge($this->_fields
, $fields);
536 // add any fields provided by hook implementers
537 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
538 $this->_fields
= array_merge($this->_fields
, $extFields);
541 // basically do all the work once, and then reuse it
542 $this->initialize($apiEntity);
546 * Function which actually does all the work for the constructor.
548 * @param string $apiEntity
549 * The api entity being called.
550 * This sort-of duplicates $mode in a confusing way. Probably not by design.
552 public function initialize($apiEntity = NULL) {
554 $this->_element
= [];
556 $this->_whereTables
= [];
559 $this->_options
= [];
561 $this->_paramLookup
= [];
564 $this->_customQuery
= NULL;
566 // reset cached static variables - CRM-5803
567 self
::$_activityRole = NULL;
568 self
::$_considerCompActivities = NULL;
569 self
::$_withContactActivitiesOnly = NULL;
571 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
572 $this->_element
['contact_id'] = 1;
573 $this->_tables
['civicrm_contact'] = 1;
575 if (!empty($this->_params
)) {
576 $this->buildParamsLookup();
579 $this->_whereTables
= $this->_tables
;
581 $this->selectClause($apiEntity);
582 $isForcePrimaryOnly = !empty($apiEntity);
583 $this->_whereClause
= $this->whereClause($isForcePrimaryOnly);
584 if (array_key_exists('civicrm_contribution', $this->_whereTables
)) {
585 $component = 'contribution';
587 if (array_key_exists('civicrm_membership', $this->_whereTables
)) {
588 $component = 'membership';
590 if (isset($component) && !$this->_skipPermission
) {
591 // Unit test coverage in api_v3_FinancialTypeACLTest::testGetACLContribution.
592 CRM_Financial_BAO_FinancialType
::buildPermissionedClause($this->_whereClause
, $component);
595 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
, $apiEntity);
596 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
598 $this->openedSearchPanes(TRUE);
602 * Function for same purpose as convertFormValues.
604 * Like convert form values this function exists to pre-Process parameters from the form.
606 * It is unclear why they are different functions & likely relates to advances search
607 * versus search builder.
609 * The direction we are going is having the form convert values to a standardised format &
610 * moving away from weird & wonderful where clause switches.
612 * Fix and handle contact deletion nicely.
614 * this code is primarily for search builder use case where different clauses can specify if they want deleted.
618 public function buildParamsLookup() {
619 $trashParamExists = FALSE;
621 foreach ($this->_params
as $k => $param) {
622 if (!empty($param[0]) && $param[0] == 'contact_is_deleted') {
623 $trashParamExists = TRUE;
625 if (!empty($param[3])) {
626 $paramByGroup[$param[3]][$k] = $param;
630 if ($trashParamExists) {
631 $this->_skipDeleteClause
= TRUE;
633 //cycle through group sets and explicitly add trash param if not set
634 foreach ($paramByGroup as $setID => $set) {
636 !in_array(['contact_is_deleted', '=', '1', $setID, '0'], $this->_params
) &&
637 !in_array(['contact_is_deleted', '=', '0', $setID, '0'], $this->_params
)
640 'contact_is_deleted',
650 foreach ($this->_params
as $value) {
651 if (empty($value[0])) {
654 $cfID = CRM_Core_BAO_CustomField
::getKeyID(str_replace('_relative', '', $value[0]));
656 if (!array_key_exists($cfID, $this->_cfIDs
)) {
657 $this->_cfIDs
[$cfID] = [];
659 // Set wildcard value based on "and/or" selection
660 foreach ($this->_params
as $key => $param) {
661 if ($param[0] == $value[0] . '_operator') {
662 $value[4] = $param[2] == 'or';
666 $this->_cfIDs
[$cfID][] = $value;
669 if (!array_key_exists($value[0], $this->_paramLookup
)) {
670 $this->_paramLookup
[$value[0]] = [];
672 if ($value[0] !== 'group') {
673 // Just trying to unravel how group interacts here! This whole function is weird.
674 $this->_paramLookup
[$value[0]][] = $value;
680 * Some composite fields do not appear in the fields array hack to make them part of the query.
683 * The api entity being called.
684 * This sort-of duplicates $mode in a confusing way. Probably not by design.
686 public function addSpecialFields($apiEntity) {
687 static $special = ['contact_type', 'contact_sub_type', 'sort_name', 'display_name'];
688 // if get called via Contact.get API having address_id as return parameter
689 if ($apiEntity == 'Contact') {
690 $special[] = 'address_id';
692 foreach ($special as $name) {
693 if (!empty($this->_returnProperties
[$name])) {
694 if ($name == 'address_id') {
695 $this->_tables
['civicrm_address'] = 1;
696 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
697 $this->_element
['address_id'] = 1;
700 $this->_select
[$name] = "contact_a.{$name} as $name";
701 $this->_element
[$name] = 1;
708 * Given a list of conditions in params and a list of desired
709 * return Properties generate the required select and from
710 * clauses. Note that since the where clause introduces new
711 * tables, the initial attempt also retrieves all variables used
714 * @param string $apiEntity
715 * The api entity being called.
716 * This sort-of duplicates $mode in a confusing way. Probably not by design.
718 public function selectClause($apiEntity = NULL) {
720 // @todo Tidy up this. This arises because 1) we are ignoring the $mode & adding a new
721 // param ($apiEntity) instead - presumably an oversight & 2 because
722 // contact is not implemented as a component.
723 $this->addSpecialFields($apiEntity);
725 foreach ($this->_fields
as $name => $field) {
726 // skip component fields
727 // there are done by the alter query below
728 // and need not be done on every field
729 // @todo remove these & handle using metadata - only obscure fields
730 // that are hack-added should need to be excluded from the main loop.
732 (substr($name, 0, 12) == 'participant_') ||
733 (substr($name, 0, 7) == 'pledge_') ||
734 (substr($name, 0, 5) == 'case_')
739 // redirect to activity select clause
741 (substr($name, 0, 9) == 'activity_') ||
742 ($name == 'parent_id')
744 CRM_Activity_BAO_Query
::select($this);
747 // if this is a hierarchical name, we ignore it
748 $names = explode('-', $name);
749 if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) {
753 // make an exception for special cases, to add the field in select clause
754 $makeException = FALSE;
756 //special handling for groups/tags
757 if (in_array($name, ['groups', 'tags', 'notes'])
758 && isset($this->_returnProperties
[substr($name, 0, -1)])
760 // @todo instead of setting make exception to get us into
761 // an if clause that has handling for these fields buried with in it
762 // move the handling to here.
763 $makeException = TRUE;
766 // since note has 3 different options we need special handling
767 // note / note_subject / note_body
768 if ($name == 'notes') {
769 foreach (['note', 'note_subject', 'note_body'] as $noteField) {
770 if (isset($this->_returnProperties
[$noteField])) {
771 $makeException = TRUE;
777 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
779 !empty($this->_paramLookup
[$name])
780 ||
!empty($this->_returnProperties
[$name])
781 ||
$this->pseudoConstantNameIsInReturnProperties($field, $name)
785 // add to cfIDs array if not present
786 if (!array_key_exists($cfID, $this->_cfIDs
)) {
787 $this->_cfIDs
[$cfID] = [];
790 elseif (isset($field['where'])) {
791 list($tableName, $fieldName) = explode('.', $field['where'], 2);
792 if (isset($tableName)) {
793 if (CRM_Utils_Array
::value($tableName, self
::$_dependencies)) {
794 $this->_tables
['civicrm_address'] = 1;
795 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
796 $this->_element
['address_id'] = 1;
799 if ($tableName == 'im_provider' ||
$tableName == 'email_greeting' ||
800 $tableName == 'postal_greeting' ||
$tableName == 'addressee'
802 if ($tableName == 'im_provider') {
803 CRM_Core_OptionValue
::select($this);
806 if (in_array($tableName,
807 ['email_greeting', 'postal_greeting', 'addressee'])) {
808 $this->_element
["{$name}_id"] = 1;
809 $this->_select
["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
810 $this->_pseudoConstantsSelect
[$name] = ['pseudoField' => $tableName, 'idCol' => "{$name}_id"];
811 $this->_pseudoConstantsSelect
[$name]['select'] = "{$name}.{$fieldName} as $name";
812 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
814 if ($tableName == 'email_greeting') {
816 $this->_pseudoConstantsSelect
[$name]['join']
817 = " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
818 $this->_pseudoConstantsSelect
[$name]['join'] .=
819 " LEFT JOIN civicrm_option_value email_greeting ON (contact_a.email_greeting_id = email_greeting.value AND option_group_email_greeting.id = email_greeting.option_group_id ) ";
821 elseif ($tableName == 'postal_greeting') {
823 $this->_pseudoConstantsSelect
[$name]['join']
824 = " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
825 $this->_pseudoConstantsSelect
[$name]['join'] .=
826 " LEFT JOIN civicrm_option_value postal_greeting ON (contact_a.postal_greeting_id = postal_greeting.value AND option_group_postal_greeting.id = postal_greeting.option_group_id ) ";
828 elseif ($tableName == 'addressee') {
830 $this->_pseudoConstantsSelect
[$name]['join']
831 = " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
832 $this->_pseudoConstantsSelect
[$name]['join'] .=
833 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
835 $this->_pseudoConstantsSelect
[$name]['table'] = $tableName;
838 $greetField = "{$name}_display";
839 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
840 $this->_element
[$greetField] = 1;
842 $greetField = "{$name}_custom";
843 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
844 $this->_element
[$greetField] = 1;
848 if (!in_array($tableName, ['civicrm_state_province', 'civicrm_country', 'civicrm_county'])) {
849 $this->_tables
[$tableName] = 1;
852 // also get the id of the tableName
853 $tName = substr($tableName, 8);
854 if (in_array($tName, ['country', 'state_province', 'county'])) {
855 if ($tName == 'state_province') {
856 $this->_pseudoConstantsSelect
['state_province_name'] = [
857 'pseudoField' => "{$tName}",
858 'idCol' => "{$tName}_id",
859 'bao' => 'CRM_Core_BAO_Address',
860 'table' => "civicrm_{$tName}",
861 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
864 $this->_pseudoConstantsSelect
[$tName] = [
865 'pseudoField' => 'state_province_abbreviation',
866 'idCol' => "{$tName}_id",
867 'table' => "civicrm_{$tName}",
868 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
872 $this->_pseudoConstantsSelect
[$name] = [
873 'pseudoField' => "{$tName}_id",
874 'idCol' => "{$tName}_id",
875 'bao' => 'CRM_Core_BAO_Address',
876 'table' => "civicrm_{$tName}",
877 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
881 $this->_select
["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
882 $this->_element
["{$tName}_id"] = 1;
884 elseif ($tName != 'contact') {
885 $this->_select
["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
886 $this->_element
["{$tName}_id"] = 1;
889 //special case for phone
890 if ($name == 'phone') {
891 $this->_select
['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
892 $this->_element
['phone_type_id'] = 1;
895 // if IM then select provider_id also
896 // to get "IM Service Provider" in a file to be exported, CRM-3140
898 $this->_select
['provider_id'] = "civicrm_im.provider_id as provider_id";
899 $this->_element
['provider_id'] = 1;
902 if ($tName == 'contact' && $fieldName == 'organization_name') {
903 // special case, when current employer is set for Individual contact
904 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
906 elseif ($tName == 'contact' && $fieldName === 'id') {
907 // Handled elsewhere, explicitly ignore. Possibly for all tables...
909 elseif (in_array($tName, ['country', 'county'])) {
910 $this->_pseudoConstantsSelect
[$name]['select'] = "{$field['where']} as `$name`";
911 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
913 elseif ($tName == 'state_province') {
914 $this->_pseudoConstantsSelect
[$tName]['select'] = "{$field['where']} as `$name`";
915 $this->_pseudoConstantsSelect
[$tName]['element'] = $name;
917 elseif (strpos($name, 'contribution_soft_credit') !== FALSE) {
918 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled($this->_params
)) {
919 $this->_select
[$name] = "{$field['where']} as `$name`";
922 elseif ($this->pseudoConstantNameIsInReturnProperties($field, $name)) {
923 $this->addPseudoconstantFieldToSelect($name);
926 $this->_select
[$name] = str_replace('civicrm_contact.', 'contact_a.', "{$field['where']} as `$name`");
928 if (!in_array($tName, ['state_province', 'country', 'county'])) {
929 $this->_element
[$name] = 1;
934 elseif ($name === 'tags') {
935 //@todo move this handling outside the big IF & ditch $makeException
936 $this->_useGroupBy
= TRUE;
937 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
938 $this->_element
[$name] = 1;
939 $this->_tables
['civicrm_tag'] = 1;
940 $this->_tables
['civicrm_entity_tag'] = 1;
942 elseif ($name === 'groups') {
943 //@todo move this handling outside the big IF & ditch $makeException
944 $this->_useGroupBy
= TRUE;
945 // Duplicates will be created here but better to sort them out in php land.
946 $this->_select
[$name] = "
948 GROUP_CONCAT(DISTINCT IF(civicrm_group_contact.status = 'Added', civicrm_group_contact.group_id, '')),
949 GROUP_CONCAT(DISTINCT civicrm_group_contact_cache.group_id)
952 $this->_element
[$name] = 1;
953 $this->_tables
['civicrm_group_contact'] = 1;
954 $this->_tables
['civicrm_group_contact_cache'] = 1;
955 $this->_pseudoConstantsSelect
["{$name}"] = [
956 'pseudoField' => "groups",
960 elseif ($name === 'notes') {
961 //@todo move this handling outside the big IF & ditch $makeException
962 // if note field is subject then return subject else body of the note
963 $noteColumn = 'note';
964 if (isset($noteField) && $noteField == 'note_subject') {
965 $noteColumn = 'subject';
968 $this->_useGroupBy
= TRUE;
969 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
970 $this->_element
[$name] = 1;
971 $this->_tables
['civicrm_note'] = 1;
973 elseif ($name === 'current_employer') {
974 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
975 $this->_element
[$name] = 1;
979 if ($cfID && !empty($field['is_search_range'])) {
980 // this is a custom field with range search enabled, so we better check for two/from values
981 if (!empty($this->_paramLookup
[$name . '_from'])) {
982 if (!array_key_exists($cfID, $this->_cfIDs
)) {
983 $this->_cfIDs
[$cfID] = [];
985 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
986 // search in the cdID array for the same grouping
988 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
989 if ($c[3] == $p[3]) {
990 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
995 $p[2] = ['from' => $p[2]];
996 $this->_cfIDs
[$cfID][] = $p;
1000 if (!empty($this->_paramLookup
[$name . '_to'])) {
1001 if (!array_key_exists($cfID, $this->_cfIDs
)) {
1002 $this->_cfIDs
[$cfID] = [];
1004 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
1005 // search in the cdID array for the same grouping
1007 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
1008 if ($c[4] == $p[4]) {
1009 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
1014 $p[2] = ['to' => $p[2]];
1015 $this->_cfIDs
[$cfID][] = $p;
1022 // add location as hierarchical elements
1023 $this->addHierarchicalElements();
1025 // add multiple field like website
1026 $this->addMultipleElements();
1029 CRM_Core_Component
::alterQuery($this, 'select');
1031 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'select');
1033 if (!empty($this->_cfIDs
)) {
1034 // @todo This function is the select function but instead of running 'select' it
1035 // is running the whole query.
1036 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
1037 $this->_customQuery
->query();
1038 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
1039 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
1040 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
1041 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
1042 $this->_options
= $this->_customQuery
->_options
;
1047 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
1049 public function addHierarchicalElements() {
1050 if (empty($this->_returnProperties
['location'])) {
1053 if (!is_array($this->_returnProperties
['location'])) {
1057 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
1061 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
1062 $addressCustomFieldIds = [];
1064 foreach ($this->_returnProperties
['location'] as $name => $elements) {
1065 $lCond = self
::getPrimaryCondition($name);
1066 $locationTypeId = is_numeric($name) ?
NULL : array_search($name, $locationTypes);
1069 if ($locationTypeId === FALSE) {
1072 $lCond = "location_type_id = $locationTypeId";
1073 $this->_useDistinct
= TRUE;
1075 //commented for CRM-3256
1076 $this->_useGroupBy
= TRUE;
1079 $name = str_replace(' ', '_', $name);
1080 $tName = "$name-location_type";
1081 $ltName = "`$name-location_type`";
1082 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1083 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
1084 $this->_element
["{$tName}_id"] = 1;
1085 $this->_element
["{$tName}"] = 1;
1087 $locationTypeName = $tName;
1088 $locationTypeJoin = [];
1091 foreach ($elements as $elementFullName => $dontCare) {
1093 $elementName = $elementCmpName = $elementFullName;
1095 if (substr($elementCmpName, 0, 5) == 'phone') {
1096 $elementCmpName = 'phone';
1099 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
1100 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
1101 $addressCustomFieldIds[$cfID][$name] = 1;
1104 // add address table - doesn't matter if we do it mutliple times - it's the same data
1105 // @todo ditch the double processing of addressJoin
1106 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
1107 && !in_array($elementCmpName, ['email', 'phone', 'im', 'openid'])
1109 list($aName, $addressJoin) = $this->addAddressTable($name, $lCond);
1110 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
1111 $processed[$aName] = 1;
1114 $cond = $elementType = '';
1115 if (strpos($elementName, '-') !== FALSE) {
1116 // this is either phone, email or IM
1117 list($elementName, $elementType) = explode('-', $elementName);
1119 if (($elementName != 'phone') && ($elementName != 'im')) {
1120 $cond = self
::getPrimaryCondition($elementType);
1122 // CRM-13011 : If location type is primary, do not restrict search to the phone
1123 // type id - we want the primary phone, regardless of what type it is.
1124 // Otherwise, restrict to the specified phone type for the given field.
1125 if ((!$cond) && ($elementName == 'phone')) {
1126 $cond = "phone_type_id = '$elementType'";
1128 elseif ((!$cond) && ($elementName == 'im')) {
1129 // IM service provider id, CRM-3140
1130 $cond = "provider_id = '$elementType'";
1132 $elementType = '-' . $elementType;
1135 $field = CRM_Utils_Array
::value($elementName, $this->_fields
);
1137 // hack for profile, add location id
1140 // fix for CRM-882( to handle phone types )
1141 !is_numeric($elementType)
1143 if (is_numeric($name)) {
1144 $field = CRM_Utils_Array
::value($elementName . "-Primary$elementType", $this->_fields
);
1147 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1150 elseif (is_numeric($name)) {
1151 //this for phone type to work
1152 if (in_array($elementName, ['phone', 'phone_ext'])) {
1153 $field = CRM_Utils_Array
::value($elementName . "-Primary" . $elementType, $this->_fields
);
1156 $field = CRM_Utils_Array
::value($elementName . "-Primary", $this->_fields
);
1160 //this is for phone type to work for profile edit
1161 if (in_array($elementName, ['phone', 'phone_ext'])) {
1162 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1165 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId", $this->_fields
);
1170 // Check if there is a value, if so also add to where Clause
1172 if ($this->_params
) {
1174 if (isset($locationTypeId)) {
1175 $nm .= "-$locationTypeId";
1177 if (!is_numeric($elementType)) {
1178 $nm .= "$elementType";
1181 foreach ($this->_params
as $id => $values) {
1182 if ((is_array($values) && $values[0] == $nm) ||
1183 (in_array($elementName, ['phone', 'im'])
1184 && (strpos($values[0], $nm) !== FALSE)
1194 if ($field && isset($field['where'])) {
1195 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1196 $pf = substr($tableName, 8);
1197 $tName = $name . '-' . $pf . $elementType;
1198 if (isset($tableName)) {
1199 if ($tableName == 'civicrm_state_province' ||
$tableName == 'civicrm_country' ||
$tableName == 'civicrm_county') {
1200 $this->_select
["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1203 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1206 $this->_element
["{$tName}_id"] = 1;
1207 if (substr($tName, -15) == '-state_province') {
1208 // FIXME: hack to fix CRM-1900
1209 $a = Civi
::settings()->get('address_format');
1211 if (substr_count($a, 'state_province_name') > 0) {
1212 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = [
1213 'pseudoField' => "{$pf}_id",
1214 'idCol' => "{$tName}_id",
1215 'bao' => 'CRM_Core_BAO_Address',
1217 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1220 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = [
1221 'pseudoField' => 'state_province_abbreviation',
1222 'idCol' => "{$tName}_id",
1224 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1228 if (substr($elementFullName, 0, 2) == 'im') {
1229 $provider = "{$name}-{$elementFullName}-provider_id";
1230 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1231 $this->_element
[$provider] = 1;
1233 if ($pf == 'country' ||
$pf == 'county') {
1234 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = [
1235 'pseudoField' => "{$pf}_id",
1236 'idCol' => "{$tName}_id",
1237 'bao' => 'CRM_Core_BAO_Address',
1239 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1242 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1246 if (in_array($pf, ['state_province', 'country', 'county'])) {
1247 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1250 $this->_element
["{$name}-{$elementFullName}"] = 1;
1253 if (empty($processed["`$tName`"])) {
1254 $processed["`$tName`"] = 1;
1255 $newName = $tableName . '_' . $index;
1256 switch ($tableName) {
1257 case 'civicrm_phone':
1258 case 'civicrm_email':
1260 case 'civicrm_openid':
1262 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id";
1263 if ($tableName != 'civicrm_phone') {
1264 $this->_tables
[$tName] .= " AND `$tName`.$lCond";
1266 elseif (is_numeric($name)) {
1267 $this->_select
[$tName] = "IF (`$tName`.is_primary = $name, `$tName`.phone, NULL) as `$tName`";
1270 // this special case to add phone type
1272 $phoneTypeCondition = " AND `$tName`.$cond ";
1273 //gross hack to pickup corrupted data also, CRM-7603
1274 if (strpos($cond, 'phone_type_id') !== FALSE) {
1275 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1276 if (!empty($lCond)) {
1277 $phoneTypeCondition .= " AND ( `$tName`.$lCond ) ";
1280 $this->_tables
[$tName] .= $phoneTypeCondition;
1283 //build locationType join
1284 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1287 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1291 case 'civicrm_state_province':
1292 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1293 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1294 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1296 $this->_whereTables
["{$name}-address"] = $addressJoin;
1300 case 'civicrm_country':
1301 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1302 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1303 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1305 $this->_whereTables
["{$name}-address"] = $addressJoin;
1309 case 'civicrm_county':
1310 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1311 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1312 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1314 $this->_whereTables
["{$name}-address"] = $addressJoin;
1319 if (isset($addressCustomFields[$elementName]['custom_field_id']) && !empty($addressCustomFields[$elementName]['custom_field_id'])) {
1320 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.id";
1323 $this->_whereTables
["{$name}-address"] = $addressJoin;
1332 // add location type join
1333 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1334 $this->_tables
[$locationTypeName] = $ltypeJoin;
1336 // table should be present in $this->_whereTables,
1337 // to add its condition in location type join, CRM-3939.
1338 if ($addWhereCount) {
1340 foreach ($this->_whereTables
as $tableName => $clause) {
1341 if (!empty($locationTypeJoin[$tableName])) {
1342 $locClause[] = $locationTypeJoin[$tableName];
1346 if (!empty($locClause)) {
1347 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1352 if (!empty($addressCustomFieldIds)) {
1353 $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
1354 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1355 foreach ($locTypeName as $name => $dnc) {
1356 $this->_locationSpecificCustomFields
[$cfID] = [$name, array_search($name, $locationTypes)];
1357 $fieldName = "$name-custom_{$cfID}";
1358 $tName = "$name-address-custom-{$cfID}";
1359 $aName = "`$name-address-custom-{$cfID}`";
1360 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1361 $this->_element
["{$tName}_id"] = 1;
1362 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1363 $this->_element
[$fieldName] = 1;
1364 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1371 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
1373 public function addMultipleElements() {
1374 if (empty($this->_returnProperties
['website'])) {
1377 if (!is_array($this->_returnProperties
['website'])) {
1381 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1382 foreach ($elements as $elementFullName => $dontCare) {
1383 $tName = "website-{$key}-{$elementFullName}";
1384 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1385 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1386 $this->_element
["{$tName}_id"] = 1;
1387 $this->_element
["{$tName}"] = 1;
1389 $type = "website-{$key}-website_type_id";
1390 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1391 $this->_element
[$type] = 1;
1392 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id AND `$tName`.website_type_id = $key )";
1398 * Generate the query based on what type of query we need.
1400 * @param bool $count
1401 * @param bool $sortByChar
1402 * @param bool $groupContacts
1403 * @param bool $onlyDeleted
1406 * sql query parts as an array
1408 public function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE, $onlyDeleted = FALSE) {
1409 // build permission clause
1410 $this->generatePermissionClause($onlyDeleted, $count);
1413 if (isset($this->_rowCountClause
)) {
1414 $select = "SELECT {$this->_rowCountClause}";
1416 elseif (isset($this->_distinctComponentClause
)) {
1417 // we add distinct to get the right count for components
1418 // for the more complex result set, we use GROUP BY the same id
1420 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} ) as rowCount";
1423 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1425 $from = $this->_simpleFromClause
;
1426 if ($this->_useDistinct
) {
1427 $this->_useGroupBy
= TRUE;
1430 elseif ($sortByChar) {
1431 // @fixme add the deprecated warning back in (it breaks CRM_Contact_SelectorTest::testSelectorQuery)
1432 // CRM_Core_Error::deprecatedFunctionWarning('sort by char is deprecated - use alphabetQuery method');
1433 $select = 'SELECT DISTINCT LEFT(contact_a.sort_name, 1) as sort_name';
1434 $from = $this->_simpleFromClause
;
1436 elseif ($groupContacts) {
1437 $select = 'SELECT contact_a.id as id';
1438 if ($this->_useDistinct
) {
1439 $this->_useGroupBy
= TRUE;
1441 $from = $this->_simpleFromClause
;
1444 if (!empty($this->_paramLookup
['group'])) {
1446 list($name, $op, $value, $grouping, $wildcard) = $this->_paramLookup
['group'][0];
1448 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
1449 $this->_paramLookup
['group'][0][1] = key($value);
1452 // Presumably the lines below come into manage groups screen.
1453 // make sure there is only one element
1454 // this is used when we are running under smog and need to know
1455 // how the contact was added (CRM-1203)
1456 $groups = (array) CRM_Utils_Array
::value($this->_paramLookup
['group'][0][1], $this->_paramLookup
['group'][0][2], $this->_paramLookup
['group'][0][2]);
1457 if ((count($this->_paramLookup
['group']) == 1) &&
1458 (count($groups) == 1)
1460 $groupId = $groups[0];
1462 //check if group is saved search
1463 $group = new CRM_Contact_BAO_Group();
1464 $group->id
= $groupId;
1467 if (!isset($group->saved_search_id
)) {
1468 $tbName = "civicrm_group_contact";
1469 // CRM-17254 don't retrieve extra fields if contact_id is specifically requested
1470 // as this will add load to an intentionally light query.
1471 // ideally this code would be removed as it appears to be to support CRM-1203
1472 // and passing in the required returnProperties from the url would
1473 // make more sense that globally applying the requirements of one form.
1474 if (($this->_returnProperties
!= ['contact_id'])) {
1475 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1476 $this->_element
['group_contact_id'] = 1;
1477 $this->_select
['status'] = "$tbName.status as status";
1478 $this->_element
['status'] = 1;
1482 $this->_useGroupBy
= TRUE;
1484 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1485 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1487 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1488 $this->_useDistinct
= FALSE;
1489 $this->_useGroupBy
= TRUE;
1493 $select = $this->getSelect();
1494 $from = $this->_fromClause
;
1498 if (!empty($this->_whereClause
)) {
1499 $where = "WHERE {$this->_whereClause}";
1502 if (!empty($this->_permissionWhereClause
) && empty($this->_displayRelationshipType
)) {
1503 if (empty($where)) {
1504 $where = "WHERE $this->_permissionWhereClause";
1507 $where = "$where AND $this->_permissionWhereClause";
1512 if (!empty($this->_having
)) {
1513 foreach ($this->_having
as $havingSets) {
1514 foreach ($havingSets as $havingSet) {
1515 $havingValue[] = $havingSet;
1518 $having = ' HAVING ' . implode(' AND ', $havingValue);
1521 // if we are doing a transform, do it here
1522 // use the $from, $where and $having to get the contact ID
1523 if ($this->_displayRelationshipType
) {
1524 $this->filterRelatedContacts($from, $where, $having);
1527 return [$select, $from, $where, $having];
1531 * Get where values from the parameters.
1533 * @param string $name
1534 * @param mixed $grouping
1538 public function getWhereValues($name, $grouping) {
1540 foreach ($this->_params
as $values) {
1541 if ($values[0] == $name && $values[3] == $grouping) {
1552 * @param bool $relative
1553 * @param string $from
1556 public static function fixDateValues($relative, &$from, &$to) {
1558 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1563 * Convert values from form-appropriate to query-object appropriate.
1565 * The query object is increasingly supporting the sql-filter syntax which is the most flexible syntax.
1566 * So, ideally we would convert all fields to look like
1569 * // Set the operator for legacy reasons, but it is ignored
1571 * // array in sql filter syntax
1572 * 2 => array('BETWEEN' => array(1,60),
1577 * There are some examples of the syntax in
1578 * https://github.com/civicrm/civicrm-core/tree/master/api/v3/examples/Relationship
1580 * More notes at CRM_Core_DAO::createSQLFilter
1582 * and a list of supported operators in CRM_Core_DAO
1584 * @param array $formValues
1585 * @param int $wildcard
1586 * @param bool $useEquals
1588 * @param string $apiEntity
1590 * @param array $entityReferenceFields
1591 * Field names of any entity reference fields (which will need reformatting to IN syntax).
1595 public static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL,
1596 $entityReferenceFields = []) {
1598 if (empty($formValues)) {
1602 self
::filterCountryFromValuesIfStateExists($formValues);
1603 // We shouldn't have to whitelist fields to not hack but here we are, for now.
1604 $nonLegacyDateFields = [
1605 'participant_register_date_relative',
1606 'receive_date_relative',
1607 'pledge_end_date_relative',
1608 'pledge_create_date_relative',
1609 'pledge_start_date_relative',
1610 'pledge_payment_scheduled_date_relative',
1611 'relationship_start_date_relative',
1612 'relationship_end_date_relative',
1613 'membership_join_date_relative',
1614 'membership_start_date_relative',
1615 'membership_end_date_relative',
1616 'case_start_date_relative',
1617 'case_end_date_relative',
1618 'mailing_job_start_date_relative',
1619 'birth_date_relative',
1620 'deceased_date_relative',
1621 'relation_active_period_date_relative',
1623 // Handle relative dates first
1624 foreach (array_keys($formValues) as $id) {
1626 !in_array($id, $nonLegacyDateFields) && (
1627 preg_match('/_date_relative$/', $id))
1629 $dateComponent = explode('_date_relative', $id);
1630 $fromRange = "{$dateComponent[0]}_date_low";
1631 $toRange = "{$dateComponent[0]}_date_high";
1633 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1634 CRM_Contact_BAO_Query
::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1639 foreach ($formValues as $id => $values) {
1640 if (self
::isAlreadyProcessedForQueryFormat($values)) {
1641 $params[] = $values;
1645 self
::legacyConvertFormValues($id, $values);
1647 // The form uses 1 field to represent two db fields
1648 if ($id == 'contact_type' && $values && (!is_array($values) ||
!array_intersect(array_keys($values), CRM_Core_DAO
::acceptedSQLOperators()))) {
1651 foreach ((array) $values as $key => $type) {
1652 $types = explode('__', is_numeric($type) ?
$key : $type, 2);
1653 $contactType[$types[0]] = $types[0];
1654 // Add sub-type if specified
1655 if (!empty($types[1])) {
1656 $subType[$types[1]] = $types[1];
1659 $params[] = ['contact_type', 'IN', $contactType, 0, 0];
1661 $params[] = ['contact_sub_type', 'IN', $subType, 0, 0];
1664 elseif ($id == 'privacy') {
1665 if (is_array($formValues['privacy'])) {
1666 $op = !empty($formValues['privacy']['do_not_toggle']) ?
'=' : '!=';
1667 foreach ($formValues['privacy'] as $key => $value) {
1669 $params[] = [$key, $op, $value, 0, 0];
1674 elseif ($id == 'email_on_hold') {
1675 if ($onHoldValue = CRM_Utils_Array
::value('email_on_hold', $formValues)) {
1676 // onHoldValue should be 0 or 1 or an array. Some legacy groups may hold ''
1677 // so in 5.11 we have an extra if that should become redundant over time.
1678 // https://lab.civicrm.org/dev/core/issues/745
1679 // @todo this renaming of email_on_hold to on_hold needs revisiting
1680 // it preceeds recent changes but causes the default not to reload.
1681 $onHoldValue = array_filter((array) $onHoldValue, 'is_numeric');
1682 if (!empty($onHoldValue)) {
1683 $params[] = ['on_hold', 'IN', $onHoldValue, 0, 0];
1687 elseif (substr($id, 0, 7) == 'custom_'
1689 substr($id, -5, 5) == '_from'
1690 ||
substr($id, -3, 3) == '_to'
1693 self
::convertCustomRelativeFields($formValues, $params, $values, $id);
1696 !in_array($id, $nonLegacyDateFields) && (
1697 preg_match('/_date_relative$/', $id))
1699 // Already handled in previous loop
1702 elseif (in_array($id, $entityReferenceFields) && !empty($values) && is_string($values) && (strpos($values, ',') !=
1704 $params[] = [$id, 'IN', explode(',', $values), 0, 0];
1707 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals, $apiEntity);
1712 $params[] = $values;
1719 * Function to support legacy format for groups and tags.
1722 * @param array|int $values
1725 public static function legacyConvertFormValues($id, &$values) {
1731 'membership_type_id',
1732 'membership_status_id',
1734 if (in_array($id, $legacyElements) && is_array($values)) {
1735 // prior to 4.7, formValues for some attributes (e.g. group, tag) are stored in array(id1 => 1, id2 => 1),
1736 // as per the recent Search fixes $values need to be in standard array(id1, id2) format
1737 $values = CRM_Utils_Array
::convertCheckboxFormatToArray($values);
1742 * Fix values from query from/to something no-one cared enough to document.
1745 * @param array $values
1746 * @param int $wildcard
1747 * @param bool $useEquals
1749 * @param string $apiEntity
1751 * @return array|null
1753 public static function fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL) {
1754 // skip a few search variables
1755 static $skipWhere = NULL;
1756 static $likeNames = NULL;
1759 // Change camelCase EntityName to lowercase with underscores
1760 $apiEntity = _civicrm_api_get_entity_name_from_camel($apiEntity);
1762 // check if $value is in OK (Operator as Key) format as used by Get API
1763 if (CRM_Utils_System
::isNull($values)) {
1775 'display_relationship_type',
1779 if (in_array($id, $skipWhere) ||
1780 substr($id, 0, 4) == '_qf_' ||
1781 substr($id, 0, 7) == 'hidden_'
1787 (substr($id, 0, strlen($apiEntity)) != $apiEntity) &&
1788 (substr($id, 0, 10) != 'financial_' && substr($id, 0, 8) != 'payment_') &&
1789 (substr($id, 0, 7) != 'custom_')
1791 $id = $apiEntity . '_' . $id;
1795 $likeNames = ['sort_name', 'email', 'note', 'display_name'];
1798 // email comes in via advanced search
1799 // so use wildcard always
1800 if ($id == 'email') {
1804 if (!$useEquals && in_array($id, $likeNames)) {
1805 $result = [$id, 'LIKE', $values, 0, 1];
1807 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1808 $result = [$id, 'LIKE', $values, 0, 0];
1810 elseif ($id == 'contact_type' ||
1811 (!empty($values) && is_array($values) && !in_array(key($values), CRM_Core_DAO
::acceptedSQLOperators(), TRUE))
1813 $result = [$id, 'IN', $values, 0, $wildcard];
1816 $result = [$id, '=', $values, 0, $wildcard];
1823 * Get the where clause for a single field.
1825 * @param array $values
1826 * @param bool $isForcePrimaryOnly
1828 * @throws \CRM_Core_Exception
1830 public function whereClauseSingle(&$values, $isForcePrimaryOnly = FALSE) {
1831 if ($this->isARelativeDateField($values[0])) {
1832 $this->buildRelativeDateQuery($values);
1835 // @todo also handle _low, _high generically here with if ($query->buildDateRangeQuery($values)) {return}
1837 // do not process custom fields or prefixed contact ids or component params
1838 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1839 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1840 (substr($values[0], 0, 13) == 'contribution_') ||
1841 (substr($values[0], 0, 6) == 'event_') ||
1842 (substr($values[0], 0, 12) == 'participant_') ||
1843 (substr($values[0], 0, 7) == 'member_') ||
1844 (substr($values[0], 0, 6) == 'grant_') ||
1845 (substr($values[0], 0, 7) == 'pledge_') ||
1846 (substr($values[0], 0, 5) == 'case_') ||
1847 (substr($values[0], 0, 10) == 'financial_') ||
1848 (substr($values[0], 0, 8) == 'payment_') ||
1849 (substr($values[0], 0, 11) == 'membership_')
1854 // skip for hook injected fields / params
1855 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1856 if (array_key_exists($values[0], $extFields)) {
1860 switch ($values[0]) {
1861 case 'deleted_contacts':
1862 $this->deletedContacts($values);
1865 case 'contact_sub_type':
1866 $this->contactSubType($values);
1871 $this->group($values);
1874 // case tag comes from find contacts
1876 $this->tagSearch($values);
1880 case 'contact_tags':
1881 $this->tag($values);
1886 case 'note_subject':
1887 $this->notes($values);
1891 $this->ufUser($values);
1895 case 'display_name':
1896 $this->sortName($values);
1900 case 'postal_greeting':
1901 case 'email_greeting':
1902 $this->greetings($values);
1907 $this->email($values, $isForcePrimaryOnly);
1910 case 'phone_numeric':
1911 $this->phone_numeric($values);
1914 case 'phone_phone_type_id':
1915 case 'phone_location_type_id':
1916 $this->phone_option_group($values);
1919 case 'street_address':
1920 $this->street_address($values);
1923 case 'street_number':
1924 $this->street_number($values);
1927 case 'sortByCharacter':
1928 $this->sortByCharacter($values);
1931 case 'location_type':
1932 $this->locationType($values);
1936 $this->county($values);
1939 case 'state_province':
1940 case 'state_province_id':
1941 case 'state_province_name':
1942 $this->stateProvince($values);
1947 $this->country($values, FALSE);
1951 case 'postal_code_low':
1952 case 'postal_code_high':
1953 $this->postalCode($values);
1956 case 'activity_date':
1957 case 'activity_date_low':
1958 case 'activity_date_high':
1959 case 'activity_date_time_low':
1960 case 'activity_date_time_high':
1961 case 'activity_role':
1962 case 'activity_status_id':
1963 case 'activity_status':
1964 case 'activity_priority':
1965 case 'activity_priority_id':
1966 case 'followup_parent_id':
1968 case 'source_contact_id':
1969 case 'activity_text':
1970 case 'activity_option':
1971 case 'test_activities':
1972 case 'activity_type_id':
1973 case 'activity_type':
1974 case 'activity_survey_id':
1975 case 'activity_tags':
1976 case 'activity_taglist':
1977 case 'activity_test':
1978 case 'activity_campaign_id':
1979 case 'activity_engagement_level':
1981 case 'activity_result':
1982 case 'source_contact':
1983 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1988 case 'birth_date_low':
1989 case 'birth_date_high':
1990 case 'deceased_date_low':
1991 case 'deceased_date_high':
1992 $this->demographics($values);
1995 case 'age_asof_date':
1996 // handled by demographics
1999 case 'log_date_low':
2000 case 'log_date_high':
2001 $this->modifiedDates($values);
2005 $this->changeLog($values);
2008 case 'do_not_phone':
2009 case 'do_not_email':
2012 case 'do_not_trade':
2014 $this->privacy($values);
2017 case 'privacy_options':
2018 $this->privacyOptions($values);
2021 case 'privacy_operator':
2022 case 'privacy_toggle':
2023 // these are handled by privacy options
2026 case 'preferred_communication_method':
2027 $this->preferredCommunication($values);
2030 case 'relation_type_id':
2031 case 'relationship_start_date_high':
2032 case 'relationship_start_date_low':
2033 case 'relationship_end_date_high':
2034 case 'relationship_end_date_low':
2035 case 'relation_active_period_date_high':
2036 case 'relation_active_period_date_low':
2037 case 'relation_target_name':
2038 case 'relation_status':
2039 case 'relation_description':
2040 case 'relation_date_low':
2041 case 'relation_date_high':
2042 $this->relationship($values);
2043 $this->_relationshipValuesAdded
= TRUE;
2046 case 'task_status_id':
2047 $this->task($values);
2051 // since this case is handled with the above
2054 case 'prox_distance':
2055 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
2058 case 'prox_street_address':
2060 case 'prox_postal_code':
2061 case 'prox_state_province_id':
2062 case 'prox_country_id':
2063 case 'prox_geo_code_1':
2064 case 'prox_geo_code_2':
2065 // handled by the proximity_distance clause
2069 $this->restWhere($values);
2075 * Given a list of conditions in params generate the required where clause.
2077 * @param bool $isForcePrimaryEmailOnly
2080 * @throws \CRM_Core_Exception
2082 public function whereClause($isForcePrimaryEmailOnly = NULL) {
2083 $this->_where
[0] = [];
2084 $this->_qill
[0] = [];
2086 $this->includeContactIds();
2087 if (!empty($this->_params
)) {
2088 foreach (array_keys($this->_params
) as $id) {
2089 if (empty($this->_params
[$id][0])) {
2092 // check for both id and contact_id
2093 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
2094 $this->_where
[0][] = self
::buildClause("contact_a.id", $this->_params
[$id][1], $this->_params
[$id][2]);
2095 $field = CRM_Utils_Array
::value('id', $this->_fields
);
2096 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(
2097 'CRM_Contact_BAO_Contact',
2099 $this->_params
[$id][2],
2100 $this->_params
[$id][1]
2102 $this->_qill
[0][] = ts("%1 %2 %3", [
2103 1 => $field['title'],
2109 $this->whereClauseSingle($this->_params
[$id], $isForcePrimaryEmailOnly);
2113 CRM_Core_Component
::alterQuery($this, 'where');
2115 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
2118 if ($this->_customQuery
) {
2119 // Added following if condition to avoid the wrong value display for 'my account' / any UF info.
2120 // Hope it wont affect the other part of civicrm.. if it does please remove it.
2121 if (!empty($this->_customQuery
->_where
)) {
2122 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
2125 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
2132 if (!empty($this->_where
)) {
2133 foreach ($this->_where
as $grouping => $values) {
2134 if ($grouping > 0 && !empty($values)) {
2135 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
2140 if (!empty($this->_where
[0])) {
2141 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
2143 if (!empty($clauses)) {
2144 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
2147 if ($validClauses > 1) {
2148 $this->_useDistinct
= TRUE;
2152 return implode(' AND ', $andClauses);
2156 * Generate where clause for any parameters not already handled.
2158 * @param array $values
2162 public function restWhere(&$values) {
2163 $name = CRM_Utils_Array
::value(0, $values);
2164 $op = CRM_Utils_Array
::value(1, $values);
2165 $value = CRM_Utils_Array
::value(2, $values);
2166 $grouping = CRM_Utils_Array
::value(3, $values);
2167 $wildcard = CRM_Utils_Array
::value(4, $values);
2169 if (isset($grouping) && empty($this->_where
[$grouping])) {
2170 $this->_where
[$grouping] = [];
2173 $multipleFields = ['url'];
2175 //check if the location type exists for fields
2177 $locType = explode('-', $name);
2179 if (!in_array($locType[0], $multipleFields)) {
2180 //add phone type if exists
2181 if (isset($locType[2]) && $locType[2]) {
2182 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
2186 $field = CRM_Utils_Array
::value($name, $this->_fields
);
2189 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
2192 // Strip any trailing _high & _low that might be appended.
2193 $realFieldName = str_replace(['_high', '_low'], '', $name);
2194 if (isset($this->_fields
[$realFieldName])) {
2195 $field = $this->_fields
[str_replace(['_high', '_low'], '', $realFieldName)];
2196 $this->dateQueryBuilder($values, $field['table_name'], $realFieldName, $field['name'], $field['title']);
2204 $locationType = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
2205 if (isset($locType[1]) && is_numeric($locType[1])) {
2206 $lType = $locationType[$locType[1]];
2209 $field['title'] .= " ($lType)";
2212 if (substr($name, 0, 14) === 'state_province') {
2213 if (isset($locType[1]) && is_numeric($locType[1])) {
2215 $aName = "{$lType}-address";
2216 $where = "`$aName`.state_province_id";
2219 $where = "civicrm_address.state_province_id";
2222 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value);
2223 $this->_tables
[$aName] = $this->_whereTables
[$aName] = 1;
2224 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
2225 $this->_qill
[$grouping][] = ts("%1 %2 %3", [1 => $field['title'], 2 => $qillop, 3 => $qillVal]);
2227 elseif (!empty($field['pseudoconstant'])) {
2228 $this->optionValueQuery(
2229 $name, $op, $value, $grouping,
2230 'CRM_Contact_DAO_Contact',
2236 if ($name == 'gender_id') {
2237 self
::$_openedPanes[ts('Demographics')] = TRUE;
2240 elseif (substr($name, 0, 7) === 'country' ||
substr($name, 0, 6) === 'county') {
2241 $name = (substr($name, 0, 7) === 'country') ?
"country_id" : "county_id";
2242 if (isset($locType[1]) && is_numeric($locType[1])) {
2244 $aName = "{$lType}-address";
2245 $where = "`$aName`.$name";
2248 $where = "civicrm_address.$name";
2251 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2252 $this->_tables
[$aName] = $this->_whereTables
[$aName] = 1;
2254 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
2255 $this->_qill
[$grouping][] = ts("%1 %2 %3", [1 => $field['title'], 2 => $qillop, 3 => $qillVal]);
2257 elseif ($name === 'world_region') {
2258 $this->optionValueQuery(
2259 $name, $op, $value, $grouping,
2267 elseif ($name === 'is_deceased') {
2268 $this->setQillAndWhere($name, $op, $value, $grouping, $field);
2269 self
::$_openedPanes[ts('Demographics')] = TRUE;
2271 elseif ($name === 'created_date' ||
$name === 'modified_date' ||
$name === 'deceased_date' ||
$name === 'birth_date') {
2272 $appendDateTime = TRUE;
2273 if ($name === 'deceased_date' ||
$name === 'birth_date') {
2274 $appendDateTime = FALSE;
2275 self
::$_openedPanes[ts('Demographics')] = TRUE;
2277 $this->dateQueryBuilder($values, 'contact_a', $name, $name, $field['title'], $appendDateTime);
2279 elseif ($name === 'contact_id') {
2280 if (is_int($value)) {
2281 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
2282 $this->_qill
[$grouping][] = "$field[title] $op $value";
2285 elseif ($name === 'name') {
2286 $value = CRM_Core_DAO
::escapeString($value);
2289 $value = self
::getWildCardedValue($wildcard, $op, $value);
2291 CRM_Core_Error
::deprecatedFunctionWarning('Untested code path');
2292 // @todo it's likely this code path is obsolete / never called. It is definitely not
2293 // passed through in our test suite.
2294 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, "'$value'");
2295 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2297 elseif ($name === 'current_employer') {
2300 $value = self
::getWildCardedValue($wildcard, $op, $value);
2302 $ceWhereClause = self
::buildClause("contact_a.organization_name", $op,
2305 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2306 $this->_where
[$grouping][] = $ceWhereClause;
2307 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2309 elseif ($name === 'email_greeting') {
2310 CRM_Core_Error
::deprecatedFunctionWarning('pass in email_greeting_id or email_greeting_display');
2311 $filterCondition = ['greeting_type' => 'email_greeting'];
2312 $this->optionValueQuery(
2313 $name, $op, $value, $grouping,
2314 CRM_Core_PseudoConstant
::greeting($filterCondition),
2316 ts('Email Greeting')
2319 elseif ($name === 'postal_greeting') {
2320 CRM_Core_Error
::deprecatedFunctionWarning('pass in postal_greeting_id or postal_greeting_display');
2321 $filterCondition = ['greeting_type' => 'postal_greeting'];
2322 $this->optionValueQuery(
2323 $name, $op, $value, $grouping,
2324 CRM_Core_PseudoConstant
::greeting($filterCondition),
2326 ts('Postal Greeting')
2329 elseif ($name === 'addressee') {
2330 CRM_Core_Error
::deprecatedFunctionWarning('pass in addressee_id or addressee_display');
2331 $filterCondition = ['greeting_type' => 'addressee'];
2332 $this->optionValueQuery(
2333 $name, $op, $value, $grouping,
2334 CRM_Core_PseudoConstant
::greeting($filterCondition),
2339 elseif (substr($name, 0, 4) === 'url-') {
2340 $tName = 'civicrm_website';
2341 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2342 $value = CRM_Core_DAO
::escapeString($value);
2345 $value = self
::getWildCardedValue($wildcard, $op, $value);
2348 $this->_where
[$grouping][] = $d = self
::buildClause('civicrm_website.url', $op, $value);
2349 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2351 elseif ($name === 'contact_is_deleted') {
2352 $this->setQillAndWhere('is_deleted', $op, $value, $grouping, $field);
2354 elseif (!empty($field['where'])) {
2356 if (!empty($field['type'])) {
2357 $type = CRM_Utils_Type
::typeToString($field['type']);
2360 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2362 if (isset($locType[1]) &&
2363 is_numeric($locType[1])
2367 //get the location name
2368 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2369 $fieldName = "`$tName`.$fldName";
2371 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2372 $this->_tables
[$tName] = $this->_whereTables
[$tName] = 1;
2376 if ($tableName == 'civicrm_contact') {
2377 $fieldName = "contact_a.{$fieldName}";
2380 $fieldName = $field['where'];
2384 list($qillop, $qillVal) = self
::buildQillForFieldValue(NULL, $field['title'], $value, $op);
2385 $this->_qill
[$grouping][] = ts("%1 %2 %3", [
2386 1 => $field['title'],
2388 3 => (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) ?
$qillVal : "'$qillVal'",
2391 if (is_array($value)) {
2392 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2393 // for api style operators for functions that hit this point without worrying about regression
2394 // (the previous comments indicated the condition for hitting this point were unknown
2395 // per CRM-14743 we are adding modified_date & created_date operator support
2396 $operations = array_keys($value);
2397 foreach ($operations as $operator) {
2398 if (!in_array($operator, CRM_Core_DAO
::acceptedSQLOperators())) {
2399 //Via Contact get api value is not in array(operator => array(values)) format ONLY for IN/NOT IN operators
2400 //so this condition will satisfy the search for now
2401 if (strpos($op, 'IN') !== FALSE) {
2402 $value = [$op => $value];
2404 // we don't know when this might happen
2406 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", [1 => $operator]));
2410 $this->_where
[$grouping][] = CRM_Core_DAO
::createSQLFilter($fieldName, $value, $type);
2415 $value = self
::getWildCardedValue($wildcard, $op, $value);
2418 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2422 if ($setTables && isset($field['where'])) {
2423 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2424 if (isset($tableName)) {
2425 $this->_tables
[$tableName] = 1;
2426 $this->_whereTables
[$tableName] = 1;
2438 public static function getLocationTableName(&$where, &$locType) {
2439 if (isset($locType[1]) && is_numeric($locType[1])) {
2440 list($tbName, $fldName) = explode(".", $where);
2442 //get the location name
2443 $locationType = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
2444 $specialFields = ['email', 'im', 'phone', 'openid', 'phone_ext'];
2445 if (in_array($locType[0], $specialFields)) {
2446 //hack to fix / special handing for phone_ext
2447 if ($locType[0] == 'phone_ext') {
2448 $locType[0] = 'phone';
2450 if (isset($locType[2]) && $locType[2]) {
2451 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2454 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2457 elseif (in_array($locType[0],
2462 'street_number_suffix',
2464 'supplemental_address_1',
2465 'supplemental_address_2',
2466 'supplemental_address_3',
2469 'postal_code_suffix',
2475 //fix for search by profile with address fields.
2476 $tName = "{$locationType[$locType[1]]}-address";
2478 elseif (in_array($locType[0],
2486 $tName = "{$locationType[$locType[1]]}-email";
2488 elseif ($locType[0] == 'provider_id') {
2489 $tName = "{$locationType[$locType[1]]}-im";
2491 elseif ($locType[0] == 'openid') {
2492 $tName = "{$locationType[$locType[1]]}-openid";
2495 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2497 $tName = str_replace(' ', '_', $tName);
2498 return [$tName, $fldName];
2500 CRM_Core_Error
::fatal();
2504 * Given a result dao, extract the values and return that array
2506 * @param CRM_Core_DAO $dao
2509 * values for this query
2511 public function store($dao) {
2514 foreach ($this->_element
as $key => $dontCare) {
2515 if (property_exists($dao, $key)) {
2516 if (strpos($key, '-') !== FALSE) {
2517 $values = explode('-', $key);
2518 $lastElement = array_pop($values);
2520 $cnt = count($values);
2522 foreach ($values as $v) {
2523 if (!array_key_exists($v, $current)) {
2526 //bad hack for im_provider
2527 if ($lastElement == 'provider_id') {
2528 if ($count < $cnt) {
2529 $current = &$current[$v];
2532 $lastElement = "{$v}_{$lastElement}";
2536 $current = &$current[$v];
2541 $current[$lastElement] = $dao->$key;
2544 $value[$key] = $dao->$key;
2552 * Getter for tables array.
2556 public function tables() {
2557 return $this->_tables
;
2561 * Sometimes used to create the from clause, but, not reliably, set
2562 * this AND set tables.
2564 * It's unclear the intent - there is a 'simpleFrom' clause which
2565 * takes whereTables into account & a fromClause which doesn't.
2567 * logic may have eroded?
2571 public function whereTables() {
2572 return $this->_whereTables
;
2576 * Generate the where clause (used in match contacts and permissions)
2578 * @param array $params
2579 * @param array $fields
2580 * @param array $tables
2581 * @param $whereTables
2582 * @param bool $strict
2586 public static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2587 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2591 $tables = array_merge($query->tables(), $tables);
2592 $whereTables = array_merge($query->whereTables(), $whereTables);
2594 return $query->_whereClause
;
2598 * Create the from clause.
2600 * @param array $tables
2601 * Tables that need to be included in this from clause. If null,
2602 * return mimimal from clause (i.e. civicrm_contact).
2603 * @param array $inner
2604 * Tables that should be inner-joined.
2605 * @param array $right
2606 * Tables that should be right-joined.
2607 * @param bool $primaryLocation
2608 * Search on primary location. See note below.
2610 * Determines search mode based on bitwise MODE_* constants.
2611 * @param string|NULL $apiEntity
2612 * Determines search mode based on entity by string.
2614 * The $primaryLocation flag only seems to be used when
2615 * locationType() has been called. This may be a search option
2616 * exposed, or perhaps it's a "search all details" approach which
2617 * predates decoupling of location types and primary fields?
2619 * @see https://issues.civicrm.org/jira/browse/CRM-19967
2624 public static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1, $apiEntity = NULL) {
2626 $from = ' FROM civicrm_contact contact_a';
2627 if (empty($tables)) {
2631 if (!empty($tables['civicrm_worldregion'])) {
2632 $tables = array_merge(['civicrm_country' => 1], $tables);
2635 if ((!empty($tables['civicrm_state_province']) ||
!empty($tables['civicrm_country']) ||
2636 CRM_Utils_Array
::value('civicrm_county', $tables)) && empty($tables['civicrm_address'])) {
2637 $tables = array_merge(['civicrm_address' => 1],
2642 // add group_contact and group table is subscription history is present
2643 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2644 $tables = array_merge([
2645 'civicrm_group' => 1,
2646 'civicrm_group_contact' => 1,
2652 // to handle table dependencies of components
2653 CRM_Core_Component
::tableNames($tables);
2654 // to handle table dependencies of hook injected tables
2655 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2657 //format the table list according to the weight
2658 $info = CRM_Core_TableHierarchy
::info();
2660 foreach ($tables as $key => $value) {
2662 if (strpos($key, '-') !== FALSE) {
2663 $keyArray = explode('-', $key);
2664 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2666 elseif (strpos($key, '_') !== FALSE) {
2667 $keyArray = explode('_', $key);
2668 if (is_numeric(array_pop($keyArray))) {
2669 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2672 $k = CRM_Utils_Array
::value($key, $info, 99);
2676 $k = CRM_Utils_Array
::value($key, $info, 99);
2678 $tempTable[$k . ".$key"] = $key;
2682 foreach ($tempTable as $key) {
2683 $newTables[$key] = $tables[$key];
2686 $tables = $newTables;
2688 foreach ($tables as $name => $value) {
2693 if (!empty($inner[$name])) {
2696 elseif (!empty($right[$name])) {
2704 // if there is already a join statement in value, use value itself
2705 if (strpos($value, 'JOIN')) {
2706 $from .= " $value ";
2709 $from .= " $side JOIN $name ON ( $value ) ";
2714 $from .= ' ' . trim(self
::getEntitySpecificJoins($name, $mode, $side, $primaryLocation)) . ' ';
2720 * Get join statements for the from clause depending on entity type
2722 * @param string $name
2724 * @param string $side
2725 * @param string $primaryLocation
2728 protected static function getEntitySpecificJoins($name, $mode, $side, $primaryLocation) {
2729 $limitToPrimaryClause = $primaryLocation ?
"AND {$name}.is_primary = 1" : '';
2731 case 'civicrm_address':
2732 //CRM-14263 further handling of address joins further down...
2733 return " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id {$limitToPrimaryClause} )";
2735 case 'civicrm_state_province':
2736 // This is encountered when doing an export after having applied a 'sort' - it pretty much implies primary
2737 // but that will have been implied-in by the calling function.
2738 // test cover in testContactIDQuery
2739 return " $side JOIN civicrm_state_province ON ( civicrm_address.state_province_id = civicrm_state_province.id )";
2741 case 'civicrm_country':
2742 // This is encountered when doing an export after having applied a 'sort' - it pretty much implies primary
2743 // but that will have been implied-in by the calling function.
2744 // test cover in testContactIDQuery
2745 return " $side JOIN civicrm_country ON ( civicrm_address.country_id = civicrm_country.id )";
2747 case 'civicrm_phone':
2748 return " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id {$limitToPrimaryClause}) ";
2750 case 'civicrm_email':
2751 return " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id {$limitToPrimaryClause})";
2754 return " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id {$limitToPrimaryClause}) ";
2757 $from = " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2758 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2759 $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)";
2762 case 'civicrm_openid':
2763 return " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id {$limitToPrimaryClause} )";
2765 case 'civicrm_worldregion':
2766 // We can be sure from the calling function that country will already be joined in.
2767 // we really don't need world_region - we could use a pseudoconstant for it.
2768 return " $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2770 case 'civicrm_location_type':
2771 return " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2773 case 'civicrm_group':
2774 return " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2776 case 'civicrm_group_contact':
2777 return " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2779 case 'civicrm_group_contact_cache':
2780 return " $side JOIN civicrm_group_contact_cache ON contact_a.id = civicrm_group_contact_cache.contact_id ";
2782 case 'civicrm_activity':
2783 case 'civicrm_activity_tag':
2784 case 'activity_type':
2785 case 'activity_status':
2787 case 'civicrm_activity_contact':
2788 case 'source_contact':
2789 case 'activity_priority':
2790 return CRM_Activity_BAO_Query
::from($name, $mode, $side);
2792 case 'civicrm_entity_tag':
2793 $from = " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact'";
2794 return "$from AND civicrm_entity_tag.entity_id = contact_a.id ) ";
2796 case 'civicrm_note':
2797 $from = " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact'";
2798 return "$from AND contact_a.id = civicrm_note.entity_id ) ";
2800 case 'civicrm_subscription_history':
2801 $from = " $side JOIN civicrm_subscription_history";
2802 $from .= " ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id";
2803 return "$from AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2805 case 'civicrm_relationship':
2806 if (self
::$_relType == 'reciprocal') {
2807 if (self
::$_relationshipTempTable) {
2808 // we have a temptable to join on
2809 $tbl = self
::$_relationshipTempTable;
2810 return " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2813 $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2814 $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)";
2818 elseif (self
::$_relType == 'b') {
2819 $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2820 return "$from $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2823 $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2824 return "$from $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2828 $from = " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2829 return "$from INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2832 return " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2834 case 'civicrm_grant':
2835 return CRM_Grant_BAO_Query
::from($name, $mode, $side);
2837 case 'civicrm_website':
2838 return " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2840 case 'civicrm_campaign':
2841 //Move to default case if not in either mode.
2842 if ($mode & CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
2843 return CRM_Contribute_BAO_Query
::from($name, $mode, $side);
2845 elseif ($mode & CRM_Contact_BAO_Query
::MODE_MAILING
) {
2846 return CRM_Mailing_BAO_Query
::from($name, $mode, $side);
2848 elseif ($mode & CRM_Contact_BAO_Query
::MODE_CAMPAIGN
) {
2849 return CRM_Campaign_BAO_Query
::from($name, $mode, $side);
2853 $locationTypeName = '';
2854 if (strpos($name, '-address') != 0) {
2855 $locationTypeName = 'address';
2857 elseif (strpos($name, '-phone') != 0) {
2858 $locationTypeName = 'phone';
2860 elseif (strpos($name, '-email') != 0) {
2861 $locationTypeName = 'email';
2863 elseif (strpos($name, '-im') != 0) {
2864 $locationTypeName = 'im';
2866 elseif (strpos($name, '-openid') != 0) {
2867 $locationTypeName = 'openid';
2870 if ($locationTypeName) {
2871 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2872 $parts = explode('-', $name);
2873 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
2874 foreach ($locationTypes as $locationTypeID => $locationType) {
2875 if ($parts[0] == str_replace(' ', '_', $locationType)) {
2876 $locationID = $locationTypeID;
2879 $from = " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2882 $from = CRM_Core_Component
::from($name, $mode, $side);
2884 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2891 * WHERE / QILL clause for deleted_contacts
2893 * @param array $values
2895 public function deletedContacts($values) {
2896 list($_, $_, $value, $grouping, $_) = $values;
2898 // *prepend* to the relevant grouping as this is quite an important factor
2899 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2904 * Where / qill clause for contact_type
2908 public function contactType(&$values) {
2909 list($name, $op, $value, $grouping, $wildcard) = $values;
2914 // account for search builder mapping multiple values
2915 if (!is_array($value)) {
2916 $values = self
::parseSearchBuilderString($value, 'String');
2917 if (is_array($values)) {
2918 $value = array_flip($values);
2922 if (is_array($value)) {
2923 foreach ($value as $k => $v) {
2928 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2929 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2932 if (!empty($subType)) {
2933 $subTypes[$subType] = 1;
2935 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2940 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2941 $contactType = $contactTypeANDSubType[0];
2942 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2943 if (!empty($subType)) {
2944 $subTypes[$subType] = 1;
2946 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2950 if (!empty($clause)) {
2952 if ($op == 'IN' ||
$op == 'NOT IN') {
2953 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2956 $type = array_pop($clause);
2957 $this->_where
[$grouping][] = self
::buildClause("contact_a.contact_type", $op, $contactType);
2960 $this->_qill
[$grouping][] = ts('Contact Type') . " $op " . implode(' ' . ts('or') . ' ', $quill);
2962 if (!empty($subTypes)) {
2963 $this->includeContactSubTypes($subTypes, $grouping);
2969 * Where / qill clause for contact_sub_type.
2971 * @param array $values
2973 public function contactSubType(&$values) {
2974 list($name, $op, $value, $grouping, $wildcard) = $values;
2975 $this->includeContactSubTypes($value, $grouping, $op);
2983 public function includeContactSubTypes($value, $grouping, $op = 'LIKE') {
2985 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2987 $value = $value[$op];
2991 $alias = "contact_a.contact_sub_type";
2992 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
2994 $op = str_replace('IN', 'LIKE', $op);
2995 $op = str_replace('=', 'LIKE', $op);
2996 $op = str_replace('!', 'NOT ', $op);
2998 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2999 $this->_where
[$grouping][] = self
::buildClause($alias, $op, $value, 'String');
3001 elseif (is_array($value)) {
3002 foreach ($value as $k => $v) {
3003 $clause[$k] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($v, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
3007 $clause[$value] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
3010 if (!empty($clause)) {
3011 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
3013 $this->_qill
[$grouping][] = ts('Contact Subtype %1 ', [1 => $qillOperators[$op]]) . implode(' ' . ts('or') . ' ', array_keys($clause));
3017 * Where / qill clause for groups.
3021 * @throws \CRM_Core_Exception
3023 public function group($values) {
3024 list($name, $op, $value, $grouping, $wildcard) = $values;
3026 // If the $value is in OK (operator as key) array format we need to extract the key as operator and value first
3027 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
3029 $value = $value[$op];
3031 // Translate EMPTY to NULL as EMPTY is cannot be used in it's intended meaning here
3032 // so has to be 'squashed into' NULL. (ie. group membership cannot be '').
3033 // even one group might equate to multiple when looking at children so IN is simpler.
3034 // @todo - also look at != casting but there are rows below to review.
3037 'NOT EMPTY' => 'NOT NULL',
3040 if (isset($opReplacements[$op])) {
3041 $op = $opReplacements[$op];
3044 if (strpos($op, 'NULL')) {
3048 if (is_array($value) && count($value) > 1) {
3049 if (strpos($op, 'IN') === FALSE && strpos($op, 'NULL') === FALSE) {
3050 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", [1 => $op]));
3052 $this->_useDistinct
= TRUE;
3055 if (isset($value)) {
3056 $value = CRM_Utils_Array
::value($op, $value, $value);
3059 if ($name == 'group_type') {
3060 $value = array_keys($this->getGroupsFromTypeCriteria($value));
3063 $regularGroupIDs = $smartGroupIDs = [];
3064 foreach ((array) $value as $id) {
3065 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
3066 $smartGroupIDs[] = (int) $id;
3069 $regularGroupIDs[] = (int) trim($id);
3072 $hasNonSmartGroups = count($regularGroupIDs);
3074 $isNotOp = ($op == 'NOT IN' ||
$op == '!=');
3076 $statusJoinClause = $this->getGroupStatusClause($grouping);
3077 // If we are searching for 'Removed' contacts then despite it being a smart group we only care about the group_contact table.
3078 $isGroupStatusSearch = (!empty($this->getSelectedGroupStatuses($grouping)) && $this->getSelectedGroupStatuses($grouping) !== ["'Added'"]);
3080 if ($hasNonSmartGroups ||
empty($value) ||
$isGroupStatusSearch) {
3081 // include child groups IDs if any
3082 $childGroupIds = (array) CRM_Contact_BAO_Group
::getChildGroupIds($regularGroupIDs);
3083 foreach ($childGroupIds as $key => $id) {
3084 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
3085 $smartGroupIDs[] = $id;
3086 unset($childGroupIds[$key]);
3089 if (count($childGroupIds)) {
3090 $regularGroupIDs = array_merge($regularGroupIDs, $childGroupIds);
3093 if (empty($regularGroupIDs)) {
3094 if ($isGroupStatusSearch) {
3095 $regularGroupIDs = $smartGroupIDs;
3097 // If it is still empty we want a filter that blocks all results.
3098 if (empty($regularGroupIDs)) {
3099 $regularGroupIDs = [0];
3103 $gcTable = "`civicrm_group_contact-" . uniqid() . "`";
3104 $joinClause = ["contact_a.id = {$gcTable}.contact_id"];
3106 // @todo consider just casting != to NOT IN & handling both together.
3109 if (!empty($regularGroupIDs)) {
3110 $groupIds = CRM_Utils_Type
::validate(
3111 implode(',', (array) $regularGroupIDs),
3112 'CommaSeparatedIntegers'
3115 $clause = "{$gcTable}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact cgc WHERE cgc.group_id = $groupIds )";
3118 $clause = self
::buildClause("{$gcTable}.group_id", $op, $regularGroupIDs);
3120 $groupClause[] = "( {$clause} )";
3122 if ($statusJoinClause) {
3123 $joinClause[] = "{$gcTable}.$statusJoinClause";
3125 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
3128 //CRM-19589: contact(s) removed from a Smart Group, resides in civicrm_group_contact table
3129 // If we are only searching for Removed or Pending contacts we don't need to resolve the smart group
3130 // as that info is in the group_contact table.
3131 if ((count($smartGroupIDs) ||
empty($value)) && !$isGroupStatusSearch) {
3132 $this->_groupUniqueKey
= uniqid();
3133 $this->_groupKeys
[] = $this->_groupUniqueKey
;
3134 $gccTableAlias = "civicrm_group_contact_cache_{$this->_groupUniqueKey}";
3135 $groupContactCacheClause = $this->addGroupContactCache($smartGroupIDs, $gccTableAlias, "contact_a", $op);
3136 if (!empty($groupContactCacheClause)) {
3138 $groupIds = implode(',', (array) $smartGroupIDs);
3139 $gcTable = "civicrm_group_contact_{$this->_groupUniqueKey}";
3140 $joinClause = ["contact_a.id = {$gcTable}.contact_id"];
3141 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
3142 if (strpos($op, 'IN') !== FALSE) {
3143 $groupClause[] = "{$gcTable}.group_id $op ( $groupIds ) AND {$gccTableAlias}.group_id IS NULL";
3146 $groupClause[] = "{$gcTable}.group_id $op $groupIds AND {$gccTableAlias}.group_id IS NULL";
3149 $groupClause[] = " ( {$groupContactCacheClause} ) ";
3153 $and = ($op == 'IS NULL') ?
' AND ' : ' OR ';
3154 if (!empty($groupClause)) {
3155 $this->_where
[$grouping][] = ' ( ' . implode($and, $groupClause) . ' ) ';
3158 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Group', 'id', $value, $op);
3159 $this->_qill
[$grouping][] = ts("Group(s) %1 %2", [1 => $qillop, 2 => $qillVal]);
3160 if (strpos($op, 'NULL') === FALSE) {
3161 $this->_qill
[$grouping][] = ts("Group Status %1", [1 => implode(' ' . ts('or') . ' ', $this->getSelectedGroupStatuses($grouping))]);
3165 public function getGroupCacheTableKeys() {
3166 return $this->_groupKeys
;
3170 * Function translates selection of group type into a list of groups.
3175 public function getGroupsFromTypeCriteria($value) {
3177 foreach ((array) $value as $groupTypeValue) {
3178 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
3179 $groupIds = ($groupIds +
$groupList);
3185 * Prime smart group cache for smart groups in the search, and join
3186 * civicrm_group_contact_cache table into the query.
3188 * @param array $groups IDs of groups specified in search criteria.
3189 * @param string $tableAlias Alias to use for civicrm_group_contact_cache table.
3190 * @param string $joinTable Table on which to join civicrm_group_contact_cache
3191 * @param string $op SQL comparison operator (NULL, IN, !=, IS NULL, etc.)
3192 * @param string $joinColumn Column in $joinTable on which to join civicrm_group_contact_cache.contact_id
3194 * @return string WHERE clause component for smart group criteria.
3196 public function addGroupContactCache($groups, $tableAlias, $joinTable = "contact_a", $op, $joinColumn = 'id') {
3197 $isNullOp = (strpos($op, 'NULL') !== FALSE);
3198 $groupsIds = $groups;
3200 $operator = ['=' => 'IN', '!=' => 'NOT IN'];
3201 if (!empty($operator[$op]) && is_array($groups)) {
3202 $op = $operator[$op];
3204 if (!$isNullOp && !$groups) {
3207 elseif (strpos($op, 'IN') !== FALSE) {
3208 $groups = [$op => $groups];
3210 elseif (is_array($groups) && count($groups)) {
3211 $groups = ['IN' => $groups];
3214 // Find all the groups that are part of a saved search.
3215 $smartGroupClause = self
::buildClause("id", $op, $groups, 'Int');
3217 SELECT id, cache_date, saved_search_id, children
3219 WHERE $smartGroupClause
3220 AND ( saved_search_id != 0
3221 OR saved_search_id IS NOT NULL
3222 OR children IS NOT NULL )
3225 $group = CRM_Core_DAO
::executeQuery($sql);
3227 while ($group->fetch()) {
3228 $this->_useDistinct
= TRUE;
3229 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
3230 CRM_Contact_BAO_GroupContactCache
::load($group);
3233 if ($group->N
== 0 && $op != 'NOT IN') {
3237 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache {$tableAlias} ON {$joinTable}.{$joinColumn} = {$tableAlias}.contact_id ";
3239 if ($op == 'NOT IN') {
3240 return "{$tableAlias}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact_cache cgcc WHERE cgcc.group_id IN ( " . implode(',', (array) $groupsIds) . " ) )";
3242 return self
::buildClause("{$tableAlias}.group_id", $op, $groups, 'Int');
3246 * Where / qill clause for cms users
3250 public function ufUser(&$values) {
3251 list($name, $op, $value, $grouping, $wildcard) = $values;
3254 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3256 $this->_qill
[$grouping][] = ts('CMS User');
3258 elseif ($value == 0) {
3259 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3261 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
3262 $this->_qill
[$grouping][] = ts('Not a CMS User');
3267 * All tag search specific.
3269 * @param array $values
3271 public function tagSearch(&$values) {
3272 list($name, $op, $value, $grouping, $wildcard) = $values;
3275 $value = "%{$value}%";
3276 $escapedValue = CRM_Utils_Type
::escape("%{$value}%", 'String');
3278 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3279 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3281 $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
3282 $tTable = "`civicrm_tag-" . uniqid() . "`";
3284 if ($useAllTagTypes[2]) {
3285 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3286 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
3287 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
3289 // search tag in cases
3290 $etCaseTable = "`civicrm_entity_case_tag-" . uniqid() . "`";
3291 $tCaseTable = "`civicrm_case_tag-" . uniqid() . "`";
3292 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3293 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3294 LEFT JOIN civicrm_case
3295 ON (civicrm_case_contact.case_id = civicrm_case.id
3296 AND civicrm_case.is_deleted = 0 )
3297 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
3298 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
3299 // search tag in activities
3300 $etActTable = "`civicrm_entity_act_tag-" . uniqid() . "`";
3301 $tActTable = "`civicrm_act_tag-" . uniqid() . "`";
3302 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
3303 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3305 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3306 = " LEFT JOIN civicrm_activity_contact
3307 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3308 LEFT JOIN civicrm_activity
3309 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3310 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3311 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
3312 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
3314 $this->_where
[$grouping][] = "({$tTable}.name $op '" . $escapedValue . "' OR {$tCaseTable}.name $op '" . $escapedValue . "' OR {$tActTable}.name $op '" . $escapedValue . "')";
3315 $this->_qill
[$grouping][] = ts('Tag %1 %2', [1 => $tagTypesText[2], 2 => $op]) . ' ' . $value;
3318 $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
3319 $tTable = "`civicrm_tag-" . uniqid() . "`";
3320 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
3321 {$etTable}.entity_table = 'civicrm_contact' )
3322 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
3324 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
3325 $this->_qill
[$grouping][] = ts('Tagged %1', [1 => $op]) . ' ' . $value;
3330 * Where / qill clause for tag.
3332 * @param array $values
3334 public function tag(&$values) {
3335 list($name, $op, $value, $grouping, $wildcard) = $values;
3337 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_EntityTag', "tag_id", $value, $op, ['onlyActive' => FALSE]);
3338 // API/Search Builder format array(operator => array(values))
3339 if (is_array($value)) {
3340 if (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
3342 $value = $value[$op];
3344 if (count($value) > 1) {
3345 $this->_useDistinct
= TRUE;
3349 // implode array, then remove all spaces
3350 $value = str_replace(' ', '', implode(',', (array) $value));
3351 if (!empty($value)) {
3352 $value = CRM_Utils_Type
::validate(
3354 'CommaSeparatedIntegers'
3358 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3359 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3361 $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
3363 if ($useAllTagTypes[2]) {
3364 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3365 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3367 // search tag in cases
3368 $etCaseTable = "`civicrm_entity_case_tag-" . uniqid() . "`";
3369 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
3370 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3372 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3373 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3374 LEFT JOIN civicrm_case
3375 ON (civicrm_case_contact.case_id = civicrm_case.id
3376 AND civicrm_case.is_deleted = 0 )
3377 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3378 // search tag in activities
3379 $etActTable = "`civicrm_entity_act_tag-" . uniqid() . "`";
3380 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3381 = " LEFT JOIN civicrm_activity_contact
3382 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3383 LEFT JOIN civicrm_activity
3384 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3385 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3386 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3389 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
3390 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3393 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (" . $value . ") OR {$etCaseTable}.tag_id $op (" . $value . ") OR {$etActTable}.tag_id $op (" . $value . "))";
3397 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3398 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3401 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
3402 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3403 $op = str_replace('EMPTY', 'NULL', $op);
3404 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
3406 // CRM-16941: for tag tried with != operator we don't show contact who don't have given $value AND also in other tag
3407 elseif ($op == '!=') {
3408 $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') . ")";
3410 elseif ($op == '=' ||
strstr($op, 'IN')) {
3411 $op = ($op == '=') ?
'IN' : $op;
3412 $this->_where
[$grouping][] = "{$etTable}.tag_id $op ( $value )";
3415 $this->_qill
[$grouping][] = ts('Tagged %1 %2', [1 => $qillop, 2 => $qillVal]);
3419 * Where/qill clause for notes
3421 * @param array $values
3423 public function notes(&$values) {
3424 list($name, $op, $value, $grouping, $wildcard) = $values;
3426 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3427 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
3428 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
3430 $this->_useDistinct
= TRUE;
3432 $this->_tables
['civicrm_note'] = $this->_whereTables
['civicrm_note']
3433 = " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3436 $value = CRM_Core_DAO
::escapeString($n);
3438 if (strpos($value, '%') === FALSE) {
3439 $value = "%$value%";
3443 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
3449 if ($noteOption %
2 == 0) {
3450 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
3451 $label = ts('Note: Body Only');
3453 if ($noteOption %
3 == 0) {
3454 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
3455 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
3457 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3458 list($qillOp, $qillVal) = self
::buildQillForFieldValue(NULL, $name, $n, $op);
3459 $this->_qill
[$grouping][] = ts("%1 %2 %3", [1 => $label, 2 => $qillOp, 3 => $qillVal]);
3463 * @param string $name
3469 public function nameNullOrEmptyOp($name, $op, $grouping) {
3473 $this->_where
[$grouping][] = "contact_a.$name $op";
3474 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3478 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3479 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3482 case 'IS NOT EMPTY':
3483 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3484 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3493 * Where / qill clause for sort_name
3495 * @param array $values
3497 public function sortName(&$values) {
3498 list($fieldName, $op, $value, $grouping, $wildcard) = $values;
3500 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3501 if ($this->nameNullOrEmptyOp($fieldName, $op, $grouping)) {
3505 $input = $value = is_array($value) ?
trim($value['LIKE']) : trim($value);
3507 if (!strlen($value)) {
3511 $config = CRM_Core_Config
::singleton();
3515 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3518 $firstChar = substr($value, 0, 1);
3519 $lastChar = substr($value, -1, 1);
3520 $quotes = ["'", '"'];
3521 // If string is quoted, strip quotes and otherwise don't alter it
3522 if ((strlen($value) > 2) && in_array($firstChar, $quotes) && in_array($lastChar, $quotes)) {
3523 $value = trim($value, implode('', $quotes));
3525 // Replace spaces with wildcards for a LIKE operation
3526 // UNLESS string contains a comma (this exception is a tiny bit questionable)
3527 elseif ($op == 'LIKE' && strpos($value, ',') === FALSE) {
3528 $value = str_replace(' ', '%', $value);
3530 $value = CRM_Core_DAO
::escapeString(trim($value));
3531 if (strlen($value)) {
3533 $value = "'" . self
::getWildCardedValue($wildcard, $op, $value) . "'";
3534 if ($fieldName == 'sort_name') {
3535 $wc = "contact_a.sort_name";
3538 $wc = "contact_a.display_name";
3540 $fieldsub[] = " ( $wc $op $value )";
3541 if ($config->includeNickNameInName
) {
3542 $wc = "contact_a.nick_name";
3543 $fieldsub[] = " ( $wc $op $value )";
3545 if ($config->includeEmailInName
) {
3546 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3548 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3551 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3553 $this->_where
[$grouping][] = $sub;
3554 if ($config->includeEmailInName
) {
3555 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3556 $this->_qill
[$grouping][] = ts('Name or Email') . " $op - '$input'";
3559 $this->_qill
[$grouping][] = ts('Name') . " $op - '$input'";
3564 * Where/qill clause for greeting fields.
3566 * @param array $values
3568 public function greetings(&$values) {
3569 list($name, $op, $value, $grouping, $wildcard) = $values;
3570 $name .= '_display';
3572 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
3573 $this->_qill
[$grouping][] = ts('Greeting %1 %2', [1 => $qillop, 2 => $qillVal]);
3574 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value, 'String');
3578 * Where / qill clause for email
3580 * @param array $values
3581 * @param string $isForcePrimaryOnly
3583 * @throws \CRM_Core_Exception
3585 protected function email(&$values, $isForcePrimaryOnly) {
3586 list($name, $op, $value, $grouping, $wildcard) = $values;
3587 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3589 // CRM-18147: for Contact's GET API, email fieldname got appended with its entity as in {$apiEntiy}_{$name}
3590 // so following code is use build whereClause for contact's primart email id
3591 if (!empty($isForcePrimaryOnly)) {
3592 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.is_primary', '=', 1, 'Integer');
3594 // @todo - this should come from the $this->_fields array
3595 $dbName = $name === 'email_id' ?
'id' : $name;
3597 if (is_array($value) ||
$name === 'email_id') {
3598 $this->_qill
[$grouping][] = $this->getQillForField($name, $value, $op);
3599 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.' . $dbName, $op, $value, 'String');
3603 // Is this ever hit now? Ideally ensure always an array & handle above.
3606 if (substr($n, 0, 1) == '"' &&
3607 substr($n, -1, 1) == '"'
3609 $n = substr($n, 1, -1);
3610 $value = CRM_Core_DAO
::escapeString($n);
3614 $value = self
::getWildCardedValue($wildcard, $op, $n);
3616 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3617 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3620 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3621 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3626 * Where / qill clause for phone number
3628 * @param array $values
3630 public function phone_numeric(&$values) {
3631 list($name, $op, $value, $grouping, $wildcard) = $values;
3632 // Strip non-numeric characters; allow wildcards
3633 $number = preg_replace('/[^\d%]/', '', $value);
3635 if (strpos($number, '%') === FALSE) {
3636 $number = "%$number%";
3639 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3640 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3641 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3646 * Where / qill clause for phone type/location
3648 * @param array $values
3650 public function phone_option_group($values) {
3651 list($name, $op, $value, $grouping, $wildcard) = $values;
3652 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3653 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3654 $optionName = $options[$value];
3655 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3656 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3657 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3661 * Where / qill clause for street_address.
3663 * @param array $values
3665 public function street_address(&$values) {
3666 list($name, $op, $value, $grouping) = $values;
3675 if (strpos($value, '%') === FALSE) {
3676 // only add wild card if not there
3677 $value = "%{$value}%";
3680 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, $value, 'String');
3681 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3684 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3685 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3688 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3692 * Where / qill clause for street_unit.
3694 * @param array $values
3696 public function street_number(&$values) {
3697 list($name, $op, $value, $grouping, $wildcard) = $values;
3705 if (strtolower($n) == 'odd') {
3706 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3707 $this->_qill
[$grouping][] = ts('Street Number is odd');
3709 elseif (strtolower($n) == 'even') {
3710 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3711 $this->_qill
[$grouping][] = ts('Street Number is even');
3715 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_number', $op, $value, 'String');
3716 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3719 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3723 * Where / qill clause for sorting by character.
3725 * @param array $values
3727 public function sortByCharacter(&$values) {
3728 list($name, $op, $value, $grouping, $wildcard) = $values;
3730 $name = trim($value);
3731 $cond = " contact_a.sort_name LIKE '" . CRM_Core_DAO
::escapeWildCardString($name) . "%'";
3732 $this->_where
[$grouping][] = $cond;
3733 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', [1 => $name]);
3737 * Where / qill clause for including contact ids.
3739 public function includeContactIDs() {
3740 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3745 foreach ($this->_params
as $id => $values) {
3746 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3747 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3750 CRM_Utils_Type
::validateAll($contactIds, 'Positive');
3751 if (!empty($contactIds)) {
3752 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3757 * Where / qill clause for postal code.
3759 * @param array $values
3761 public function postalCode(&$values) {
3762 // skip if the fields dont have anything to do with postal_code
3763 if (empty($this->_fields
['postal_code'])) {
3767 list($name, $op, $value, $grouping, $wildcard) = $values;
3769 // Handle numeric postal code range searches properly by casting the column as numeric
3770 if (is_numeric($value)) {
3771 $field = "IF (civicrm_address.postal_code REGEXP '^[0-9]{1,10}$', CAST(civicrm_address.postal_code AS UNSIGNED), 0)";
3772 $val = CRM_Utils_Type
::escape($value, 'Integer');
3775 $field = 'civicrm_address.postal_code';
3776 // Per CRM-17060 we might be looking at an 'IN' syntax so don't case arrays to string.
3777 if (!is_array($value)) {
3778 $val = CRM_Utils_Type
::escape($value, 'String');
3781 // Do we need to escape values here? I would expect buildClause does.
3786 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3788 if ($name == 'postal_code') {
3789 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3790 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3792 elseif ($name == 'postal_code_low') {
3793 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3794 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', [1 => $value]);
3796 elseif ($name == 'postal_code_high') {
3797 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3798 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', [1 => $value]);
3803 * Where / qill clause for location type.
3805 * @param array $values
3806 * @param null $status
3810 public function locationType(&$values, $status = NULL) {
3811 list($name, $op, $value, $grouping, $wildcard) = $values;
3813 if (is_array($value)) {
3814 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')';
3815 $this->_tables
['civicrm_address'] = 1;
3816 $this->_whereTables
['civicrm_address'] = 1;
3818 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3820 foreach ($value as $id) {
3821 $names[] = $locationType[$id];
3824 $this->_primaryLocation
= FALSE;
3827 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3830 return implode(' ' . ts('or') . ' ', $names);
3837 * @param bool $fromStateProvince
3839 * @return array|NULL
3841 public function country(&$values, $fromStateProvince = TRUE) {
3842 list($name, $op, $value, $grouping, $wildcard) = $values;
3844 if (!$fromStateProvince) {
3845 $stateValues = $this->getWhereValues('state_province', $grouping);
3846 if (!empty($stateValues)) {
3847 // return back to caller if there are state province values
3848 // since that handles this case
3853 $countryClause = $countryQill = NULL;
3854 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY']) ||
($values && !empty($value))) {
3855 $this->_tables
['civicrm_address'] = 1;
3856 $this->_whereTables
['civicrm_address'] = 1;
3858 $countryClause = self
::buildClause('civicrm_address.country_id', $op, $value, 'Positive');
3859 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, 'country_id', $value, $op);
3860 $countryQill = ts("%1 %2 %3", [1 => 'Country', 2 => $qillop, 3 => $qillVal]);
3862 if (!$fromStateProvince) {
3863 $this->_where
[$grouping][] = $countryClause;
3864 $this->_qill
[$grouping][] = $countryQill;
3868 if ($fromStateProvince) {
3869 if (!empty($countryClause)) {
3872 " ...AND... " . $countryQill,
3876 return [NULL, NULL];
3882 * Where / qill clause for county (if present).
3884 * @param array $values
3885 * @param null $status
3889 public function county(&$values, $status = NULL) {
3890 list($name, $op, $value, $grouping, $wildcard) = $values;
3892 if (!is_array($value)) {
3893 // force the county to be an array
3897 // check if the values are ids OR names of the counties
3898 $inputFormat = 'id';
3899 foreach ($value as $v) {
3900 if (!is_numeric($v)) {
3901 $inputFormat = 'name';
3909 elseif ($op == '!=') {
3913 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3914 $op = str_replace('EMPTY', 'NULL', $op);
3917 if (in_array($op, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
3918 $clause = "civicrm_address.county_id $op";
3920 elseif ($inputFormat == 'id') {
3921 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3923 $county = CRM_Core_PseudoConstant
::county();
3924 foreach ($value as $id) {
3925 $names[] = CRM_Utils_Array
::value($id, $county);
3930 $county = CRM_Core_PseudoConstant
::county();
3931 foreach ($value as $name) {
3932 $name = trim($name);
3933 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3935 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3938 $this->_tables
['civicrm_address'] = 1;
3939 $this->_whereTables
['civicrm_address'] = 1;
3941 $this->_where
[$grouping][] = $clause;
3943 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3946 return implode(' ' . ts('or') . ' ', $names);
3951 * Where / qill clause for state/province AND country (if present).
3953 * @param array $values
3954 * @param null $status
3958 public function stateProvince(&$values, $status = NULL) {
3959 list($name, $op, $value, $grouping, $wildcard) = $values;
3961 $stateClause = self
::buildClause('civicrm_address.state_province_id', $op, $value, 'Positive');
3962 $this->_tables
['civicrm_address'] = 1;
3963 $this->_whereTables
['civicrm_address'] = 1;
3965 $countryValues = $this->getWhereValues('country', $grouping);
3966 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3967 if ($countryClause) {
3968 $clause = "( $stateClause AND $countryClause )";
3971 $clause = $stateClause;
3974 $this->_where
[$grouping][] = $clause;
3975 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
3977 $this->_qill
[$grouping][] = ts("State/Province %1 %2 %3", [1 => $qillop, 2 => $qillVal, 3 => $countryQill]);
3980 return implode(' ' . ts('or') . ' ', $qillVal) . $countryQill;
3985 * Where / qill clause for change log.
3987 * @param array $values
3989 public function changeLog(&$values) {
3990 list($name, $op, $value, $grouping, $wildcard) = $values;
3992 $targetName = $this->getWhereValues('changed_by', $grouping);
3997 $name = trim($targetName[2]);
3998 $name = CRM_Core_DAO
::escapeString($name);
3999 $name = $targetName[4] ?
"%$name%" : $name;
4000 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
4001 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
4002 $fieldTitle = ts('Added By');
4003 foreach ($this->_params
as $params) {
4004 if ($params[0] == 'log_date') {
4005 if ($params[2] == 2) {
4006 $fieldTitle = ts('Modified By');
4011 list($qillop, $qillVal) = self
::buildQillForFieldValue(NULL, 'changed_by', $name, 'LIKE');
4012 $this->_qill
[$grouping][] = ts("%1 %2 '%3'", [
4022 public function modifiedDates($values) {
4023 $this->_useDistinct
= TRUE;
4025 // CRM-11281, default to added date if not set
4026 $fieldTitle = ts('Added Date');
4027 $fieldName = 'created_date';
4028 foreach (array_keys($this->_params
) as $id) {
4029 if ($this->_params
[$id][0] == 'log_date') {
4030 if ($this->_params
[$id][2] == 2) {
4031 $fieldTitle = ts('Modified Date');
4032 $fieldName = 'modified_date';
4037 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
4039 self
::$_openedPanes[ts('Change Log')] = TRUE;
4045 public function demographics(&$values) {
4046 list($name, $op, $value, $grouping, $wildcard) = $values;
4048 if (($name == 'age_low') ||
($name == 'age_high')) {
4049 $this->ageRangeQueryBuilder($values,
4050 'contact_a', 'age', 'birth_date', ts('Age')
4053 elseif (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
4055 $this->dateQueryBuilder($values,
4056 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
4059 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
4061 $this->dateQueryBuilder($values,
4062 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
4066 self
::$_openedPanes[ts('Demographics')] = TRUE;
4072 public function privacy(&$values) {
4073 list($name, $op, $value, $grouping) = $values;
4074 //fixed for profile search listing CRM-4633
4075 if (strpbrk($value, "[")) {
4076 $value = "'{$value}'";
4078 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
4081 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
4083 $field = CRM_Utils_Array
::value($name, $this->_fields
);
4084 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
4085 $title = $field ?
$field['title'] : $name;
4086 $this->_qill
[$grouping][] = "$title $op $value";
4092 public function privacyOptions($values) {
4093 list($name, $op, $value, $grouping, $wildcard) = $values;
4095 if (empty($value) ||
!is_array($value)) {
4099 // get the operator and toggle values
4100 $opValues = $this->getWhereValues('privacy_operator', $grouping);
4103 strtolower($opValues[2] == 'AND')
4105 // @todo this line is logially unreachable
4109 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
4111 if ($toggleValues &&
4112 $toggleValues[2] == 2
4119 foreach ($value as $dontCare => $pOption) {
4120 $clauses[] = " ( contact_a.{$pOption} = 1 ) ";
4121 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
4122 $title = $field ?
$field['title'] : $pOption;
4123 $qill[] = " $title = 1 ";
4126 $this->_where
[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )';
4127 $this->_qill
[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )';
4133 public function preferredCommunication(&$values) {
4134 list($name, $op, $value, $grouping, $wildcard) = $values;
4136 if (!is_array($value)) {
4137 $value = str_replace(['(', ')'], '', explode(",", $value));
4139 elseif (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
4141 $value = $value[$op];
4143 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Contact', $name, $value, $op);
4145 if (self
::caseImportant($op)) {
4146 $value = implode("[[:cntrl:]]|[[:cntrl:]]", (array) $value);
4147 $op = (strstr($op, '!') ||
strstr($op, 'NOT')) ?
'NOT RLIKE' : 'RLIKE';
4148 $value = "[[:cntrl:]]" . $value . "[[:cntrl:]]";
4151 $this->_where
[$grouping][] = self
::buildClause("contact_a.preferred_communication_method", $op, $value);
4152 $this->_qill
[$grouping][] = ts('Preferred Communication Method %1 %2', [1 => $qillop, 2 => $qillVal]);
4156 * Where / qill clause for relationship.
4158 * @param array $values
4160 public function relationship(&$values) {
4161 list($name, $op, $value, $grouping, $wildcard) = $values;
4162 if ($this->_relationshipValuesAdded
) {
4165 // also get values array for relation_target_name
4166 // for relationship search we always do wildcard
4167 $relationType = $this->getWhereValues('relation_type_id', $grouping);
4168 $description = $this->getWhereValues('relation_description', $grouping);
4169 $targetName = $this->getWhereValues('relation_target_name', $grouping);
4170 $relStatus = $this->getWhereValues('relation_status', $grouping);
4171 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
4173 $nameClause = $name = NULL;
4175 $name = trim($targetName[2]);
4176 if (substr($name, 0, 1) == '"' &&
4177 substr($name, -1, 1) == '"'
4179 $name = substr($name, 1, -1);
4180 $name = CRM_Core_DAO
::escapeString($name);
4181 $nameClause = "= '$name'";
4184 $name = CRM_Core_DAO
::escapeString($name);
4185 $nameClause = "LIKE '%{$name}%'";
4189 $relTypes = $relTypesIds = [];
4190 if (!empty($relationType)) {
4191 $relationType[2] = (array) $relationType[2];
4192 foreach ($relationType[2] as $relType) {
4193 $rel = explode('_', $relType);
4194 self
::$_relType = $rel[1];
4195 $params = ['id' => $rel[0]];
4197 $rTypeValue = CRM_Contact_BAO_RelationshipType
::retrieve($params, $typeValues);
4198 if (!empty($rTypeValue)) {
4199 if ($rTypeValue->name_a_b
== $rTypeValue->name_b_a
) {
4200 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4201 self
::$_relType = 'reciprocal';
4203 $relTypesIds[] = $rel[0];
4204 $relTypes[] = $relType;
4209 // if we are creating a temp table we build our own where for the relationship table
4210 $relationshipTempTable = NULL;
4211 if (self
::$_relType == 'reciprocal') {
4213 self
::$_relationshipTempTable = $relationshipTempTable = CRM_Core_DAO
::createTempTableName('civicrm_rel');
4215 $where[$grouping][] = " sort_name $nameClause ";
4217 $groupJoinTable = "civicrm_relationship";
4218 $groupJoinColumn = "contact_id_alt";
4221 $where = &$this->_where
;
4223 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4225 $groupJoinTable = "contact_b";
4226 $groupJoinColumn = "id";
4228 $allRelationshipType = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, NULL, TRUE);
4229 if ($nameClause ||
!$targetGroup) {
4230 if (!empty($relationType)) {
4232 foreach ($relTypes as $rel) {
4233 if (!empty($relQill)) {
4236 $relQill .= $allRelationshipType[$rel];
4238 $this->_qill
[$grouping][] = 'Relationship Type(s) ' . $relQill . " $name";
4241 $this->_qill
[$grouping][] = $name;
4245 //check to see if the target contact is in specified group
4247 //add contacts from static groups
4248 $this->_tables
['civicrm_relationship_group_contact'] = $this->_whereTables
['civicrm_relationship_group_contact']
4249 = " 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'";
4250 $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" .
4251 implode(",", $targetGroup[2]) . ") ) ";
4253 //add contacts from saved searches
4254 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", $groupJoinTable, $op, $groupJoinColumn);
4256 //set the group where clause
4258 $groupWhere[] = "( " . $ssWhere . " )";
4260 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4262 //Get the names of the target groups for the qill
4263 $groupNames = CRM_Core_PseudoConstant
::group();
4265 foreach ($targetGroup[2] as $groupId) {
4266 if (array_key_exists($groupId, $groupNames)) {
4267 $qillNames[] = $groupNames[$groupId];
4270 if (!empty($relationType)) {
4272 foreach ($relTypes as $rel) {
4273 if (!empty($relQill)) {
4276 $relQill .= CRM_Utils_Array
::value($rel, $allRelationshipType);
4278 $this->_qill
[$grouping][] = 'Relationship Type(s) ' . $relQill . " ( " . implode(", ", $qillNames) . " )";
4281 $this->_qill
[$grouping][] = implode(", ", $qillNames);
4286 if (!empty($description[2]) && trim($description[2])) {
4287 $this->_qill
[$grouping][] = ts('Relationship description - ' . $description[2]);
4288 $description = CRM_Core_DAO
::escapeString(trim($description[2]));
4289 $where[$grouping][] = "civicrm_relationship.description LIKE '%{$description}%'";
4292 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4293 $today = date('Ymd');
4294 //check for active, inactive and all relation status
4295 if ($relStatus[2] == 0) {
4296 $where[$grouping][] = "(
4297 civicrm_relationship.is_active = 1 AND
4298 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4299 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4301 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
4303 elseif ($relStatus[2] == 1) {
4304 $where[$grouping][] = "(
4305 civicrm_relationship.is_active = 0 OR
4306 civicrm_relationship.end_date < {$today} OR
4307 civicrm_relationship.start_date > {$today}
4309 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
4313 if (in_array(['deleted_contacts', '=', '1', '0', '0'], $this->_params
)) {
4316 $where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})";
4318 $this->addRelationshipPermissionClauses($grouping, $where);
4319 $this->addRelationshipDateClauses($grouping, $where);
4320 $this->addRelationshipActivePeriodClauses($grouping, $where);
4321 if (!empty($relTypes)) {
4322 $where[$grouping][] = 'civicrm_relationship.relationship_type_id IN (' . implode(',', $relTypesIds) . ')';
4324 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
4325 $this->_useDistinct
= TRUE;
4326 $this->_relationshipValuesAdded
= TRUE;
4327 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4329 if ($relationshipTempTable) {
4331 if (!empty($where[$grouping])) {
4332 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4333 $whereClause = str_replace('contact_b', 'c', $whereClause);
4336 CREATE TEMPORARY TABLE {$relationshipTempTable}
4338 `contact_id` int(10) unsigned NOT NULL DEFAULT '0',
4339 `contact_id_alt` int(10) unsigned NOT NULL DEFAULT '0',
4340 KEY `contact_id` (`contact_id`),
4341 KEY `contact_id_alt` (`contact_id_alt`)
4343 (SELECT contact_id_b as contact_id, contact_id_a as contact_id_alt, civicrm_relationship.id
4344 FROM civicrm_relationship
4345 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4348 (SELECT contact_id_a as contact_id, contact_id_b as contact_id_alt, civicrm_relationship.id
4349 FROM civicrm_relationship
4350 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4353 CRM_Core_DAO
::executeQuery($sql);
4358 * Add relationship permission criteria to where clause.
4360 * @param string $grouping
4361 * @param array $where Array to add "where" criteria to, in case you are generating a temp table.
4362 * Not the main query.
4364 public function addRelationshipPermissionClauses($grouping, &$where) {
4365 $relPermission = $this->getWhereValues('relation_permission', $grouping);
4366 if ($relPermission) {
4367 if (!is_array($relPermission[2])) {
4368 // this form value was scalar in previous versions of Civi
4369 $relPermission[2] = [$relPermission[2]];
4371 $where[$grouping][] = "(civicrm_relationship.is_permission_a_b IN (" . implode(",", $relPermission[2]) . "))";
4373 $allRelationshipPermissions = CRM_Contact_BAO_Relationship
::buildOptions('is_permission_a_b');
4375 $relPermNames = array_intersect_key($allRelationshipPermissions, array_flip($relPermission[2]));
4376 $this->_qill
[$grouping][] = ts('Permissioned Relationships') . ' - ' . implode(' OR ', $relPermNames);
4381 * Add start & end date criteria in
4382 * @param string $grouping
4383 * @param array $where
4384 * = array to add where clauses to, in case you are generating a temp table.
4385 * not the main query.
4387 public function addRelationshipDateClauses($grouping, &$where) {
4388 foreach (['start_date', 'end_date'] as $dateField) {
4389 $dateValueLow = $this->getWhereValues('relationship_' . $dateField . '_low', $grouping);
4390 $dateValueHigh = $this->getWhereValues('relationship_' . $dateField . '_high', $grouping);
4391 if (!empty($dateValueLow)) {
4392 $date = date('Ymd', strtotime($dateValueLow[2]));
4393 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4394 $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);
4396 if (!empty($dateValueHigh)) {
4397 $date = date('Ymd', strtotime($dateValueHigh[2]));
4398 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4399 $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);
4405 * Add start & end active period criteria in
4406 * @param string $grouping
4407 * @param array $where
4408 * = array to add where clauses to, in case you are generating a temp table.
4409 * not the main query.
4411 public function addRelationshipActivePeriodClauses($grouping, &$where) {
4413 $dateField = 'active_period_date';
4415 $dateValueLow = $this->getWhereValues('relation_active_period_date_low', $grouping);
4416 $dateValueHigh = $this->getWhereValues('relation_active_period_date_high', $grouping);
4417 $dateValueLowFormated = $dateValueHighFormated = NULL;
4418 if (!empty($dateValueLow) && !empty($dateValueHigh)) {
4419 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4420 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
4421 $this->_qill
[$grouping][] = (ts('Relationship was active between')) . " " . CRM_Utils_Date
::customFormat($dateValueLowFormated) . " and " . CRM_Utils_Date
::customFormat($dateValueHighFormated);
4423 elseif (!empty($dateValueLow)) {
4424 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4425 $this->_qill
[$grouping][] = (ts('Relationship was active after')) . " " . CRM_Utils_Date
::customFormat($dateValueLowFormated);
4427 elseif (!empty($dateValueHigh)) {
4428 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
4429 $this->_qill
[$grouping][] = (ts('Relationship was active before')) . " " . CRM_Utils_Date
::customFormat($dateValueHighFormated);
4432 if ($activePeriodClauses = self
::getRelationshipActivePeriodClauses($dateValueLowFormated, $dateValueHighFormated, TRUE)) {
4433 $where[$grouping][] = $activePeriodClauses;
4438 * Get start & end active period criteria
4440 public static function getRelationshipActivePeriodClauses($from, $to, $forceTableName) {
4441 $tableName = $forceTableName ?
'civicrm_relationship.' : '';
4442 if (!is_null($from) && !is_null($to)) {
4443 return '(((' . $tableName . 'start_date >= ' . $from . ' AND ' . $tableName . 'start_date <= ' . $to . ') OR
4444 (' . $tableName . 'end_date >= ' . $from . ' AND ' . $tableName . 'end_date <= ' . $to . ') OR
4445 (' . $tableName . 'start_date <= ' . $from . ' AND ' . $tableName . 'end_date >= ' . $to . ' )) OR
4446 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4447 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . ') OR
4448 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4450 elseif (!is_null($from)) {
4451 return '((' . $tableName . 'start_date >= ' . $from . ') OR
4452 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4453 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . '))';
4455 elseif (!is_null($to)) {
4456 return '((' . $tableName . 'start_date <= ' . $to . ') OR
4457 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4458 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4463 * Default set of return properties.
4468 * derault return properties
4470 public static function &defaultReturnProperties($mode = 1) {
4471 if (!isset(self
::$_defaultReturnProperties)) {
4472 self
::$_defaultReturnProperties = [];
4475 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4476 // add activity return properties
4477 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4478 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4481 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4484 if (empty(self
::$_defaultReturnProperties[$mode])) {
4485 self
::$_defaultReturnProperties[$mode] = [
4488 'legal_identifier' => 1,
4489 'external_identifier' => 1,
4490 'contact_type' => 1,
4491 'contact_sub_type' => 1,
4493 'display_name' => 1,
4494 'preferred_mail_format' => 1,
4501 'formal_title' => 1,
4502 'communication_style_id' => 1,
4505 'street_address' => 1,
4506 'supplemental_address_1' => 1,
4507 'supplemental_address_2' => 1,
4508 'supplemental_address_3' => 1,
4511 'postal_code_suffix' => 1,
4512 'state_province' => 1,
4514 'world_region' => 1,
4521 'household_name' => 1,
4522 'organization_name' => 1,
4523 'deceased_date' => 1,
4528 'current_employer' => 1,
4529 // FIXME: should we use defaultHierReturnProperties() for the below?
4530 'do_not_email' => 1,
4533 'do_not_phone' => 1,
4534 'do_not_trade' => 1,
4536 'contact_is_deleted' => 1,
4537 'preferred_communication_method' => 1,
4538 'preferred_language' => 1,
4542 return self
::$_defaultReturnProperties[$mode];
4546 * Get primary condition for a sql clause.
4550 * @return string|NULL
4552 public static function getPrimaryCondition($value) {
4553 if (is_numeric($value)) {
4554 $value = (int ) $value;
4555 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4561 * Wrapper for a simple search query.
4563 * @param array $params
4564 * @param array $returnProperties
4565 * @param bool $count
4569 public static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4570 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4571 list($select, $from, $where, $having) = $query->query();
4572 $groupBy = ($query->_useGroupBy
) ?
'GROUP BY contact_a.id' : '';
4574 $query = "$select $from $where $groupBy $having";
4579 * These are stub comments as this function needs more explanation - particularly in terms of how it
4580 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4582 * This function was originally written as a wrapper for the api query but is called from multiple places
4583 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4584 * but it is unclear as to whehter that is historical or there is a reason
4585 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4587 * @param array $params
4588 * @param array $returnProperties
4589 * @param null $fields
4590 * @param string $sort
4591 * @param int $offset
4592 * @param int $row_count
4593 * @param bool $smartGroupCache
4594 * ?? update smart group cache?.
4595 * @param bool $count
4596 * Return count obnly.
4597 * @param bool $skipPermissions
4598 * Should permissions be ignored or should the logged in user's permissions be applied.
4600 * This basically correlates to the component.
4601 * @param string $apiEntity
4602 * The api entity being called.
4603 * This sort-of duplicates $mode in a confusing way. Probably not by design.
4605 * @param bool|null $primaryLocationOnly
4608 public static function apiQuery(
4610 $returnProperties = NULL,
4615 $smartGroupCache = TRUE,
4617 $skipPermissions = TRUE,
4618 $mode = CRM_Contact_BAO_Query
::MODE_CONTACTS
,
4620 $primaryLocationOnly = NULL
4623 $query = new CRM_Contact_BAO_Query(
4624 $params, $returnProperties,
4625 NULL, TRUE, FALSE, $mode,
4627 TRUE, $smartGroupCache,
4629 $apiEntity, $primaryLocationOnly
4632 //this should add a check for view deleted if permissions are enabled
4633 if ($skipPermissions) {
4634 $query->_skipDeleteClause
= TRUE;
4636 $query->generatePermissionClause(FALSE, $count);
4638 // note : this modifies _fromClause and _simpleFromClause
4639 $query->includePseudoFieldsJoin($sort);
4641 list($select, $from, $where, $having) = $query->query($count);
4643 $options = $query->_options
;
4644 if (!empty($query->_permissionWhereClause
)) {
4645 if (empty($where)) {
4646 $where = "WHERE $query->_permissionWhereClause";
4649 $where = "$where AND $query->_permissionWhereClause";
4653 $sql = "$select $from $where $having";
4655 // add group by only when API action is not getcount
4656 // otherwise query fetches incorrect count
4657 if ($query->_useGroupBy
&& !$count) {
4658 $sql .= self
::getGroupByFromSelectColumns($query->_select
, 'contact_a.id');
4660 if (!empty($sort)) {
4661 $sort = CRM_Utils_Type
::escape($sort, 'String');
4662 $sql .= " ORDER BY $sort ";
4664 if ($row_count > 0 && $offset >= 0) {
4665 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4666 $row_count = CRM_Utils_Type
::escape($row_count, 'Int');
4667 $sql .= " LIMIT $offset, $row_count ";
4670 $dao = CRM_Core_DAO
::executeQuery($sql);
4672 // @todo derive this from the component class rather than hard-code two options.
4673 $entityIDField = ($mode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) ?
'contribution_id' : 'contact_id';
4676 while ($dao->fetch()) {
4678 $noRows = $dao->rowCount
;
4679 return [$noRows, NULL];
4681 $val = $query->store($dao);
4682 $convertedVals = $query->convertToPseudoNames($dao, TRUE, TRUE);
4684 if (!empty($convertedVals)) {
4685 $val = array_replace_recursive($val, $convertedVals);
4687 $values[$dao->$entityIDField] = $val;
4689 return [$values, $options];
4693 * Get the actual custom field name by stripping off the appended string.
4695 * The string could be _relative, _from, or _to
4697 * @todo use metadata rather than convention to do this.
4699 * @param string $parameterName
4700 * The name of the parameter submitted to the form.
4707 public static function getCustomFieldName($parameterName) {
4708 if (substr($parameterName, -5, 5) == '_from') {
4709 return substr($parameterName, 0, strpos($parameterName, '_from'));
4711 if (substr($parameterName, -9, 9) == '_relative') {
4712 return substr($parameterName, 0, strpos($parameterName, '_relative'));
4714 if (substr($parameterName, -3, 3) == '_to') {
4715 return substr($parameterName, 0, strpos($parameterName, '_to'));
4720 * Convert submitted values for relative custom fields to query object format.
4722 * The query will support the sqlOperator format so convert to that format.
4724 * @param array $formValues
4726 * @param array $params
4727 * Converted parameters for the query object.
4728 * @param string $values
4730 * @param string $fieldName
4731 * Submitted field name. (Matches form field not DB field.)
4733 protected static function convertCustomRelativeFields(&$formValues, &$params, $values, $fieldName) {
4734 if (empty($values)) {
4735 // e.g we might have relative set & from & to empty. The form flow is a bit funky &
4736 // this function gets called again after they fields have been converted which can get ugly.
4739 $customFieldName = self
::getCustomFieldName($fieldName);
4741 if (substr($fieldName, -9, 9) == '_relative') {
4742 list($from, $to) = CRM_Utils_Date
::getFromTo($values, NULL, NULL);
4745 if ($fieldName == $customFieldName . '_to' && CRM_Utils_Array
::value($customFieldName . '_from', $formValues)) {
4746 // Both to & from are set. We only need to acton one, choosing from.
4750 $from = CRM_Utils_Array
::value($customFieldName . '_from', $formValues, NULL);
4751 $to = CRM_Utils_Array
::value($customFieldName . '_to', $formValues, NULL);
4753 if (self
::isCustomDateField($customFieldName)) {
4754 list($from, $to) = CRM_Utils_Date
::getFromTo(NULL, $from, $to);
4760 $relativeFunction = ['BETWEEN' => [$from, $to]];
4763 $relativeFunction = ['>=' => $from];
4767 $relativeFunction = ['<=' => $to];
4779 * Are we dealing with custom field of type date.
4785 public static function isCustomDateField($fieldName) {
4786 if (($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($fieldName)) == FALSE) {
4789 if ('Date' == civicrm_api3('CustomField', 'getvalue', ['id' => $customFieldID, 'return' => 'data_type'])) {
4796 * Has this field already been reformatting to Query object syntax.
4798 * The form layer passed formValues to this function in preProcess & postProcess. Reason unknown. This seems
4799 * to come with associated double queries & is possibly damaging performance.
4801 * However, here we add a tested function to ensure convertFormValues identifies pre-processed fields & returns
4804 * @param mixed $values
4805 * Value in formValues for the field.
4809 public static function isAlreadyProcessedForQueryFormat($values) {
4810 if (!is_array($values)) {
4813 if (($operator = CRM_Utils_Array
::value(1, $values)) == FALSE) {
4816 return in_array($operator, CRM_Core_DAO
::acceptedSQLOperators());
4820 * If the state and country are passed remove state.
4822 * Country is implicit from the state, but including both results in
4823 * a poor query as there is no combined index on state AND country.
4827 * @param array $formValues
4829 public static function filterCountryFromValuesIfStateExists(&$formValues) {
4830 if (!empty($formValues['country']) && !empty($formValues['state_province'])) {
4831 // The use of array map sanitises the data by ensuring we are dealing with integers.
4832 $states = implode(', ', array_map('intval', $formValues['state_province']));
4833 $countryList = CRM_Core_DAO
::singleValueQuery(
4834 "SELECT GROUP_CONCAT(country_id) FROM civicrm_state_province WHERE id IN ($states)"
4836 if ($countryList == $formValues['country']) {
4837 unset($formValues['country']);
4843 * For some special cases, grouping by subset of select fields becomes mandatory.
4844 * Hence, full_group_by mode is handled by appending any_value
4845 * keyword to select fields not present in groupBy
4847 * @param array $selectClauses
4848 * @param array $groupBy - Columns already included in GROUP By clause.
4849 * @param string $aggregateFunction
4853 public static function appendAnyValueToSelect($selectClauses, $groupBy, $aggregateFunction = 'ANY_VALUE') {
4854 if (!CRM_Utils_SQL
::disableFullGroupByMode()) {
4855 $groupBy = array_map('trim', (array) $groupBy);
4856 $aggregateFunctions = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN|IF)[[:blank:]]*\(/i';
4857 foreach ($selectClauses as $key => &$val) {
4858 list($selectColumn, $alias) = array_pad(preg_split('/ as /i', $val), 2, NULL);
4859 // append ANY_VALUE() keyword
4860 if (!in_array($selectColumn, $groupBy) && preg_match($aggregateFunctions, trim($selectColumn)) !== 1) {
4861 $val = ($aggregateFunction == 'GROUP_CONCAT') ?
4862 str_replace($selectColumn, "$aggregateFunction(DISTINCT {$selectColumn})", $val) :
4863 str_replace($selectColumn, "$aggregateFunction({$selectColumn})", $val);
4868 return "SELECT " . implode(', ', $selectClauses) . " ";
4872 * For some special cases, where if non-aggregate ORDER BY columns are not present in GROUP BY
4873 * on full_group_by mode, then append the those missing columns to GROUP BY clause
4874 * keyword to select fields not present in groupBy
4876 * @param string $groupBy - GROUP BY clause where missing ORDER BY columns will be appended if not present
4877 * @param array $orderBys - ORDER BY sub-clauses
4880 public static function getGroupByFromOrderBy(&$groupBy, $orderBys) {
4881 if (!CRM_Utils_SQL
::disableFullGroupByMode()) {
4882 foreach ($orderBys as $orderBy) {
4883 // remove sort syntax from ORDER BY clauses if present
4884 $orderBy = str_ireplace([' DESC', ' ASC', '`'], '', $orderBy);
4885 // if ORDER BY column is not present in GROUP BY then append it to end
4886 if (preg_match('/(MAX|MIN)\(/i', trim($orderBy)) !== 1 && !strstr($groupBy, $orderBy)) {
4887 $groupBy .= ", {$orderBy}";
4894 * Include Select columns in groupBy clause.
4896 * @param array $selectClauses
4897 * @param array $groupBy - Columns already included in GROUP By clause.
4901 public static function getGroupByFromSelectColumns($selectClauses, $groupBy = NULL) {
4902 $groupBy = (array) $groupBy;
4903 $mysqlVersion = CRM_Core_DAO
::singleValueQuery('SELECT VERSION()');
4904 $sqlMode = CRM_Core_DAO
::singleValueQuery('SELECT @@sql_mode');
4906 //return if ONLY_FULL_GROUP_BY is not enabled.
4907 if (CRM_Utils_SQL
::supportsFullGroupBy() && !empty($sqlMode) && in_array('ONLY_FULL_GROUP_BY', explode(',', $sqlMode))) {
4908 $regexToExclude = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN|IF)[[:blank:]]*\(/i';
4909 foreach ($selectClauses as $key => $val) {
4910 $aliasArray = preg_split('/ as /i', $val);
4911 // if more than 1 alias we need to split by ','.
4912 if (count($aliasArray) > 2) {
4913 $aliasArray = preg_split('/,/', $val);
4914 foreach ($aliasArray as $key => $value) {
4915 $alias = current(preg_split('/ as /i', $value));
4916 if (!in_array($alias, $groupBy) && preg_match($regexToExclude, trim($alias)) !== 1) {
4917 $groupBy[] = $alias;
4922 list($selectColumn, $alias) = array_pad($aliasArray, 2, NULL);
4923 $dateRegex = '/^(DATE_FORMAT|DATE_ADD|CASE)/i';
4924 $tableName = current(explode('.', $selectColumn));
4925 $primaryKey = "{$tableName}.id";
4926 // exclude columns which are already included in groupBy and aggregate functions from select
4927 // CRM-18439 - Also exclude the columns which are functionally dependent on columns in $groupBy (MySQL 5.7+)
4928 if (!in_array($selectColumn, $groupBy) && !in_array($primaryKey, $groupBy) && preg_match($regexToExclude, trim($selectColumn)) !== 1) {
4929 if (!empty($alias) && preg_match($dateRegex, trim($selectColumn))) {
4930 $groupBy[] = $alias;
4933 $groupBy[] = $selectColumn;
4940 if (!empty($groupBy)) {
4941 return " GROUP BY " . implode(', ', $groupBy);
4947 * Create and query the db for an contact search.
4949 * @param int $offset
4950 * The offset for the query.
4951 * @param int $rowCount
4952 * The number of rows to return.
4953 * @param string|CRM_Utils_Sort $sort
4954 * The order by string.
4955 * @param bool $count
4956 * Is this a count only query ?.
4957 * @param bool $includeContactIds
4958 * Should we include contact ids?.
4959 * @param bool $sortByChar
4960 * If true returns the distinct array of first characters for search results.
4961 * @param bool $groupContacts
4962 * If true, return only the contact ids.
4963 * @param bool $returnQuery
4964 * Should we return the query as a string.
4965 * @param string $additionalWhereClause
4966 * If the caller wants to further restrict the search (used for components).
4967 * @param null $sortOrder
4968 * @param string $additionalFromClause
4969 * Should be clause with proper joins, effective to reduce where clause load.
4971 * @param bool $skipOrderAndLimit
4973 * @return CRM_Core_DAO
4975 public function searchQuery(
4976 $offset = 0, $rowCount = 0, $sort = NULL,
4977 $count = FALSE, $includeContactIds = FALSE,
4978 $sortByChar = FALSE, $groupContacts = FALSE,
4979 $returnQuery = FALSE,
4980 $additionalWhereClause = NULL, $sortOrder = NULL,
4981 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4984 $query = $this->getSearchSQL($offset, $rowCount, $sort, $count, $includeContactIds, $sortByChar, $groupContacts, $additionalWhereClause, $sortOrder, $additionalFromClause, $skipOrderAndLimit);
4990 return CRM_Core_DAO
::singleValueQuery($query);
4993 $dao = CRM_Core_DAO
::executeQuery($query);
4995 // We can always call this - it will only re-enable if it was originally enabled.
4996 CRM_Core_DAO
::reenableFullGroupByMode();
4998 if ($groupContacts) {
5000 while ($dao->fetch()) {
5003 return implode(',', $ids);
5010 * Create and query the db for the list of all first letters used by contacts
5012 * @return CRM_Core_DAO
5014 public function alphabetQuery() {
5015 $sqlParts = $this->getSearchSQLParts(NULL, NULL, NULL, FALSE, FALSE, TRUE);
5016 $query = "SELECT DISTINCT LEFT(contact_a.sort_name, 1) as sort_name
5018 {$sqlParts['where']}
5019 {$sqlParts['having']}
5021 ORDER BY sort_name asc";
5022 $dao = CRM_Core_DAO
::executeQuery($query);
5027 * Fetch a list of contacts for displaying a search results page
5029 * @param array $cids
5030 * List of contact IDs
5031 * @param bool $includeContactIds
5032 * @return CRM_Core_DAO
5034 public function getCachedContacts($cids, $includeContactIds) {
5035 CRM_Core_DAO
::disableFullGroupByMode();
5036 CRM_Utils_Type
::validateAll($cids, 'Positive');
5037 $this->_includeContactIds
= $includeContactIds;
5038 $onlyDeleted = in_array(['deleted_contacts', '=', '1', '0', '0'], $this->_params
);
5039 list($select, $from, $where) = $this->query(FALSE, FALSE, FALSE, $onlyDeleted);
5040 $select .= sprintf(", (%s) AS _wgt", $this->createSqlCase('contact_a.id', $cids));
5041 $where .= sprintf(' AND contact_a.id IN (%s)', implode(',', $cids));
5042 $order = 'ORDER BY _wgt';
5043 $groupBy = $this->_useGroupBy ?
' GROUP BY contact_a.id' : '';
5045 $query = "$select $from $where $groupBy $order $limit";
5047 $result = CRM_Core_DAO
::executeQuery($query);
5048 CRM_Core_DAO
::reenableFullGroupByMode();
5053 * Construct a SQL CASE expression.
5055 * @param string $idCol
5056 * The name of a column with ID's (eg 'contact_a.id').
5057 * @param array $cids
5058 * Array(int $weight => int $id).
5060 * CASE WHEN id=123 THEN 1 WHEN id=456 THEN 2 END
5062 private function createSqlCase($idCol, $cids) {
5064 foreach ($cids as $weight => $cid) {
5065 $buf .= " WHEN $idCol = $cid THEN $weight \n";
5072 * Populate $this->_permissionWhereClause with permission related clause and update other
5073 * query related properties.
5075 * Function calls ACL permission class and hooks to filter the query appropriately
5077 * Note that these 2 params were in the code when extracted from another function
5078 * and a second round extraction would be to make them properties of the class
5080 * @param bool $onlyDeleted
5081 * Only get deleted contacts.
5082 * @param bool $count
5083 * Return Count only.
5085 public function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
5086 if (!$this->_skipPermission
) {
5087 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
5088 CRM_Core_Permission
::VIEW
,
5090 $this->_whereTables
,
5093 $this->_skipDeleteClause
5096 // regenerate fromClause since permission might have added tables
5097 if ($this->_permissionWhereClause
) {
5098 //fix for row count in qill (in contribute/membership find)
5100 $this->_useDistinct
= TRUE;
5103 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
5104 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
5105 // note : this modifies _fromClause and _simpleFromClause
5106 $this->includePseudoFieldsJoin($this->_sort
);
5110 // add delete clause if needed even if we are skipping permission
5112 if (!$this->_skipDeleteClause
) {
5113 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
5114 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
5118 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
5127 public function setSkipPermission($val) {
5128 $this->_skipPermission
= $val;
5132 * @param null $context
5136 public function summaryContribution($context = NULL) {
5137 list($innerselect, $from, $where, $having) = $this->query(TRUE);
5138 if ($this->_permissionWhereClause
) {
5139 $where .= " AND " . $this->_permissionWhereClause
;
5141 if ($context == 'search') {
5142 $where .= " AND contact_a.is_deleted = 0 ";
5145 $this->appendFinancialTypeWhereAndFromToQueryStrings($where, $from);
5147 $summary = ['total' => []];
5148 $this->addBasicStatsToSummary($summary, $where, $from);
5150 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
5151 $this->addBasicSoftCreditStatsToStats($summary, $where, $from);
5154 $this->addBasicCancelStatsToSummary($summary, $where, $from);
5160 * Append financial ACL limits to the query from & where clauses, if applicable.
5162 * @param string $where
5163 * @param string $from
5165 public function appendFinancialTypeWhereAndFromToQueryStrings(&$where, &$from) {
5166 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
5169 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
5170 if (!empty($financialTypes)) {
5171 $where .= " AND civicrm_contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND li.id IS NULL";
5172 $from .= " LEFT JOIN civicrm_line_item li
5173 ON civicrm_contribution.id = li.contribution_id AND
5174 li.entity_table = 'civicrm_contribution' AND li.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ") ";
5177 $where .= " AND civicrm_contribution.financial_type_id IN (0)";
5182 * Getter for the qill object.
5186 public function qill() {
5187 return $this->_qill
;
5191 * Default set of return default hier return properties.
5195 public static function &defaultHierReturnProperties() {
5196 if (!isset(self
::$_defaultHierReturnProperties)) {
5197 self
::$_defaultHierReturnProperties = [
5200 'legal_identifier' => 1,
5201 'external_identifier' => 1,
5202 'contact_type' => 1,
5203 'contact_sub_type' => 1,
5205 'display_name' => 1,
5212 'formal_title' => 1,
5213 'communication_style_id' => 1,
5214 'email_greeting' => 1,
5215 'postal_greeting' => 1,
5219 'preferred_communication_method' => 1,
5220 'do_not_phone' => 1,
5221 'do_not_email' => 1,
5224 'do_not_trade' => 1,
5227 'location_type' => 1,
5228 'street_address' => 1,
5230 'state_province' => 1,
5232 'postal_code_suffix' => 1,
5235 'phone-Mobile' => 1,
5248 'location_type' => 1,
5249 'street_address' => 1,
5251 'state_province' => 1,
5253 'postal_code_suffix' => 1,
5256 'phone-Mobile' => 1,
5270 return self
::$_defaultHierReturnProperties;
5274 * Build query for a date field.
5276 * @param array $values
5277 * @param string $tableName
5278 * @param string $fieldName
5279 * @param string $dbFieldName
5280 * @param string $fieldTitle
5281 * @param bool $appendTimeStamp
5282 * @param string $dateFormat
5283 * @param string|null $highDBFieldName
5284 * Optional field name for when the 'high' part of the calculation uses a different field than the 'low' part.
5285 * This is an obscure situation & one we don't want to do more of but supporting them here is the only way for now.
5286 * Examples are event date & relationship active date -in both cases we are looking for things greater than the start
5287 * date & less than the end date.
5289 * @throws \CRM_Core_Exception
5291 public function dateQueryBuilder(
5292 $values, $tableName, $fieldName,
5293 $dbFieldName, $fieldTitle,
5294 $appendTimeStamp = TRUE,
5295 $dateFormat = 'YmdHis',
5296 $highDBFieldName = NULL
5298 // @todo - remove dateFormat - pretty sure it's never passed in...
5299 list($name, $op, $value, $grouping, $wildcard) = $values;
5301 if ($name == "{$fieldName}_low" ||
5302 $name == "{$fieldName}_high"
5304 if (isset($this->_rangeCache
[$fieldName]) ||
!$value) {
5307 $this->_rangeCache
[$fieldName] = 1;
5309 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
5311 if ($name == $fieldName . '_low') {
5313 $firstPhrase = ts('greater than or equal to');
5314 $firstDate = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5316 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5317 if (!empty($secondValues) && $secondValues[2]) {
5319 $secondPhrase = ts('less than or equal to');
5320 $secondValue = $secondValues[2];
5322 if ($appendTimeStamp && strlen($secondValue) == 10) {
5323 $secondValue .= ' 23:59:59';
5325 $secondDate = CRM_Utils_Date
::processDate($secondValue, NULL, FALSE, $dateFormat);
5328 elseif ($name == $fieldName . '_high') {
5330 $firstPhrase = ts('less than or equal to');
5332 if ($appendTimeStamp && strlen($value) == 10) {
5333 $value .= ' 23:59:59';
5335 $firstDate = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5337 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5338 if (!empty($secondValues) && $secondValues[2]) {
5340 $secondPhrase = ts('greater than or equal to');
5341 $secondValue = $secondValues[2];
5342 $secondDate = CRM_Utils_Date
::processDate($secondValue, NULL, FALSE, $dateFormat);
5346 if (!$appendTimeStamp) {
5347 $firstDate = substr($firstDate, 0, 8);
5349 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
5352 if (!$appendTimeStamp) {
5353 $secondDate = substr($secondDate, 0, 8);
5355 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
5358 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5360 $highDBFieldName = $highDBFieldName ??
$dbFieldName;
5361 $this->_where
[$grouping][] = "
5362 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5363 ( {$tableName}.{$highDBFieldName} $secondOP '$secondDate' )
5365 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
5368 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5369 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5373 if ($name == $fieldName) {
5374 //In Get API, for operators other then '=' the $value is in array(op => value) format
5375 if (is_array($value) && !empty($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
5377 $value = $value[$op];
5380 $date = $format = NULL;
5381 if (strstr($op, 'IN')) {
5383 foreach ($value as &$date) {
5384 $date = CRM_Utils_Date
::processDate($date, NULL, FALSE, $dateFormat);
5385 if (!$appendTimeStamp) {
5386 $date = substr($date, 0, 8);
5388 $format[] = CRM_Utils_Date
::customFormat($date);
5390 $date = "('" . implode("','", $value) . "')";
5391 $format = implode(', ', $format);
5393 elseif ($value && (!strstr($op, 'NULL') && !strstr($op, 'EMPTY'))) {
5394 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5395 if (!$appendTimeStamp) {
5396 $date = substr($date, 0, 8);
5398 $format = CRM_Utils_Date
::customFormat($date);
5403 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op $date";
5406 $this->_where
[$grouping][] = self
::buildClause("{$tableName}.{$dbFieldName}", $op);
5409 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5411 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
5412 $this->_qill
[$grouping][] = "$fieldTitle $op $format";
5418 * @param string $tableName
5419 * @param string $fieldName
5420 * @param string $dbFieldName
5421 * @param $fieldTitle
5422 * @param null $options
5424 public function numberRangeBuilder(
5426 $tableName, $fieldName,
5427 $dbFieldName, $fieldTitle,
5430 list($name, $op, $value, $grouping, $wildcard) = $values;
5432 if ($name == "{$fieldName}_low" ||
5433 $name == "{$fieldName}_high"
5435 if (isset($this->_rangeCache
[$fieldName])) {
5438 $this->_rangeCache
[$fieldName] = 1;
5440 $secondOP = $secondPhrase = $secondValue = NULL;
5442 if ($name == "{$fieldName}_low") {
5444 $firstPhrase = ts('greater than');
5446 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5447 if (!empty($secondValues)) {
5449 $secondPhrase = ts('less than');
5450 $secondValue = $secondValues[2];
5455 $firstPhrase = ts('less than');
5457 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5458 if (!empty($secondValues)) {
5460 $secondPhrase = ts('greater than');
5461 $secondValue = $secondValues[2];
5466 $this->_where
[$grouping][] = "
5467 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5468 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5470 $displayValue = $options ?
$options[$value] : $value;
5471 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5473 $this->_qill
[$grouping][]
5474 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5477 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5478 $displayValue = $options ?
$options[$value] : $value;
5479 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5481 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5486 if ($name == $fieldName) {
5490 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5492 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5493 $displayValue = $options ?
$options[$value] : $value;
5494 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5500 * @param string $tableName
5501 * @param string $fieldName
5502 * @param string $dbFieldName
5503 * @param $fieldTitle
5504 * @param null $options
5506 public function ageRangeQueryBuilder(
5508 $tableName, $fieldName,
5509 $dbFieldName, $fieldTitle,
5512 list($name, $op, $value, $grouping, $wildcard) = $values;
5514 $asofDateValues = $this->getWhereValues("{$fieldName}_asof_date", $grouping);
5515 // will be treated as current day
5517 if ($asofDateValues) {
5518 $asofDate = CRM_Utils_Date
::processDate($asofDateValues[2]);
5519 $asofDateFormat = CRM_Utils_Date
::customFormat(substr($asofDate, 0, 8));
5520 $fieldTitle .= ' ' . ts('as of') . ' ' . $asofDateFormat;
5523 if ($name == "{$fieldName}_low" ||
5524 $name == "{$fieldName}_high"
5526 if (isset($this->_rangeCache
[$fieldName])) {
5529 $this->_rangeCache
[$fieldName] = 1;
5531 $secondOP = $secondPhrase = $secondValue = NULL;
5533 if ($name == "{$fieldName}_low") {
5534 $firstPhrase = ts('greater than or equal to');
5535 // NB: age > X means date of birth < Y
5537 $firstDate = self
::calcDateFromAge($asofDate, $value, 'min');
5539 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5540 if (!empty($secondValues)) {
5542 $secondPhrase = ts('less than or equal to');
5543 $secondValue = $secondValues[2];
5544 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'max');
5549 $firstPhrase = ts('less than or equal to');
5550 $firstDate = self
::calcDateFromAge($asofDate, $value, 'max');
5552 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5553 if (!empty($secondValues)) {
5555 $secondPhrase = ts('greater than or equal to');
5556 $secondValue = $secondValues[2];
5557 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'min');
5562 $this->_where
[$grouping][] = "
5563 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5564 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5566 $displayValue = $options ?
$options[$value] : $value;
5567 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5569 $this->_qill
[$grouping][]
5570 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5573 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5574 $displayValue = $options ?
$options[$value] : $value;
5575 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5577 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5583 * Calculate date from age.
5585 * @param string $asofDate
5587 * @param string $type
5591 public static function calcDateFromAge($asofDate, $age, $type) {
5592 $date = new DateTime($asofDate);
5593 if ($type == "min") {
5594 // minimum age is $age: dob <= date - age "235959"
5595 $date->sub(new DateInterval("P" . $age . "Y"));
5596 return $date->format('Ymd') . "235959";
5599 // max age is $age: dob >= date - (age + 1y) + 1d "000000"
5600 $date->sub(new DateInterval("P" . ($age +
1) . "Y"))->add(new DateInterval("P1D"));
5601 return $date->format('Ymd') . "000000";
5606 * Given the field name, operator, value & its data type
5607 * builds the where Clause for the query
5608 * used for handling 'IS NULL'/'IS NOT NULL' operators
5610 * @param string $field
5614 * @param string $value
5616 * @param string $dataType
5617 * Data type of the field.
5620 * Where clause for the query.
5622 public static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5624 $clause = "$field $op";
5632 $clause = ($dataType == 'Date') ?
" $field IS NULL " : " (NULLIF($field, '') IS NULL) ";
5635 case 'IS NOT EMPTY':
5636 $clause = ($dataType == 'Date') ?
" $field IS NOT NULL " : " (NULLIF($field, '') IS NOT NULL) ";
5640 return " {$clause} BINARY '{$value}' ";
5644 // I feel like this would be escaped properly if passed through $queryString = CRM_Core_DAO::createSqlFilter.
5645 if (!empty($value) && (!is_array($value) ||
!array_key_exists($op, $value))) {
5646 $value = [$op => (array) $value];
5650 if (empty($dataType) ||
$dataType == 'Date') {
5651 $dataType = 'String';
5653 if (is_array($value)) {
5654 //this could have come from the api - as in the restWhere section we potentially use the api operator syntax which is becoming more
5655 // widely used and consistent across the codebase
5656 // adding this here won't accept the search functions which don't submit an array
5657 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, $value, $dataType)) != FALSE) {
5659 return $queryString;
5661 if (!empty($value[0]) && $op === 'BETWEEN') {
5662 CRM_Core_Error
::deprecatedFunctionWarning('Fix search input params');
5663 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, [$op => $value], $dataType)) != FALSE) {
5664 return $queryString;
5667 throw new CRM_Core_Exception(ts('Failed to interpret input for search'));
5670 $value = CRM_Utils_Type
::escape($value, $dataType);
5671 // if we don't have a dataType we should assume
5672 if ($dataType == 'String' ||
$dataType == 'Text') {
5673 $value = "'" . $value . "'";
5675 return "$clause $value";
5680 * @param bool $reset
5684 public function openedSearchPanes($reset = FALSE) {
5685 if (!$reset ||
empty($this->_whereTables
)) {
5686 return self
::$_openedPanes;
5689 // pane name to table mapper
5691 ts('Contributions') => 'civicrm_contribution',
5692 ts('Memberships') => 'civicrm_membership',
5693 ts('Events') => 'civicrm_participant',
5694 ts('Relationships') => 'civicrm_relationship',
5695 ts('Activities') => 'civicrm_activity',
5696 ts('Pledges') => 'civicrm_pledge',
5697 ts('Cases') => 'civicrm_case',
5698 ts('Grants') => 'civicrm_grant',
5699 ts('Address Fields') => 'civicrm_address',
5700 ts('Notes') => 'civicrm_note',
5701 ts('Change Log') => 'civicrm_log',
5702 ts('Mailings') => 'civicrm_mailing',
5704 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
5706 foreach (array_keys($this->_whereTables
) as $table) {
5707 if ($panName = array_search($table, $panesMapper)) {
5708 self
::$_openedPanes[$panName] = TRUE;
5712 return self
::$_openedPanes;
5718 public function setOperator($operator) {
5719 $validOperators = ['AND', 'OR'];
5720 if (!in_array($operator, $validOperators)) {
5723 $this->_operator
= $operator;
5729 public function getOperator() {
5730 return $this->_operator
;
5738 public function filterRelatedContacts(&$from, &$where, &$having) {
5739 if (!isset(Civi
::$statics[__CLASS__
]['related_contacts_filter'])) {
5740 Civi
::$statics[__CLASS__
]['related_contacts_filter'] = [];
5742 $_rTempCache =& Civi
::$statics[__CLASS__
]['related_contacts_filter'];
5743 // since there only can be one instance of this filter in every query
5744 // skip if filter has already applied
5745 foreach ($_rTempCache as $acache) {
5746 foreach ($acache['queries'] as $aqcache) {
5747 if (strpos($from, $aqcache['from']) !== FALSE) {
5753 $arg_sig = sha1("$from $where $having");
5754 if (isset($_rTempCache[$arg_sig])) {
5755 $cache = $_rTempCache[$arg_sig];
5758 // create temp table with contact ids
5760 $tableName = CRM_Utils_SQL_TempTable
::build()->createWithColumns('contact_id int primary key')->setMemory(TRUE)->getName();
5763 REPLACE INTO $tableName ( contact_id )
5769 CRM_Core_DAO
::executeQuery($sql);
5771 $cache = ['tableName' => $tableName, 'queries' => []];
5772 $_rTempCache[$arg_sig] = $cache;
5774 // upsert the query depending on relationship type
5775 if (isset($cache['queries'][$this->_displayRelationshipType
])) {
5776 $qcache = $cache['queries'][$this->_displayRelationshipType
];
5779 $tableName = $cache['tableName'];
5784 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5785 if (is_numeric($this->_displayRelationshipType
)) {
5786 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5788 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5789 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5791 $qcache['where'] = "
5792 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5793 AND displayRelType.is_active = 1
5797 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5798 if ($dirOne == 'a') {
5799 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5800 $qcache['from'] .= "
5801 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5802 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5806 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5807 $qcache['from'] .= "
5808 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5809 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5812 $qcache['where'] = "
5813 WHERE displayRelType.relationship_type_id = $relType
5814 AND displayRelType.is_active = 1
5817 $qcache['relTypeLabel'] = $relationshipTypeLabel;
5818 $_rTempCache[$arg_sig]['queries'][$this->_displayRelationshipType
] = $qcache;
5820 $qillMessage = ts('Contacts with a Relationship Type of: ');
5821 $iqill = $qillMessage . "'" . $qcache['relTypeLabel'] . "'";
5822 if (!is_array($this->_qill
[0]) ||
!in_array($iqill, $this->_qill
[0])) {
5823 $this->_qill
[0][] = $iqill;
5825 if (strpos($from, $qcache['from']) === FALSE) {
5826 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5827 // this happens when we have an event_type in the quert (CRM-7969)
5828 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5829 $from .= $qcache['from'];
5830 $where = $qcache['where'];
5831 if (!empty($this->_permissionWhereClause
)) {
5832 $where .= "AND $this->_permissionWhereClause";
5840 * See CRM-19811 for why this is database hurty without apparent benefit.
5846 public static function caseImportant($op) {
5847 return in_array($op, ['LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY']) ?
FALSE : TRUE;
5851 * @param $returnProperties
5856 public static function componentPresent(&$returnProperties, $prefix) {
5857 foreach ($returnProperties as $name => $dontCare) {
5858 if (substr($name, 0, strlen($prefix)) == $prefix) {
5866 * Builds the necessary structures for all fields that are similar to option value look-ups.
5868 * @param string $name
5869 * the name of the field.
5871 * the sql operator, this function should handle ALL SQL operators.
5872 * @param string $value
5873 * depends on the operator and who's calling the query builder.
5874 * @param int $grouping
5875 * the index where to place the where clause.
5876 * @param string $daoName
5878 * @param array $field
5879 * an array that contains various properties of the field identified by $name.
5880 * @param string $label
5881 * The label for this field element.
5882 * @param string $dataType
5883 * The data type for this element.
5884 * @param bool $useIDsOnly
5886 public function optionValueQuery(
5894 $dataType = 'String',
5905 'communication_style_id',
5909 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5910 if ($tableName == 'civicrm_contact') {
5911 $wc = "contact_a.$fieldName";
5914 // Special handling for on_hold, so that we actually use the 'where'
5915 // property in order to limit the query by the on_hold status of the email,
5916 // instead of using email.id which would be nonsensical.
5917 if ($field['name'] == 'on_hold') {
5918 $wc = "{$field['where']}";
5921 $wc = "$tableName.id";
5926 CRM_Core_Error
::deprecatedFunctionWarning('pass $ids to this method');
5927 $wc = "{$field['where']}";
5929 if (in_array($name, $pseudoFields)) {
5930 if (!in_array($name, ['gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'])) {
5931 $wc = "contact_a.{$name}_id";
5933 $dataType = 'Positive';
5934 $value = (!$value) ?
0 : $value;
5936 if ($name == "world_region") {
5937 $field['name'] = $name;
5940 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue($daoName, $field['name'], $value, $op);
5941 $this->_qill
[$grouping][] = ts("%1 %2 %3", [1 => $label, 2 => $qillop, 3 => $qillVal]);
5942 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5946 * Check and explode a user defined numeric string into an array
5947 * this was the protocol used by search builder in the old old days before we had
5948 * super nice js widgets to do the hard work
5950 * @param string $string
5951 * @param string $dataType
5952 * The dataType we should check for the values, default integer.
5954 * @return bool|array
5955 * false if string does not match the pattern
5956 * array of numeric values if string does match the pattern
5958 public static function parseSearchBuilderString($string, $dataType = 'Integer') {
5959 $string = trim($string);
5960 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5964 $string = substr($string, 1, -1);
5965 $values = explode(',', $string);
5966 if (empty($values)) {
5971 foreach ($values as $v) {
5972 if ($dataType == 'Integer' && !is_numeric($v)) {
5975 elseif ($dataType == 'String' && !is_string($v)) {
5978 $returnValues[] = trim($v);
5981 if (empty($returnValues)) {
5985 return $returnValues;
5989 * Convert the pseudo constants id's to their names
5991 * @param CRM_Core_DAO $dao
5992 * @param bool $return
5993 * @param bool $usedForAPI
5995 * @return array|NULL
5997 public function convertToPseudoNames(&$dao, $return = FALSE, $usedForAPI = FALSE) {
5998 if (empty($this->_pseudoConstantsSelect
)) {
6002 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
6003 if (!empty($this->_pseudoConstantsSelect
[$key]['sorting'])) {
6007 if (is_object($dao) && property_exists($dao, $value['idCol'])) {
6008 $val = $dao->{$value['idCol']};
6009 if ($key == 'groups') {
6010 $dao->groups
= $this->convertGroupIDStringToLabelString($dao, $val);
6014 if (CRM_Utils_System
::isNull($val)) {
6017 elseif (!empty($value['pseudoconstant'])) {
6018 // If pseudoconstant is set that is kind of defacto for 'we have a bit more info about this'
6019 // and we can use the metadata to figure it out.
6020 // ideally this bit of IF will absorb & replace all the rest in time as we move to
6021 // more metadata based choices.
6022 if (strpos($val, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
6023 $dbValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($val, CRM_Core_DAO
::VALUE_SEPARATOR
));
6024 foreach ($dbValues as $pseudoValue) {
6025 $convertedValues[] = CRM_Core_PseudoConstant
::getLabel($value['bao'], $value['idCol'], $pseudoValue);
6028 $dao->$key = ($usedForAPI) ?
$convertedValues : implode(', ', $convertedValues);
6029 $realFieldName = CRM_Utils_Array
::value('field_name', $this->_pseudoConstantsSelect
[$key]);
6030 if ($usedForAPI && $realFieldName) {
6031 // normally we would see 2 fields returned for pseudoConstants. An exception is
6032 // preferred_communication_method where there is no id-variant.
6033 // For the api we prioritise getting the real data returned.
6034 // over the resolved version
6035 $dao->$realFieldName = $dbValues;
6040 // This is basically the same as the default but since we have the bao we can use
6041 // a cached function.
6042 $dao->$key = CRM_Core_PseudoConstant
::getLabel($value['bao'], $value['idCol'], $val);
6045 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
6047 $idColumn = "{$key}_id";
6048 $dao->$idColumn = $val;
6050 if ($key == 'state_province_name') {
6051 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::stateProvince($val);
6054 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
6057 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
6058 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
6060 // @todo handle this in the section above for pseudoconstants.
6061 elseif (in_array($value['pseudoField'], ['participant_role_id', 'participant_role'])) {
6062 // @todo define bao on this & merge into the above condition.
6063 $viewValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $val);
6065 if ($value['pseudoField'] == 'participant_role') {
6066 $pseudoOptions = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'role_id');
6067 foreach ($viewValues as $k => $v) {
6068 $viewValues[$k] = $pseudoOptions[$v];
6071 $dao->$key = ($usedForAPI && count($viewValues) > 1) ?
$viewValues : implode(', ', $viewValues);
6074 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
6075 $dao->$key = $labels[$val];
6078 // return converted values in array format
6080 if (strpos($key, '-') !== FALSE) {
6081 $keyVal = explode('-', $key);
6082 $current = &$values;
6083 $lastElement = array_pop($keyVal);
6084 foreach ($keyVal as $v) {
6085 if (!array_key_exists($v, $current)) {
6088 $current = &$current[$v];
6090 $current[$lastElement] = $dao->$key;
6093 $values[$key] = $dao->$key;
6099 foreach ($this->legacyHackedFields
as $realField => $labelField) {
6100 // This is a temporary routine for handling these fields while
6101 // we figure out how to handled them based on metadata in
6102 /// export and search builder. CRM-19815, CRM-19830.
6103 if (isset($dao->$realField) && is_numeric($dao->$realField) && isset($dao->$labelField)) {
6104 $dao->$realField = $dao->$labelField;
6112 * Include pseudo fields LEFT JOIN.
6113 * @param string|array $sort can be a object or string
6115 * @return array|NULL
6117 public function includePseudoFieldsJoin($sort) {
6118 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
6121 $sort = is_string($sort) ?
$sort : $sort->orderBy();
6124 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
6125 if (!empty($value['table'])) {
6126 $regex = "/({$value['table']}\.|{$name})/";
6127 if (preg_match($regex, $sort)) {
6128 $this->_elemnt
[$value['element']] = 1;
6129 $this->_select
[$value['element']] = $value['select'];
6130 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
6131 $present[$value['table']] = $value['join'];
6135 $presentSimpleFrom = $present;
6137 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
6138 array_key_exists('civicrm_country', $presentSimpleFrom)
6140 unset($presentSimpleFrom['civicrm_country']);
6142 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
6143 array_key_exists('civicrm_country', $present)
6145 unset($present['civicrm_country']);
6148 $presentClause = $presentSimpleFromClause = NULL;
6149 if (!empty($present)) {
6150 $presentClause = implode(' ', $present);
6152 if (!empty($presentSimpleFrom)) {
6153 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
6156 $this->_fromClause
= $this->_fromClause
. $presentClause;
6157 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
6159 return [$presentClause, $presentSimpleFromClause];
6163 * Build qill for field.
6165 * Qill refers to the query detail visible on the UI.
6167 * @param string $daoName
6168 * @param string $fieldName
6169 * @param mixed $fieldValue
6171 * @param array $pseudoExtraParam
6173 * Type of the field per CRM_Utils_Type
6177 public static function buildQillForFieldValue(
6182 $pseudoExtraParam = [],
6183 $type = CRM_Utils_Type
::T_STRING
6185 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
6187 //API usually have fieldValue format as array(operator => array(values)),
6188 //so we need to separate operator out of fieldValue param
6189 if (is_array($fieldValue) && in_array(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
6190 $op = key($fieldValue);
6191 $fieldValue = $fieldValue[$op];
6194 // if Operator chosen is NULL/EMPTY then
6195 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
6196 return [CRM_Utils_Array
::value($op, $qillOperators, $op), ''];
6199 if ($fieldName == 'activity_type_id') {
6200 $pseudoOptions = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE);
6202 elseif ($fieldName == 'country_id') {
6203 $pseudoOptions = CRM_Core_PseudoConstant
::country();
6205 elseif ($fieldName == 'county_id') {
6206 $pseudoOptions = CRM_Core_PseudoConstant
::county();
6208 elseif ($fieldName == 'world_region') {
6209 $pseudoOptions = CRM_Core_PseudoConstant
::worldRegion();
6211 elseif ($daoName == 'CRM_Event_DAO_Event' && $fieldName == 'id') {
6212 $checkPermission = CRM_Utils_Array
::value('check_permission', $pseudoExtraParam, TRUE);
6213 $pseudoOptions = CRM_Event_BAO_Event
::getEvents(0, $fieldValue, TRUE, $checkPermission, TRUE);
6215 elseif ($fieldName == 'contribution_product_id') {
6216 $pseudoOptions = CRM_Contribute_PseudoConstant
::products();
6218 elseif ($daoName == 'CRM_Contact_DAO_Group' && $fieldName == 'id') {
6219 $pseudoOptions = CRM_Core_PseudoConstant
::group();
6221 elseif ($daoName == 'CRM_Batch_BAO_EntityBatch' && $fieldName == 'batch_id') {
6222 $pseudoOptions = CRM_Contribute_PseudoConstant
::batch();
6225 $pseudoOptions = CRM_Core_PseudoConstant
::get($daoName, $fieldName, $pseudoExtraParam);
6228 if (is_array($fieldValue)) {
6230 if (!empty($pseudoOptions)) {
6231 foreach ((array) $fieldValue as $val) {
6232 $qillString[] = CRM_Utils_Array
::value($val, $pseudoOptions, $val);
6234 $fieldValue = implode(', ', $qillString);
6237 if ($type == CRM_Utils_Type
::T_DATE
) {
6238 foreach ($fieldValue as $index => $value) {
6239 $fieldValue[$index] = CRM_Utils_Date
::customFormat($value);
6243 // @todo - this is a bit specific (one operator).
6244 // However it is covered by a unit test so can be altered later with
6246 if ($op == 'BETWEEN') {
6247 $separator = ' AND ';
6249 $fieldValue = implode($separator, $fieldValue);
6252 elseif (!empty($pseudoOptions) && array_key_exists($fieldValue, $pseudoOptions)) {
6253 $fieldValue = $pseudoOptions[$fieldValue];
6255 elseif ($type === CRM_Utils_Type
::T_DATE
) {
6256 $fieldValue = CRM_Utils_Date
::customFormat($fieldValue);
6259 return [CRM_Utils_Array
::value($op, $qillOperators, $op), $fieldValue];
6263 * Get the qill (search description for field) for the specified field.
6265 * @param string $daoName
6266 * @param string $name
6267 * @param string $value
6268 * @param string|array $op
6269 * @param string $label
6273 public static function getQillValue($daoName, string $name, $value, $op, string $label) {
6274 list($op, $value) = self
::buildQillForFieldValue($daoName, $name, $value, $op);
6275 return ts('%1 %2 %3', [1 => $label, 2 => $op, 3 => $value]);
6279 * Alter value to reflect wildcard settings.
6281 * The form will have tried to guess whether this is a good field to wildcard but there is
6282 * also a site-wide setting that specifies whether it is OK to append the wild card to the beginning
6283 * or only the end of the string
6285 * @param bool $wildcard
6286 * This is a bool made on an assessment 'elsewhere' on whether this is a good field to wildcard.
6288 * Generally '=' or 'LIKE'.
6289 * @param string $value
6290 * The search string.
6294 public static function getWildCardedValue($wildcard, $op, $value) {
6295 if ($wildcard && $op == 'LIKE') {
6296 if (CRM_Core_Config
::singleton()->includeWildCardInName
&& (substr($value, 0, 1) != '%')) {
6309 * Process special fields of Search Form in OK (Operator in Key) format
6311 * @param array $formValues
6312 * @param array $specialFields
6313 * Special params to be processed
6314 * @param array $changeNames
6315 * Array of fields whose name should be changed
6317 public static function processSpecialFormValue(&$formValues, $specialFields, $changeNames = []) {
6318 // Array of special fields whose value are considered only for NULL or EMPTY operators
6319 $nullableFields = ['contribution_batch_id'];
6321 foreach ($specialFields as $element) {
6322 $value = CRM_Utils_Array
::value($element, $formValues);
6324 if (is_array($value)) {
6325 if (in_array($element, array_keys($changeNames))) {
6326 unset($formValues[$element]);
6327 $element = $changeNames[$element];
6329 $formValues[$element] = ['IN' => $value];
6331 elseif (in_array($value, ['IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'])) {
6332 $formValues[$element] = [$value => 1];
6334 elseif (!in_array($element, $nullableFields)) {
6335 // if wildcard is already present return searchString as it is OR append and/or prepend with wildcard
6336 $isWilcard = strstr($value, '%') ?
FALSE : CRM_Core_Config
::singleton()->includeWildCardInName
;
6337 $formValues[$element] = ['LIKE' => self
::getWildCardedValue($isWilcard, 'LIKE', $value)];
6344 * Parse and assimilate the various sort options.
6346 * Side-effect: if sorting on a common column from a related table (`city`, `postal_code`,
6347 * `email`), the related table may be joined automatically.
6349 * At time of writing, this code is deeply flawed and should be rewritten. For the moment,
6350 * it's been extracted to a standalone function.
6352 * @param string|CRM_Utils_Sort $sort
6353 * The order by string.
6354 * @param null $sortOrder
6355 * Who knows? Hu knows. He who knows Hu knows who.
6358 * list(string $orderByClause, string $additionalFromClause).
6360 protected function prepareOrderBy($sort, $sortOrder) {
6364 if (CRM_Core_Config
::singleton()->includeOrderByClause ||
6365 isset($this->_distinctComponentClause
)
6368 if (is_string($sort)) {
6372 $orderBy = trim($sort->orderBy());
6374 // Deliberately remove the backticks again, as they mess up the evil
6375 // string munging below. This balanced by re-escaping before use.
6376 $orderBy = str_replace('`', '', $orderBy);
6378 if (!empty($orderBy)) {
6379 // this is special case while searching for
6380 // change log CRM-1718
6381 if (preg_match('/sort_name/i', $orderBy)) {
6382 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
6386 $orderBy .= " $sortOrder";
6389 // always add contact_a.id to the ORDER clause
6390 // so the order is deterministic
6391 if (strpos('contact_a.id', $orderBy) === FALSE) {
6392 $orderBy .= ", contact_a.id";
6397 $orderBy = " contact_a.sort_name ASC, contact_a.id";
6403 // Remove this here & add it at the end for simplicity.
6404 $order = trim($orderBy);
6405 $orderByArray = explode(',', $order);
6407 foreach ($orderByArray as $orderByClause) {
6408 $orderByClauseParts = explode(' ', trim($orderByClause));
6409 $field = $orderByClauseParts[0];
6410 $direction = isset($orderByClauseParts[1]) ?
$orderByClauseParts[1] : 'asc';
6411 $fieldSpec = $this->getMetadataForRealField($field);
6413 // This is a hacky add-in for primary address joins. Feel free to iterate as it is unit tested.
6414 // @todo much more cleanup on location handling in addHierarchical elements. Potentially
6415 // add keys to $this->fields to represent the actual keys for locations.
6416 if (empty($fieldSpec) && substr($field, 0, 2) === '1-') {
6417 $fieldSpec = $this->getMetadataForField(substr($field, 2));
6418 $this->addAddressTable('1-' . str_replace('civicrm_', '', $fieldSpec['table_name']), 'is_primary = 1');
6421 if ($this->_returnProperties
=== []) {
6422 if (!empty($fieldSpec['table_name']) && !isset($this->_tables
[$fieldSpec['table_name']])) {
6423 $this->_tables
[$fieldSpec['table_name']] = 1;
6424 $order = $fieldSpec['where'] . ' ' . $direction;
6428 $cfID = CRM_Core_BAO_CustomField
::getKeyID($field);
6429 // add to cfIDs array if not present
6430 if (!empty($cfID) && !array_key_exists($cfID, $this->_cfIDs
)) {
6431 $this->_cfIDs
[$cfID] = [];
6432 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
6433 $this->_customQuery
->query();
6434 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
6435 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
6438 // By replacing the join to the option value table with the mysql construct
6439 // ORDER BY field('contribution_status_id', 2,1,4)
6440 // we can remove a join. In the case of the option value join it is
6441 /// a join known to cause slow queries.
6442 // @todo cover other pseudoconstant types. Limited to option group ones & Foreign keys
6443 // matching an id+name parrern in the
6444 // first instance for scope reasons. They require slightly different handling as the column (label)
6445 // is not declared for them.
6446 // @todo so far only integer fields are being handled. If we add string fields we need to look at
6448 $pseudoConstantMetadata = CRM_Utils_Array
::value('pseudoconstant', $fieldSpec, FALSE);
6449 if (!empty($pseudoConstantMetadata)
6451 if (!empty($pseudoConstantMetadata['optionGroupName'])
6452 ||
$this->isPseudoFieldAnFK($fieldSpec)
6454 // dev/core#1305 @todo this is not the right thing to do but for now avoid fatal error
6455 if (empty($fieldSpec['bao'])) {
6458 $sortedOptions = $fieldSpec['bao']::buildOptions($fieldSpec['name'], NULL, [
6459 'orderColumn' => CRM_Utils_Array
::value('labelColumn', $pseudoConstantMetadata, 'label'),
6461 $fieldIDsInOrder = implode(',', array_keys($sortedOptions));
6462 // Pretty sure this validation ALSO happens in the order clause & this can't be reached but...
6463 // this might give some early warning.
6464 CRM_Utils_Type
::validate($fieldIDsInOrder, 'CommaSeparatedIntegers');
6465 $order = str_replace("$field", "field({$fieldSpec['name']},$fieldIDsInOrder)", $order);
6467 //CRM-12565 add "`" around $field if it is a pseudo constant
6468 // This appears to be for 'special' fields like locations with appended numbers or hyphens .. maybe.
6469 if (!empty($pseudoConstantMetadata['element']) && $pseudoConstantMetadata['element'] == $field) {
6470 $order = str_replace($field, "`{$field}`", $order);
6475 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6476 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6478 // The above code relies on crazy brittle string manipulation of a peculiarly-encoded ORDER BY
6479 // clause. But this magic helper which forgivingly reescapes ORDER BY.
6481 $order = CRM_Utils_Type
::escape($order, 'MysqlOrderBy');
6482 return ' ORDER BY ' . $order;
6487 * Convert a string of group IDs to a string of group labels.
6489 * The original string may include duplicates and groups the user does not have
6490 * permission to see.
6492 * @param CRM_Core_DAO $dao
6493 * @param string $val
6497 public function convertGroupIDStringToLabelString(&$dao, $val) {
6498 $groupIDs = explode(',', $val);
6499 // Note that groups that the user does not have permission to will be excluded (good).
6500 $groups = array_intersect_key(CRM_Core_PseudoConstant
::group(), array_flip($groupIDs));
6501 return implode(', ', $groups);
6506 * Set the qill and where properties for a field.
6508 * This function is intended as a short-term function to encourage refactoring
6509 * & re-use - but really we should just have less special-casing.
6511 * @param string $name
6513 * @param string|array $value
6514 * @param string $grouping
6515 * @param string $field
6517 public function setQillAndWhere($name, $op, $value, $grouping, $field) {
6518 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
6519 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
6520 $this->_qill
[$grouping][] = ts("%1 %2 %3", [
6521 1 => $field['title'],
6528 * Has the pseudoconstant of the field been requested.
6530 * For example if the field is payment_instrument_id then it
6531 * has been requested if either payment_instrument_id or payment_instrument
6532 * have been requested. Payment_instrument is the option groun name field value.
6534 * @param array $field
6535 * @param string $fieldName
6536 * The unique name of the field - ie. the one it will be aliased to in the query.
6540 private function pseudoConstantNameIsInReturnProperties($field, $fieldName = NULL) {
6541 $realField = $this->getMetadataForRealField($fieldName);
6542 if (!isset($realField['pseudoconstant'])) {
6545 $pseudoConstant = $realField['pseudoconstant'];
6546 if (empty($pseudoConstant['optionGroupName']) &&
6547 CRM_Utils_Array
::value('labelColumn', $pseudoConstant) !== 'name') {
6548 // We are increasing our pseudoconstant handling - but still very cautiously,
6549 // hence the check for labelColumn === name
6553 if (!empty($pseudoConstant['optionGroupName']) && CRM_Utils_Array
::value($pseudoConstant['optionGroupName'], $this->_returnProperties
)) {
6556 if (CRM_Utils_Array
::value($fieldName, $this->_returnProperties
)) {
6559 // Is this still required - the above goes off the unique name. Test with things like
6560 // communication_preferences & prefix_id.
6561 if (CRM_Utils_Array
::value($field['name'], $this->_returnProperties
)) {
6568 * Get Select Clause.
6572 public function getSelect() {
6573 $select = "SELECT ";
6574 if (isset($this->_distinctComponentClause
)) {
6575 $select .= "{$this->_distinctComponentClause}, ";
6577 $select .= implode(', ', $this->_select
);
6582 * Add basic statistics to the summary.
6584 * @param array $summary
6585 * @param string $where
6586 * @param string $from
6590 * @throws \CRM_Core_Exception
6592 protected function addBasicStatsToSummary(&$summary, $where, $from) {
6593 $summary['total']['count'] = 0;
6594 $summary['total']['amount'] = $summary['total']['avg'] = [];
6597 SELECT COUNT( conts.total_amount ) as total_count,
6598 SUM( conts.total_amount ) as total_amount,
6599 AVG( conts.total_amount ) as total_avg,
6600 conts.currency as currency
6602 SELECT civicrm_contribution.total_amount, COUNT(civicrm_contribution.total_amount) as civicrm_contribution_total_amount_count,
6603 civicrm_contribution.currency
6605 $where AND civicrm_contribution.contribution_status_id = 1
6606 GROUP BY civicrm_contribution.id
6610 $dao = CRM_Core_DAO
::executeQuery($query);
6612 while ($dao->fetch()) {
6613 $summary['total']['count'] +
= $dao->total_count
;
6614 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
6615 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
6618 if (!empty($summary['total']['amount'])) {
6619 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
6620 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
6623 $summary['total']['amount'] = $summary['total']['avg'] = 0;
6629 * Add basic soft credit statistics to summary array.
6631 * @param array $summary
6632 * @param string $where
6633 * @param string $from
6635 protected function addBasicSoftCreditStatsToStats(&$summary, $where, $from) {
6637 SELECT COUNT( conts.total_amount ) as total_count,
6638 SUM( conts.total_amount ) as total_amount,
6639 AVG( conts.total_amount ) as total_avg,
6640 conts.currency as currency
6642 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency
6644 $where AND civicrm_contribution.contribution_status_id = 1 AND civicrm_contribution_soft.id IS NOT NULL
6645 GROUP BY civicrm_contribution_soft.id
6649 $dao = CRM_Core_DAO
::executeQuery($query);
6650 $summary['soft_credit']['count'] = 0;
6651 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = [];
6652 while ($dao->fetch()) {
6653 $summary['soft_credit']['count'] +
= $dao->total_count
;
6654 $summary['soft_credit']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
6655 $summary['soft_credit']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
6657 if (!empty($summary['soft_credit']['amount'])) {
6658 $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
6659 $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
6662 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
6667 * Add basic stats about cancelled contributions to the summary.
6669 * @param array $summary
6670 * @param string $where
6671 * @param string $from
6673 protected function addBasicCancelStatsToSummary(&$summary, $where, $from) {
6675 SELECT COUNT( conts.total_amount ) as cancel_count,
6676 SUM( conts.total_amount ) as cancel_amount,
6677 AVG( conts.total_amount ) as cancel_avg,
6678 conts.currency as currency
6680 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency
6682 $where AND civicrm_contribution.cancel_date IS NOT NULL
6683 GROUP BY civicrm_contribution.id
6687 $dao = CRM_Core_DAO
::executeQuery($query);
6690 if ($dao->fetch()) {
6691 $summary['cancel']['count'] = $dao->cancel_count
;
6692 $summary['cancel']['amount'] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
6693 $summary['cancel']['avg'] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
6697 $summary['cancel']['count'] = 0;
6698 $summary['cancel']['amount'] = $summary['cancel']['avg'] = [];
6699 while ($dao->fetch()) {
6700 $summary['cancel']['count'] +
= $dao->cancel_count
;
6701 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
6702 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
6704 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
6705 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
6710 * Create the sql query for an contact search.
6712 * @param int $offset
6713 * The offset for the query.
6714 * @param int $rowCount
6715 * The number of rows to return.
6716 * @param string|CRM_Utils_Sort $sort
6717 * The order by string.
6718 * @param bool $count
6719 * Is this a count only query ?.
6720 * @param bool $includeContactIds
6721 * Should we include contact ids?.
6722 * @param bool $sortByChar
6723 * If true returns the distinct array of first characters for search results.
6724 * @param bool $groupContacts
6725 * If true, return only the contact ids.
6726 * @param string $additionalWhereClause
6727 * If the caller wants to further restrict the search (used for components).
6728 * @param null $sortOrder
6729 * @param string $additionalFromClause
6730 * Should be clause with proper joins, effective to reduce where clause load.
6732 * @param bool $skipOrderAndLimit
6735 public function getSearchSQL(
6736 $offset = 0, $rowCount = 0, $sort = NULL,
6737 $count = FALSE, $includeContactIds = FALSE,
6738 $sortByChar = FALSE, $groupContacts = FALSE,
6739 $additionalWhereClause = NULL, $sortOrder = NULL,
6740 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE) {
6742 $sqlParts = $this->getSearchSQLParts($offset, $rowCount, $sort, $count, $includeContactIds, $sortByChar, $groupContacts, $additionalWhereClause, $sortOrder, $additionalFromClause);
6745 CRM_Core_Error
::deprecatedFunctionWarning('sort by char is deprecated - use alphabetQuery method');
6746 $sqlParts['order_by'] = 'ORDER BY sort_name asc';
6749 if ($skipOrderAndLimit) {
6750 CRM_Core_Error
::deprecatedFunctionWarning('skipOrderAndLimit is deprected - call getSearchSQLParts & construct it in the calling function');
6751 $query = "{$sqlParts['select']} {$sqlParts['from']} {$sqlParts['where']} {$sqlParts['having']} {$sqlParts['group_by']}";
6754 $query = "{$sqlParts['select']} {$sqlParts['from']} {$sqlParts['where']} {$sqlParts['having']} {$sqlParts['group_by']} {$sqlParts['order_by']} {$sqlParts['limit']}";
6760 * Get the component parts of the search query as an array.
6762 * @param int $offset
6763 * The offset for the query.
6764 * @param int $rowCount
6765 * The number of rows to return.
6766 * @param string|CRM_Utils_Sort $sort
6767 * The order by string.
6768 * @param bool $count
6769 * Is this a count only query ?.
6770 * @param bool $includeContactIds
6771 * Should we include contact ids?.
6772 * @param bool $sortByChar
6773 * If true returns the distinct array of first characters for search results.
6774 * @param bool $groupContacts
6775 * If true, return only the contact ids.
6776 * @param string $additionalWhereClause
6777 * If the caller wants to further restrict the search (used for components).
6778 * @param null $sortOrder
6779 * @param string $additionalFromClause
6780 * Should be clause with proper joins, effective to reduce where clause load.
6784 public function getSearchSQLParts($offset = 0, $rowCount = 0, $sort = NULL,
6785 $count = FALSE, $includeContactIds = FALSE,
6786 $sortByChar = FALSE, $groupContacts = FALSE,
6787 $additionalWhereClause = NULL, $sortOrder = NULL,
6788 $additionalFromClause = NULL) {
6789 if ($includeContactIds) {
6790 $this->_includeContactIds
= TRUE;
6791 $this->_whereClause
= $this->whereClause();
6793 $onlyDeleted = in_array([
6801 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
6802 // and that contact happens to be deleted, set $onlyDeleted to true
6803 foreach ($this->_params
as $values) {
6804 $name = CRM_Utils_Array
::value(0, $values);
6805 $op = CRM_Utils_Array
::value(1, $values);
6806 $value = CRM_Utils_Array
::value(2, $values);
6807 if ($name == 'contact_id' and $op == '=') {
6808 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
6809 $onlyDeleted = TRUE;
6815 // building the query string
6816 $groupBy = $groupByCols = NULL;
6818 if (isset($this->_groupByComponentClause
)) {
6819 $groupByCols = preg_replace('/^GROUP BY /', '', trim($this->_groupByComponentClause
));
6820 $groupByCols = explode(', ', $groupByCols);
6822 elseif ($this->_useGroupBy
) {
6823 $groupByCols = ['contact_a.id'];
6826 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
6827 $groupByCols = ['civicrm_activity.id'];
6829 if (!empty($groupByCols)) {
6830 $groupBy = " GROUP BY " . implode(', ', $groupByCols);
6833 $order = $orderBy = '';
6836 $order = $this->prepareOrderBy($sort, $sortOrder);
6839 // Cases where we are disabling FGB (FULL_GROUP_BY_MODE):
6840 // 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
6841 // clause. This will impact the search query output.
6842 $disableFullGroupByMode = (!empty($groupBy) ||
$groupContacts);
6844 if ($disableFullGroupByMode) {
6845 CRM_Core_DAO
::disableFullGroupByMode();
6849 $this->_sort
= $sort;
6852 $this->includePseudoFieldsJoin($sort);
6854 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
6856 if ($additionalWhereClause) {
6857 $where = $where . ' AND ' . $additionalWhereClause;
6860 //additional from clause should be w/ proper joins.
6861 if ($additionalFromClause) {
6862 $from .= "\n" . $additionalFromClause;
6865 // if we are doing a transform, do it here
6866 // use the $from, $where and $having to get the contact ID
6867 if ($this->_displayRelationshipType
) {
6868 $this->filterRelatedContacts($from, $where, $having);
6870 $limit = (!$count && $rowCount) ?
" LIMIT " . CRM_Utils_Type
::escape($offset, 'Int') . ", " . CRM_Utils_Type
::escape($rowCount, 'Int') : '';
6873 'select' => $select,
6876 'order_by' => $order,
6877 'group_by' => $groupBy,
6878 'having' => $having,
6884 * Get the metadata for a given field.
6886 * @param string $fieldName
6890 protected function getMetadataForField($fieldName) {
6891 if ($fieldName === 'contact_a.id') {
6892 // This seems to be the only anomaly.
6895 $pseudoField = isset($this->_pseudoConstantsSelect
[$fieldName]) ?
$this->_pseudoConstantsSelect
[$fieldName] : [];
6896 $field = isset($this->_fields
[$fieldName]) ?
$this->_fields
[$fieldName] : $pseudoField;
6897 $field = array_merge($field, $pseudoField);
6898 if (!empty($field) && empty($field['name'])) {
6899 // standardising field formatting here - over time we can phase out variants.
6900 // all paths using this currently unit tested
6901 $field['name'] = CRM_Utils_Array
::value('field_name', $field, CRM_Utils_Array
::value('idCol', $field, $fieldName));
6907 * Get the metadata for a given field, returning the 'real field' if it is a pseudofield.
6909 * @param string $fieldName
6913 protected function getMetadataForRealField($fieldName) {
6914 $field = $this->getMetadataForField($fieldName);
6915 if (!empty($field['is_pseudofield_for'])) {
6916 $field = $this->getMetadataForField($field['is_pseudofield_for']);
6917 $field['pseudofield_name'] = $fieldName;
6919 elseif (!empty($field['pseudoconstant'])) {
6920 if (!empty($field['pseudoconstant']['optionGroupName'])) {
6921 $field['pseudofield_name'] = $field['pseudoconstant']['optionGroupName'];
6922 if (empty($field['table_name'])) {
6923 if (!empty($field['where'])) {
6924 $field['table_name'] = explode('.', $field['where'])[0];
6927 $field['table_name'] = 'civicrm_contact';
6936 * If we have a field that is better rendered via the pseudoconstant handled them here.
6938 * Rather than joining in the additional table we render the option value on output.
6940 * @todo - so far this applies to a narrow range of pseudocontants. We are adding them
6941 * carefully with test coverage but aim to extend.
6943 * @param string $name
6945 protected function addPseudoconstantFieldToSelect($name) {
6946 $field = $this->getMetadataForRealField($name);
6947 $realFieldName = $field['name'];
6948 $pseudoFieldName = CRM_Utils_Array
::value('pseudofield_name', $field);
6949 if ($pseudoFieldName) {
6950 // @todo - we don't really need to build this array now we have metadata more available with getMetadataForField fn.
6951 $this->_pseudoConstantsSelect
[$pseudoFieldName] = [
6952 'pseudoField' => $pseudoFieldName,
6953 'idCol' => $realFieldName,
6954 'field_name' => $field['name'],
6955 'bao' => $field['bao'],
6956 'pseudoconstant' => $field['pseudoconstant'],
6960 $this->_tables
[$field['table_name']] = 1;
6961 $this->_element
[$realFieldName] = 1;
6962 $this->_select
[$field['name']] = str_replace('civicrm_contact.', 'contact_a.', "{$field['where']} as `$realFieldName`");
6966 * Is this pseudofield a foreign key constraint.
6968 * We are trying to cautiously expand our pseudoconstant handling. This check allows us
6969 * to extend to a narrowly defined type (and then only if the pseudofield is in the fields
6970 * array which is done for contributions which are mostly handled as pseudoconstants.
6976 protected function isPseudoFieldAnFK($fieldSpec) {
6977 if (empty($fieldSpec['FKClassName'])
6978 || CRM_Utils_Array
::value('keyColumn', $fieldSpec['pseudoconstant']) !== 'id'
6979 || CRM_Utils_Array
::value('labelColumn', $fieldSpec['pseudoconstant']) !== 'name') {
6986 * Is the field a relative date field.
6988 * @param string $fieldName
6992 protected function isARelativeDateField($fieldName) {
6993 if (substr($fieldName, -9, 9) !== '_relative') {
6996 $realField = substr($fieldName, 0, strlen($fieldName) - 9);
6997 return isset($this->_fields
[$realField]);
7001 * Get the specifications for the field, if available.
7003 * @param string $fieldName
7004 * Fieldname as displayed on the form.
7008 public function getFieldSpec($fieldName) {
7009 if (isset($this->_fields
[$fieldName])) {
7010 return $this->_fields
[$fieldName];
7012 $lowFieldName = str_replace('_low', '', $fieldName);
7013 if (isset($this->_fields
[$lowFieldName])) {
7014 return array_merge($this->_fields
[$lowFieldName], ['field_name' => $lowFieldName]);
7016 $highFieldName = str_replace('_high', '', $fieldName);
7017 if (isset($this->_fields
[$highFieldName])) {
7018 return array_merge($this->_fields
[$highFieldName], ['field_name' => $highFieldName]);
7023 public function buildWhereForDate() {
7028 * Is the field a relative date field.
7030 * @param string $fieldName
7034 protected function isADateRangeField($fieldName) {
7035 if (substr($fieldName, -4, 4) !== '_low' && substr($fieldName, -5, 5) !== '_high') {
7038 return !empty($this->getFieldSpec($fieldName));
7044 protected function buildRelativeDateQuery(&$values) {
7045 $value = CRM_Utils_Array
::value(2, $values);
7046 if (empty($value)) {
7049 $fieldName = substr($values[0], 0, strlen($values[0]) - 9);
7050 $fieldSpec = $this->_fields
[$fieldName];
7051 $tableName = $fieldSpec['table_name'];
7052 $filters = CRM_Core_OptionGroup
::values('relative_date_filters');
7053 $grouping = CRM_Utils_Array
::value(3, $values);
7054 // If the table value is already set for a custom field it will be more nuanced than just '1'.
7055 $this->_tables
[$tableName] = $this->_tables
[$tableName] ??
1;
7056 $this->_whereTables
[$tableName] = $this->_whereTables
[$tableName] ??
1;
7058 $dates = CRM_Utils_Date
::getFromTo($value, NULL, NULL);
7059 // Where end would be populated only if we are handling one of the weird ones with different from & to fields.
7060 $secondWhere = $fieldSpec['where_end'] ??
$fieldSpec['where'];
7061 if (empty($dates[0])) {
7062 // ie. no start date we only have end date
7063 $this->_where
[$grouping][] = $secondWhere . " <= '{$dates[1]}'";
7065 $this->_qill
[$grouping][] = ts('%1 is ', [$fieldSpec['title']]) . $filters[$value] . ' (' . ts("to %1", [
7066 CRM_Utils_Date
::customFormat($dates[1]),
7069 elseif (empty($dates[1])) {
7071 // ie. no end date we only have start date
7072 $this->_where
[$grouping][] = $fieldSpec['where'] . " >= '{$dates[1]}'";
7074 $this->_qill
[$grouping][] = ts('%1 is ', [$fieldSpec['title']]) . $filters[$value] . ' (' . ts("from %1", [
7075 CRM_Utils_Date
::customFormat($dates[0]),
7079 // we have start and end dates.
7080 $where = $fieldSpec['where'];
7081 if ($fieldSpec['table_name'] === 'civicrm_contact') {
7082 // Special handling for contact table as it has a known alias in advanced search.
7083 $where = str_replace('civicrm_contact.', 'contact_a.', $where);
7085 if ($secondWhere !== $fieldSpec['where']) {
7086 $this->_where
[$grouping][] = $fieldSpec['where'] . ">= '{$dates[0]}' AND $secondWhere <='{$dates[1]}'";
7089 $this->_where
[$grouping][] = $where . " BETWEEN '{$dates[0]}' AND '{$dates[1]}'";
7092 $this->_qill
[$grouping][] = ts('%1 is ', [$fieldSpec['title']]) . $filters[$value] . ' (' . ts("between %1 and %2", [
7093 CRM_Utils_Date
::customFormat($dates[0]),
7094 CRM_Utils_Date
::customFormat($dates[1]),
7100 * Build the query for a date field if it is a _high or _low field.
7105 * @throws \CRM_Core_Exception
7107 public function buildDateRangeQuery($values) {
7108 if ($this->isADateRangeField($values[0])) {
7109 $fieldSpec = $this->getFieldSpec($values[0]);
7110 $title = empty($fieldSpec['unique_title']) ?
$fieldSpec['title'] : $fieldSpec['unique_title'];
7111 $this->dateQueryBuilder($values, $fieldSpec['table_name'], $fieldSpec['field_name'], $fieldSpec['name'], $title);
7118 * Add the address table into the query.
7120 * @param string $tableKey
7121 * @param string $joinCondition
7127 protected function addAddressTable($tableKey, $joinCondition) {
7128 $tName = "$tableKey-address";
7129 $aName = "`$tableKey-address`";
7130 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
7131 $this->_element
["{$tName}_id"] = 1;
7132 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$joinCondition)";
7133 $this->_tables
[$tName] = $addressJoin;
7142 * Get the clause for group status.
7144 * @param int $grouping
7148 protected function getGroupStatusClause($grouping) {
7149 $statuses = $this->getSelectedGroupStatuses($grouping);
7150 return "status IN (" . implode(', ', $statuses) . ")";
7154 * Get an array of the statuses that have been selected.
7156 * @param string $grouping
7160 protected function getSelectedGroupStatuses($grouping) {
7162 $gcsValues = $this->getWhereValues('group_contact_status', $grouping);
7164 is_array($gcsValues[2])
7166 foreach ($gcsValues[2] as $k => $v) {
7168 $statuses[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
7173 $statuses[] = "'Added'";
7179 * Get the qill value for the field.
7182 * @param array|int|string $value
7187 protected function getQillForField($name, $value, $op): string {
7188 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
7189 return (string) ts("%1 %2 %3", [