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 static $_defaultReturnProperties = NULL;
86 * The default set of hier return properties.
90 static $_defaultHierReturnProperties;
93 * The set of input params.
101 public $_paramLookup;
106 * The set of output params
110 public $_returnProperties;
120 * The name of the elements that are in the select clause
121 * used to extract the values.
128 * The tables involved in the query.
135 * The table involved in the where clause.
139 public $_whereTables;
142 * Array of WHERE clause components.
149 * The WHERE clause as a string.
153 public $_whereClause;
156 * Additional WHERE clause for permissions.
160 public $_permissionWhereClause;
170 * Additional permission from clause
174 public $_permissionFromClause;
177 * The from clause for the simple select and alphabetical
182 public $_simpleFromClause;
192 * The english language version of the query
199 * All the fields that could potentially be involved in
207 * The cache to translate the option values into labels.
214 * Are we in search mode.
218 public $_search = TRUE;
221 * Should we skip permission checking.
225 public $_skipPermission = FALSE;
228 * Should we skip adding of delete clause.
232 public $_skipDeleteClause = FALSE;
235 * Are we in strict mode (use equality over LIKE)
239 public $_strict = FALSE;
242 * What operator to use to group the clauses.
246 public $_operator = 'AND';
251 * Should we only search on primary location.
255 public $_primaryLocation = TRUE;
258 * Are contact ids part of the query.
262 public $_includeContactIds = FALSE;
265 * Should we use the smart group cache.
269 public $_smartGroupCache = TRUE;
272 * Should we display contacts with a specific relationship type.
276 public $_displayRelationshipType = NULL;
279 * Reference to the query object for custom values.
283 public $_customQuery;
286 * Should we enable the distinct clause, used if we are including
287 * more than one group
291 public $_useDistinct = FALSE;
294 * Should we just display one contact record
296 public $_useGroupBy = FALSE;
299 * The relationship type direction
310 static $_activityRole;
313 * Consider the component activity type
314 * during activity search.
318 static $_considerCompActivities;
321 * Consider with contact activities only,
322 * during activity search.
326 static $_withContactActivitiesOnly;
329 * Use distinct component clause for component searches
333 public $_distinctComponentClause;
335 public $_rowCountClause;
338 * Use groupBy component clause for component searches
342 public $_groupByComponentClause;
345 * Track open panes, useful in advance search
349 public static $_openedPanes = array();
352 * For search builder - which custom fields are location-dependent
355 public $_locationSpecificCustomFields = array();
358 * The tables which have a dependency on location and/or address
362 static $_dependencies = array(
363 'civicrm_state_province' => 1,
364 'civicrm_country' => 1,
365 'civicrm_county' => 1,
366 'civicrm_address' => 1,
367 'civicrm_location_type' => 1,
371 * List of location specific fields.
373 static $_locationSpecificFields = array(
378 'supplemental_address_1',
379 'supplemental_address_2',
380 'supplemental_address_3',
383 'postal_code_suffix',
397 * Remember if we handle either end of a number or date range
398 * so we can skip the other
400 protected $_rangeCache = array();
402 * Set to true when $this->relationship is run to avoid adding twice
405 protected $_relationshipValuesAdded = FALSE;
408 * Set to the name of the temp table if one has been created
411 static $_relationshipTempTable = NULL;
413 public $_pseudoConstantsSelect = array();
415 public $_groupUniqueKey = NULL;
416 public $_groupKeys = [];
419 * Class constructor which also does all the work.
421 * @param array $params
422 * @param array $returnProperties
423 * @param array $fields
424 * @param bool $includeContactIds
425 * @param bool $strict
426 * @param bool|int $mode - mode the search is operating on
428 * @param bool $skipPermission
429 * @param bool $searchDescendentGroups
430 * @param bool $smartGroupCache
431 * @param null $displayRelationshipType
432 * @param string $operator
433 * @param string $apiEntity
434 * @param bool|NULL $primaryLocationOnly
436 public function __construct(
437 $params = NULL, $returnProperties = NULL, $fields = NULL,
438 $includeContactIds = FALSE, $strict = FALSE, $mode = 1,
439 $skipPermission = FALSE, $searchDescendentGroups = TRUE,
440 $smartGroupCache = TRUE, $displayRelationshipType = NULL,
443 $primaryLocationOnly = NULL
445 if ($primaryLocationOnly === NULL) {
446 $primaryLocationOnly = Civi
::settings()->get('searchPrimaryDetailsOnly');
448 $this->_primaryLocation
= $primaryLocationOnly;
449 $this->_params
= &$params;
450 if ($this->_params
== NULL) {
451 $this->_params
= array();
454 if ($returnProperties === self
::NO_RETURN_PROPERTIES
) {
455 $this->_returnProperties
= array();
457 elseif (empty($returnProperties)) {
458 $this->_returnProperties
= self
::defaultReturnProperties($mode);
461 $this->_returnProperties
= &$returnProperties;
464 $this->_includeContactIds
= $includeContactIds;
465 $this->_strict
= $strict;
466 $this->_mode
= $mode;
467 $this->_skipPermission
= $skipPermission;
468 $this->_smartGroupCache
= $smartGroupCache;
469 $this->_displayRelationshipType
= $displayRelationshipType;
470 $this->setOperator($operator);
473 $this->_fields
= &$fields;
474 $this->_search
= FALSE;
475 $this->_skipPermission
= TRUE;
478 $this->_fields
= CRM_Contact_BAO_Contact
::exportableFields('All', FALSE, TRUE, TRUE, FALSE, !$skipPermission);
480 $fields = CRM_Core_Component
::getQueryFields(!$this->_skipPermission
);
481 unset($fields['note']);
482 $this->_fields
= array_merge($this->_fields
, $fields);
484 // add activity fields
485 $fields = CRM_Activity_BAO_Activity
::exportableFields();
486 $this->_fields
= array_merge($this->_fields
, $fields);
488 // add any fields provided by hook implementers
489 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
490 $this->_fields
= array_merge($this->_fields
, $extFields);
493 // basically do all the work once, and then reuse it
494 $this->initialize($apiEntity);
498 * Function which actually does all the work for the constructor.
500 * @param string $apiEntity
501 * The api entity being called.
502 * This sort-of duplicates $mode in a confusing way. Probably not by design.
504 public function initialize($apiEntity = NULL) {
505 $this->_select
= array();
506 $this->_element
= array();
507 $this->_tables
= array();
508 $this->_whereTables
= array();
509 $this->_where
= array();
510 $this->_qill
= array();
511 $this->_options
= array();
512 $this->_cfIDs
= array();
513 $this->_paramLookup
= array();
514 $this->_having
= array();
516 $this->_customQuery
= NULL;
518 // reset cached static variables - CRM-5803
519 self
::$_activityRole = NULL;
520 self
::$_considerCompActivities = NULL;
521 self
::$_withContactActivitiesOnly = NULL;
523 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
524 $this->_element
['contact_id'] = 1;
525 $this->_tables
['civicrm_contact'] = 1;
527 if (!empty($this->_params
)) {
528 $this->buildParamsLookup();
531 $this->_whereTables
= $this->_tables
;
533 $this->selectClause($apiEntity);
534 $this->_whereClause
= $this->whereClause($apiEntity);
535 if (array_key_exists('civicrm_contribution', $this->_whereTables
)) {
536 $component = 'contribution';
538 if (array_key_exists('civicrm_membership', $this->_whereTables
)) {
539 $component = 'membership';
541 if (isset($component)) {
542 // @todo should be if (isset($component && !$this->_skipPermission)
543 CRM_Financial_BAO_FinancialType
::buildPermissionedClause($this->_whereClause
, $component);
546 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
, $apiEntity);
547 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
549 $this->openedSearchPanes(TRUE);
553 * Function for same purpose as convertFormValues.
555 * Like convert form values this function exists to pre-Process parameters from the form.
557 * It is unclear why they are different functions & likely relates to advances search
558 * versus search builder.
560 * The direction we are going is having the form convert values to a standardised format &
561 * moving away from weird & wonderful where clause switches.
563 * Fix and handle contact deletion nicely.
565 * this code is primarily for search builder use case where different clauses can specify if they want deleted.
569 public function buildParamsLookup() {
570 $trashParamExists = FALSE;
571 $paramByGroup = array();
572 foreach ($this->_params
as $k => $param) {
573 if (!empty($param[0]) && $param[0] == 'contact_is_deleted') {
574 $trashParamExists = TRUE;
576 if (!empty($param[3])) {
577 $paramByGroup[$param[3]][$k] = $param;
581 if ($trashParamExists) {
582 $this->_skipDeleteClause
= TRUE;
584 //cycle through group sets and explicitly add trash param if not set
585 foreach ($paramByGroup as $setID => $set) {
587 !in_array(array('contact_is_deleted', '=', '1', $setID, '0'), $this->_params
) &&
588 !in_array(array('contact_is_deleted', '=', '0', $setID, '0'), $this->_params
)
590 $this->_params
[] = array(
591 'contact_is_deleted',
601 foreach ($this->_params
as $value) {
602 if (empty($value[0])) {
605 $cfID = CRM_Core_BAO_CustomField
::getKeyID($value[0]);
607 if (!array_key_exists($cfID, $this->_cfIDs
)) {
608 $this->_cfIDs
[$cfID] = array();
610 // Set wildcard value based on "and/or" selection
611 foreach ($this->_params
as $key => $param) {
612 if ($param[0] == $value[0] . '_operator') {
613 $value[4] = $param[2] == 'or';
617 $this->_cfIDs
[$cfID][] = $value;
620 if (!array_key_exists($value[0], $this->_paramLookup
)) {
621 $this->_paramLookup
[$value[0]] = array();
623 if ($value[0] !== 'group') {
624 // Just trying to unravel how group interacts here! This whole function is weird.
625 $this->_paramLookup
[$value[0]][] = $value;
631 * Some composite fields do not appear in the fields array hack to make them part of the query.
634 * The api entity being called.
635 * This sort-of duplicates $mode in a confusing way. Probably not by design.
637 public function addSpecialFields($apiEntity) {
638 static $special = array('contact_type', 'contact_sub_type', 'sort_name', 'display_name');
639 // if get called via Contact.get API having address_id as return parameter
640 if ($apiEntity == 'Contact') {
641 $special[] = 'address_id';
643 foreach ($special as $name) {
644 if (!empty($this->_returnProperties
[$name])) {
645 if ($name == 'address_id') {
646 $this->_tables
['civicrm_address'] = 1;
647 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
648 $this->_element
['address_id'] = 1;
651 $this->_select
[$name] = "contact_a.{$name} as $name";
652 $this->_element
[$name] = 1;
659 * Given a list of conditions in params and a list of desired
660 * return Properties generate the required select and from
661 * clauses. Note that since the where clause introduces new
662 * tables, the initial attempt also retrieves all variables used
665 * @param string $apiEntity
666 * The api entity being called.
667 * This sort-of duplicates $mode in a confusing way. Probably not by design.
669 public function selectClause($apiEntity = NULL) {
671 // @todo Tidy up this. This arises because 1) we are ignoring the $mode & adding a new
672 // param ($apiEntity) instead - presumably an oversight & 2 because
673 // contact is not implemented as a component.
674 $this->addSpecialFields($apiEntity);
676 foreach ($this->_fields
as $name => $field) {
677 // skip component fields
678 // there are done by the alter query below
679 // and need not be done on every field
680 // @todo remove these & handle using metadata - only obscure fields
681 // that are hack-added should need to be excluded from the main loop.
683 (substr($name, 0, 12) == 'participant_') ||
684 (substr($name, 0, 7) == 'pledge_') ||
685 (substr($name, 0, 5) == 'case_')
690 // redirect to activity select clause
692 (substr($name, 0, 9) == 'activity_') ||
693 ($name == 'parent_id')
695 CRM_Activity_BAO_Query
::select($this);
698 // if this is a hierarchical name, we ignore it
699 $names = explode('-', $name);
700 if (count($names) > 1 && isset($names[1]) && is_numeric($names[1])) {
704 // make an exception for special cases, to add the field in select clause
705 $makeException = FALSE;
707 //special handling for groups/tags
708 if (in_array($name, array('groups', 'tags', 'notes'))
709 && isset($this->_returnProperties
[substr($name, 0, -1)])
711 // @todo instead of setting make exception to get us into
712 // an if clause that has handling for these fields buried with in it
713 // move the handling to here.
714 $makeException = TRUE;
717 // since note has 3 different options we need special handling
718 // note / note_subject / note_body
719 if ($name == 'notes') {
720 foreach (array('note', 'note_subject', 'note_body') as $noteField) {
721 if (isset($this->_returnProperties
[$noteField])) {
722 $makeException = TRUE;
728 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
730 !empty($this->_paramLookup
[$name])
731 ||
!empty($this->_returnProperties
[$name])
732 ||
$this->pseudoConstantNameIsInReturnProperties($field, $name)
736 // add to cfIDs array if not present
737 if (!array_key_exists($cfID, $this->_cfIDs
)) {
738 $this->_cfIDs
[$cfID] = array();
741 elseif (isset($field['where'])) {
742 list($tableName, $fieldName) = explode('.', $field['where'], 2);
743 if (isset($tableName)) {
744 if (CRM_Utils_Array
::value($tableName, self
::$_dependencies)) {
745 $this->_tables
['civicrm_address'] = 1;
746 $this->_select
['address_id'] = 'civicrm_address.id as address_id';
747 $this->_element
['address_id'] = 1;
750 if ($tableName == 'im_provider' ||
$tableName == 'email_greeting' ||
751 $tableName == 'postal_greeting' ||
$tableName == 'addressee'
753 if ($tableName == 'im_provider') {
754 CRM_Core_OptionValue
::select($this);
757 if (in_array($tableName,
758 array('email_greeting', 'postal_greeting', 'addressee'))) {
759 $this->_element
["{$name}_id"] = 1;
760 $this->_select
["{$name}_id"] = "contact_a.{$name}_id as {$name}_id";
761 $this->_pseudoConstantsSelect
[$name] = array('pseudoField' => $tableName, 'idCol' => "{$name}_id");
762 $this->_pseudoConstantsSelect
[$name]['select'] = "{$name}.{$fieldName} as $name";
763 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
765 if ($tableName == 'email_greeting') {
767 $this->_pseudoConstantsSelect
[$name]['join']
768 = " LEFT JOIN civicrm_option_group option_group_email_greeting ON (option_group_email_greeting.name = 'email_greeting')";
769 $this->_pseudoConstantsSelect
[$name]['join'] .=
770 " 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 ) ";
772 elseif ($tableName == 'postal_greeting') {
774 $this->_pseudoConstantsSelect
[$name]['join']
775 = " LEFT JOIN civicrm_option_group option_group_postal_greeting ON (option_group_postal_greeting.name = 'postal_greeting')";
776 $this->_pseudoConstantsSelect
[$name]['join'] .=
777 " 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 ) ";
779 elseif ($tableName == 'addressee') {
781 $this->_pseudoConstantsSelect
[$name]['join']
782 = " LEFT JOIN civicrm_option_group option_group_addressee ON (option_group_addressee.name = 'addressee')";
783 $this->_pseudoConstantsSelect
[$name]['join'] .=
784 " LEFT JOIN civicrm_option_value addressee ON (contact_a.addressee_id = addressee.value AND option_group_addressee.id = addressee.option_group_id ) ";
786 $this->_pseudoConstantsSelect
[$name]['table'] = $tableName;
789 $greetField = "{$name}_display";
790 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
791 $this->_element
[$greetField] = 1;
793 $greetField = "{$name}_custom";
794 $this->_select
[$greetField] = "contact_a.{$greetField} as {$greetField}";
795 $this->_element
[$greetField] = 1;
799 if (!in_array($tableName, array('civicrm_state_province', 'civicrm_country', 'civicrm_county'))) {
800 $this->_tables
[$tableName] = 1;
803 // also get the id of the tableName
804 $tName = substr($tableName, 8);
805 if (in_array($tName, array('country', 'state_province', 'county'))) {
806 if ($tName == 'state_province') {
807 $this->_pseudoConstantsSelect
['state_province_name'] = array(
808 'pseudoField' => "{$tName}",
809 'idCol' => "{$tName}_id",
810 'bao' => 'CRM_Core_BAO_Address',
811 'table' => "civicrm_{$tName}",
812 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
815 $this->_pseudoConstantsSelect
[$tName] = array(
816 'pseudoField' => 'state_province_abbreviation',
817 'idCol' => "{$tName}_id",
818 'table' => "civicrm_{$tName}",
819 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
823 $this->_pseudoConstantsSelect
[$name] = array(
824 'pseudoField' => "{$tName}_id",
825 'idCol' => "{$tName}_id",
826 'bao' => 'CRM_Core_BAO_Address',
827 'table' => "civicrm_{$tName}",
828 'join' => " LEFT JOIN civicrm_{$tName} ON civicrm_address.{$tName}_id = civicrm_{$tName}.id ",
832 $this->_select
["{$tName}_id"] = "civicrm_address.{$tName}_id as {$tName}_id";
833 $this->_element
["{$tName}_id"] = 1;
835 elseif ($tName != 'contact') {
836 $this->_select
["{$tName}_id"] = "{$tableName}.id as {$tName}_id";
837 $this->_element
["{$tName}_id"] = 1;
840 //special case for phone
841 if ($name == 'phone') {
842 $this->_select
['phone_type_id'] = "civicrm_phone.phone_type_id as phone_type_id";
843 $this->_element
['phone_type_id'] = 1;
846 // if IM then select provider_id also
847 // to get "IM Service Provider" in a file to be exported, CRM-3140
849 $this->_select
['provider_id'] = "civicrm_im.provider_id as provider_id";
850 $this->_element
['provider_id'] = 1;
853 if ($tName == 'contact' && $fieldName == 'organization_name') {
854 // special case, when current employer is set for Individual contact
855 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', NULL, contact_a.organization_name ) as organization_name";
857 elseif ($tName == 'contact' && $fieldName === 'id') {
858 // Handled elsewhere, explicitly ignore. Possibly for all tables...
860 elseif (in_array($tName, array('country', 'county'))) {
861 $this->_pseudoConstantsSelect
[$name]['select'] = "{$field['where']} as `$name`";
862 $this->_pseudoConstantsSelect
[$name]['element'] = $name;
864 elseif ($tName == 'state_province') {
865 $this->_pseudoConstantsSelect
[$tName]['select'] = "{$field['where']} as `$name`";
866 $this->_pseudoConstantsSelect
[$tName]['element'] = $name;
868 elseif (strpos($name, 'contribution_soft_credit') !== FALSE) {
869 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled($this->_params
)) {
870 $this->_select
[$name] = "{$field['where']} as `$name`";
873 elseif ($this->pseudoConstantNameIsInReturnProperties($field, $name)) {
874 $this->addPseudoconstantFieldToSelect($name);
877 $this->_select
[$name] = str_replace('civicrm_contact.', 'contact_a.', "{$field['where']} as `$name`");
879 if (!in_array($tName, array('state_province', 'country', 'county'))) {
880 $this->_element
[$name] = 1;
885 elseif ($name === 'tags') {
886 //@todo move this handling outside the big IF & ditch $makeException
887 $this->_useGroupBy
= TRUE;
888 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_tag.name)) as tags";
889 $this->_element
[$name] = 1;
890 $this->_tables
['civicrm_tag'] = 1;
891 $this->_tables
['civicrm_entity_tag'] = 1;
893 elseif ($name === 'groups') {
894 //@todo move this handling outside the big IF & ditch $makeException
895 $this->_useGroupBy
= TRUE;
896 // Duplicates will be created here but better to sort them out in php land.
897 $this->_select
[$name] = "
899 GROUP_CONCAT(DISTINCT IF(civicrm_group_contact.status = 'Added', civicrm_group_contact.group_id, '')),
900 GROUP_CONCAT(DISTINCT civicrm_group_contact_cache.group_id)
903 $this->_element
[$name] = 1;
904 $this->_tables
['civicrm_group_contact'] = 1;
905 $this->_tables
['civicrm_group_contact_cache'] = 1;
906 $this->_pseudoConstantsSelect
["{$name}"] = array(
907 'pseudoField' => "groups",
911 elseif ($name === 'notes') {
912 //@todo move this handling outside the big IF & ditch $makeException
913 // if note field is subject then return subject else body of the note
914 $noteColumn = 'note';
915 if (isset($noteField) && $noteField == 'note_subject') {
916 $noteColumn = 'subject';
919 $this->_useGroupBy
= TRUE;
920 $this->_select
[$name] = "GROUP_CONCAT(DISTINCT(civicrm_note.$noteColumn)) as notes";
921 $this->_element
[$name] = 1;
922 $this->_tables
['civicrm_note'] = 1;
924 elseif ($name === 'current_employer') {
925 $this->_select
[$name] = "IF ( contact_a.contact_type = 'Individual', contact_a.organization_name, NULL ) as current_employer";
926 $this->_element
[$name] = 1;
930 if ($cfID && !empty($field['is_search_range'])) {
931 // this is a custom field with range search enabled, so we better check for two/from values
932 if (!empty($this->_paramLookup
[$name . '_from'])) {
933 if (!array_key_exists($cfID, $this->_cfIDs
)) {
934 $this->_cfIDs
[$cfID] = array();
936 foreach ($this->_paramLookup
[$name . '_from'] as $pID => $p) {
937 // search in the cdID array for the same grouping
939 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
940 if ($c[3] == $p[3]) {
941 $this->_cfIDs
[$cfID][$cID][2]['from'] = $p[2];
946 $p[2] = array('from' => $p[2]);
947 $this->_cfIDs
[$cfID][] = $p;
951 if (!empty($this->_paramLookup
[$name . '_to'])) {
952 if (!array_key_exists($cfID, $this->_cfIDs
)) {
953 $this->_cfIDs
[$cfID] = array();
955 foreach ($this->_paramLookup
[$name . '_to'] as $pID => $p) {
956 // search in the cdID array for the same grouping
958 foreach ($this->_cfIDs
[$cfID] as $cID => $c) {
959 if ($c[4] == $p[4]) {
960 $this->_cfIDs
[$cfID][$cID][2]['to'] = $p[2];
965 $p[2] = array('to' => $p[2]);
966 $this->_cfIDs
[$cfID][] = $p;
973 // add location as hierarchical elements
974 $this->addHierarchicalElements();
976 // add multiple field like website
977 $this->addMultipleElements();
980 CRM_Core_Component
::alterQuery($this, 'select');
982 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'select');
984 if (!empty($this->_cfIDs
)) {
985 // @todo This function is the select function but instead of running 'select' it
986 // is running the whole query.
987 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
988 $this->_customQuery
->query();
989 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
990 $this->_element
= array_merge($this->_element
, $this->_customQuery
->_element
);
991 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
992 $this->_whereTables
= array_merge($this->_whereTables
, $this->_customQuery
->_whereTables
);
993 $this->_options
= $this->_customQuery
->_options
;
998 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
1000 public function addHierarchicalElements() {
1001 if (empty($this->_returnProperties
['location'])) {
1004 if (!is_array($this->_returnProperties
['location'])) {
1008 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
1009 $processed = array();
1012 $addressCustomFields = CRM_Core_BAO_CustomField
::getFieldsForImport('Address');
1013 $addressCustomFieldIds = array();
1015 foreach ($this->_returnProperties
['location'] as $name => $elements) {
1016 $lCond = self
::getPrimaryCondition($name);
1019 $locationTypeId = array_search($name, $locationTypes);
1020 if ($locationTypeId === FALSE) {
1023 $lCond = "location_type_id = $locationTypeId";
1024 $this->_useDistinct
= TRUE;
1026 //commented for CRM-3256
1027 $this->_useGroupBy
= TRUE;
1030 $name = str_replace(' ', '_', $name);
1032 $tName = "$name-location_type";
1033 $ltName = "`$name-location_type`";
1034 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1035 $this->_select
["{$tName}"] = "`$tName`.name as `{$tName}`";
1036 $this->_element
["{$tName}_id"] = 1;
1037 $this->_element
["{$tName}"] = 1;
1039 $locationTypeName = $tName;
1040 $locationTypeJoin = array();
1042 $addAddress = FALSE;
1044 foreach ($elements as $elementFullName => $dontCare) {
1046 $elementName = $elementCmpName = $elementFullName;
1048 if (substr($elementCmpName, 0, 5) == 'phone') {
1049 $elementCmpName = 'phone';
1052 if (in_array($elementCmpName, array_keys($addressCustomFields))) {
1053 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($elementCmpName)) {
1054 $addressCustomFieldIds[$cfID][$name] = 1;
1057 //add address table only once
1058 if ((in_array($elementCmpName, self
::$_locationSpecificFields) ||
!empty($addressCustomFieldIds))
1060 && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))
1062 $tName = "$name-address";
1063 $aName = "`$name-address`";
1064 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1065 $this->_element
["{$tName}_id"] = 1;
1066 $addressJoin = "\nLEFT JOIN civicrm_address $aName ON ($aName.contact_id = contact_a.id AND $aName.$lCond)";
1067 $this->_tables
[$tName] = $addressJoin;
1068 $locationTypeJoin[$tName] = " ( $aName.location_type_id = $ltName.id ) ";
1069 $processed[$aName] = 1;
1073 $cond = $elementType = '';
1074 if (strpos($elementName, '-') !== FALSE) {
1075 // this is either phone, email or IM
1076 list($elementName, $elementType) = explode('-', $elementName);
1078 if (($elementName != 'phone') && ($elementName != 'im')) {
1079 $cond = self
::getPrimaryCondition($elementType);
1081 // CRM-13011 : If location type is primary, do not restrict search to the phone
1082 // type id - we want the primary phone, regardless of what type it is.
1083 // Otherwise, restrict to the specified phone type for the given field.
1084 if ((!$cond) && ($elementName == 'phone')) {
1085 $cond = "phone_type_id = '$elementType'";
1087 elseif ((!$cond) && ($elementName == 'im')) {
1088 // IM service provider id, CRM-3140
1089 $cond = "provider_id = '$elementType'";
1091 $elementType = '-' . $elementType;
1094 $field = CRM_Utils_Array
::value($elementName, $this->_fields
);
1096 // hack for profile, add location id
1099 // fix for CRM-882( to handle phone types )
1100 !is_numeric($elementType)
1102 if (is_numeric($name)) {
1103 $field = CRM_Utils_Array
::value($elementName . "-Primary$elementType", $this->_fields
);
1106 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1109 elseif (is_numeric($name)) {
1110 //this for phone type to work
1111 if (in_array($elementName, array('phone', 'phone_ext'))) {
1112 $field = CRM_Utils_Array
::value($elementName . "-Primary" . $elementType, $this->_fields
);
1115 $field = CRM_Utils_Array
::value($elementName . "-Primary", $this->_fields
);
1119 //this is for phone type to work for profile edit
1120 if (in_array($elementName, array('phone', 'phone_ext'))) {
1121 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId$elementType", $this->_fields
);
1124 $field = CRM_Utils_Array
::value($elementName . "-$locationTypeId", $this->_fields
);
1129 // Check if there is a value, if so also add to where Clause
1131 if ($this->_params
) {
1133 if (isset($locationTypeId)) {
1134 $nm .= "-$locationTypeId";
1136 if (!is_numeric($elementType)) {
1137 $nm .= "$elementType";
1140 foreach ($this->_params
as $id => $values) {
1141 if ((is_array($values) && $values[0] == $nm) ||
1142 (in_array($elementName, array('phone', 'im'))
1143 && (strpos($values[0], $nm) !== FALSE)
1153 if ($field && isset($field['where'])) {
1154 list($tableName, $fieldName) = explode('.', $field['where'], 2);
1155 $pf = substr($tableName, 8);
1156 $tName = $name . '-' . $pf . $elementType;
1157 if (isset($tableName)) {
1158 if ($tableName == 'civicrm_state_province' ||
$tableName == 'civicrm_country' ||
$tableName == 'civicrm_county') {
1159 $this->_select
["{$tName}_id"] = "{$aName}.{$pf}_id as `{$tName}_id`";
1162 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1165 $this->_element
["{$tName}_id"] = 1;
1166 if (substr($tName, -15) == '-state_province') {
1167 // FIXME: hack to fix CRM-1900
1168 $a = Civi
::settings()->get('address_format');
1170 if (substr_count($a, 'state_province_name') > 0) {
1171 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1172 'pseudoField' => "{$pf}_id",
1173 'idCol' => "{$tName}_id",
1174 'bao' => 'CRM_Core_BAO_Address',
1176 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.name as `{$name}-{$elementFullName}`";
1179 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1180 'pseudoField' => 'state_province_abbreviation',
1181 'idCol' => "{$tName}_id",
1183 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.abbreviation as `{$name}-{$elementFullName}`";
1187 if (substr($elementFullName, 0, 2) == 'im') {
1188 $provider = "{$name}-{$elementFullName}-provider_id";
1189 $this->_select
[$provider] = "`$tName`.provider_id as `{$name}-{$elementFullName}-provider_id`";
1190 $this->_element
[$provider] = 1;
1192 if ($pf == 'country' ||
$pf == 'county') {
1193 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"] = array(
1194 'pseudoField' => "{$pf}_id",
1195 'idCol' => "{$tName}_id",
1196 'bao' => 'CRM_Core_BAO_Address',
1198 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['select'] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1201 $this->_select
["{$name}-{$elementFullName}"] = "`$tName`.$fieldName as `{$name}-{$elementFullName}`";
1205 if (in_array($pf, array('state_province', 'country', 'county'))) {
1206 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['element'] = "{$name}-{$elementFullName}";
1209 $this->_element
["{$name}-{$elementFullName}"] = 1;
1212 if (empty($processed["`$tName`"])) {
1213 $processed["`$tName`"] = 1;
1214 $newName = $tableName . '_' . $index;
1215 switch ($tableName) {
1216 case 'civicrm_phone':
1217 case 'civicrm_email':
1219 case 'civicrm_openid':
1221 $this->_tables
[$tName] = "\nLEFT JOIN $tableName `$tName` ON contact_a.id = `$tName`.contact_id";
1222 if ($tableName != 'civicrm_phone') {
1223 $this->_tables
[$tName] .= " AND `$tName`.$lCond";
1225 elseif (is_numeric($name)) {
1226 $this->_select
[$tName] = "IF (`$tName`.is_primary = $name, `$tName`.phone, NULL) as `$tName`";
1229 // this special case to add phone type
1231 $phoneTypeCondition = " AND `$tName`.$cond ";
1232 //gross hack to pickup corrupted data also, CRM-7603
1233 if (strpos($cond, 'phone_type_id') !== FALSE) {
1234 $phoneTypeCondition = " AND ( `$tName`.$cond OR `$tName`.phone_type_id IS NULL ) ";
1235 if (!empty($lCond)) {
1236 $phoneTypeCondition .= " AND ( `$tName`.$lCond ) ";
1239 $this->_tables
[$tName] .= $phoneTypeCondition;
1242 //build locationType join
1243 $locationTypeJoin[$tName] = " ( `$tName`.location_type_id = $ltName.id )";
1246 $this->_whereTables
[$tName] = $this->_tables
[$tName];
1250 case 'civicrm_state_province':
1251 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $tName;
1252 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1253 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.state_province_id";
1255 $this->_whereTables
["{$name}-address"] = $addressJoin;
1259 case 'civicrm_country':
1260 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1261 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1262 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.country_id";
1264 $this->_whereTables
["{$name}-address"] = $addressJoin;
1268 case 'civicrm_county':
1269 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['table'] = $newName;
1270 $this->_pseudoConstantsSelect
["{$name}-{$elementFullName}"]['join']
1271 = "\nLEFT JOIN $tableName `$tName` ON `$tName`.id = $aName.county_id";
1273 $this->_whereTables
["{$name}-address"] = $addressJoin;
1279 $this->_whereTables
["{$name}-address"] = $addressJoin;
1288 // add location type join
1289 $ltypeJoin = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locationTypeJoin) . " )";
1290 $this->_tables
[$locationTypeName] = $ltypeJoin;
1292 // table should be present in $this->_whereTables,
1293 // to add its condition in location type join, CRM-3939.
1294 if ($addWhereCount) {
1295 $locClause = array();
1296 foreach ($this->_whereTables
as $tableName => $clause) {
1297 if (!empty($locationTypeJoin[$tableName])) {
1298 $locClause[] = $locationTypeJoin[$tableName];
1302 if (!empty($locClause)) {
1303 $this->_whereTables
[$locationTypeName] = "\nLEFT JOIN civicrm_location_type $ltName ON ( " . implode('OR', $locClause) . " )";
1308 if (!empty($addressCustomFieldIds)) {
1309 $customQuery = new CRM_Core_BAO_CustomQuery($addressCustomFieldIds);
1310 foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
1311 foreach ($locTypeName as $name => $dnc) {
1312 $this->_locationSpecificCustomFields
[$cfID] = array($name, array_search($name, $locationTypes));
1313 $fieldName = "$name-custom_{$cfID}";
1314 $tName = "$name-address-custom-{$cfID}";
1315 $aName = "`$name-address-custom-{$cfID}`";
1316 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1317 $this->_element
["{$tName}_id"] = 1;
1318 $this->_select
[$fieldName] = "`$tName`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
1319 $this->_element
[$fieldName] = 1;
1320 $this->_tables
[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} $aName ON ($aName.entity_id = `$name-address`.id)";
1327 * If the return Properties are set in a hierarchy, traverse the hierarchy to get the return values.
1329 public function addMultipleElements() {
1330 if (empty($this->_returnProperties
['website'])) {
1333 if (!is_array($this->_returnProperties
['website'])) {
1337 foreach ($this->_returnProperties
['website'] as $key => $elements) {
1338 foreach ($elements as $elementFullName => $dontCare) {
1339 $tName = "website-{$key}-{$elementFullName}";
1340 $this->_select
["{$tName}_id"] = "`$tName`.id as `{$tName}_id`";
1341 $this->_select
["{$tName}"] = "`$tName`.url as `{$tName}`";
1342 $this->_element
["{$tName}_id"] = 1;
1343 $this->_element
["{$tName}"] = 1;
1345 $type = "website-{$key}-website_type_id";
1346 $this->_select
[$type] = "`$tName`.website_type_id as `{$type}`";
1347 $this->_element
[$type] = 1;
1348 $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website `$tName` ON (`$tName`.contact_id = contact_a.id AND `$tName`.website_type_id = $key )";
1354 * Generate the query based on what type of query we need.
1356 * @param bool $count
1357 * @param bool $sortByChar
1358 * @param bool $groupContacts
1359 * @param bool $onlyDeleted
1362 * sql query parts as an array
1364 public function query($count = FALSE, $sortByChar = FALSE, $groupContacts = FALSE, $onlyDeleted = FALSE) {
1365 // build permission clause
1366 $this->generatePermissionClause($onlyDeleted, $count);
1369 if (isset($this->_rowCountClause
)) {
1370 $select = "SELECT {$this->_rowCountClause}";
1372 elseif (isset($this->_distinctComponentClause
)) {
1373 // we add distinct to get the right count for components
1374 // for the more complex result set, we use GROUP BY the same id
1376 $select = "SELECT count( DISTINCT {$this->_distinctComponentClause} ) as rowCount";
1379 $select = 'SELECT count(DISTINCT contact_a.id) as rowCount';
1381 $from = $this->_simpleFromClause
;
1382 if ($this->_useDistinct
) {
1383 $this->_useGroupBy
= TRUE;
1386 elseif ($sortByChar) {
1387 $select = 'SELECT DISTINCT LEFT(contact_a.sort_name, 1) as sort_name';
1388 $from = $this->_simpleFromClause
;
1390 elseif ($groupContacts) {
1391 $select = 'SELECT contact_a.id as id';
1392 if ($this->_useDistinct
) {
1393 $this->_useGroupBy
= TRUE;
1395 $from = $this->_simpleFromClause
;
1398 if (!empty($this->_paramLookup
['group'])) {
1400 list($name, $op, $value, $grouping, $wildcard) = $this->_paramLookup
['group'][0];
1402 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
1403 $this->_paramLookup
['group'][0][1] = key($value);
1406 // Presumably the lines below come into manage groups screen.
1407 // make sure there is only one element
1408 // this is used when we are running under smog and need to know
1409 // how the contact was added (CRM-1203)
1410 $groups = (array) CRM_Utils_Array
::value($this->_paramLookup
['group'][0][1], $this->_paramLookup
['group'][0][2], $this->_paramLookup
['group'][0][2]);
1411 if ((count($this->_paramLookup
['group']) == 1) &&
1412 (count($groups) == 1)
1414 $groupId = $groups[0];
1416 //check if group is saved search
1417 $group = new CRM_Contact_BAO_Group();
1418 $group->id
= $groupId;
1421 if (!isset($group->saved_search_id
)) {
1422 $tbName = "civicrm_group_contact";
1423 // CRM-17254 don't retrieve extra fields if contact_id is specifically requested
1424 // as this will add load to an intentionally light query.
1425 // ideally this code would be removed as it appears to be to support CRM-1203
1426 // and passing in the required returnProperties from the url would
1427 // make more sense that globally applying the requirements of one form.
1428 if (($this->_returnProperties
!= array('contact_id'))) {
1429 $this->_select
['group_contact_id'] = "$tbName.id as group_contact_id";
1430 $this->_element
['group_contact_id'] = 1;
1431 $this->_select
['status'] = "$tbName.status as status";
1432 $this->_element
['status'] = 1;
1436 $this->_useGroupBy
= TRUE;
1438 if ($this->_useDistinct
&& !isset($this->_distinctComponentClause
)) {
1439 if (!($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
)) {
1441 $this->_select
['contact_id'] = 'contact_a.id as contact_id';
1442 $this->_useDistinct
= FALSE;
1443 $this->_useGroupBy
= TRUE;
1447 $select = $this->getSelect();
1448 $from = $this->_fromClause
;
1452 if (!empty($this->_whereClause
)) {
1453 $where = "WHERE {$this->_whereClause}";
1456 if (!empty($this->_permissionWhereClause
) && empty($this->_displayRelationshipType
)) {
1457 if (empty($where)) {
1458 $where = "WHERE $this->_permissionWhereClause";
1461 $where = "$where AND $this->_permissionWhereClause";
1466 if (!empty($this->_having
)) {
1467 foreach ($this->_having
as $havingSets) {
1468 foreach ($havingSets as $havingSet) {
1469 $havingValue[] = $havingSet;
1472 $having = ' HAVING ' . implode(' AND ', $havingValue);
1475 // if we are doing a transform, do it here
1476 // use the $from, $where and $having to get the contact ID
1477 if ($this->_displayRelationshipType
) {
1478 $this->filterRelatedContacts($from, $where, $having);
1481 return array($select, $from, $where, $having);
1485 * Get where values from the parameters.
1487 * @param string $name
1488 * @param mixed $grouping
1492 public function getWhereValues($name, $grouping) {
1494 foreach ($this->_params
as $values) {
1495 if ($values[0] == $name && $values[3] == $grouping) {
1506 * @param bool $relative
1507 * @param string $from
1510 public static function fixDateValues($relative, &$from, &$to) {
1512 list($from, $to) = CRM_Utils_Date
::getFromTo($relative, $from, $to);
1517 * Convert values from form-appropriate to query-object appropriate.
1519 * The query object is increasingly supporting the sql-filter syntax which is the most flexible syntax.
1520 * So, ideally we would convert all fields to look like
1523 * // Set the operator for legacy reasons, but it is ignored
1525 * // array in sql filter syntax
1526 * 2 => array('BETWEEN' => array(1,60),
1531 * There are some examples of the syntax in
1532 * https://github.com/civicrm/civicrm-core/tree/master/api/v3/examples/Relationship
1534 * More notes at CRM_Core_DAO::createSQLFilter
1536 * and a list of supported operators in CRM_Core_DAO
1538 * @param array $formValues
1539 * @param int $wildcard
1540 * @param bool $useEquals
1542 * @param string $apiEntity
1544 * @param array $entityReferenceFields
1545 * Field names of any entity reference fields (which will need reformatting to IN syntax).
1549 public static function convertFormValues(&$formValues, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL,
1550 $entityReferenceFields = array()) {
1552 if (empty($formValues)) {
1556 self
::filterCountryFromValuesIfStateExists($formValues);
1558 // Handle relative dates first
1559 foreach (array_keys($formValues) as $id) {
1560 if (preg_match('/_date_relative$/', $id) ||
1561 $id == 'event_relative' ||
1562 $id == 'case_from_relative' ||
1563 $id == 'case_to_relative' ||
1564 $id == 'participant_relative'
1566 if ($id == 'event_relative') {
1567 $fromRange = 'event_start_date_low';
1568 $toRange = 'event_end_date_high';
1570 elseif ($id == 'participant_relative') {
1571 $fromRange = 'participant_register_date_low';
1572 $toRange = 'participant_register_date_high';
1574 elseif ($id == 'case_from_relative') {
1575 $fromRange = 'case_from_start_date_low';
1576 $toRange = 'case_from_start_date_high';
1578 elseif ($id == 'case_to_relative') {
1579 $fromRange = 'case_to_end_date_low';
1580 $toRange = 'case_to_end_date_high';
1583 $dateComponent = explode('_date_relative', $id);
1584 $fromRange = "{$dateComponent[0]}_date_low";
1585 $toRange = "{$dateComponent[0]}_date_high";
1588 if (array_key_exists($fromRange, $formValues) && array_key_exists($toRange, $formValues)) {
1589 CRM_Contact_BAO_Query
::fixDateValues($formValues[$id], $formValues[$fromRange], $formValues[$toRange]);
1594 foreach ($formValues as $id => $values) {
1595 if (self
::isAlreadyProcessedForQueryFormat($values)) {
1596 $params[] = $values;
1600 self
::legacyConvertFormValues($id, $values);
1602 // The form uses 1 field to represent two db fields
1603 if ($id == 'contact_type' && $values && (!is_array($values) ||
!array_intersect(array_keys($values), CRM_Core_DAO
::acceptedSQLOperators()))) {
1604 $contactType = array();
1606 foreach ((array) $values as $key => $type) {
1607 $types = explode('__', is_numeric($type) ?
$key : $type, 2);
1608 $contactType[$types[0]] = $types[0];
1609 // Add sub-type if specified
1610 if (!empty($types[1])) {
1611 $subType[$types[1]] = $types[1];
1614 $params[] = array('contact_type', 'IN', $contactType, 0, 0);
1616 $params[] = array('contact_sub_type', 'IN', $subType, 0, 0);
1619 elseif ($id == 'privacy') {
1620 if (is_array($formValues['privacy'])) {
1621 $op = !empty($formValues['privacy']['do_not_toggle']) ?
'=' : '!=';
1622 foreach ($formValues['privacy'] as $key => $value) {
1624 $params[] = array($key, $op, $value, 0, 0);
1629 elseif ($id == 'email_on_hold') {
1630 if ($onHoldValue = CRM_Utils_Array
::value('email_on_hold', $formValues)) {
1631 $onHoldValue = (array) $onHoldValue;
1632 $params[] = array('on_hold', 'IN', $onHoldValue, 0, 0);
1635 elseif (substr($id, 0, 7) == 'custom_'
1637 substr($id, -9, 9) == '_relative'
1638 ||
substr($id, -5, 5) == '_from'
1639 ||
substr($id, -3, 3) == '_to'
1642 self
::convertCustomRelativeFields($formValues, $params, $values, $id);
1644 elseif (preg_match('/_date_relative$/', $id) ||
1645 $id == 'event_relative' ||
1646 $id == 'case_from_relative' ||
1647 $id == 'case_to_relative' ||
1648 $id == 'participant_relative'
1650 // Already handled in previous loop
1653 elseif (in_array($id, $entityReferenceFields) && !empty($values) && is_string($values) && (strpos($values, ',') !=
1655 $params[] = array($id, 'IN', explode(',', $values), 0, 0);
1658 $values = CRM_Contact_BAO_Query
::fixWhereValues($id, $values, $wildcard, $useEquals, $apiEntity);
1663 $params[] = $values;
1670 * Function to support legacy format for groups and tags.
1673 * @param array|int $values
1676 public static function legacyConvertFormValues($id, &$values) {
1677 $legacyElements = array(
1682 'membership_type_id',
1683 'membership_status_id',
1685 if (in_array($id, $legacyElements) && is_array($values)) {
1686 // prior to 4.7, formValues for some attributes (e.g. group, tag) are stored in array(id1 => 1, id2 => 1),
1687 // as per the recent Search fixes $values need to be in standard array(id1, id2) format
1688 $values = CRM_Utils_Array
::convertCheckboxFormatToArray($values);
1693 * Fix values from query from/to something no-one cared enough to document.
1696 * @param array $values
1697 * @param int $wildcard
1698 * @param bool $useEquals
1700 * @param string $apiEntity
1702 * @return array|null
1704 public static function fixWhereValues($id, &$values, $wildcard = 0, $useEquals = FALSE, $apiEntity = NULL) {
1705 // skip a few search variables
1706 static $skipWhere = NULL;
1707 static $likeNames = NULL;
1710 // Change camelCase EntityName to lowercase with underscores
1711 $apiEntity = _civicrm_api_get_entity_name_from_camel($apiEntity);
1713 // check if $value is in OK (Operator as Key) format as used by Get API
1714 if (CRM_Utils_System
::isNull($values)) {
1726 'display_relationship_type',
1730 if (in_array($id, $skipWhere) ||
1731 substr($id, 0, 4) == '_qf_' ||
1732 substr($id, 0, 7) == 'hidden_'
1738 (substr($id, 0, strlen($apiEntity)) != $apiEntity) &&
1739 (substr($id, 0, 10) != 'financial_' && substr($id, 0, 8) != 'payment_') &&
1740 (substr($id, 0, 7) != 'custom_')
1742 $id = $apiEntity . '_' . $id;
1746 $likeNames = array('sort_name', 'email', 'note', 'display_name');
1749 // email comes in via advanced search
1750 // so use wildcard always
1751 if ($id == 'email') {
1755 if (!$useEquals && in_array($id, $likeNames)) {
1756 $result = array($id, 'LIKE', $values, 0, 1);
1758 elseif (is_string($values) && strpos($values, '%') !== FALSE) {
1759 $result = array($id, 'LIKE', $values, 0, 0);
1761 elseif ($id == 'contact_type' ||
1762 (!empty($values) && is_array($values) && !in_array(key($values), CRM_Core_DAO
::acceptedSQLOperators(), TRUE))
1764 $result = array($id, 'IN', $values, 0, $wildcard);
1767 $result = array($id, '=', $values, 0, $wildcard);
1774 * Get the where clause for a single field.
1776 * @param array $values
1777 * @param string $apiEntity
1779 public function whereClauseSingle(&$values, $apiEntity = NULL) {
1780 // do not process custom fields or prefixed contact ids or component params
1781 if (CRM_Core_BAO_CustomField
::getKeyID($values[0]) ||
1782 (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) ||
1783 (substr($values[0], 0, 13) == 'contribution_') ||
1784 (substr($values[0], 0, 6) == 'event_') ||
1785 (substr($values[0], 0, 12) == 'participant_') ||
1786 (substr($values[0], 0, 7) == 'member_') ||
1787 (substr($values[0], 0, 6) == 'grant_') ||
1788 (substr($values[0], 0, 7) == 'pledge_') ||
1789 (substr($values[0], 0, 5) == 'case_') ||
1790 (substr($values[0], 0, 10) == 'financial_') ||
1791 (substr($values[0], 0, 8) == 'payment_') ||
1792 (substr($values[0], 0, 11) == 'membership_')
1797 // skip for hook injected fields / params
1798 $extFields = CRM_Contact_BAO_Query_Hook
::singleton()->getFields();
1799 if (array_key_exists($values[0], $extFields)) {
1803 switch ($values[0]) {
1804 case 'deleted_contacts':
1805 $this->deletedContacts($values);
1808 case 'contact_sub_type':
1809 $this->contactSubType($values);
1814 $this->group($values);
1817 // case tag comes from find contacts
1819 $this->tagSearch($values);
1823 case 'contact_tags':
1824 $this->tag($values);
1829 case 'note_subject':
1830 $this->notes($values);
1834 $this->ufUser($values);
1838 case 'display_name':
1839 $this->sortName($values);
1843 case 'postal_greeting':
1844 case 'email_greeting':
1845 $this->greetings($values);
1850 $this->email($values, $apiEntity);
1853 case 'phone_numeric':
1854 $this->phone_numeric($values);
1857 case 'phone_phone_type_id':
1858 case 'phone_location_type_id':
1859 $this->phone_option_group($values);
1862 case 'street_address':
1863 $this->street_address($values);
1866 case 'street_number':
1867 $this->street_number($values);
1870 case 'sortByCharacter':
1871 $this->sortByCharacter($values);
1874 case 'location_type':
1875 $this->locationType($values);
1879 $this->county($values);
1882 case 'state_province':
1883 case 'state_province_id':
1884 case 'state_province_name':
1885 $this->stateProvince($values);
1890 $this->country($values, FALSE);
1894 case 'postal_code_low':
1895 case 'postal_code_high':
1896 $this->postalCode($values);
1899 case 'activity_date':
1900 case 'activity_date_low':
1901 case 'activity_date_high':
1902 case 'activity_role':
1903 case 'activity_status_id':
1904 case 'activity_status':
1905 case 'activity_priority':
1906 case 'activity_priority_id':
1907 case 'followup_parent_id':
1909 case 'source_contact_id':
1910 case 'activity_text':
1911 case 'activity_option':
1912 case 'test_activities':
1913 case 'activity_type_id':
1914 case 'activity_type':
1915 case 'activity_survey_id':
1916 case 'activity_tags':
1917 case 'activity_taglist':
1918 case 'activity_test':
1919 case 'activity_campaign_id':
1920 case 'activity_engagement_level':
1922 case 'activity_result':
1923 case 'source_contact':
1924 CRM_Activity_BAO_Query
::whereClauseSingle($values, $this);
1929 case 'birth_date_low':
1930 case 'birth_date_high':
1931 case 'deceased_date_low':
1932 case 'deceased_date_high':
1933 $this->demographics($values);
1936 case 'age_asof_date':
1937 // handled by demographics
1940 case 'log_date_low':
1941 case 'log_date_high':
1942 $this->modifiedDates($values);
1946 $this->changeLog($values);
1949 case 'do_not_phone':
1950 case 'do_not_email':
1953 case 'do_not_trade':
1955 $this->privacy($values);
1958 case 'privacy_options':
1959 $this->privacyOptions($values);
1962 case 'privacy_operator':
1963 case 'privacy_toggle':
1964 // these are handled by privacy options
1967 case 'preferred_communication_method':
1968 $this->preferredCommunication($values);
1971 case 'relation_type_id':
1972 case 'relation_start_date_high':
1973 case 'relation_start_date_low':
1974 case 'relation_end_date_high':
1975 case 'relation_end_date_low':
1976 case 'relation_active_period_date_high':
1977 case 'relation_active_period_date_low':
1978 case 'relation_target_name':
1979 case 'relation_status':
1980 case 'relation_date_low':
1981 case 'relation_date_high':
1982 $this->relationship($values);
1983 $this->_relationshipValuesAdded
= TRUE;
1986 case 'task_status_id':
1987 $this->task($values);
1991 // since this case is handled with the above
1994 case 'prox_distance':
1995 CRM_Contact_BAO_ProximityQuery
::process($this, $values);
1998 case 'prox_street_address':
2000 case 'prox_postal_code':
2001 case 'prox_state_province_id':
2002 case 'prox_country_id':
2003 case 'prox_geo_code_1':
2004 case 'prox_geo_code_2':
2005 // handled by the proximity_distance clause
2009 $this->restWhere($values);
2015 * Given a list of conditions in params generate the required where clause.
2017 * @param string $apiEntity
2021 public function whereClause($apiEntity = NULL) {
2022 $this->_where
[0] = array();
2023 $this->_qill
[0] = array();
2025 $this->includeContactIds();
2026 if (!empty($this->_params
)) {
2027 foreach (array_keys($this->_params
) as $id) {
2028 if (empty($this->_params
[$id][0])) {
2031 // check for both id and contact_id
2032 if ($this->_params
[$id][0] == 'id' ||
$this->_params
[$id][0] == 'contact_id') {
2033 $this->_where
[0][] = self
::buildClause("contact_a.id", $this->_params
[$id][1], $this->_params
[$id][2]);
2034 $field = CRM_Utils_Array
::value('id', $this->_fields
);
2035 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(
2036 'CRM_Contact_BAO_Contact',
2038 $this->_params
[$id][2],
2039 $this->_params
[$id][1]
2041 $this->_qill
[0][] = ts("%1 %2 %3", [
2042 1 => $field['title'],
2048 $this->whereClauseSingle($this->_params
[$id], $apiEntity);
2052 CRM_Core_Component
::alterQuery($this, 'where');
2054 CRM_Contact_BAO_Query_Hook
::singleton()->alterSearchQuery($this, 'where');
2057 if ($this->_customQuery
) {
2058 // Added following if condition to avoid the wrong value display for 'my account' / any UF info.
2059 // Hope it wont affect the other part of civicrm.. if it does please remove it.
2060 if (!empty($this->_customQuery
->_where
)) {
2061 $this->_where
= CRM_Utils_Array
::crmArrayMerge($this->_where
, $this->_customQuery
->_where
);
2064 $this->_qill
= CRM_Utils_Array
::crmArrayMerge($this->_qill
, $this->_customQuery
->_qill
);
2068 $andClauses = array();
2071 if (!empty($this->_where
)) {
2072 foreach ($this->_where
as $grouping => $values) {
2073 if ($grouping > 0 && !empty($values)) {
2074 $clauses[$grouping] = ' ( ' . implode(" {$this->_operator} ", $values) . ' ) ';
2079 if (!empty($this->_where
[0])) {
2080 $andClauses[] = ' ( ' . implode(" {$this->_operator} ", $this->_where
[0]) . ' ) ';
2082 if (!empty($clauses)) {
2083 $andClauses[] = ' ( ' . implode(' OR ', $clauses) . ' ) ';
2086 if ($validClauses > 1) {
2087 $this->_useDistinct
= TRUE;
2091 return implode(' AND ', $andClauses);
2095 * Generate where clause for any parameters not already handled.
2097 * @param array $values
2101 public function restWhere(&$values) {
2102 $name = CRM_Utils_Array
::value(0, $values);
2103 $op = CRM_Utils_Array
::value(1, $values);
2104 $value = CRM_Utils_Array
::value(2, $values);
2105 $grouping = CRM_Utils_Array
::value(3, $values);
2106 $wildcard = CRM_Utils_Array
::value(4, $values);
2108 if (isset($grouping) && empty($this->_where
[$grouping])) {
2109 $this->_where
[$grouping] = array();
2112 $multipleFields = array('url');
2114 //check if the location type exists for fields
2116 $locType = explode('-', $name);
2118 if (!in_array($locType[0], $multipleFields)) {
2119 //add phone type if exists
2120 if (isset($locType[2]) && $locType[2]) {
2121 $locType[2] = CRM_Core_DAO
::escapeString($locType[2]);
2125 $field = CRM_Utils_Array
::value($name, $this->_fields
);
2128 $field = CRM_Utils_Array
::value($locType[0], $this->_fields
);
2137 $locationType = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
2138 if (isset($locType[1]) && is_numeric($locType[1])) {
2139 $lType = $locationType[$locType[1]];
2142 $field['title'] .= " ($lType)";
2145 if (substr($name, 0, 14) === 'state_province') {
2146 if (isset($locType[1]) && is_numeric($locType[1])) {
2148 $aName = "{$lType}-address";
2149 $where = "`$aName`.state_province_id";
2152 $where = "civicrm_address.state_province_id";
2155 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value);
2156 $this->_tables
[$aName] = $this->_whereTables
[$aName] = 1;
2157 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
2158 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $field['title'], 2 => $qillop, 3 => $qillVal));
2160 elseif (!empty($field['pseudoconstant'])) {
2161 $this->optionValueQuery(
2162 $name, $op, $value, $grouping,
2163 'CRM_Contact_DAO_Contact',
2169 if ($name == 'gender_id') {
2170 self
::$_openedPanes[ts('Demographics')] = TRUE;
2173 elseif (substr($name, 0, 7) === 'country' ||
substr($name, 0, 6) === 'county') {
2174 $name = (substr($name, 0, 7) === 'country') ?
"country_id" : "county_id";
2175 if (isset($locType[1]) && is_numeric($locType[1])) {
2177 $aName = "{$lType}-address";
2178 $where = "`$aName`.$name";
2181 $where = "civicrm_address.$name";
2184 $this->_where
[$grouping][] = self
::buildClause($where, $op, $value, 'Positive');
2185 $this->_tables
[$aName] = $this->_whereTables
[$aName] = 1;
2187 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
2188 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $field['title'], 2 => $qillop, 3 => $qillVal));
2190 elseif ($name === 'world_region') {
2191 $this->optionValueQuery(
2192 $name, $op, $value, $grouping,
2200 elseif ($name === 'is_deceased') {
2201 $this->setQillAndWhere($name, $op, $value, $grouping, $field);
2202 self
::$_openedPanes[ts('Demographics')] = TRUE;
2204 elseif ($name === 'created_date' ||
$name === 'modified_date' ||
$name === 'deceased_date' ||
$name === 'birth_date') {
2205 $appendDateTime = TRUE;
2206 if ($name === 'deceased_date' ||
$name === 'birth_date') {
2207 $appendDateTime = FALSE;
2208 self
::$_openedPanes[ts('Demographics')] = TRUE;
2210 $this->dateQueryBuilder($values, 'contact_a', $name, $name, $field['title'], $appendDateTime);
2212 elseif ($name === 'contact_id') {
2213 if (is_int($value)) {
2214 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, $value);
2215 $this->_qill
[$grouping][] = "$field[title] $op $value";
2218 elseif ($name === 'name') {
2219 $value = CRM_Core_DAO
::escapeString($value);
2222 $value = self
::getWildCardedValue($wildcard, $op, $value);
2224 CRM_Core_Error
::deprecatedFunctionWarning('Untested code path');
2225 // @todo it's likely this code path is obsolete / never called. It is definitely not
2226 // passed through in our test suite.
2227 $this->_where
[$grouping][] = self
::buildClause($field['where'], $op, "'$value'");
2228 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2230 elseif ($name === 'current_employer') {
2233 $value = self
::getWildCardedValue($wildcard, $op, $value);
2235 $ceWhereClause = self
::buildClause("contact_a.organization_name", $op,
2238 $ceWhereClause .= " AND contact_a.contact_type = 'Individual'";
2239 $this->_where
[$grouping][] = $ceWhereClause;
2240 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2242 elseif ($name === 'email_greeting') {
2243 CRM_Core_Error
::deprecatedFunctionWarning('pass in email_greeting_id or email_greeting_display');
2244 $filterCondition = array('greeting_type' => 'email_greeting');
2245 $this->optionValueQuery(
2246 $name, $op, $value, $grouping,
2247 CRM_Core_PseudoConstant
::greeting($filterCondition),
2249 ts('Email Greeting')
2252 elseif ($name === 'postal_greeting') {
2253 CRM_Core_Error
::deprecatedFunctionWarning('pass in postal_greeting_id or postal_greeting_display');
2254 $filterCondition = array('greeting_type' => 'postal_greeting');
2255 $this->optionValueQuery(
2256 $name, $op, $value, $grouping,
2257 CRM_Core_PseudoConstant
::greeting($filterCondition),
2259 ts('Postal Greeting')
2262 elseif ($name === 'addressee') {
2263 CRM_Core_Error
::deprecatedFunctionWarning('pass in addressee_id or addressee_display');
2264 $filterCondition = array('greeting_type' => 'addressee');
2265 $this->optionValueQuery(
2266 $name, $op, $value, $grouping,
2267 CRM_Core_PseudoConstant
::greeting($filterCondition),
2272 elseif (substr($name, 0, 4) === 'url-') {
2273 $tName = 'civicrm_website';
2274 $this->_whereTables
[$tName] = $this->_tables
[$tName] = "\nLEFT JOIN civicrm_website ON ( civicrm_website.contact_id = contact_a.id )";
2275 $value = CRM_Core_DAO
::escapeString($value);
2278 $value = self
::getWildCardedValue($wildcard, $op, $value);
2281 $this->_where
[$grouping][] = $d = self
::buildClause('civicrm_website.url', $op, $value);
2282 $this->_qill
[$grouping][] = "$field[title] $op \"$value\"";
2284 elseif ($name === 'contact_is_deleted') {
2285 $this->setQillAndWhere('is_deleted', $op, $value, $grouping, $field);
2287 elseif (!empty($field['where'])) {
2289 if (!empty($field['type'])) {
2290 $type = CRM_Utils_Type
::typeToString($field['type']);
2293 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2295 if (isset($locType[1]) &&
2296 is_numeric($locType[1])
2300 //get the location name
2301 list($tName, $fldName) = self
::getLocationTableName($field['where'], $locType);
2302 $fieldName = "`$tName`.$fldName";
2304 // we set both _tables & whereTables because whereTables doesn't seem to do what the name implies it should
2305 $this->_tables
[$tName] = $this->_whereTables
[$tName] = 1;
2309 if ($tableName == 'civicrm_contact') {
2310 $fieldName = "contact_a.{$fieldName}";
2313 $fieldName = $field['where'];
2317 list($qillop, $qillVal) = self
::buildQillForFieldValue(NULL, $field['title'], $value, $op);
2318 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(
2319 1 => $field['title'],
2321 3 => (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) ?
$qillVal : "'$qillVal'"));
2323 if (is_array($value)) {
2324 // traditionally an array being passed has been a fatal error. We can take advantage of this to add support
2325 // for api style operators for functions that hit this point without worrying about regression
2326 // (the previous comments indicated the condition for hitting this point were unknown
2327 // per CRM-14743 we are adding modified_date & created_date operator support
2328 $operations = array_keys($value);
2329 foreach ($operations as $operator) {
2330 if (!in_array($operator, CRM_Core_DAO
::acceptedSQLOperators())) {
2331 //Via Contact get api value is not in array(operator => array(values)) format ONLY for IN/NOT IN operators
2332 //so this condition will satisfy the search for now
2333 if (strpos($op, 'IN') !== FALSE) {
2334 $value = array($op => $value);
2336 // we don't know when this might happen
2338 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", array(1 => $operator)));
2342 $this->_where
[$grouping][] = CRM_Core_DAO
::createSQLFilter($fieldName, $value, $type);
2347 $value = self
::getWildCardedValue($wildcard, $op, $value);
2350 $this->_where
[$grouping][] = self
::buildClause($fieldName, $op, $value, $type);
2354 if ($setTables && isset($field['where'])) {
2355 list($tableName, $fieldName) = explode('.', $field['where'], 2);
2356 if (isset($tableName)) {
2357 $this->_tables
[$tableName] = 1;
2358 $this->_whereTables
[$tableName] = 1;
2370 public static function getLocationTableName(&$where, &$locType) {
2371 if (isset($locType[1]) && is_numeric($locType[1])) {
2372 list($tbName, $fldName) = explode(".", $where);
2374 //get the location name
2375 $locationType = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
2376 $specialFields = array('email', 'im', 'phone', 'openid', 'phone_ext');
2377 if (in_array($locType[0], $specialFields)) {
2378 //hack to fix / special handing for phone_ext
2379 if ($locType[0] == 'phone_ext') {
2380 $locType[0] = 'phone';
2382 if (isset($locType[2]) && $locType[2]) {
2383 $tName = "{$locationType[$locType[1]]}-{$locType[0]}-{$locType[2]}";
2386 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2389 elseif (in_array($locType[0],
2394 'street_number_suffix',
2396 'supplemental_address_1',
2397 'supplemental_address_2',
2398 'supplemental_address_3',
2401 'postal_code_suffix',
2407 //fix for search by profile with address fields.
2408 $tName = "{$locationType[$locType[1]]}-address";
2410 elseif (in_array($locType[0],
2418 $tName = "{$locationType[$locType[1]]}-email";
2420 elseif ($locType[0] == 'provider_id') {
2421 $tName = "{$locationType[$locType[1]]}-im";
2423 elseif ($locType[0] == 'openid') {
2424 $tName = "{$locationType[$locType[1]]}-openid";
2427 $tName = "{$locationType[$locType[1]]}-{$locType[0]}";
2429 $tName = str_replace(' ', '_', $tName);
2430 return array($tName, $fldName);
2432 CRM_Core_Error
::fatal();
2436 * Given a result dao, extract the values and return that array
2438 * @param CRM_Core_DAO $dao
2441 * values for this query
2443 public function store($dao) {
2446 foreach ($this->_element
as $key => $dontCare) {
2447 if (property_exists($dao, $key)) {
2448 if (strpos($key, '-') !== FALSE) {
2449 $values = explode('-', $key);
2450 $lastElement = array_pop($values);
2452 $cnt = count($values);
2454 foreach ($values as $v) {
2455 if (!array_key_exists($v, $current)) {
2456 $current[$v] = array();
2458 //bad hack for im_provider
2459 if ($lastElement == 'provider_id') {
2460 if ($count < $cnt) {
2461 $current = &$current[$v];
2464 $lastElement = "{$v}_{$lastElement}";
2468 $current = &$current[$v];
2473 $current[$lastElement] = $dao->$key;
2476 $value[$key] = $dao->$key;
2484 * Getter for tables array.
2488 public function tables() {
2489 return $this->_tables
;
2493 * Sometimes used to create the from clause, but, not reliably, set
2494 * this AND set tables.
2496 * It's unclear the intent - there is a 'simpleFrom' clause which
2497 * takes whereTables into account & a fromClause which doesn't.
2499 * logic may have eroded?
2503 public function whereTables() {
2504 return $this->_whereTables
;
2508 * Generate the where clause (used in match contacts and permissions)
2510 * @param array $params
2511 * @param array $fields
2512 * @param array $tables
2513 * @param $whereTables
2514 * @param bool $strict
2518 public static function getWhereClause($params, $fields, &$tables, &$whereTables, $strict = FALSE) {
2519 $query = new CRM_Contact_BAO_Query($params, NULL, $fields,
2523 $tables = array_merge($query->tables(), $tables);
2524 $whereTables = array_merge($query->whereTables(), $whereTables);
2526 return $query->_whereClause
;
2530 * Create the from clause.
2532 * @param array $tables
2533 * Tables that need to be included in this from clause. If null,
2534 * return mimimal from clause (i.e. civicrm_contact).
2535 * @param array $inner
2536 * Tables that should be inner-joined.
2537 * @param array $right
2538 * Tables that should be right-joined.
2539 * @param bool $primaryLocation
2540 * Search on primary location. See note below.
2542 * Determines search mode based on bitwise MODE_* constants.
2543 * @param string|NULL $apiEntity
2544 * Determines search mode based on entity by string.
2546 * The $primaryLocation flag only seems to be used when
2547 * locationType() has been called. This may be a search option
2548 * exposed, or perhaps it's a "search all details" approach which
2549 * predates decoupling of location types and primary fields?
2551 * @see https://issues.civicrm.org/jira/browse/CRM-19967
2556 public static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1, $apiEntity = NULL) {
2558 $from = ' FROM civicrm_contact contact_a';
2559 if (empty($tables)) {
2563 if (!empty($tables['civicrm_worldregion'])) {
2564 $tables = array_merge(array('civicrm_country' => 1), $tables);
2567 if ((!empty($tables['civicrm_state_province']) ||
!empty($tables['civicrm_country']) ||
2568 CRM_Utils_Array
::value('civicrm_county', $tables)
2569 ) && empty($tables['civicrm_address'])
2571 $tables = array_merge(array('civicrm_address' => 1),
2576 // add group_contact and group table is subscription history is present
2577 if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) {
2578 $tables = array_merge(array(
2579 'civicrm_group' => 1,
2580 'civicrm_group_contact' => 1,
2586 // to handle table dependencies of components
2587 CRM_Core_Component
::tableNames($tables);
2588 // to handle table dependencies of hook injected tables
2589 CRM_Contact_BAO_Query_Hook
::singleton()->setTableDependency($tables);
2591 //format the table list according to the weight
2592 $info = CRM_Core_TableHierarchy
::info();
2594 foreach ($tables as $key => $value) {
2596 if (strpos($key, '-') !== FALSE) {
2597 $keyArray = explode('-', $key);
2598 $k = CRM_Utils_Array
::value('civicrm_' . $keyArray[1], $info, 99);
2600 elseif (strpos($key, '_') !== FALSE) {
2601 $keyArray = explode('_', $key);
2602 if (is_numeric(array_pop($keyArray))) {
2603 $k = CRM_Utils_Array
::value(implode('_', $keyArray), $info, 99);
2606 $k = CRM_Utils_Array
::value($key, $info, 99);
2610 $k = CRM_Utils_Array
::value($key, $info, 99);
2612 $tempTable[$k . ".$key"] = $key;
2615 $newTables = array();
2616 foreach ($tempTable as $key) {
2617 $newTables[$key] = $tables[$key];
2620 $tables = $newTables;
2622 foreach ($tables as $name => $value) {
2627 if (!empty($inner[$name])) {
2630 elseif (!empty($right[$name])) {
2638 // if there is already a join statement in value, use value itself
2639 if (strpos($value, 'JOIN')) {
2640 $from .= " $value ";
2643 $from .= " $side JOIN $name ON ( $value ) ";
2648 $from .= self
::getEntitySpecificJoins($name, $mode, $side, $primaryLocation);
2654 * Get join statements for the from clause depending on entity type
2656 * @param string $name
2658 * @param string $side
2659 * @param string $primaryLocation
2662 protected static function getEntitySpecificJoins($name, $mode, $side, $primaryLocation) {
2663 $limitToPrimaryClause = $primaryLocation ?
"AND {$name}.is_primary = 1" : '';
2665 case 'civicrm_address':
2666 //CRM-14263 further handling of address joins further down...
2667 return " $side JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id {$limitToPrimaryClause} )";
2669 case 'civicrm_phone':
2670 return " $side JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id {$limitToPrimaryClause}) ";
2672 case 'civicrm_email':
2673 return " $side JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id {$limitToPrimaryClause})";
2676 return " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id {$limitToPrimaryClause}) ";
2679 $from = " $side JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) ";
2680 $from .= " $side JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'";
2681 $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)";
2684 case 'civicrm_openid':
2685 return " $side JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id {$limitToPrimaryClause} )";
2687 case 'civicrm_worldregion':
2688 $from = " $side JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id ";
2689 return "$from $side JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id ";
2691 case 'civicrm_location_type':
2692 return " $side JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id ";
2694 case 'civicrm_group':
2695 return " $side JOIN civicrm_group ON civicrm_group.id = civicrm_group_contact.group_id ";
2697 case 'civicrm_group_contact':
2698 return " $side JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id ";
2700 case 'civicrm_group_contact_cache':
2701 return " $side JOIN civicrm_group_contact_cache ON contact_a.id = civicrm_group_contact_cache.contact_id ";
2703 case 'civicrm_activity':
2704 case 'civicrm_activity_tag':
2705 case 'activity_type':
2706 case 'activity_status':
2708 case 'civicrm_activity_contact':
2709 case 'source_contact':
2710 case 'activity_priority':
2711 return CRM_Activity_BAO_Query
::from($name, $mode, $side);
2713 case 'civicrm_entity_tag':
2714 $from = " $side JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact'";
2715 return "$from AND civicrm_entity_tag.entity_id = contact_a.id ) ";
2717 case 'civicrm_note':
2718 $from = " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact'";
2719 return "$from AND contact_a.id = civicrm_note.entity_id ) ";
2721 case 'civicrm_subscription_history':
2722 $from = " $side JOIN civicrm_subscription_history";
2723 $from .= " ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id";
2724 return "$from AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id";
2726 case 'civicrm_relationship':
2727 if (self
::$_relType == 'reciprocal') {
2728 if (self
::$_relationshipTempTable) {
2729 // we have a temptable to join on
2730 $tbl = self
::$_relationshipTempTable;
2731 return " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id";
2734 $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)";
2735 $from .= " $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id OR civicrm_relationship.contact_id_b = contact_b.id)";
2739 elseif (self
::$_relType == 'b') {
2740 $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )";
2741 return "$from $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )";
2744 $from = " $side JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )";
2745 return "$from $side JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )";
2749 $from = " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')";
2750 return "$from INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)";
2753 return " $side JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id ";
2755 case 'civicrm_grant':
2756 return CRM_Grant_BAO_Query
::from($name, $mode, $side);
2758 case 'civicrm_website':
2759 return " $side JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id ";
2761 case 'civicrm_campaign':
2762 //Move to default case if not in either mode.
2763 if ($mode & CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
2764 return CRM_Contribute_BAO_Query
::from($name, $mode, $side);
2766 elseif ($mode & CRM_Contact_BAO_Query
::MODE_MAILING
) {
2767 return CRM_Mailing_BAO_Query
::from($name, $mode, $side);
2769 elseif ($mode & CRM_Contact_BAO_Query
::MODE_CAMPAIGN
) {
2770 return CRM_Campaign_BAO_Query
::from($name, $mode, $side);
2774 $locationTypeName = '';
2775 if (strpos($name, '-address') != 0) {
2776 $locationTypeName = 'address';
2778 elseif (strpos($name, '-phone') != 0) {
2779 $locationTypeName = 'phone';
2781 elseif (strpos($name, '-email') != 0) {
2782 $locationTypeName = 'email';
2784 elseif (strpos($name, '-im') != 0) {
2785 $locationTypeName = 'im';
2787 elseif (strpos($name, '-openid') != 0) {
2788 $locationTypeName = 'openid';
2791 if ($locationTypeName) {
2792 //we have a join on an location table - possibly in conjunction with search builder - CRM-14263
2793 $parts = explode('-', $name);
2794 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
2795 foreach ($locationTypes as $locationTypeID => $locationType) {
2796 if ($parts[0] == str_replace(' ', '_', $locationType)) {
2797 $locationID = $locationTypeID;
2800 $from = " $side JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = $locationID ";
2803 $from = CRM_Core_Component
::from($name, $mode, $side);
2805 $from .= CRM_Contact_BAO_Query_Hook
::singleton()->buildSearchfrom($name, $mode, $side);
2812 * WHERE / QILL clause for deleted_contacts
2814 * @param array $values
2816 public function deletedContacts($values) {
2817 list($_, $_, $value, $grouping, $_) = $values;
2819 // *prepend* to the relevant grouping as this is quite an important factor
2820 array_unshift($this->_qill
[$grouping], ts('Search in Trash'));
2825 * Where / qill clause for contact_type
2829 public function contactType(&$values) {
2830 list($name, $op, $value, $grouping, $wildcard) = $values;
2832 $subTypes = array();
2835 // account for search builder mapping multiple values
2836 if (!is_array($value)) {
2837 $values = self
::parseSearchBuilderString($value, 'String');
2838 if (is_array($values)) {
2839 $value = array_flip($values);
2843 if (is_array($value)) {
2844 foreach ($value as $k => $v) {
2849 if (strpos($k, CRM_Core_DAO
::VALUE_SEPARATOR
)) {
2850 list($contactType, $subType) = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $k, 2);
2853 if (!empty($subType)) {
2854 $subTypes[$subType] = 1;
2856 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2861 $contactTypeANDSubType = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value, 2);
2862 $contactType = $contactTypeANDSubType[0];
2863 $subType = CRM_Utils_Array
::value(1, $contactTypeANDSubType);
2864 if (!empty($subType)) {
2865 $subTypes[$subType] = 1;
2867 $clause[$contactType] = "'" . CRM_Utils_Type
::escape($contactType, 'String') . "'";
2871 if (!empty($clause)) {
2873 if ($op == 'IN' ||
$op == 'NOT IN') {
2874 $this->_where
[$grouping][] = "contact_a.contact_type $op (" . implode(',', $clause) . ')';
2877 $type = array_pop($clause);
2878 $this->_where
[$grouping][] = self
::buildClause("contact_a.contact_type", $op, $contactType);
2881 $this->_qill
[$grouping][] = ts('Contact Type') . " $op " . implode(' ' . ts('or') . ' ', $quill);
2883 if (!empty($subTypes)) {
2884 $this->includeContactSubTypes($subTypes, $grouping);
2890 * Where / qill clause for contact_sub_type.
2892 * @param array $values
2894 public function contactSubType(&$values) {
2895 list($name, $op, $value, $grouping, $wildcard) = $values;
2896 $this->includeContactSubTypes($value, $grouping, $op);
2904 public function includeContactSubTypes($value, $grouping, $op = 'LIKE') {
2906 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2908 $value = $value[$op];
2912 $alias = "contact_a.contact_sub_type";
2913 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
2915 $op = str_replace('IN', 'LIKE', $op);
2916 $op = str_replace('=', 'LIKE', $op);
2917 $op = str_replace('!', 'NOT ', $op);
2919 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
2920 $this->_where
[$grouping][] = self
::buildClause($alias, $op, $value, 'String');
2922 elseif (is_array($value)) {
2923 foreach ($value as $k => $v) {
2924 $clause[$k] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($v, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2928 $clause[$value] = "($alias $op '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. CRM_Utils_Type
::escape($value, 'String') . CRM_Core_DAO
::VALUE_SEPARATOR
. "%')";
2931 if (!empty($clause)) {
2932 $this->_where
[$grouping][] = "( " . implode(' OR ', $clause) . " )";
2934 $this->_qill
[$grouping][] = ts('Contact Subtype %1 ', array(1 => $qillOperators[$op])) . implode(' ' . ts('or') . ' ', array_keys($clause));
2938 * Where / qill clause for groups.
2942 public function group($values) {
2943 list($name, $op, $value, $grouping, $wildcard) = $values;
2945 // If the $value is in OK (operator as key) array format we need to extract the key as operator and value first
2946 if (is_array($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
2948 $value = $value[$op];
2951 // Replace pseudo operators from search builder
2952 $op = str_replace('EMPTY', 'NULL', $op);
2954 if (strpos($op, 'NULL')) {
2958 if (is_array($value) && count($value) > 1) {
2959 if (strpos($op, 'IN') === FALSE && strpos($op, 'NULL') === FALSE) {
2960 CRM_Core_Error
::fatal(ts("%1 is not a valid operator", array(1 => $op)));
2962 $this->_useDistinct
= TRUE;
2965 if (isset($value)) {
2966 $value = CRM_Utils_Array
::value($op, $value, $value);
2969 if ($name == 'group_type') {
2970 $value = array_keys($this->getGroupsFromTypeCriteria($value));
2973 $regularGroupIDs = $smartGroupIDs = array();
2974 foreach ((array) $value as $id) {
2975 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
2976 $smartGroupIDs[] = $id;
2979 $regularGroupIDs[] = trim($id);
2983 $isNotOp = ($op == 'NOT IN' ||
$op == '!=');
2986 $gcsValues = $this->getWhereValues('group_contact_status', $grouping);
2988 is_array($gcsValues[2])
2990 foreach ($gcsValues[2] as $k => $v) {
2992 $statii[] = "'" . CRM_Utils_Type
::escape($k, 'String') . "'";
2997 $statii[] = "'Added'";
2999 $groupClause = array();
3000 if (count($regularGroupIDs) ||
empty($value)) {
3001 // include child groups IDs if any
3002 $childGroupIds = (array) CRM_Contact_BAO_Group
::getChildGroupIds($regularGroupIDs);
3003 foreach ($childGroupIds as $key => $id) {
3004 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $id, 'saved_search_id')) {
3005 $smartGroupIDs[] = $id;
3006 unset($childGroupIds[$key]);
3009 if (count($childGroupIds)) {
3010 $regularGroupIDs = array_merge($regularGroupIDs, $childGroupIds);
3013 // if $regularGroupIDs is populated with regular child group IDs
3014 // then change the mysql operator to desired
3015 if (count($regularGroupIDs) > 1) {
3016 $op = strpos($op, 'IN') ?
$op : ($op == '!=') ?
'NOT IN' : 'IN';
3019 if (!empty($regularGroupIDs)) {
3020 $groupIds = CRM_Utils_Type
::validate(
3021 implode(',', (array) $regularGroupIDs),
3022 'CommaSeparatedIntegers'
3025 $gcTable = "`civicrm_group_contact-" . uniqid() . "`";
3026 $joinClause = array("contact_a.id = {$gcTable}.contact_id");
3028 if (strpos($op, 'IN') !== FALSE) {
3029 $clause = "{$gcTable}.group_id $op ( $groupIds ) ";
3031 elseif ($op == '!=') {
3032 $clause = "{$gcTable}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact cgc WHERE cgc.group_id = $groupIds )";
3035 $clause = "{$gcTable}.group_id $op $groupIds ";
3037 $groupClause[] = "( {$clause} )";
3040 $joinClause[] = "{$gcTable}.status IN (" . implode(', ', $statii) . ")";
3042 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
3045 //CRM-19589: contact(s) removed from a Smart Group, resides in civicrm_group_contact table
3046 $groupContactCacheClause = '';
3047 if (count($smartGroupIDs) ||
empty($value)) {
3048 $this->_groupUniqueKey
= uniqid();
3049 $this->_groupKeys
[] = $this->_groupUniqueKey
;
3050 $gccTableAlias = "civicrm_group_contact_cache_{$this->_groupUniqueKey}";
3051 $groupContactCacheClause = $this->addGroupContactCache($smartGroupIDs, $gccTableAlias, "contact_a", $op);
3052 if (!empty($groupContactCacheClause)) {
3054 $groupIds = implode(',', (array) $smartGroupIDs);
3055 $gcTable = "civicrm_group_contact_{$this->_groupUniqueKey}";
3056 $joinClause = array("contact_a.id = {$gcTable}.contact_id");
3057 $this->_tables
[$gcTable] = $this->_whereTables
[$gcTable] = " LEFT JOIN civicrm_group_contact {$gcTable} ON (" . implode(' AND ', $joinClause) . ")";
3058 if (strpos($op, 'IN') !== FALSE) {
3059 $groupClause[] = "{$gcTable}.group_id $op ( $groupIds ) AND {$gccTableAlias}.group_id IS NULL";
3062 $groupClause[] = "{$gcTable}.group_id $op $groupIds AND {$gccTableAlias}.group_id IS NULL";
3065 $groupClause[] = " ( {$groupContactCacheClause} ) ";
3069 $and = ($op == 'IS NULL') ?
' AND ' : ' OR ';
3070 if (!empty($groupClause)) {
3071 $this->_where
[$grouping][] = ' ( ' . implode($and, $groupClause) . ' ) ';
3074 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Group', 'id', $value, $op);
3075 $this->_qill
[$grouping][] = ts("Group(s) %1 %2", array(1 => $qillop, 2 => $qillVal));
3076 if (strpos($op, 'NULL') === FALSE) {
3077 $this->_qill
[$grouping][] = ts("Group Status %1", array(1 => implode(' ' . ts('or') . ' ', $statii)));
3081 public function getGroupCacheTableKeys() {
3082 return $this->_groupKeys
;
3086 * Function translates selection of group type into a list of groups.
3091 public function getGroupsFromTypeCriteria($value) {
3092 $groupIds = array();
3093 foreach ((array) $value as $groupTypeValue) {
3094 $groupList = CRM_Core_PseudoConstant
::group($groupTypeValue);
3095 $groupIds = ($groupIds +
$groupList);
3101 * Prime smart group cache for smart groups in the search, and join
3102 * civicrm_group_contact_cache table into the query.
3104 * @param array $groups IDs of groups specified in search criteria.
3105 * @param string $tableAlias Alias to use for civicrm_group_contact_cache table.
3106 * @param string $joinTable Table on which to join civicrm_group_contact_cache
3107 * @param string $op SQL comparison operator (NULL, IN, !=, IS NULL, etc.)
3108 * @param string $joinColumn Column in $joinTable on which to join civicrm_group_contact_cache.contact_id
3110 * @return string WHERE clause component for smart group criteria.
3112 public function addGroupContactCache($groups, $tableAlias, $joinTable = "contact_a", $op, $joinColumn = 'id') {
3113 $isNullOp = (strpos($op, 'NULL') !== FALSE);
3114 $groupsIds = $groups;
3116 $operator = ['=' => 'IN', '!=' => 'NOT IN'];
3117 if (!empty($operator[$op]) && is_array($groups)) {
3118 $op = $operator[$op];
3120 if (!$isNullOp && !$groups) {
3123 elseif (strpos($op, 'IN') !== FALSE) {
3124 $groups = array($op => $groups);
3126 elseif (is_array($groups) && count($groups)) {
3127 $groups = array('IN' => $groups);
3130 // Find all the groups that are part of a saved search.
3131 $smartGroupClause = self
::buildClause("id", $op, $groups, 'Int');
3133 SELECT id, cache_date, saved_search_id, children
3135 WHERE $smartGroupClause
3136 AND ( saved_search_id != 0
3137 OR saved_search_id IS NOT NULL
3138 OR children IS NOT NULL )
3141 $group = CRM_Core_DAO
::executeQuery($sql);
3143 while ($group->fetch()) {
3144 $this->_useDistinct
= TRUE;
3145 if (!$this->_smartGroupCache ||
$group->cache_date
== NULL) {
3146 CRM_Contact_BAO_GroupContactCache
::load($group);
3149 if ($group->N
== 0 && $op != 'NOT IN') {
3153 $this->_tables
[$tableAlias] = $this->_whereTables
[$tableAlias] = " LEFT JOIN civicrm_group_contact_cache {$tableAlias} ON {$joinTable}.{$joinColumn} = {$tableAlias}.contact_id ";
3155 if ($op == 'NOT IN') {
3156 return "{$tableAlias}.contact_id NOT IN (SELECT contact_id FROM civicrm_group_contact_cache cgcc WHERE cgcc.group_id IN ( " . implode(',', (array) $groupsIds) . " ) )";
3158 return self
::buildClause("{$tableAlias}.group_id", $op, $groups, 'Int');
3162 * Where / qill clause for cms users
3166 public function ufUser(&$values) {
3167 list($name, $op, $value, $grouping, $wildcard) = $values;
3170 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' INNER JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3172 $this->_qill
[$grouping][] = ts('CMS User');
3174 elseif ($value == 0) {
3175 $this->_tables
['civicrm_uf_match'] = $this->_whereTables
['civicrm_uf_match'] = ' LEFT JOIN civicrm_uf_match ON civicrm_uf_match.contact_id = contact_a.id ';
3177 $this->_where
[$grouping][] = " civicrm_uf_match.contact_id IS NULL";
3178 $this->_qill
[$grouping][] = ts('Not a CMS User');
3183 * All tag search specific.
3185 * @param array $values
3187 public function tagSearch(&$values) {
3188 list($name, $op, $value, $grouping, $wildcard) = $values;
3191 $value = "%{$value}%";
3192 $escapedValue = CRM_Utils_Type
::escape("%{$value}%", 'String');
3194 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3195 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3197 $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
3198 $tTable = "`civicrm_tag-" . uniqid() . "`";
3200 if ($useAllTagTypes[2]) {
3201 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3202 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id)
3203 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id )";
3205 // search tag in cases
3206 $etCaseTable = "`civicrm_entity_case_tag-" . uniqid() . "`";
3207 $tCaseTable = "`civicrm_case_tag-" . uniqid() . "`";
3208 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3209 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3210 LEFT JOIN civicrm_case
3211 ON (civicrm_case_contact.case_id = civicrm_case.id
3212 AND civicrm_case.is_deleted = 0 )
3213 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id )
3214 LEFT JOIN civicrm_tag {$tCaseTable} ON ( {$etCaseTable}.tag_id = {$tCaseTable}.id )";
3215 // search tag in activities
3216 $etActTable = "`civicrm_entity_act_tag-" . uniqid() . "`";
3217 $tActTable = "`civicrm_act_tag-" . uniqid() . "`";
3218 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
3219 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3221 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3222 = " LEFT JOIN civicrm_activity_contact
3223 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3224 LEFT JOIN civicrm_activity
3225 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3226 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3227 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id )
3228 LEFT JOIN civicrm_tag {$tActTable} ON ( {$etActTable}.tag_id = {$tActTable}.id )";
3230 $this->_where
[$grouping][] = "({$tTable}.name $op '" . $escapedValue . "' OR {$tCaseTable}.name $op '" . $escapedValue . "' OR {$tActTable}.name $op '" . $escapedValue . "')";
3231 $this->_qill
[$grouping][] = ts('Tag %1 %2', array(1 => $tagTypesText[2], 2 => $op)) . ' ' . $value;
3234 $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
3235 $tTable = "`civicrm_tag-" . uniqid() . "`";
3236 $this->_tables
[$etTable] = $this->_whereTables
[$etTable] = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND
3237 {$etTable}.entity_table = 'civicrm_contact' )
3238 LEFT JOIN civicrm_tag {$tTable} ON ( {$etTable}.tag_id = {$tTable}.id ) ";
3240 $this->_where
[$grouping][] = self
::buildClause("{$tTable}.name", $op, $value, 'String');
3241 $this->_qill
[$grouping][] = ts('Tagged %1', array(1 => $op)) . ' ' . $value;
3246 * Where / qill clause for tag.
3248 * @param array $values
3250 public function tag(&$values) {
3251 list($name, $op, $value, $grouping, $wildcard) = $values;
3253 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_EntityTag', "tag_id", $value, $op, array('onlyActive' => FALSE));
3254 // API/Search Builder format array(operator => array(values))
3255 if (is_array($value)) {
3256 if (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
3258 $value = $value[$op];
3260 if (count($value) > 1) {
3261 $this->_useDistinct
= TRUE;
3265 // implode array, then remove all spaces
3266 $value = str_replace(' ', '', implode(',', (array) $value));
3267 if (!empty($value)) {
3268 $value = CRM_Utils_Type
::validate(
3270 'CommaSeparatedIntegers'
3274 $useAllTagTypes = $this->getWhereValues('all_tag_types', $grouping);
3275 $tagTypesText = $this->getWhereValues('tag_types_text', $grouping);
3277 $etTable = "`civicrm_entity_tag-" . uniqid() . "`";
3279 if ($useAllTagTypes[2]) {
3280 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3281 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3283 // search tag in cases
3284 $etCaseTable = "`civicrm_entity_case_tag-" . uniqid() . "`";
3285 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
3286 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
3288 $this->_tables
[$etCaseTable] = $this->_whereTables
[$etCaseTable]
3289 = " LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
3290 LEFT JOIN civicrm_case
3291 ON (civicrm_case_contact.case_id = civicrm_case.id
3292 AND civicrm_case.is_deleted = 0 )
3293 LEFT JOIN civicrm_entity_tag {$etCaseTable} ON ( {$etCaseTable}.entity_table = 'civicrm_case' AND {$etCaseTable}.entity_id = civicrm_case.id ) ";
3294 // search tag in activities
3295 $etActTable = "`civicrm_entity_act_tag-" . uniqid() . "`";
3296 $this->_tables
[$etActTable] = $this->_whereTables
[$etActTable]
3297 = " LEFT JOIN civicrm_activity_contact
3298 ON ( civicrm_activity_contact.contact_id = contact_a.id AND civicrm_activity_contact.record_type_id = {$targetID} )
3299 LEFT JOIN civicrm_activity
3300 ON ( civicrm_activity.id = civicrm_activity_contact.activity_id
3301 AND civicrm_activity.is_deleted = 0 AND civicrm_activity.is_current_revision = 1 )
3302 LEFT JOIN civicrm_entity_tag as {$etActTable} ON ( {$etActTable}.entity_table = 'civicrm_activity' AND {$etActTable}.entity_id = civicrm_activity.id ) ";
3305 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3306 $this->_where
[$grouping][] = "({$etTable}.tag_id $op OR {$etCaseTable}.tag_id $op OR {$etActTable}.tag_id $op)";
3309 $this->_where
[$grouping][] = "({$etTable}.tag_id $op (" . $value . ") OR {$etCaseTable}.tag_id $op (" . $value . ") OR {$etActTable}.tag_id $op (" . $value . "))";
3313 $this->_tables
[$etTable] = $this->_whereTables
[$etTable]
3314 = " LEFT JOIN civicrm_entity_tag {$etTable} ON ( {$etTable}.entity_id = contact_a.id AND {$etTable}.entity_table = 'civicrm_contact') ";
3317 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3318 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3319 $op = str_replace('EMPTY', 'NULL', $op);
3320 $this->_where
[$grouping][] = "{$etTable}.tag_id $op";
3322 // CRM-16941: for tag tried with != operator we don't show contact who don't have given $value AND also in other tag
3323 elseif ($op == '!=') {
3324 $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') . ")";
3326 elseif ($op == '=' ||
strstr($op, 'IN')) {
3327 $op = ($op == '=') ?
'IN' : $op;
3328 $this->_where
[$grouping][] = "{$etTable}.tag_id $op ( $value )";
3331 $this->_qill
[$grouping][] = ts('Tagged %1 %2', array(1 => $qillop, 2 => $qillVal));
3335 * Where/qill clause for notes
3337 * @param array $values
3339 public function notes(&$values) {
3340 list($name, $op, $value, $grouping, $wildcard) = $values;
3342 $noteOptionValues = $this->getWhereValues('note_option', $grouping);
3343 $noteOption = CRM_Utils_Array
::value('2', $noteOptionValues, '6');
3344 $noteOption = ($name == 'note_body') ?
2 : (($name == 'note_subject') ?
3 : $noteOption);
3346 $this->_useDistinct
= TRUE;
3348 $this->_tables
['civicrm_note'] = $this->_whereTables
['civicrm_note']
3349 = " LEFT JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND contact_a.id = civicrm_note.entity_id ) ";
3352 $value = CRM_Core_DAO
::escapeString($n);
3354 if (strpos($value, '%') === FALSE) {
3355 $value = "%$value%";
3359 elseif ($op == 'IS NULL' ||
$op == 'IS NOT NULL') {
3365 if ($noteOption %
2 == 0) {
3366 $clauses[] = self
::buildClause('civicrm_note.note', $op, $value, 'String');
3367 $label = ts('Note: Body Only');
3369 if ($noteOption %
3 == 0) {
3370 $clauses[] = self
::buildClause('civicrm_note.subject', $op, $value, 'String');
3371 $label = $label ?
ts('Note: Body and Subject') : ts('Note: Subject Only');
3373 $this->_where
[$grouping][] = "( " . implode(' OR ', $clauses) . " )";
3374 list($qillOp, $qillVal) = self
::buildQillForFieldValue(NULL, $name, $n, $op);
3375 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $label, 2 => $qillOp, 3 => $qillVal));
3379 * @param string $name
3385 public function nameNullOrEmptyOp($name, $op, $grouping) {
3389 $this->_where
[$grouping][] = "contact_a.$name $op";
3390 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3394 $this->_where
[$grouping][] = "(contact_a.$name IS NULL OR contact_a.$name = '')";
3395 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3398 case 'IS NOT EMPTY':
3399 $this->_where
[$grouping][] = "(contact_a.$name IS NOT NULL AND contact_a.$name <> '')";
3400 $this->_qill
[$grouping][] = ts('Name') . ' ' . $op;
3409 * Where / qill clause for sort_name
3411 * @param array $values
3413 public function sortName(&$values) {
3414 list($fieldName, $op, $value, $grouping, $wildcard) = $values;
3416 // handle IS NULL / IS NOT NULL / IS EMPTY / IS NOT EMPTY
3417 if ($this->nameNullOrEmptyOp($fieldName, $op, $grouping)) {
3421 $input = $value = trim($value);
3423 if (!strlen($value)) {
3427 $config = CRM_Core_Config
::singleton();
3431 //By default, $sub elements should be joined together with OR statements (don't change this variable).
3434 $firstChar = substr($value, 0, 1);
3435 $lastChar = substr($value, -1, 1);
3436 $quotes = array("'", '"');
3437 // If string is quoted, strip quotes and otherwise don't alter it
3438 if ((strlen($value) > 2) && in_array($firstChar, $quotes) && in_array($lastChar, $quotes)) {
3439 $value = trim($value, implode('', $quotes));
3441 // Replace spaces with wildcards for a LIKE operation
3442 // UNLESS string contains a comma (this exception is a tiny bit questionable)
3443 elseif ($op == 'LIKE' && strpos($value, ',') === FALSE) {
3444 $value = str_replace(' ', '%', $value);
3446 $value = CRM_Core_DAO
::escapeString(trim($value));
3447 if (strlen($value)) {
3448 $fieldsub = array();
3449 $value = "'" . self
::getWildCardedValue($wildcard, $op, $value) . "'";
3450 if ($fieldName == 'sort_name') {
3451 $wc = "contact_a.sort_name";
3454 $wc = "contact_a.display_name";
3456 $fieldsub[] = " ( $wc $op $value )";
3457 if ($config->includeNickNameInName
) {
3458 $wc = "contact_a.nick_name";
3459 $fieldsub[] = " ( $wc $op $value )";
3461 if ($config->includeEmailInName
) {
3462 $fieldsub[] = " ( civicrm_email.email $op $value ) ";
3464 $sub[] = ' ( ' . implode(' OR ', $fieldsub) . ' ) ';
3467 $sub = ' ( ' . implode($subGlue, $sub) . ' ) ';
3469 $this->_where
[$grouping][] = $sub;
3470 if ($config->includeEmailInName
) {
3471 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3472 $this->_qill
[$grouping][] = ts('Name or Email') . " $op - '$input'";
3475 $this->_qill
[$grouping][] = ts('Name') . " $op - '$input'";
3480 * Where/qill clause for greeting fields.
3482 * @param array $values
3484 public function greetings(&$values) {
3485 list($name, $op, $value, $grouping, $wildcard) = $values;
3486 $name .= '_display';
3488 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
3489 $this->_qill
[$grouping][] = ts('Greeting %1 %2', array(1 => $qillop, 2 => $qillVal));
3490 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value, 'String');
3494 * Where / qill clause for email
3496 * @param array $values
3497 * @param string $apiEntity
3499 protected function email(&$values, $apiEntity) {
3500 list($name, $op, $value, $grouping, $wildcard) = $values;
3501 $this->_tables
['civicrm_email'] = $this->_whereTables
['civicrm_email'] = 1;
3503 // CRM-18147: for Contact's GET API, email fieldname got appended with its entity as in {$apiEntiy}_{$name}
3504 // so following code is use build whereClause for contact's primart email id
3505 if (!empty($apiEntity)) {
3506 $dataType = 'String';
3507 if ($name == 'email_id') {
3508 $dataType = 'Integer';
3512 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.is_primary', '=', 1, 'Integer');
3513 $this->_where
[$grouping][] = self
::buildClause("civicrm_email.$name", $op, $value, $dataType);
3519 if (substr($n, 0, 1) == '"' &&
3520 substr($n, -1, 1) == '"'
3522 $n = substr($n, 1, -1);
3523 $value = CRM_Core_DAO
::escapeString($n);
3527 $value = self
::getWildCardedValue($wildcard, $op, $n);
3529 $this->_qill
[$grouping][] = ts('Email') . " $op '$n'";
3530 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, $value, 'String');
3533 $this->_qill
[$grouping][] = ts('Email') . " $op ";
3534 $this->_where
[$grouping][] = self
::buildClause('civicrm_email.email', $op, NULL, 'String');
3539 * Where / qill clause for phone number
3541 * @param array $values
3543 public function phone_numeric(&$values) {
3544 list($name, $op, $value, $grouping, $wildcard) = $values;
3545 // Strip non-numeric characters; allow wildcards
3546 $number = preg_replace('/[^\d%]/', '', $value);
3548 if (strpos($number, '%') === FALSE) {
3549 $number = "%$number%";
3552 $this->_qill
[$grouping][] = ts('Phone number contains') . " $number";
3553 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.phone_numeric', 'LIKE', "$number", 'String');
3554 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3559 * Where / qill clause for phone type/location
3561 * @param array $values
3563 public function phone_option_group($values) {
3564 list($name, $op, $value, $grouping, $wildcard) = $values;
3565 $option = ($name == 'phone_phone_type_id' ?
'phone_type_id' : 'location_type_id');
3566 $options = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', $option);
3567 $optionName = $options[$value];
3568 $this->_qill
[$grouping][] = ts('Phone') . ' ' . ($name == 'phone_phone_type_id' ?
ts('type') : ('location')) . " $op $optionName";
3569 $this->_where
[$grouping][] = self
::buildClause('civicrm_phone.' . substr($name, 6), $op, $value, 'Integer');
3570 $this->_tables
['civicrm_phone'] = $this->_whereTables
['civicrm_phone'] = 1;
3574 * Where / qill clause for street_address.
3576 * @param array $values
3578 public function street_address(&$values) {
3579 list($name, $op, $value, $grouping) = $values;
3588 if (strpos($value, '%') === FALSE) {
3589 // only add wild card if not there
3590 $value = "%{$value}%";
3593 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, $value, 'String');
3594 $this->_qill
[$grouping][] = ts('Street') . " $op '$n'";
3597 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_address', $op, NULL, 'String');
3598 $this->_qill
[$grouping][] = ts('Street') . " $op ";
3601 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3605 * Where / qill clause for street_unit.
3607 * @param array $values
3609 public function street_number(&$values) {
3610 list($name, $op, $value, $grouping, $wildcard) = $values;
3618 if (strtolower($n) == 'odd') {
3619 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 1 )";
3620 $this->_qill
[$grouping][] = ts('Street Number is odd');
3622 elseif (strtolower($n) == 'even') {
3623 $this->_where
[$grouping][] = " ( civicrm_address.street_number % 2 = 0 )";
3624 $this->_qill
[$grouping][] = ts('Street Number is even');
3628 $this->_where
[$grouping][] = self
::buildClause('civicrm_address.street_number', $op, $value, 'String');
3629 $this->_qill
[$grouping][] = ts('Street Number') . " $op '$n'";
3632 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3636 * Where / qill clause for sorting by character.
3638 * @param array $values
3640 public function sortByCharacter(&$values) {
3641 list($name, $op, $value, $grouping, $wildcard) = $values;
3643 $name = trim($value);
3644 $cond = " contact_a.sort_name LIKE '" . CRM_Core_DAO
::escapeWildCardString($name) . "%'";
3645 $this->_where
[$grouping][] = $cond;
3646 $this->_qill
[$grouping][] = ts('Showing only Contacts starting with: \'%1\'', array(1 => $name));
3650 * Where / qill clause for including contact ids.
3652 public function includeContactIDs() {
3653 if (!$this->_includeContactIds ||
empty($this->_params
)) {
3657 $contactIds = array();
3658 foreach ($this->_params
as $id => $values) {
3659 if (substr($values[0], 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
3660 $contactIds[] = substr($values[0], CRM_Core_Form
::CB_PREFIX_LEN
);
3663 CRM_Utils_Type
::validateAll($contactIds, 'Positive');
3664 if (!empty($contactIds)) {
3665 $this->_where
[0][] = " ( contact_a.id IN (" . implode(',', $contactIds) . " ) ) ";
3670 * Where / qill clause for postal code.
3672 * @param array $values
3674 public function postalCode(&$values) {
3675 // skip if the fields dont have anything to do with postal_code
3676 if (empty($this->_fields
['postal_code'])) {
3680 list($name, $op, $value, $grouping, $wildcard) = $values;
3682 // Handle numeric postal code range searches properly by casting the column as numeric
3683 if (is_numeric($value)) {
3684 $field = "IF (civicrm_address.postal_code REGEXP '^[0-9]{1,10}$', CAST(civicrm_address.postal_code AS UNSIGNED), 0)";
3685 $val = CRM_Utils_Type
::escape($value, 'Integer');
3688 $field = 'civicrm_address.postal_code';
3689 // Per CRM-17060 we might be looking at an 'IN' syntax so don't case arrays to string.
3690 if (!is_array($value)) {
3691 $val = CRM_Utils_Type
::escape($value, 'String');
3694 // Do we need to escape values here? I would expect buildClause does.
3699 $this->_tables
['civicrm_address'] = $this->_whereTables
['civicrm_address'] = 1;
3701 if ($name == 'postal_code') {
3702 $this->_where
[$grouping][] = self
::buildClause($field, $op, $val, 'String');
3703 $this->_qill
[$grouping][] = ts('Postal code') . " {$op} {$value}";
3705 elseif ($name == 'postal_code_low') {
3706 $this->_where
[$grouping][] = " ( $field >= '$val' ) ";
3707 $this->_qill
[$grouping][] = ts('Postal code greater than or equal to \'%1\'', array(1 => $value));
3709 elseif ($name == 'postal_code_high') {
3710 $this->_where
[$grouping][] = " ( $field <= '$val' ) ";
3711 $this->_qill
[$grouping][] = ts('Postal code less than or equal to \'%1\'', array(1 => $value));
3716 * Where / qill clause for location type.
3718 * @param array $values
3719 * @param null $status
3723 public function locationType(&$values, $status = NULL) {
3724 list($name, $op, $value, $grouping, $wildcard) = $values;
3726 if (is_array($value)) {
3727 $this->_where
[$grouping][] = 'civicrm_address.location_type_id IN (' . implode(',', $value) . ')';
3728 $this->_tables
['civicrm_address'] = 1;
3729 $this->_whereTables
['civicrm_address'] = 1;
3731 $locationType = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
3733 foreach ($value as $id) {
3734 $names[] = $locationType[$id];
3737 $this->_primaryLocation
= FALSE;
3740 $this->_qill
[$grouping][] = ts('Location Type') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3743 return implode(' ' . ts('or') . ' ', $names);
3750 * @param bool $fromStateProvince
3752 * @return array|NULL
3754 public function country(&$values, $fromStateProvince = TRUE) {
3755 list($name, $op, $value, $grouping, $wildcard) = $values;
3757 if (!$fromStateProvince) {
3758 $stateValues = $this->getWhereValues('state_province', $grouping);
3759 if (!empty($stateValues)) {
3760 // return back to caller if there are state province values
3761 // since that handles this case
3766 $countryClause = $countryQill = NULL;
3767 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ||
($values && !empty($value))) {
3768 $this->_tables
['civicrm_address'] = 1;
3769 $this->_whereTables
['civicrm_address'] = 1;
3771 $countryClause = self
::buildClause('civicrm_address.country_id', $op, $value, 'Positive');
3772 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, 'country_id', $value, $op);
3773 $countryQill = ts("%1 %2 %3", array(1 => 'Country', 2 => $qillop, 3 => $qillVal));
3775 if (!$fromStateProvince) {
3776 $this->_where
[$grouping][] = $countryClause;
3777 $this->_qill
[$grouping][] = $countryQill;
3781 if ($fromStateProvince) {
3782 if (!empty($countryClause)) {
3785 " ...AND... " . $countryQill,
3789 return array(NULL, NULL);
3795 * Where / qill clause for county (if present).
3797 * @param array $values
3798 * @param null $status
3802 public function county(&$values, $status = NULL) {
3803 list($name, $op, $value, $grouping, $wildcard) = $values;
3805 if (!is_array($value)) {
3806 // force the county to be an array
3807 $value = array($value);
3810 // check if the values are ids OR names of the counties
3811 $inputFormat = 'id';
3812 foreach ($value as $v) {
3813 if (!is_numeric($v)) {
3814 $inputFormat = 'name';
3822 elseif ($op == '!=') {
3826 // this converts IS (NOT)? EMPTY to IS (NOT)? NULL
3827 $op = str_replace('EMPTY', 'NULL', $op);
3830 if (in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
3831 $clause = "civicrm_address.county_id $op";
3833 elseif ($inputFormat == 'id') {
3834 $clause = 'civicrm_address.county_id IN (' . implode(',', $value) . ')';
3836 $county = CRM_Core_PseudoConstant
::county();
3837 foreach ($value as $id) {
3838 $names[] = CRM_Utils_Array
::value($id, $county);
3842 $inputClause = array();
3843 $county = CRM_Core_PseudoConstant
::county();
3844 foreach ($value as $name) {
3845 $name = trim($name);
3846 $inputClause[] = CRM_Utils_Array
::key($name, $county);
3848 $clause = 'civicrm_address.county_id IN (' . implode(',', $inputClause) . ')';
3851 $this->_tables
['civicrm_address'] = 1;
3852 $this->_whereTables
['civicrm_address'] = 1;
3854 $this->_where
[$grouping][] = $clause;
3856 $this->_qill
[$grouping][] = ts('County') . ' - ' . implode(' ' . ts('or') . ' ', $names);
3859 return implode(' ' . ts('or') . ' ', $names);
3864 * Where / qill clause for state/province AND country (if present).
3866 * @param array $values
3867 * @param null $status
3871 public function stateProvince(&$values, $status = NULL) {
3872 list($name, $op, $value, $grouping, $wildcard) = $values;
3874 $stateClause = self
::buildClause('civicrm_address.state_province_id', $op, $value, 'Positive');
3875 $this->_tables
['civicrm_address'] = 1;
3876 $this->_whereTables
['civicrm_address'] = 1;
3878 $countryValues = $this->getWhereValues('country', $grouping);
3879 list($countryClause, $countryQill) = $this->country($countryValues, TRUE);
3880 if ($countryClause) {
3881 $clause = "( $stateClause AND $countryClause )";
3884 $clause = $stateClause;
3887 $this->_where
[$grouping][] = $clause;
3888 list($qillop, $qillVal) = self
::buildQillForFieldValue('CRM_Core_DAO_Address', "state_province_id", $value, $op);
3890 $this->_qill
[$grouping][] = ts("State/Province %1 %2 %3", array(1 => $qillop, 2 => $qillVal, 3 => $countryQill));
3893 return implode(' ' . ts('or') . ' ', $qillVal) . $countryQill;
3898 * Where / qill clause for change log.
3900 * @param array $values
3902 public function changeLog(&$values) {
3903 list($name, $op, $value, $grouping, $wildcard) = $values;
3905 $targetName = $this->getWhereValues('changed_by', $grouping);
3910 $name = trim($targetName[2]);
3911 $name = CRM_Core_DAO
::escapeString($name);
3912 $name = $targetName[4] ?
"%$name%" : $name;
3913 $this->_where
[$grouping][] = "contact_b_log.sort_name LIKE '%$name%'";
3914 $this->_tables
['civicrm_log'] = $this->_whereTables
['civicrm_log'] = 1;
3915 $fieldTitle = ts('Added By');
3916 foreach ($this->_params
as $params) {
3917 if ($params[0] == 'log_date') {
3918 if ($params[2] == 2) {
3919 $fieldTitle = ts('Modified By');
3924 list($qillop, $qillVal) = self
::buildQillForFieldValue(NULL, 'changed_by', $name, 'LIKE');
3925 $this->_qill
[$grouping][] = ts("%1 %2 '%3'", [
3935 public function modifiedDates($values) {
3936 $this->_useDistinct
= TRUE;
3938 // CRM-11281, default to added date if not set
3939 $fieldTitle = ts('Added Date');
3940 $fieldName = 'created_date';
3941 foreach (array_keys($this->_params
) as $id) {
3942 if ($this->_params
[$id][0] == 'log_date') {
3943 if ($this->_params
[$id][2] == 2) {
3944 $fieldTitle = ts('Modified Date');
3945 $fieldName = 'modified_date';
3950 $this->dateQueryBuilder($values, 'contact_a', 'log_date', $fieldName, $fieldTitle);
3952 self
::$_openedPanes[ts('Change Log')] = TRUE;
3958 public function demographics(&$values) {
3959 list($name, $op, $value, $grouping, $wildcard) = $values;
3961 if (($name == 'age_low') ||
($name == 'age_high')) {
3962 $this->ageRangeQueryBuilder($values,
3963 'contact_a', 'age', 'birth_date', ts('Age')
3966 elseif (($name == 'birth_date_low') ||
($name == 'birth_date_high')) {
3968 $this->dateQueryBuilder($values,
3969 'contact_a', 'birth_date', 'birth_date', ts('Birth Date')
3972 elseif (($name == 'deceased_date_low') ||
($name == 'deceased_date_high')) {
3974 $this->dateQueryBuilder($values,
3975 'contact_a', 'deceased_date', 'deceased_date', ts('Deceased Date')
3979 self
::$_openedPanes[ts('Demographics')] = TRUE;
3985 public function privacy(&$values) {
3986 list($name, $op, $value, $grouping) = $values;
3987 //fixed for profile search listing CRM-4633
3988 if (strpbrk($value, "[")) {
3989 $value = "'{$value}'";
3991 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3994 $this->_where
[$grouping][] = "contact_a.{$name} $op $value";
3996 $field = CRM_Utils_Array
::value($name, $this->_fields
);
3997 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
3998 $title = $field ?
$field['title'] : $name;
3999 $this->_qill
[$grouping][] = "$title $op $value";
4005 public function privacyOptions($values) {
4006 list($name, $op, $value, $grouping, $wildcard) = $values;
4008 if (empty($value) ||
!is_array($value)) {
4012 // get the operator and toggle values
4013 $opValues = $this->getWhereValues('privacy_operator', $grouping);
4016 strtolower($opValues[2] == 'AND')
4018 // @todo this line is logially unreachable
4022 $toggleValues = $this->getWhereValues('privacy_toggle', $grouping);
4024 if ($toggleValues &&
4025 $toggleValues[2] == 2
4032 foreach ($value as $dontCare => $pOption) {
4033 $clauses[] = " ( contact_a.{$pOption} = 1 ) ";
4034 $field = CRM_Utils_Array
::value($pOption, $this->_fields
);
4035 $title = $field ?
$field['title'] : $pOption;
4036 $qill[] = " $title = 1 ";
4039 $this->_where
[$grouping][] = $compareOP . '( ' . implode($operator, $clauses) . ' )';
4040 $this->_qill
[$grouping][] = $compareOP . '( ' . implode($operator, $qill) . ' )';
4046 public function preferredCommunication(&$values) {
4047 list($name, $op, $value, $grouping, $wildcard) = $values;
4049 if (!is_array($value)) {
4050 $value = str_replace(array('(', ')'), '', explode(",", $value));
4052 elseif (in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
4054 $value = $value[$op];
4056 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue('CRM_Contact_DAO_Contact', $name, $value, $op);
4058 if (self
::caseImportant($op)) {
4059 $value = implode("[[:cntrl:]]|[[:cntrl:]]", (array) $value);
4060 $op = (strstr($op, '!') ||
strstr($op, 'NOT')) ?
'NOT RLIKE' : 'RLIKE';
4061 $value = "[[:cntrl:]]" . $value . "[[:cntrl:]]";
4064 $this->_where
[$grouping][] = self
::buildClause("contact_a.preferred_communication_method", $op, $value);
4065 $this->_qill
[$grouping][] = ts('Preferred Communication Method %1 %2', array(1 => $qillop, 2 => $qillVal));
4069 * Where / qill clause for relationship.
4071 * @param array $values
4073 public function relationship(&$values) {
4074 list($name, $op, $value, $grouping, $wildcard) = $values;
4075 if ($this->_relationshipValuesAdded
) {
4078 // also get values array for relation_target_name
4079 // for relationship search we always do wildcard
4080 $relationType = $this->getWhereValues('relation_type_id', $grouping);
4081 $targetName = $this->getWhereValues('relation_target_name', $grouping);
4082 $relStatus = $this->getWhereValues('relation_status', $grouping);
4083 $targetGroup = $this->getWhereValues('relation_target_group', $grouping);
4085 $nameClause = $name = NULL;
4087 $name = trim($targetName[2]);
4088 if (substr($name, 0, 1) == '"' &&
4089 substr($name, -1, 1) == '"'
4091 $name = substr($name, 1, -1);
4092 $name = CRM_Core_DAO
::escapeString($name);
4093 $nameClause = "= '$name'";
4096 $name = CRM_Core_DAO
::escapeString($name);
4097 $nameClause = "LIKE '%{$name}%'";
4101 $relTypes = $relTypesIds = array();
4102 if (!empty($relationType)) {
4103 $relationType[2] = (array) $relationType[2];
4104 foreach ($relationType[2] as $relType) {
4105 $rel = explode('_', $relType);
4106 self
::$_relType = $rel[1];
4107 $params = array('id' => $rel[0]);
4108 $typeValues = array();
4109 $rTypeValue = CRM_Contact_BAO_RelationshipType
::retrieve($params, $typeValues);
4110 if (!empty($rTypeValue)) {
4111 if ($rTypeValue->name_a_b
== $rTypeValue->name_b_a
) {
4112 // if we don't know which end of the relationship we are dealing with we'll create a temp table
4113 self
::$_relType = 'reciprocal';
4115 $relTypesIds[] = $rel[0];
4116 $relTypes[] = $relType;
4121 // if we are creating a temp table we build our own where for the relationship table
4122 $relationshipTempTable = NULL;
4123 if (self
::$_relType == 'reciprocal') {
4125 self
::$_relationshipTempTable = $relationshipTempTable = CRM_Core_DAO
::createTempTableName('civicrm_rel');
4127 $where[$grouping][] = " sort_name $nameClause ";
4129 $groupJoinTable = "civicrm_relationship";
4130 $groupJoinColumn = "contact_id_alt";
4133 $where = &$this->_where
;
4135 $where[$grouping][] = "( contact_b.sort_name $nameClause AND contact_b.id != contact_a.id )";
4137 $groupJoinTable = "contact_b";
4138 $groupJoinColumn = "id";
4140 $allRelationshipType = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, 'null', NULL, NULL, TRUE);
4141 if ($nameClause ||
!$targetGroup) {
4142 if (!empty($relationType)) {
4144 foreach ($relTypes as $rel) {
4145 if (!empty($relQill)) {
4148 $relQill .= $allRelationshipType[$rel];
4150 $this->_qill
[$grouping][] = 'Relationship Type(s) ' . $relQill . " $name";
4153 $this->_qill
[$grouping][] = $name;
4157 //check to see if the target contact is in specified group
4159 //add contacts from static groups
4160 $this->_tables
['civicrm_relationship_group_contact'] = $this->_whereTables
['civicrm_relationship_group_contact']
4161 = " 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'";
4162 $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" .
4163 implode(",", $targetGroup[2]) . ") ) ";
4165 //add contacts from saved searches
4166 $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", $groupJoinTable, $op, $groupJoinColumn);
4168 //set the group where clause
4170 $groupWhere[] = "( " . $ssWhere . " )";
4172 $this->_where
[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )";
4174 //Get the names of the target groups for the qill
4175 $groupNames = CRM_Core_PseudoConstant
::group();
4176 $qillNames = array();
4177 foreach ($targetGroup[2] as $groupId) {
4178 if (array_key_exists($groupId, $groupNames)) {
4179 $qillNames[] = $groupNames[$groupId];
4182 if (!empty($relationType)) {
4184 foreach ($relTypes as $rel) {
4185 if (!empty($relQill)) {
4188 $relQill .= CRM_Utils_Array
::value($rel, $allRelationshipType);
4190 $this->_qill
[$grouping][] = 'Relationship Type(s) ' . $relQill . " ( " . implode(", ", $qillNames) . " )";
4193 $this->_qill
[$grouping][] = implode(", ", $qillNames);
4197 // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way
4198 $today = date('Ymd');
4199 //check for active, inactive and all relation status
4200 if ($relStatus[2] == 0) {
4201 $where[$grouping][] = "(
4202 civicrm_relationship.is_active = 1 AND
4203 ( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND
4204 ( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )
4206 $this->_qill
[$grouping][] = ts('Relationship - Active and Current');
4208 elseif ($relStatus[2] == 1) {
4209 $where[$grouping][] = "(
4210 civicrm_relationship.is_active = 0 OR
4211 civicrm_relationship.end_date < {$today} OR
4212 civicrm_relationship.start_date > {$today}
4214 $this->_qill
[$grouping][] = ts('Relationship - Inactive or not Current');
4218 if (in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
)) {
4221 $where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})";
4223 $this->addRelationshipPermissionClauses($grouping, $where);
4224 $this->addRelationshipDateClauses($grouping, $where);
4225 $this->addRelationshipActivePeriodClauses($grouping, $where);
4226 if (!empty($relTypes)) {
4227 $where[$grouping][] = 'civicrm_relationship.relationship_type_id IN (' . implode(',', $relTypesIds) . ')';
4229 $this->_tables
['civicrm_relationship'] = $this->_whereTables
['civicrm_relationship'] = 1;
4230 $this->_useDistinct
= TRUE;
4231 $this->_relationshipValuesAdded
= TRUE;
4232 // it could be a or b, using an OR creates an unindexed join - better to create a temp table &
4234 if ($relationshipTempTable) {
4236 if (!empty($where[$grouping])) {
4237 $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]);
4238 $whereClause = str_replace('contact_b', 'c', $whereClause);
4241 CREATE TEMPORARY TABLE {$relationshipTempTable}
4243 `contact_id` int(10) unsigned NOT NULL DEFAULT '0',
4244 `contact_id_alt` int(10) unsigned NOT NULL DEFAULT '0',
4245 KEY `contact_id` (`contact_id`),
4246 KEY `contact_id_alt` (`contact_id_alt`)
4248 (SELECT contact_id_b as contact_id, contact_id_a as contact_id_alt, civicrm_relationship.id
4249 FROM civicrm_relationship
4250 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id
4253 (SELECT contact_id_a as contact_id, contact_id_b as contact_id_alt, civicrm_relationship.id
4254 FROM civicrm_relationship
4255 INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id
4258 CRM_Core_DAO
::executeQuery($sql);
4263 * Add relationship permission criteria to where clause.
4265 * @param string $grouping
4266 * @param array $where Array to add "where" criteria to, in case you are generating a temp table.
4267 * Not the main query.
4269 public function addRelationshipPermissionClauses($grouping, &$where) {
4270 $relPermission = $this->getWhereValues('relation_permission', $grouping);
4271 if ($relPermission) {
4272 if (!is_array($relPermission[2])) {
4273 // this form value was scalar in previous versions of Civi
4274 $relPermission[2] = array($relPermission[2]);
4276 $where[$grouping][] = "(civicrm_relationship.is_permission_a_b IN (" . implode(",", $relPermission[2]) . "))";
4278 $allRelationshipPermissions = CRM_Contact_BAO_Relationship
::buildOptions('is_permission_a_b');
4280 $relPermNames = array_intersect_key($allRelationshipPermissions, array_flip($relPermission[2]));
4281 $this->_qill
[$grouping][] = ts('Permissioned Relationships') . ' - ' . implode(' OR ', $relPermNames);
4286 * Add start & end date criteria in
4287 * @param string $grouping
4288 * @param array $where
4289 * = array to add where clauses to, in case you are generating a temp table.
4290 * not the main query.
4292 public function addRelationshipDateClauses($grouping, &$where) {
4293 $dateValues = array();
4299 foreach ($dateTypes as $dateField) {
4300 $dateValueLow = $this->getWhereValues('relation_' . $dateField . '_low', $grouping);
4301 $dateValueHigh = $this->getWhereValues('relation_' . $dateField . '_high', $grouping);
4302 if (!empty($dateValueLow)) {
4303 $date = date('Ymd', strtotime($dateValueLow[2]));
4304 $where[$grouping][] = "civicrm_relationship.$dateField >= $date";
4305 $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);
4307 if (!empty($dateValueHigh)) {
4308 $date = date('Ymd', strtotime($dateValueHigh[2]));
4309 $where[$grouping][] = "civicrm_relationship.$dateField <= $date";
4310 $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);
4316 * Add start & end active period criteria in
4317 * @param string $grouping
4318 * @param array $where
4319 * = array to add where clauses to, in case you are generating a temp table.
4320 * not the main query.
4322 public function addRelationshipActivePeriodClauses($grouping, &$where) {
4323 $dateValues = array();
4324 $dateField = 'active_period_date';
4326 $dateValueLow = $this->getWhereValues('relation_active_period_date_low', $grouping);
4327 $dateValueHigh = $this->getWhereValues('relation_active_period_date_high', $grouping);
4328 $dateValueLowFormated = $dateValueHighFormated = NULL;
4329 if (!empty($dateValueLow) && !empty($dateValueHigh)) {
4330 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4331 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
4332 $this->_qill
[$grouping][] = (ts('Relationship was active between')) . " " . CRM_Utils_Date
::customFormat($dateValueLowFormated) . " and " . CRM_Utils_Date
::customFormat($dateValueHighFormated);
4334 elseif (!empty($dateValueLow)) {
4335 $dateValueLowFormated = date('Ymd', strtotime($dateValueLow[2]));
4336 $this->_qill
[$grouping][] = (ts('Relationship was active after')) . " " . CRM_Utils_Date
::customFormat($dateValueLowFormated);
4338 elseif (!empty($dateValueHigh)) {
4339 $dateValueHighFormated = date('Ymd', strtotime($dateValueHigh[2]));
4340 $this->_qill
[$grouping][] = (ts('Relationship was active before')) . " " . CRM_Utils_Date
::customFormat($dateValueHighFormated);
4343 if ($activePeriodClauses = self
::getRelationshipActivePeriodClauses($dateValueLowFormated, $dateValueHighFormated, TRUE)) {
4344 $where[$grouping][] = $activePeriodClauses;
4349 * Get start & end active period criteria
4351 public static function getRelationshipActivePeriodClauses($from, $to, $forceTableName) {
4352 $tableName = $forceTableName ?
'civicrm_relationship.' : '';
4353 if (!is_null($from) && !is_null($to)) {
4354 return '(((' . $tableName . 'start_date >= ' . $from . ' AND ' . $tableName . 'start_date <= ' . $to . ') OR
4355 (' . $tableName . 'end_date >= ' . $from . ' AND ' . $tableName . 'end_date <= ' . $to . ') OR
4356 (' . $tableName . 'start_date <= ' . $from . ' AND ' . $tableName . 'end_date >= ' . $to . ' )) OR
4357 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4358 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . ') OR
4359 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4361 elseif (!is_null($from)) {
4362 return '((' . $tableName . 'start_date >= ' . $from . ') OR
4363 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4364 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date >= ' . $from . '))';
4366 elseif (!is_null($to)) {
4367 return '((' . $tableName . 'start_date <= ' . $to . ') OR
4368 (' . $tableName . 'start_date IS NULL AND ' . $tableName . 'end_date IS NULL) OR
4369 (' . $tableName . 'end_date IS NULL AND ' . $tableName . 'start_date <= ' . $to . '))';
4374 * Default set of return properties.
4379 * derault return properties
4381 public static function &defaultReturnProperties($mode = 1) {
4382 if (!isset(self
::$_defaultReturnProperties)) {
4383 self
::$_defaultReturnProperties = array();
4386 if (!isset(self
::$_defaultReturnProperties[$mode])) {
4387 // add activity return properties
4388 if ($mode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
4389 self
::$_defaultReturnProperties[$mode] = CRM_Activity_BAO_Query
::defaultReturnProperties($mode, FALSE);
4392 self
::$_defaultReturnProperties[$mode] = CRM_Core_Component
::defaultReturnProperties($mode, FALSE);
4395 if (empty(self
::$_defaultReturnProperties[$mode])) {
4396 self
::$_defaultReturnProperties[$mode] = array(
4399 'legal_identifier' => 1,
4400 'external_identifier' => 1,
4401 'contact_type' => 1,
4402 'contact_sub_type' => 1,
4404 'display_name' => 1,
4405 'preferred_mail_format' => 1,
4412 'formal_title' => 1,
4413 'communication_style_id' => 1,
4416 'street_address' => 1,
4417 'supplemental_address_1' => 1,
4418 'supplemental_address_2' => 1,
4419 'supplemental_address_3' => 1,
4422 'postal_code_suffix' => 1,
4423 'state_province' => 1,
4425 'world_region' => 1,
4432 'household_name' => 1,
4433 'organization_name' => 1,
4434 'deceased_date' => 1,
4439 'current_employer' => 1,
4440 // FIXME: should we use defaultHierReturnProperties() for the below?
4441 'do_not_email' => 1,
4444 'do_not_phone' => 1,
4445 'do_not_trade' => 1,
4447 'contact_is_deleted' => 1,
4448 'preferred_communication_method' => 1,
4449 'preferred_language' => 1,
4453 return self
::$_defaultReturnProperties[$mode];
4457 * Get primary condition for a sql clause.
4461 * @return string|NULL
4463 public static function getPrimaryCondition($value) {
4464 if (is_numeric($value)) {
4465 $value = (int ) $value;
4466 return ($value == 1) ?
'is_primary = 1' : 'is_primary = 0';
4472 * Wrapper for a simple search query.
4474 * @param array $params
4475 * @param array $returnProperties
4476 * @param bool $count
4480 public static function getQuery($params = NULL, $returnProperties = NULL, $count = FALSE) {
4481 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
4482 list($select, $from, $where, $having) = $query->query();
4483 $groupBy = ($query->_useGroupBy
) ?
'GROUP BY contact_a.id' : '';
4485 $query = "$select $from $where $groupBy $having";
4490 * These are stub comments as this function needs more explanation - particularly in terms of how it
4491 * relates to $this->searchQuery and why it replicates rather than calles $this->searchQuery.
4493 * This function was originally written as a wrapper for the api query but is called from multiple places
4494 * in the core code directly so the name is misleading. This function does not use the searchQuery function
4495 * but it is unclear as to whehter that is historical or there is a reason
4496 * CRM-11290 led to the permissioning action being extracted from searchQuery & shared with this function
4498 * @param array $params
4499 * @param array $returnProperties
4500 * @param null $fields
4501 * @param string $sort
4502 * @param int $offset
4503 * @param int $row_count
4504 * @param bool $smartGroupCache
4505 * ?? update smart group cache?.
4506 * @param bool $count
4507 * Return count obnly.
4508 * @param bool $skipPermissions
4509 * Should permissions be ignored or should the logged in user's permissions be applied.
4511 * This basically correlates to the component.
4512 * @param string $apiEntity
4513 * The api entity being called.
4514 * This sort-of duplicates $mode in a confusing way. Probably not by design.
4516 * @param bool|null $primaryLocationOnly
4519 public static function apiQuery(
4521 $returnProperties = NULL,
4526 $smartGroupCache = TRUE,
4528 $skipPermissions = TRUE,
4529 $mode = CRM_Contact_BAO_Query
::MODE_CONTACTS
,
4531 $primaryLocationOnly = NULL
4534 $query = new CRM_Contact_BAO_Query(
4535 $params, $returnProperties,
4536 NULL, TRUE, FALSE, $mode,
4538 TRUE, $smartGroupCache,
4540 $apiEntity, $primaryLocationOnly
4543 //this should add a check for view deleted if permissions are enabled
4544 if ($skipPermissions) {
4545 $query->_skipDeleteClause
= TRUE;
4547 $query->generatePermissionClause(FALSE, $count);
4549 // note : this modifies _fromClause and _simpleFromClause
4550 $query->includePseudoFieldsJoin($sort);
4552 list($select, $from, $where, $having) = $query->query($count);
4554 $options = $query->_options
;
4555 if (!empty($query->_permissionWhereClause
)) {
4556 if (empty($where)) {
4557 $where = "WHERE $query->_permissionWhereClause";
4560 $where = "$where AND $query->_permissionWhereClause";
4564 $sql = "$select $from $where $having";
4566 // add group by only when API action is not getcount
4567 // otherwise query fetches incorrect count
4568 if ($query->_useGroupBy
&& !$count) {
4569 $sql .= self
::getGroupByFromSelectColumns($query->_select
, 'contact_a.id');
4571 if (!empty($sort)) {
4572 $sort = CRM_Utils_Type
::escape($sort, 'String');
4573 $sql .= " ORDER BY $sort ";
4575 if ($row_count > 0 && $offset >= 0) {
4576 $offset = CRM_Utils_Type
::escape($offset, 'Int');
4577 $row_count = CRM_Utils_Type
::escape($row_count, 'Int');
4578 $sql .= " LIMIT $offset, $row_count ";
4581 $dao = CRM_Core_DAO
::executeQuery($sql);
4583 // @todo derive this from the component class rather than hard-code two options.
4584 $entityIDField = ($mode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) ?
'contribution_id' : 'contact_id';
4587 while ($dao->fetch()) {
4589 $noRows = $dao->rowCount
;
4590 return array($noRows, NULL);
4592 $val = $query->store($dao);
4593 $convertedVals = $query->convertToPseudoNames($dao, TRUE, TRUE);
4595 if (!empty($convertedVals)) {
4596 $val = array_replace_recursive($val, $convertedVals);
4598 $values[$dao->$entityIDField] = $val;
4600 return array($values, $options);
4604 * Get the actual custom field name by stripping off the appended string.
4606 * The string could be _relative, _from, or _to
4608 * @todo use metadata rather than convention to do this.
4610 * @param string $parameterName
4611 * The name of the parameter submitted to the form.
4618 public static function getCustomFieldName($parameterName) {
4619 if (substr($parameterName, -5, 5) == '_from') {
4620 return substr($parameterName, 0, strpos($parameterName, '_from'));
4622 if (substr($parameterName, -9, 9) == '_relative') {
4623 return substr($parameterName, 0, strpos($parameterName, '_relative'));
4625 if (substr($parameterName, -3, 3) == '_to') {
4626 return substr($parameterName, 0, strpos($parameterName, '_to'));
4631 * Convert submitted values for relative custom fields to query object format.
4633 * The query will support the sqlOperator format so convert to that format.
4635 * @param array $formValues
4637 * @param array $params
4638 * Converted parameters for the query object.
4639 * @param string $values
4641 * @param string $fieldName
4642 * Submitted field name. (Matches form field not DB field.)
4644 protected static function convertCustomRelativeFields(&$formValues, &$params, $values, $fieldName) {
4645 if (empty($values)) {
4646 // e.g we might have relative set & from & to empty. The form flow is a bit funky &
4647 // this function gets called again after they fields have been converted which can get ugly.
4650 $customFieldName = self
::getCustomFieldName($fieldName);
4652 if (substr($fieldName, -9, 9) == '_relative') {
4653 list($from, $to) = CRM_Utils_Date
::getFromTo($values, NULL, NULL);
4656 if ($fieldName == $customFieldName . '_to' && CRM_Utils_Array
::value($customFieldName . '_from', $formValues)) {
4657 // Both to & from are set. We only need to acton one, choosing from.
4661 $from = CRM_Utils_Array
::value($customFieldName . '_from', $formValues, NULL);
4662 $to = CRM_Utils_Array
::value($customFieldName . '_to', $formValues, NULL);
4664 if (self
::isCustomDateField($customFieldName)) {
4665 list($from, $to) = CRM_Utils_Date
::getFromTo(NULL, $from, $to);
4671 $relativeFunction = array('BETWEEN' => array($from, $to));
4674 $relativeFunction = array('>=' => $from);
4678 $relativeFunction = array('<=' => $to);
4690 * Are we dealing with custom field of type date.
4696 public static function isCustomDateField($fieldName) {
4697 if (($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($fieldName)) == FALSE) {
4700 if ('Date' == civicrm_api3('CustomField', 'getvalue', array('id' => $customFieldID, 'return' => 'data_type'))) {
4707 * Has this field already been reformatting to Query object syntax.
4709 * The form layer passed formValues to this function in preProcess & postProcess. Reason unknown. This seems
4710 * to come with associated double queries & is possibly damaging performance.
4712 * However, here we add a tested function to ensure convertFormValues identifies pre-processed fields & returns
4715 * @param mixed $values
4716 * Value in formValues for the field.
4720 public static function isAlreadyProcessedForQueryFormat($values) {
4721 if (!is_array($values)) {
4724 if (($operator = CRM_Utils_Array
::value(1, $values)) == FALSE) {
4727 return in_array($operator, CRM_Core_DAO
::acceptedSQLOperators());
4731 * If the state and country are passed remove state.
4733 * Country is implicit from the state, but including both results in
4734 * a poor query as there is no combined index on state AND country.
4738 * @param array $formValues
4740 public static function filterCountryFromValuesIfStateExists(&$formValues) {
4741 if (!empty($formValues['country']) && !empty($formValues['state_province'])) {
4742 // The use of array map sanitises the data by ensuring we are dealing with integers.
4743 $states = implode(', ', array_map('intval', $formValues['state_province']));
4744 $countryList = CRM_Core_DAO
::singleValueQuery(
4745 "SELECT GROUP_CONCAT(country_id) FROM civicrm_state_province WHERE id IN ($states)"
4747 if ($countryList == $formValues['country']) {
4748 unset($formValues['country']);
4754 * For some special cases, grouping by subset of select fields becomes mandatory.
4755 * Hence, full_group_by mode is handled by appending any_value
4756 * keyword to select fields not present in groupBy
4758 * @param array $selectClauses
4759 * @param array $groupBy - Columns already included in GROUP By clause.
4760 * @param string $aggregateFunction
4764 public static function appendAnyValueToSelect($selectClauses, $groupBy, $aggregateFunction = 'ANY_VALUE') {
4765 if (!CRM_Utils_SQL
::disableFullGroupByMode()) {
4766 $groupBy = array_map('trim', (array) $groupBy);
4767 $aggregateFunctions = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN|IF)[[:blank:]]*\(/i';
4768 foreach ($selectClauses as $key => &$val) {
4769 list($selectColumn, $alias) = array_pad(preg_split('/ as /i', $val), 2, NULL);
4770 // append ANY_VALUE() keyword
4771 if (!in_array($selectColumn, $groupBy) && preg_match($aggregateFunctions, trim($selectColumn)) !== 1) {
4772 $val = ($aggregateFunction == 'GROUP_CONCAT') ?
4773 str_replace($selectColumn, "$aggregateFunction(DISTINCT {$selectColumn})", $val) :
4774 str_replace($selectColumn, "$aggregateFunction({$selectColumn})", $val);
4779 return "SELECT " . implode(', ', $selectClauses) . " ";
4783 * For some special cases, where if non-aggregate ORDER BY columns are not present in GROUP BY
4784 * on full_group_by mode, then append the those missing columns to GROUP BY clause
4785 * keyword to select fields not present in groupBy
4787 * @param string $groupBy - GROUP BY clause where missing ORDER BY columns will be appended if not present
4788 * @param array $orderBys - ORDER BY sub-clauses
4791 public static function getGroupByFromOrderBy(&$groupBy, $orderBys) {
4792 if (!CRM_Utils_SQL
::disableFullGroupByMode()) {
4793 foreach ($orderBys as $orderBy) {
4794 $orderBy = str_ireplace(array(' DESC', ' ASC', '`'), '', $orderBy); // remove sort syntax from ORDER BY clauses if present
4795 // if ORDER BY column is not present in GROUP BY then append it to end
4796 if (preg_match('/(MAX|MIN)\(/i', trim($orderBy)) !== 1 && !strstr($groupBy, $orderBy)) {
4797 $groupBy .= ", {$orderBy}";
4804 * Include Select columns in groupBy clause.
4806 * @param array $selectClauses
4807 * @param array $groupBy - Columns already included in GROUP By clause.
4811 public static function getGroupByFromSelectColumns($selectClauses, $groupBy = NULL) {
4812 $groupBy = (array) $groupBy;
4813 $mysqlVersion = CRM_Core_DAO
::singleValueQuery('SELECT VERSION()');
4814 $sqlMode = CRM_Core_DAO
::singleValueQuery('SELECT @@sql_mode');
4816 //return if ONLY_FULL_GROUP_BY is not enabled.
4817 if (CRM_Utils_SQL
::supportsFullGroupBy() && !empty($sqlMode) && in_array('ONLY_FULL_GROUP_BY', explode(',', $sqlMode))) {
4818 $regexToExclude = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN|IF)[[:blank:]]*\(/i';
4819 foreach ($selectClauses as $key => $val) {
4820 $aliasArray = preg_split('/ as /i', $val);
4821 // if more than 1 alias we need to split by ','.
4822 if (count($aliasArray) > 2) {
4823 $aliasArray = preg_split('/,/', $val);
4824 foreach ($aliasArray as $key => $value) {
4825 $alias = current(preg_split('/ as /i', $value));
4826 if (!in_array($alias, $groupBy) && preg_match($regexToExclude, trim($alias)) !== 1) {
4827 $groupBy[] = $alias;
4832 list($selectColumn, $alias) = array_pad($aliasArray, 2, NULL);
4833 $dateRegex = '/^(DATE_FORMAT|DATE_ADD|CASE)/i';
4834 $tableName = current(explode('.', $selectColumn));
4835 $primaryKey = "{$tableName}.id";
4836 // exclude columns which are already included in groupBy and aggregate functions from select
4837 // CRM-18439 - Also exclude the columns which are functionally dependent on columns in $groupBy (MySQL 5.7+)
4838 if (!in_array($selectColumn, $groupBy) && !in_array($primaryKey, $groupBy) && preg_match($regexToExclude, trim($selectColumn)) !== 1) {
4839 if (!empty($alias) && preg_match($dateRegex, trim($selectColumn))) {
4840 $groupBy[] = $alias;
4843 $groupBy[] = $selectColumn;
4850 if (!empty($groupBy)) {
4851 return " GROUP BY " . implode(', ', $groupBy);
4857 * Create and query the db for an contact search.
4859 * @param int $offset
4860 * The offset for the query.
4861 * @param int $rowCount
4862 * The number of rows to return.
4863 * @param string|CRM_Utils_Sort $sort
4864 * The order by string.
4865 * @param bool $count
4866 * Is this a count only query ?.
4867 * @param bool $includeContactIds
4868 * Should we include contact ids?.
4869 * @param bool $sortByChar
4870 * If true returns the distinct array of first characters for search results.
4871 * @param bool $groupContacts
4872 * If true, return only the contact ids.
4873 * @param bool $returnQuery
4874 * Should we return the query as a string.
4875 * @param string $additionalWhereClause
4876 * If the caller wants to further restrict the search (used for components).
4877 * @param null $sortOrder
4878 * @param string $additionalFromClause
4879 * Should be clause with proper joins, effective to reduce where clause load.
4881 * @param bool $skipOrderAndLimit
4883 * @return CRM_Core_DAO
4885 public function searchQuery(
4886 $offset = 0, $rowCount = 0, $sort = NULL,
4887 $count = FALSE, $includeContactIds = FALSE,
4888 $sortByChar = FALSE, $groupContacts = FALSE,
4889 $returnQuery = FALSE,
4890 $additionalWhereClause = NULL, $sortOrder = NULL,
4891 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE
4894 $query = $this->getSearchSQL($offset, $rowCount, $sort, $count, $includeContactIds, $sortByChar, $groupContacts, $additionalWhereClause, $sortOrder, $additionalFromClause, $skipOrderAndLimit);
4900 return CRM_Core_DAO
::singleValueQuery($query);
4903 $dao = CRM_Core_DAO
::executeQuery($query);
4905 // We can always call this - it will only re-enable if it was originally enabled.
4906 CRM_Core_DAO
::reenableFullGroupByMode();
4908 if ($groupContacts) {
4910 while ($dao->fetch()) {
4913 return implode(',', $ids);
4920 * Create and query the db for a contact search.
4922 * @return CRM_Core_DAO
4924 public function alphabetQuery() {
4925 $query = $this->getSearchSQL(NULL, NULL, NULL, FALSE, FALSE, TRUE);
4927 $dao = CRM_Core_DAO
::executeQuery($query);
4929 // We can always call this - it will only re-enable if it was originally enabled.
4930 CRM_Core_DAO
::reenableFullGroupByMode();
4936 * Fetch a list of contacts for displaying a search results page
4938 * @param array $cids
4939 * List of contact IDs
4940 * @param bool $includeContactIds
4941 * @return CRM_Core_DAO
4943 public function getCachedContacts($cids, $includeContactIds) {
4944 CRM_Utils_Type
::validateAll($cids, 'Positive');
4945 $this->_includeContactIds
= $includeContactIds;
4946 $onlyDeleted = in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params
);
4947 list($select, $from, $where) = $this->query(FALSE, FALSE, FALSE, $onlyDeleted);
4948 $select .= sprintf(", (%s) AS _wgt", $this->createSqlCase('contact_a.id', $cids));
4949 $where .= sprintf(' AND contact_a.id IN (%s)', implode(',', $cids));
4950 $order = 'ORDER BY _wgt';
4951 $groupBy = $this->_useGroupBy ?
' GROUP BY contact_a.id' : '';
4953 $query = "$select $from $where $groupBy $order $limit";
4955 return CRM_Core_DAO
::executeQuery($query);
4959 * Construct a SQL CASE expression.
4961 * @param string $idCol
4962 * The name of a column with ID's (eg 'contact_a.id').
4963 * @param array $cids
4964 * Array(int $weight => int $id).
4966 * CASE WHEN id=123 THEN 1 WHEN id=456 THEN 2 END
4968 private function createSqlCase($idCol, $cids) {
4970 foreach ($cids as $weight => $cid) {
4971 $buf .= " WHEN $idCol = $cid THEN $weight \n";
4978 * Populate $this->_permissionWhereClause with permission related clause and update other
4979 * query related properties.
4981 * Function calls ACL permission class and hooks to filter the query appropriately
4983 * Note that these 2 params were in the code when extracted from another function
4984 * and a second round extraction would be to make them properties of the class
4986 * @param bool $onlyDeleted
4987 * Only get deleted contacts.
4988 * @param bool $count
4989 * Return Count only.
4991 public function generatePermissionClause($onlyDeleted = FALSE, $count = FALSE) {
4992 if (!$this->_skipPermission
) {
4993 $this->_permissionWhereClause
= CRM_ACL_API
::whereClause(
4994 CRM_Core_Permission
::VIEW
,
4996 $this->_whereTables
,
4999 $this->_skipDeleteClause
5002 // regenerate fromClause since permission might have added tables
5003 if ($this->_permissionWhereClause
) {
5004 //fix for row count in qill (in contribute/membership find)
5006 $this->_useDistinct
= TRUE;
5009 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
5010 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
5011 // note : this modifies _fromClause and _simpleFromClause
5012 $this->includePseudoFieldsJoin($this->_sort
);
5016 // add delete clause if needed even if we are skipping permission
5018 if (!$this->_skipDeleteClause
) {
5019 if (CRM_Core_Permission
::check('access deleted contacts') and $onlyDeleted) {
5020 $this->_permissionWhereClause
= '(contact_a.is_deleted)';
5024 $this->_permissionWhereClause
= '(contact_a.is_deleted = 0)';
5033 public function setSkipPermission($val) {
5034 $this->_skipPermission
= $val;
5038 * @param null $context
5042 public function summaryContribution($context = NULL) {
5043 list($innerselect, $from, $where, $having) = $this->query(TRUE);
5044 if ($this->_permissionWhereClause
) {
5045 $where .= " AND " . $this->_permissionWhereClause
;
5047 if ($context == 'search') {
5048 $where .= " AND contact_a.is_deleted = 0 ";
5051 $this->appendFinancialTypeWhereAndFromToQueryStrings($where, $from);
5053 $summary = ['total' => []];
5054 $this->addBasicStatsToSummary($summary, $where, $from);
5056 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
5057 $this->addBasicSoftCreditStatsToStats($summary, $where, $from);
5060 $this->addBasicCancelStatsToSummary($summary, $where, $from);
5066 * Append financial ACL limits to the query from & where clauses, if applicable.
5068 * @param string $where
5069 * @param string $from
5071 public function appendFinancialTypeWhereAndFromToQueryStrings(&$where, &$from) {
5072 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
5075 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
5076 if (!empty($financialTypes)) {
5077 $where .= " AND civicrm_contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND li.id IS NULL";
5078 $from .= " LEFT JOIN civicrm_line_item li
5079 ON civicrm_contribution.id = li.contribution_id AND
5080 li.entity_table = 'civicrm_contribution' AND li.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ") ";
5083 $where .= " AND civicrm_contribution.financial_type_id IN (0)";
5088 * Getter for the qill object.
5092 public function qill() {
5093 return $this->_qill
;
5097 * Default set of return default hier return properties.
5101 public static function &defaultHierReturnProperties() {
5102 if (!isset(self
::$_defaultHierReturnProperties)) {
5103 self
::$_defaultHierReturnProperties = array(
5106 'legal_identifier' => 1,
5107 'external_identifier' => 1,
5108 'contact_type' => 1,
5109 'contact_sub_type' => 1,
5111 'display_name' => 1,
5118 'formal_title' => 1,
5119 'communication_style_id' => 1,
5120 'email_greeting' => 1,
5121 'postal_greeting' => 1,
5125 'preferred_communication_method' => 1,
5126 'do_not_phone' => 1,
5127 'do_not_email' => 1,
5130 'do_not_trade' => 1,
5131 'location' => array(
5133 'location_type' => 1,
5134 'street_address' => 1,
5136 'state_province' => 1,
5138 'postal_code_suffix' => 1,
5141 'phone-Mobile' => 1,
5154 'location_type' => 1,
5155 'street_address' => 1,
5157 'state_province' => 1,
5159 'postal_code_suffix' => 1,
5162 'phone-Mobile' => 1,
5176 return self
::$_defaultHierReturnProperties;
5180 * Build query for a date field.
5182 * @param array $values
5183 * @param string $tableName
5184 * @param string $fieldName
5185 * @param string $dbFieldName
5186 * @param string $fieldTitle
5187 * @param bool $appendTimeStamp
5188 * @param string $dateFormat
5190 public function dateQueryBuilder(
5191 &$values, $tableName, $fieldName,
5192 $dbFieldName, $fieldTitle,
5193 $appendTimeStamp = TRUE,
5194 $dateFormat = 'YmdHis'
5196 list($name, $op, $value, $grouping, $wildcard) = $values;
5198 if ($name == "{$fieldName}_low" ||
5199 $name == "{$fieldName}_high"
5201 if (isset($this->_rangeCache
[$fieldName]) ||
!$value) {
5204 $this->_rangeCache
[$fieldName] = 1;
5206 $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = NULL;
5208 if ($name == $fieldName . '_low') {
5210 $firstPhrase = ts('greater than or equal to');
5211 $firstDate = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5213 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5214 if (!empty($secondValues) && $secondValues[2]) {
5216 $secondPhrase = ts('less than or equal to');
5217 $secondValue = $secondValues[2];
5219 if ($appendTimeStamp && strlen($secondValue) == 10) {
5220 $secondValue .= ' 23:59:59';
5222 $secondDate = CRM_Utils_Date
::processDate($secondValue, NULL, FALSE, $dateFormat);
5225 elseif ($name == $fieldName . '_high') {
5227 $firstPhrase = ts('less than or equal to');
5229 if ($appendTimeStamp && strlen($value) == 10) {
5230 $value .= ' 23:59:59';
5232 $firstDate = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5234 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5235 if (!empty($secondValues) && $secondValues[2]) {
5237 $secondPhrase = ts('greater than or equal to');
5238 $secondValue = $secondValues[2];
5239 $secondDate = CRM_Utils_Date
::processDate($secondValue, NULL, FALSE, $dateFormat);
5243 if (!$appendTimeStamp) {
5244 $firstDate = substr($firstDate, 0, 8);
5246 $firstDateFormat = CRM_Utils_Date
::customFormat($firstDate);
5249 if (!$appendTimeStamp) {
5250 $secondDate = substr($secondDate, 0, 8);
5252 $secondDateFormat = CRM_Utils_Date
::customFormat($secondDate);
5255 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5257 $this->_where
[$grouping][] = "
5258 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5259 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5261 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\" " . ts('AND') . " $secondPhrase \"$secondDateFormat\"";
5264 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5265 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
5269 if ($name == $fieldName) {
5270 //In Get API, for operators other then '=' the $value is in array(op => value) format
5271 if (is_array($value) && !empty($value) && in_array(key($value), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
5273 $value = $value[$op];
5276 $date = $format = NULL;
5277 if (strstr($op, 'IN')) {
5279 foreach ($value as &$date) {
5280 $date = CRM_Utils_Date
::processDate($date, NULL, FALSE, $dateFormat);
5281 if (!$appendTimeStamp) {
5282 $date = substr($date, 0, 8);
5284 $format[] = CRM_Utils_Date
::customFormat($date);
5286 $date = "('" . implode("','", $value) . "')";
5287 $format = implode(', ', $format);
5289 elseif ($value && (!strstr($op, 'NULL') && !strstr($op, 'EMPTY'))) {
5290 $date = CRM_Utils_Date
::processDate($value, NULL, FALSE, $dateFormat);
5291 if (!$appendTimeStamp) {
5292 $date = substr($date, 0, 8);
5294 $format = CRM_Utils_Date
::customFormat($date);
5299 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op $date";
5302 $this->_where
[$grouping][] = self
::buildClause("{$tableName}.{$dbFieldName}", $op);
5305 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5307 $op = CRM_Utils_Array
::value($op, CRM_Core_SelectValues
::getSearchBuilderOperators(), $op);
5308 $this->_qill
[$grouping][] = "$fieldTitle $op $format";
5314 * @param string $tableName
5315 * @param string $fieldName
5316 * @param string $dbFieldName
5317 * @param $fieldTitle
5318 * @param null $options
5320 public function numberRangeBuilder(
5322 $tableName, $fieldName,
5323 $dbFieldName, $fieldTitle,
5326 list($name, $op, $value, $grouping, $wildcard) = $values;
5328 if ($name == "{$fieldName}_low" ||
5329 $name == "{$fieldName}_high"
5331 if (isset($this->_rangeCache
[$fieldName])) {
5334 $this->_rangeCache
[$fieldName] = 1;
5336 $secondOP = $secondPhrase = $secondValue = NULL;
5338 if ($name == "{$fieldName}_low") {
5340 $firstPhrase = ts('greater than');
5342 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5343 if (!empty($secondValues)) {
5345 $secondPhrase = ts('less than');
5346 $secondValue = $secondValues[2];
5351 $firstPhrase = ts('less than');
5353 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5354 if (!empty($secondValues)) {
5356 $secondPhrase = ts('greater than');
5357 $secondValue = $secondValues[2];
5362 $this->_where
[$grouping][] = "
5363 ( {$tableName}.{$dbFieldName} $firstOP {$value} ) AND
5364 ( {$tableName}.{$dbFieldName} $secondOP {$secondValue} )
5366 $displayValue = $options ?
$options[$value] : $value;
5367 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5369 $this->_qill
[$grouping][]
5370 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5373 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP {$value}";
5374 $displayValue = $options ?
$options[$value] : $value;
5375 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5377 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5382 if ($name == $fieldName) {
5386 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $op {$value}";
5388 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5389 $displayValue = $options ?
$options[$value] : $value;
5390 $this->_qill
[$grouping][] = "$fieldTitle - $phrase \"$displayValue\"";
5397 * @param string $tableName
5398 * @param string $fieldName
5399 * @param string $dbFieldName
5400 * @param $fieldTitle
5401 * @param null $options
5403 public function ageRangeQueryBuilder(
5405 $tableName, $fieldName,
5406 $dbFieldName, $fieldTitle,
5409 list($name, $op, $value, $grouping, $wildcard) = $values;
5411 $asofDateValues = $this->getWhereValues("{$fieldName}_asof_date", $grouping);
5412 $asofDate = NULL; // will be treated as current day
5413 if ($asofDateValues) {
5414 $asofDate = CRM_Utils_Date
::processDate($asofDateValues[2]);
5415 $asofDateFormat = CRM_Utils_Date
::customFormat(substr($asofDate, 0, 8));
5416 $fieldTitle .= ' ' . ts('as of') . ' ' . $asofDateFormat;
5419 if ($name == "{$fieldName}_low" ||
5420 $name == "{$fieldName}_high"
5422 if (isset($this->_rangeCache
[$fieldName])) {
5425 $this->_rangeCache
[$fieldName] = 1;
5427 $secondOP = $secondPhrase = $secondValue = NULL;
5429 if ($name == "{$fieldName}_low") {
5430 $firstPhrase = ts('greater than or equal to');
5431 // NB: age > X means date of birth < Y
5433 $firstDate = self
::calcDateFromAge($asofDate, $value, 'min');
5435 $secondValues = $this->getWhereValues("{$fieldName}_high", $grouping);
5436 if (!empty($secondValues)) {
5438 $secondPhrase = ts('less than or equal to');
5439 $secondValue = $secondValues[2];
5440 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'max');
5445 $firstPhrase = ts('less than or equal to');
5446 $firstDate = self
::calcDateFromAge($asofDate, $value, 'max');
5448 $secondValues = $this->getWhereValues("{$fieldName}_low", $grouping);
5449 if (!empty($secondValues)) {
5451 $secondPhrase = ts('greater than or equal to');
5452 $secondValue = $secondValues[2];
5453 $secondDate = self
::calcDateFromAge($asofDate, $secondValue, 'min');
5458 $this->_where
[$grouping][] = "
5459 ( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
5460 ( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
5462 $displayValue = $options ?
$options[$value] : $value;
5463 $secondDisplayValue = $options ?
$options[$secondValue] : $secondValue;
5465 $this->_qill
[$grouping][]
5466 = "$fieldTitle - $firstPhrase \"$displayValue\" " . ts('AND') . " $secondPhrase \"$secondDisplayValue\"";
5469 $this->_where
[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
5470 $displayValue = $options ?
$options[$value] : $value;
5471 $this->_qill
[$grouping][] = "$fieldTitle - $firstPhrase \"$displayValue\"";
5473 $this->_tables
[$tableName] = $this->_whereTables
[$tableName] = 1;
5479 * Calculate date from age.
5481 * @param string $asofDate
5483 * @param string $type
5487 public static function calcDateFromAge($asofDate, $age, $type) {
5488 $date = new DateTime($asofDate);
5489 if ($type == "min") {
5490 // minimum age is $age: dob <= date - age "235959"
5491 $date->sub(new DateInterval("P" . $age . "Y"));
5492 return $date->format('Ymd') . "235959";
5495 // max age is $age: dob >= date - (age + 1y) + 1d "000000"
5496 $date->sub(new DateInterval("P" . ($age +
1) . "Y"))->add(new DateInterval("P1D"));
5497 return $date->format('Ymd') . "000000";
5502 * Given the field name, operator, value & its data type
5503 * builds the where Clause for the query
5504 * used for handling 'IS NULL'/'IS NOT NULL' operators
5506 * @param string $field
5510 * @param string $value
5512 * @param string $dataType
5513 * Data type of the field.
5516 * Where clause for the query.
5518 public static function buildClause($field, $op, $value = NULL, $dataType = NULL) {
5520 $clause = "$field $op";
5528 $clause = ($dataType == 'Date') ?
" $field IS NULL " : " (NULLIF($field, '') IS NULL) ";
5531 case 'IS NOT EMPTY':
5532 $clause = ($dataType == 'Date') ?
" $field IS NOT NULL " : " (NULLIF($field, '') IS NOT NULL) ";
5536 return " {$clause} BINARY '{$value}' ";
5540 // I feel like this would be escaped properly if passed through $queryString = CRM_Core_DAO::createSqlFilter.
5541 if (!empty($value) && (!is_array($value) ||
!array_key_exists($op, $value))) {
5542 $value = array($op => (array) $value);
5546 if (empty($dataType) ||
$dataType == 'Date') {
5547 $dataType = 'String';
5549 if (is_array($value)) {
5550 //this could have come from the api - as in the restWhere section we potentially use the api operator syntax which is becoming more
5551 // widely used and consistent across the codebase
5552 // adding this here won't accept the search functions which don't submit an array
5553 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, $value, $dataType)) != FALSE) {
5555 return $queryString;
5557 if (!empty($value[0]) && $op === 'BETWEEN') {
5558 CRM_Core_Error
::deprecatedFunctionWarning('Fix search input params');
5559 if (($queryString = CRM_Core_DAO
::createSqlFilter($field, array($op => $value), $dataType)) != FALSE) {
5560 return $queryString;
5563 throw new CRM_Core_Exception(ts('Failed to interpret input for search'));
5566 $value = CRM_Utils_Type
::escape($value, $dataType);
5567 // if we don't have a dataType we should assume
5568 if ($dataType == 'String' ||
$dataType == 'Text') {
5569 $value = "'" . $value . "'";
5571 return "$clause $value";
5576 * @param bool $reset
5580 public function openedSearchPanes($reset = FALSE) {
5581 if (!$reset ||
empty($this->_whereTables
)) {
5582 return self
::$_openedPanes;
5585 // pane name to table mapper
5586 $panesMapper = array(
5587 ts('Contributions') => 'civicrm_contribution',
5588 ts('Memberships') => 'civicrm_membership',
5589 ts('Events') => 'civicrm_participant',
5590 ts('Relationships') => 'civicrm_relationship',
5591 ts('Activities') => 'civicrm_activity',
5592 ts('Pledges') => 'civicrm_pledge',
5593 ts('Cases') => 'civicrm_case',
5594 ts('Grants') => 'civicrm_grant',
5595 ts('Address Fields') => 'civicrm_address',
5596 ts('Notes') => 'civicrm_note',
5597 ts('Change Log') => 'civicrm_log',
5598 ts('Mailings') => 'civicrm_mailing',
5600 CRM_Contact_BAO_Query_Hook
::singleton()->getPanesMapper($panesMapper);
5602 foreach (array_keys($this->_whereTables
) as $table) {
5603 if ($panName = array_search($table, $panesMapper)) {
5604 self
::$_openedPanes[$panName] = TRUE;
5608 return self
::$_openedPanes;
5614 public function setOperator($operator) {
5615 $validOperators = array('AND', 'OR');
5616 if (!in_array($operator, $validOperators)) {
5619 $this->_operator
= $operator;
5625 public function getOperator() {
5626 return $this->_operator
;
5634 public function filterRelatedContacts(&$from, &$where, &$having) {
5635 if (!isset(Civi
::$statics[__CLASS__
]['related_contacts_filter'])) {
5636 Civi
::$statics[__CLASS__
]['related_contacts_filter'] = array();
5638 $_rTempCache =& Civi
::$statics[__CLASS__
]['related_contacts_filter'];
5639 // since there only can be one instance of this filter in every query
5640 // skip if filter has already applied
5641 foreach ($_rTempCache as $acache) {
5642 foreach ($acache['queries'] as $aqcache) {
5643 if (strpos($from, $aqcache['from']) !== FALSE) {
5649 $arg_sig = sha1("$from $where $having");
5650 if (isset($_rTempCache[$arg_sig])) {
5651 $cache = $_rTempCache[$arg_sig];
5654 // create temp table with contact ids
5655 $tableName = CRM_Core_DAO
::createTempTableName('civicrm_transform', TRUE);
5657 $sql = "CREATE TEMPORARY TABLE $tableName ( contact_id int primary key) ENGINE=HEAP";
5658 CRM_Core_DAO
::executeQuery($sql);
5661 REPLACE INTO $tableName ( contact_id )
5667 CRM_Core_DAO
::executeQuery($sql);
5669 $cache = array('tableName' => $tableName, 'queries' => array());
5670 $_rTempCache[$arg_sig] = $cache;
5672 // upsert the query depending on relationship type
5673 if (isset($cache['queries'][$this->_displayRelationshipType
])) {
5674 $qcache = $cache['queries'][$this->_displayRelationshipType
];
5677 $tableName = $cache['tableName'];
5682 $rTypes = CRM_Core_PseudoConstant
::relationshipType();
5683 if (is_numeric($this->_displayRelationshipType
)) {
5684 $relationshipTypeLabel = $rTypes[$this->_displayRelationshipType
]['label_a_b'];
5686 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id OR displayRelType.contact_id_b = contact_a.id )
5687 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
5689 $qcache['where'] = "
5690 WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
5691 AND displayRelType.is_active = 1
5695 list($relType, $dirOne, $dirTwo) = explode('_', $this->_displayRelationshipType
);
5696 if ($dirOne == 'a') {
5697 $relationshipTypeLabel = $rTypes[$relType]['label_a_b'];
5698 $qcache['from'] .= "
5699 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a = contact_a.id )
5700 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_b )
5704 $relationshipTypeLabel = $rTypes[$relType]['label_b_a'];
5705 $qcache['from'] .= "
5706 INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_b = contact_a.id )
5707 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a )
5710 $qcache['where'] = "
5711 WHERE displayRelType.relationship_type_id = $relType
5712 AND displayRelType.is_active = 1
5715 $qcache['relTypeLabel'] = $relationshipTypeLabel;
5716 $_rTempCache[$arg_sig]['queries'][$this->_displayRelationshipType
] = $qcache;
5718 $qillMessage = ts('Contacts with a Relationship Type of: ');
5719 $iqill = $qillMessage . "'" . $qcache['relTypeLabel'] . "'";
5720 if (!is_array($this->_qill
[0]) ||
!in_array($iqill, $this->_qill
[0])) {
5721 $this->_qill
[0][] = $iqill;
5723 if (strpos($from, $qcache['from']) === FALSE) {
5724 // lets replace all the INNER JOIN's in the $from so we dont exclude other data
5725 // this happens when we have an event_type in the quert (CRM-7969)
5726 $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
5727 $from .= $qcache['from'];
5728 $where = $qcache['where'];
5729 if (!empty($this->_permissionWhereClause
)) {
5730 $where .= "AND $this->_permissionWhereClause";
5738 * See CRM-19811 for why this is database hurty without apparent benefit.
5744 public static function caseImportant($op) {
5746 in_array($op, array('LIKE', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY')) ?
FALSE : TRUE;
5750 * @param $returnProperties
5755 public static function componentPresent(&$returnProperties, $prefix) {
5756 foreach ($returnProperties as $name => $dontCare) {
5757 if (substr($name, 0, strlen($prefix)) == $prefix) {
5765 * Builds the necessary structures for all fields that are similar to option value look-ups.
5767 * @param string $name
5768 * the name of the field.
5770 * the sql operator, this function should handle ALL SQL operators.
5771 * @param string $value
5772 * depends on the operator and who's calling the query builder.
5773 * @param int $grouping
5774 * the index where to place the where clause.
5775 * @param string $daoName
5777 * @param array $field
5778 * an array that contains various properties of the field identified by $name.
5779 * @param string $label
5780 * The label for this field element.
5781 * @param string $dataType
5782 * The data type for this element.
5783 * @param bool $useIDsOnly
5785 public function optionValueQuery(
5793 $dataType = 'String',
5797 $pseudoFields = array(
5804 'communication_style_id',
5808 list($tableName, $fieldName) = explode('.', $field['where'], 2);
5809 if ($tableName == 'civicrm_contact') {
5810 $wc = "contact_a.$fieldName";
5813 // Special handling for on_hold, so that we actually use the 'where'
5814 // property in order to limit the query by the on_hold status of the email,
5815 // instead of using email.id which would be nonsensical.
5816 if ($field['name'] == 'on_hold') {
5817 $wc = "{$field['where']}";
5820 $wc = "$tableName.id";
5825 CRM_Core_Error
::deprecatedFunctionWarning('pass $ids to this method');
5826 $wc = "{$field['where']}";
5828 if (in_array($name, $pseudoFields)) {
5829 if (!in_array($name, array('gender_id', 'prefix_id', 'suffix_id', 'communication_style_id'))) {
5830 $wc = "contact_a.{$name}_id";
5832 $dataType = 'Positive';
5833 $value = (!$value) ?
0 : $value;
5835 if ($name == "world_region") {
5836 $field['name'] = $name;
5839 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue($daoName, $field['name'], $value, $op);
5840 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(1 => $label, 2 => $qillop, 3 => $qillVal));
5841 $this->_where
[$grouping][] = self
::buildClause($wc, $op, $value, $dataType);
5845 * Check and explode a user defined numeric string into an array
5846 * this was the protocol used by search builder in the old old days before we had
5847 * super nice js widgets to do the hard work
5849 * @param string $string
5850 * @param string $dataType
5851 * The dataType we should check for the values, default integer.
5853 * @return bool|array
5854 * false if string does not match the pattern
5855 * array of numeric values if string does match the pattern
5857 public static function parseSearchBuilderString($string, $dataType = 'Integer') {
5858 $string = trim($string);
5859 if (substr($string, 0, 1) != '(' ||
substr($string, -1, 1) != ')') {
5863 $string = substr($string, 1, -1);
5864 $values = explode(',', $string);
5865 if (empty($values)) {
5869 $returnValues = array();
5870 foreach ($values as $v) {
5871 if ($dataType == 'Integer' && !is_numeric($v)) {
5874 elseif ($dataType == 'String' && !is_string($v)) {
5877 $returnValues[] = trim($v);
5880 if (empty($returnValues)) {
5884 return $returnValues;
5888 * Convert the pseudo constants id's to their names
5890 * @param CRM_Core_DAO $dao
5891 * @param bool $return
5892 * @param bool $usedForAPI
5894 * @return array|NULL
5896 public function convertToPseudoNames(&$dao, $return = FALSE, $usedForAPI = FALSE) {
5897 if (empty($this->_pseudoConstantsSelect
)) {
5901 foreach ($this->_pseudoConstantsSelect
as $key => $value) {
5902 if (!empty($this->_pseudoConstantsSelect
[$key]['sorting'])) {
5906 if (is_object($dao) && property_exists($dao, $value['idCol'])) {
5907 $val = $dao->{$value['idCol']};
5908 if ($key == 'groups') {
5909 $dao->groups
= $this->convertGroupIDStringToLabelString($dao, $val);
5913 if (CRM_Utils_System
::isNull($val)) {
5916 elseif (!empty($value['pseudoconstant'])) {
5917 // If pseudoconstant is set that is kind of defacto for 'we have a bit more info about this'
5918 // and we can use the metadata to figure it out.
5919 // ideally this bit of IF will absorb & replace all the rest in time as we move to
5920 // more metadata based choices.
5921 if (strpos($val, CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
5922 $dbValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, trim($val, CRM_Core_DAO
::VALUE_SEPARATOR
));
5923 foreach ($dbValues as $pseudoValue) {
5924 $convertedValues[] = CRM_Core_PseudoConstant
::getLabel($value['bao'], $value['idCol'], $pseudoValue);
5927 $dao->$key = ($usedForAPI) ?
$convertedValues : implode(', ', $convertedValues);
5928 $realFieldName = CRM_Utils_Array
::value('field_name', $this->_pseudoConstantsSelect
[$key]);
5929 if ($usedForAPI && $realFieldName) {
5930 // normally we would see 2 fields returned for pseudoConstants. An exception is
5931 // preferred_communication_method where there is no id-variant.
5932 // For the api we prioritise getting the real data returned.
5933 // over the resolved version
5934 $dao->$realFieldName = $dbValues;
5939 // This is basically the same as the default but since we have the bao we can use
5940 // a cached function.
5941 $dao->$key = CRM_Core_PseudoConstant
::getLabel($value['bao'], $value['idCol'], $val);
5944 elseif ($baoName = CRM_Utils_Array
::value('bao', $value, NULL)) {
5946 $idColumn = "{$key}_id";
5947 $dao->$idColumn = $val;
5949 if ($key == 'state_province_name') {
5950 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::stateProvince($val);
5953 $dao->{$value['pseudoField']} = $dao->$key = CRM_Core_PseudoConstant
::getLabel($baoName, $value['pseudoField'], $val);
5956 elseif ($value['pseudoField'] == 'state_province_abbreviation') {
5957 $dao->$key = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($val);
5959 // @todo handle this in the section above for pseudoconstants.
5960 elseif (in_array($value['pseudoField'], array('participant_role_id', 'participant_role'))) {
5961 // @todo define bao on this & merge into the above condition.
5962 $viewValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $val);
5964 if ($value['pseudoField'] == 'participant_role') {
5965 $pseudoOptions = CRM_Core_PseudoConstant
::get('CRM_Event_DAO_Participant', 'role_id');
5966 foreach ($viewValues as $k => $v) {
5967 $viewValues[$k] = $pseudoOptions[$v];
5970 $dao->$key = ($usedForAPI && count($viewValues) > 1) ?
$viewValues : implode(', ', $viewValues);
5973 $labels = CRM_Core_OptionGroup
::values($value['pseudoField']);
5974 $dao->$key = $labels[$val];
5977 // return converted values in array format
5979 if (strpos($key, '-') !== FALSE) {
5980 $keyVal = explode('-', $key);
5981 $current = &$values;
5982 $lastElement = array_pop($keyVal);
5983 foreach ($keyVal as $v) {
5984 if (!array_key_exists($v, $current)) {
5985 $current[$v] = array();
5987 $current = &$current[$v];
5989 $current[$lastElement] = $dao->$key;
5992 $values[$key] = $dao->$key;
5999 'gender_id' => 'gender',
6000 'prefix_id' => 'individual_prefix',
6001 'suffix_id' => 'individual_suffix',
6002 'communication_style_id' => 'communication_style',
6003 ) as $realField => $labelField) {
6004 // This is a temporary routine for handling these fields while
6005 // we figure out how to handled them based on metadata in
6006 /// export and search builder. CRM-19815, CRM-19830.
6007 if (isset($dao->$realField) && is_numeric($dao->$realField) && isset($dao->$labelField)) {
6008 $dao->$realField = $dao->$labelField;
6016 * Include pseudo fields LEFT JOIN.
6017 * @param string|array $sort can be a object or string
6019 * @return array|NULL
6021 public function includePseudoFieldsJoin($sort) {
6022 if (!$sort ||
empty($this->_pseudoConstantsSelect
)) {
6025 $sort = is_string($sort) ?
$sort : $sort->orderBy();
6028 foreach ($this->_pseudoConstantsSelect
as $name => $value) {
6029 if (!empty($value['table'])) {
6030 $regex = "/({$value['table']}\.|{$name})/";
6031 if (preg_match($regex, $sort)) {
6032 $this->_elemnt
[$value['element']] = 1;
6033 $this->_select
[$value['element']] = $value['select'];
6034 $this->_pseudoConstantsSelect
[$name]['sorting'] = 1;
6035 $present[$value['table']] = $value['join'];
6039 $presentSimpleFrom = $present;
6041 if (array_key_exists('civicrm_worldregion', $this->_whereTables
) &&
6042 array_key_exists('civicrm_country', $presentSimpleFrom)
6044 unset($presentSimpleFrom['civicrm_country']);
6046 if (array_key_exists('civicrm_worldregion', $this->_tables
) &&
6047 array_key_exists('civicrm_country', $present)
6049 unset($present['civicrm_country']);
6052 $presentClause = $presentSimpleFromClause = NULL;
6053 if (!empty($present)) {
6054 $presentClause = implode(' ', $present);
6056 if (!empty($presentSimpleFrom)) {
6057 $presentSimpleFromClause = implode(' ', $presentSimpleFrom);
6060 $this->_fromClause
= $this->_fromClause
. $presentClause;
6061 $this->_simpleFromClause
= $this->_simpleFromClause
. $presentSimpleFromClause;
6063 return array($presentClause, $presentSimpleFromClause);
6067 * Build qill for field.
6069 * Qill refers to the query detail visible on the UI.
6071 * @param string $daoName
6072 * @param string $fieldName
6073 * @param mixed $fieldValue
6075 * @param array $pseudoExtraParam
6077 * Type of the field per CRM_Utils_Type
6081 public static function buildQillForFieldValue(
6086 $pseudoExtraParam = array(),
6087 $type = CRM_Utils_Type
::T_STRING
6089 $qillOperators = CRM_Core_SelectValues
::getSearchBuilderOperators();
6091 //API usually have fieldValue format as array(operator => array(values)),
6092 //so we need to separate operator out of fieldValue param
6093 if (is_array($fieldValue) && in_array(key($fieldValue), CRM_Core_DAO
::acceptedSQLOperators(), TRUE)) {
6094 $op = key($fieldValue);
6095 $fieldValue = $fieldValue[$op];
6098 // if Operator chosen is NULL/EMPTY then
6099 if (strpos($op, 'NULL') !== FALSE ||
strpos($op, 'EMPTY') !== FALSE) {
6100 return array(CRM_Utils_Array
::value($op, $qillOperators, $op), '');
6103 if ($fieldName == 'activity_type_id') {
6104 $pseudoOptions = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'label', TRUE);
6106 elseif ($fieldName == 'country_id') {
6107 $pseudoOptions = CRM_Core_PseudoConstant
::country();
6109 elseif ($fieldName == 'county_id') {
6110 $pseudoOptions = CRM_Core_PseudoConstant
::county();
6112 elseif ($fieldName == 'world_region') {
6113 $pseudoOptions = CRM_Core_PseudoConstant
::worldRegion();
6115 elseif ($daoName == 'CRM_Event_DAO_Event' && $fieldName == 'id') {
6116 $checkPermission = CRM_Utils_Array
::value('check_permission', $pseudoExtraParam, TRUE);
6117 $pseudoOptions = CRM_Event_BAO_Event
::getEvents(0, $fieldValue, TRUE, $checkPermission, TRUE);
6119 elseif ($fieldName == 'contribution_product_id') {
6120 $pseudoOptions = CRM_Contribute_PseudoConstant
::products();
6122 elseif ($daoName == 'CRM_Contact_DAO_Group' && $fieldName == 'id') {
6123 $pseudoOptions = CRM_Core_PseudoConstant
::group();
6125 elseif ($daoName == 'CRM_Batch_BAO_EntityBatch' && $fieldName == 'batch_id') {
6126 $pseudoOptions = CRM_Contribute_PseudoConstant
::batch();
6129 $pseudoOptions = CRM_Core_PseudoConstant
::get($daoName, $fieldName, $pseudoExtraParam);
6132 if (is_array($fieldValue)) {
6133 $qillString = array();
6134 if (!empty($pseudoOptions)) {
6135 foreach ((array) $fieldValue as $val) {
6136 $qillString[] = CRM_Utils_Array
::value($val, $pseudoOptions, $val);
6138 $fieldValue = implode(', ', $qillString);
6141 if ($type == CRM_Utils_Type
::T_DATE
) {
6142 foreach ($fieldValue as $index => $value) {
6143 $fieldValue[$index] = CRM_Utils_Date
::customFormat($value);
6147 // @todo - this is a bit specific (one operator).
6148 // However it is covered by a unit test so can be altered later with
6150 if ($op == 'BETWEEN') {
6151 $separator = ' AND ';
6153 $fieldValue = implode($separator, $fieldValue);
6156 elseif (!empty($pseudoOptions) && array_key_exists($fieldValue, $pseudoOptions)) {
6157 $fieldValue = $pseudoOptions[$fieldValue];
6159 elseif ($type === CRM_Utils_Type
::T_DATE
) {
6160 $fieldValue = CRM_Utils_Date
::customFormat($fieldValue);
6163 return array(CRM_Utils_Array
::value($op, $qillOperators, $op), $fieldValue);
6167 * Alter value to reflect wildcard settings.
6169 * The form will have tried to guess whether this is a good field to wildcard but there is
6170 * also a site-wide setting that specifies whether it is OK to append the wild card to the beginning
6171 * or only the end of the string
6173 * @param bool $wildcard
6174 * This is a bool made on an assessment 'elsewhere' on whether this is a good field to wildcard.
6176 * Generally '=' or 'LIKE'.
6177 * @param string $value
6178 * The search string.
6182 public static function getWildCardedValue($wildcard, $op, $value) {
6183 if ($wildcard && $op == 'LIKE') {
6184 if (CRM_Core_Config
::singleton()->includeWildCardInName
&& (substr($value, 0, 1) != '%')) {
6197 * Process special fields of Search Form in OK (Operator in Key) format
6199 * @param array $formValues
6200 * @param array $specialFields
6201 * Special params to be processed
6202 * @param array $changeNames
6203 * Array of fields whose name should be changed
6205 public static function processSpecialFormValue(&$formValues, $specialFields, $changeNames = array()) {
6206 // Array of special fields whose value are considered only for NULL or EMPTY operators
6207 $nullableFields = array('contribution_batch_id');
6209 foreach ($specialFields as $element) {
6210 $value = CRM_Utils_Array
::value($element, $formValues);
6212 if (is_array($value)) {
6213 if (in_array($element, array_keys($changeNames))) {
6214 unset($formValues[$element]);
6215 $element = $changeNames[$element];
6217 $formValues[$element] = array('IN' => $value);
6219 elseif (in_array($value, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
6220 $formValues[$element] = array($value => 1);
6222 elseif (!in_array($element, $nullableFields)) {
6223 // if wildcard is already present return searchString as it is OR append and/or prepend with wildcard
6224 $isWilcard = strstr($value, '%') ?
FALSE : CRM_Core_Config
::singleton()->includeWildCardInName
;
6225 $formValues[$element] = array('LIKE' => self
::getWildCardedValue($isWilcard, 'LIKE', $value));
6232 * Parse and assimilate the various sort options.
6234 * Side-effect: if sorting on a common column from a related table (`city`, `postal_code`,
6235 * `email`), the related table may be joined automatically.
6237 * At time of writing, this code is deeply flawed and should be rewritten. For the moment,
6238 * it's been extracted to a standalone function.
6240 * @param string|CRM_Utils_Sort $sort
6241 * The order by string.
6242 * @param bool $sortByChar
6243 * If true returns the distinct array of first characters for search results.
6244 * @param null $sortOrder
6245 * Who knows? Hu knows. He who knows Hu knows who.
6246 * @param string $additionalFromClause
6247 * Should be clause with proper joins, effective to reduce where clause load.
6249 * list(string $orderByClause, string $additionalFromClause).
6251 protected function prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFromClause) {
6255 if (CRM_Core_Config
::singleton()->includeOrderByClause ||
6256 isset($this->_distinctComponentClause
)
6259 if (is_string($sort)) {
6263 $orderBy = trim($sort->orderBy());
6265 // Deliberately remove the backticks again, as they mess up the evil
6266 // string munging below. This balanced by re-escaping before use.
6267 $orderBy = str_replace('`', '', $orderBy);
6269 if (!empty($orderBy)) {
6270 // this is special case while searching for
6271 // change log CRM-1718
6272 if (preg_match('/sort_name/i', $orderBy)) {
6273 $orderBy = str_replace('sort_name', 'contact_a.sort_name', $orderBy);
6277 $orderBy .= " $sortOrder";
6280 // always add contact_a.id to the ORDER clause
6281 // so the order is deterministic
6282 if (strpos('contact_a.id', $orderBy) === FALSE) {
6283 $orderBy .= ", contact_a.id";
6287 elseif ($sortByChar) {
6288 $orderBy = " sort_name asc";
6291 $orderBy = " contact_a.sort_name ASC, contact_a.id";
6295 return [NULL, $additionalFromClause];
6297 // Remove this here & add it at the end for simplicity.
6298 $order = trim($orderBy);
6299 $orderByArray = explode(',', $order);
6301 foreach ($orderByArray as $orderByClause) {
6302 $orderByClauseParts = explode(' ', trim($orderByClause));
6303 $field = $orderByClauseParts[0];
6304 $direction = isset($orderByClauseParts[1]) ?
$orderByClauseParts[1] : 'asc';
6309 $this->_tables
["civicrm_address"] = $this->_whereTables
["civicrm_address"] = 1;
6310 $order = str_replace($field, "civicrm_address.{$field}", $order);
6314 case 'state_province':
6315 $this->_tables
["civicrm_{$field}"] = $this->_whereTables
["civicrm_{$field}"] = 1;
6316 if (is_array($this->_returnProperties
) && empty($this->_returnProperties
)) {
6317 $additionalFromClause .= " LEFT JOIN civicrm_{$field} ON civicrm_{$field}.id = civicrm_address.{$field}_id";
6319 $order = str_replace($field, "civicrm_{$field}.name", $order);
6323 $this->_tables
["civicrm_email"] = $this->_whereTables
["civicrm_email"] = 1;
6324 $order = str_replace($field, "civicrm_email.{$field}", $order);
6328 $cfID = CRM_Core_BAO_CustomField
::getKeyID($field);
6329 // add to cfIDs array if not present
6330 if (!empty($cfID) && !array_key_exists($cfID, $this->_cfIDs
)) {
6331 $this->_cfIDs
[$cfID] = array();
6332 $this->_customQuery
= new CRM_Core_BAO_CustomQuery($this->_cfIDs
, TRUE, $this->_locationSpecificCustomFields
);
6333 $this->_customQuery
->query();
6334 $this->_select
= array_merge($this->_select
, $this->_customQuery
->_select
);
6335 $this->_tables
= array_merge($this->_tables
, $this->_customQuery
->_tables
);
6338 // By replacing the join to the option value table with the mysql construct
6339 // ORDER BY field('contribution_status_id', 2,1,4)
6340 // we can remove a join. In the case of the option value join it is
6341 /// a join known to cause slow queries.
6342 // @todo cover other pseudoconstant types. Limited to option group ones & Foreign keys
6343 // matching an id+name parrern in the
6344 // first instance for scope reasons. They require slightly different handling as the column (label)
6345 // is not declared for them.
6346 // @todo so far only integer fields are being handled. If we add string fields we need to look at
6348 $fieldSpec = $this->getMetadataForRealField($field);
6349 $pseudoConstantMetadata = CRM_Utils_Array
::value('pseudoconstant', $fieldSpec, FALSE);
6350 if (!empty($pseudoConstantMetadata)
6352 if (!empty($pseudoConstantMetadata['optionGroupName'])
6353 ||
$this->isPseudoFieldAnFK($fieldSpec)
6355 $sortedOptions = $fieldSpec['bao']::buildOptions($fieldSpec['name'], NULL, [
6356 'orderColumn' => CRM_Utils_Array
::value('labelColumn', $pseudoConstantMetadata, 'label'),
6358 $fieldIDsInOrder = implode(',', array_keys($sortedOptions));
6359 // Pretty sure this validation ALSO happens in the order clause & this can't be reached but...
6360 // this might give some early warning.
6361 CRM_Utils_Type
::validate($fieldIDsInOrder, 'CommaSeparatedIntegers');
6362 $order = str_replace("$field", "field({$fieldSpec['name']},$fieldIDsInOrder)", $order);
6364 //CRM-12565 add "`" around $field if it is a pseudo constant
6365 // This appears to be for 'special' fields like locations with appended numbers or hyphens .. maybe.
6366 if (!empty($pseudoConstantMetadata['element']) && $pseudoConstantMetadata['element'] == $field) {
6367 $order = str_replace($field, "`{$field}`", $order);
6373 $this->_fromClause
= self
::fromClause($this->_tables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6374 $this->_simpleFromClause
= self
::fromClause($this->_whereTables
, NULL, NULL, $this->_primaryLocation
, $this->_mode
);
6376 // The above code relies on crazy brittle string manipulation of a peculiarly-encoded ORDER BY
6377 // clause. But this magic helper which forgivingly reescapes ORDER BY.
6378 // Note: $sortByChar implies that $order was hard-coded/trusted, so it can do funky things.
6380 return array(' ORDER BY ' . $order, $additionalFromClause);
6383 $order = CRM_Utils_Type
::escape($order, 'MysqlOrderBy');
6384 return array(' ORDER BY ' . $order, $additionalFromClause);
6389 * Convert a string of group IDs to a string of group labels.
6391 * The original string may include duplicates and groups the user does not have
6392 * permission to see.
6394 * @param CRM_Core_DAO $dao
6395 * @param string $val
6399 public function convertGroupIDStringToLabelString(&$dao, $val) {
6400 $groupIDs = explode(',', $val);
6401 // Note that groups that the user does not have permission to will be excluded (good).
6402 $groups = array_intersect_key(CRM_Core_PseudoConstant
::group(), array_flip($groupIDs));
6403 return implode(', ', $groups);
6408 * Set the qill and where properties for a field.
6410 * This function is intended as a short-term function to encourage refactoring
6411 * & re-use - but really we should just have less special-casing.
6413 * @param string $name
6415 * @param string|array $value
6416 * @param string $grouping
6417 * @param string $field
6419 public function setQillAndWhere($name, $op, $value, $grouping, $field) {
6420 $this->_where
[$grouping][] = self
::buildClause("contact_a.{$name}", $op, $value);
6421 list($qillop, $qillVal) = CRM_Contact_BAO_Query
::buildQillForFieldValue(NULL, $name, $value, $op);
6422 $this->_qill
[$grouping][] = ts("%1 %2 %3", array(
6423 1 => $field['title'],
6430 * Has the pseudoconstant of the field been requested.
6432 * For example if the field is payment_instrument_id then it
6433 * has been requested if either payment_instrument_id or payment_instrument
6434 * have been requested. Payment_instrument is the option groun name field value.
6436 * @param array $field
6437 * @param string $fieldName
6438 * The unique name of the field - ie. the one it will be aliased to in the query.
6442 private function pseudoConstantNameIsInReturnProperties($field, $fieldName = NULL) {
6443 $realField = $this->getMetadataForRealField($fieldName);
6444 if (!isset($realField['pseudoconstant'])) {
6447 $pseudoConstant = $realField['pseudoconstant'];
6448 if (empty($pseudoConstant['optionGroupName']) &&
6449 CRM_Utils_Array
::value('labelColumn', $pseudoConstant) !== 'name') {
6450 // We are increasing our pseudoconstant handling - but still very cautiously,
6451 // hence the check for labelColumn === name
6455 if (!empty($pseudoConstant['optionGroupName']) && CRM_Utils_Array
::value($pseudoConstant['optionGroupName'], $this->_returnProperties
)) {
6458 if (CRM_Utils_Array
::value($fieldName, $this->_returnProperties
)) {
6461 // Is this still required - the above goes off the unique name. Test with things like
6462 // communication_preferences & prefix_id.
6463 if (CRM_Utils_Array
::value($field['name'], $this->_returnProperties
)) {
6470 * Get Select Clause.
6474 public function getSelect() {
6475 $select = "SELECT ";
6476 if (isset($this->_distinctComponentClause
)) {
6477 $select .= "{$this->_distinctComponentClause}, ";
6479 $select .= implode(', ', $this->_select
);
6484 * Add basic statistics to the summary.
6486 * @param array $summary
6487 * @param string $where
6488 * @param string $from
6492 protected function addBasicStatsToSummary(&$summary, $where, $from) {
6493 $summary['total']['count'] = 0;
6494 $summary['total']['amount'] = $summary['total']['avg'] = [];
6497 SELECT COUNT( conts.total_amount ) as total_count,
6498 SUM( conts.total_amount ) as total_amount,
6499 AVG( conts.total_amount ) as total_avg,
6500 conts.currency as currency
6502 SELECT civicrm_contribution.total_amount, COUNT(civicrm_contribution.total_amount) as civicrm_contribution_total_amount_count,
6503 civicrm_contribution.currency
6505 $where AND civicrm_contribution.contribution_status_id = 1
6506 GROUP BY civicrm_contribution.id
6510 $dao = CRM_Core_DAO
::executeQuery($query);
6512 while ($dao->fetch()) {
6513 $summary['total']['count'] +
= $dao->total_count
;
6514 $summary['total']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
6515 $summary['total']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
6518 if (!empty($summary['total']['amount'])) {
6519 $summary['total']['amount'] = implode(', ', $summary['total']['amount']);
6520 $summary['total']['avg'] = implode(', ', $summary['total']['avg']);
6523 $summary['total']['amount'] = $summary['total']['avg'] = 0;
6529 * Add basic soft credit statistics to summary array.
6531 * @param array $summary
6532 * @param string $where
6533 * @param string $from
6535 protected function addBasicSoftCreditStatsToStats(&$summary, $where, $from) {
6537 SELECT COUNT( conts.total_amount ) as total_count,
6538 SUM( conts.total_amount ) as total_amount,
6539 AVG( conts.total_amount ) as total_avg,
6540 conts.currency as currency
6542 SELECT civicrm_contribution_soft.amount as total_amount, civicrm_contribution_soft.currency
6544 $where AND civicrm_contribution.contribution_status_id = 1 AND civicrm_contribution_soft.id IS NOT NULL
6545 GROUP BY civicrm_contribution_soft.id
6549 $dao = CRM_Core_DAO
::executeQuery($query);
6550 $summary['soft_credit']['count'] = 0;
6551 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = [];
6552 while ($dao->fetch()) {
6553 $summary['soft_credit']['count'] +
= $dao->total_count
;
6554 $summary['soft_credit']['amount'][] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
6555 $summary['soft_credit']['avg'][] = CRM_Utils_Money
::format($dao->total_avg
, $dao->currency
);
6557 if (!empty($summary['soft_credit']['amount'])) {
6558 $summary['soft_credit']['amount'] = implode(', ', $summary['soft_credit']['amount']);
6559 $summary['soft_credit']['avg'] = implode(', ', $summary['soft_credit']['avg']);
6562 $summary['soft_credit']['amount'] = $summary['soft_credit']['avg'] = 0;
6567 * Add basic stats about cancelled contributions to the summary.
6569 * @param array $summary
6570 * @param string $where
6571 * @param string $from
6573 protected function addBasicCancelStatsToSummary(&$summary, $where, $from) {
6575 SELECT COUNT( conts.total_amount ) as cancel_count,
6576 SUM( conts.total_amount ) as cancel_amount,
6577 AVG( conts.total_amount ) as cancel_avg,
6578 conts.currency as currency
6580 SELECT civicrm_contribution.total_amount, civicrm_contribution.currency
6582 $where AND civicrm_contribution.cancel_date IS NOT NULL
6583 GROUP BY civicrm_contribution.id
6587 $dao = CRM_Core_DAO
::executeQuery($query);
6590 if ($dao->fetch()) {
6591 $summary['cancel']['count'] = $dao->cancel_count
;
6592 $summary['cancel']['amount'] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
6593 $summary['cancel']['avg'] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
6597 $summary['cancel']['count'] = 0;
6598 $summary['cancel']['amount'] = $summary['cancel']['avg'] = [];
6599 while ($dao->fetch()) {
6600 $summary['cancel']['count'] +
= $dao->cancel_count
;
6601 $summary['cancel']['amount'][] = CRM_Utils_Money
::format($dao->cancel_amount
, $dao->currency
);
6602 $summary['cancel']['avg'][] = CRM_Utils_Money
::format($dao->cancel_avg
, $dao->currency
);
6604 $summary['cancel']['amount'] = implode(', ', $summary['cancel']['amount']);
6605 $summary['cancel']['avg'] = implode(', ', $summary['cancel']['avg']);
6610 * Create the sql query for an contact search.
6612 * @param int $offset
6613 * The offset for the query.
6614 * @param int $rowCount
6615 * The number of rows to return.
6616 * @param string|CRM_Utils_Sort $sort
6617 * The order by string.
6618 * @param bool $count
6619 * Is this a count only query ?.
6620 * @param bool $includeContactIds
6621 * Should we include contact ids?.
6622 * @param bool $sortByChar
6623 * If true returns the distinct array of first characters for search results.
6624 * @param bool $groupContacts
6625 * If true, return only the contact ids.
6626 * @param string $additionalWhereClause
6627 * If the caller wants to further restrict the search (used for components).
6628 * @param null $sortOrder
6629 * @param string $additionalFromClause
6630 * Should be clause with proper joins, effective to reduce where clause load.
6632 * @param bool $skipOrderAndLimit
6635 public function getSearchSQL(
6636 $offset = 0, $rowCount = 0, $sort = NULL,
6637 $count = FALSE, $includeContactIds = FALSE,
6638 $sortByChar = FALSE, $groupContacts = FALSE,
6639 $additionalWhereClause = NULL, $sortOrder = NULL,
6640 $additionalFromClause = NULL, $skipOrderAndLimit = FALSE) {
6642 $sqlParts = $this->getSearchSQLParts($offset, $rowCount, $sort, $count, $includeContactIds, $sortByChar, $groupContacts, $additionalWhereClause, $sortOrder, $additionalFromClause);
6644 if ($skipOrderAndLimit) {
6645 CRM_Core_Error
::deprecatedFunctionWarning('skipOrderAndLimit is deprected - call getSearchSQLParts & construct it in the calling function');
6646 $query = "{$sqlParts['select']} {$sqlParts['from']} {$sqlParts['where']} {$sqlParts['having']} {$sqlParts['group_by']}";
6649 $query = "{$sqlParts['select']} {$sqlParts['from']} {$sqlParts['where']} {$sqlParts['having']} {$sqlParts['group_by']} {$sqlParts['order_by']} {$sqlParts['limit']}";
6655 * Get the component parts of the search query as an array.
6657 * @param int $offset
6658 * The offset for the query.
6659 * @param int $rowCount
6660 * The number of rows to return.
6661 * @param string|CRM_Utils_Sort $sort
6662 * The order by string.
6663 * @param bool $count
6664 * Is this a count only query ?.
6665 * @param bool $includeContactIds
6666 * Should we include contact ids?.
6667 * @param bool $sortByChar
6668 * If true returns the distinct array of first characters for search results.
6669 * @param bool $groupContacts
6670 * If true, return only the contact ids.
6671 * @param string $additionalWhereClause
6672 * If the caller wants to further restrict the search (used for components).
6673 * @param null $sortOrder
6674 * @param string $additionalFromClause
6675 * Should be clause with proper joins, effective to reduce where clause load.
6679 public function getSearchSQLParts($offset = 0, $rowCount = 0, $sort = NULL,
6680 $count = FALSE, $includeContactIds = FALSE,
6681 $sortByChar = FALSE, $groupContacts = FALSE,
6682 $additionalWhereClause = NULL, $sortOrder = NULL,
6683 $additionalFromClause = NULL) {
6684 if ($includeContactIds) {
6685 $this->_includeContactIds
= TRUE;
6686 $this->_whereClause
= $this->whereClause();
6688 $onlyDeleted = in_array([
6696 // if we’re explicitly looking for a certain contact’s contribs, events, etc.
6697 // and that contact happens to be deleted, set $onlyDeleted to true
6698 foreach ($this->_params
as $values) {
6699 $name = CRM_Utils_Array
::value(0, $values);
6700 $op = CRM_Utils_Array
::value(1, $values);
6701 $value = CRM_Utils_Array
::value(2, $values);
6702 if ($name == 'contact_id' and $op == '=') {
6703 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $value, 'is_deleted')) {
6704 $onlyDeleted = TRUE;
6710 // building the query string
6711 $groupBy = $groupByCols = NULL;
6713 if (isset($this->_groupByComponentClause
)) {
6714 $groupByCols = preg_replace('/^GROUP BY /', '', trim($this->_groupByComponentClause
));
6715 $groupByCols = explode(', ', $groupByCols);
6717 elseif ($this->_useGroupBy
) {
6718 $groupByCols = ['contact_a.id'];
6721 if ($this->_mode
& CRM_Contact_BAO_Query
::MODE_ACTIVITY
&& (!$count)) {
6722 $groupByCols = ['civicrm_activity.id'];
6724 if (!empty($groupByCols)) {
6725 $groupBy = " GROUP BY " . implode(', ', $groupByCols);
6728 $order = $orderBy = '';
6730 list($order, $additionalFromClause) = $this->prepareOrderBy($sort, $sortByChar, $sortOrder, $additionalFromClause);
6732 // Two cases where we are disabling FGB (FULL_GROUP_BY_MODE):
6733 // 1. Expecting the search query to return all the first single letter characters of contacts ONLY, but when FGB is enabled
6734 // MySQL expect the columns present in GROUP BY, must be present in SELECT clause and that results into error, needless to have other columns.
6735 // 2. When GROUP BY columns are present then disable FGB otherwise it demands to add ORDER BY columns in GROUP BY and eventually in SELECT
6736 // clause. This will impact the search query output.
6737 $disableFullGroupByMode = ($sortByChar ||
!empty($groupBy) ||
$groupContacts);
6739 if ($disableFullGroupByMode) {
6740 CRM_Core_DAO
::disableFullGroupByMode();
6744 $this->_sort
= $sort;
6747 $this->includePseudoFieldsJoin($sort);
6749 list($select, $from, $where, $having) = $this->query($count, $sortByChar, $groupContacts, $onlyDeleted);
6751 if ($additionalWhereClause) {
6752 $where = $where . ' AND ' . $additionalWhereClause;
6755 //additional from clause should be w/ proper joins.
6756 if ($additionalFromClause) {
6757 $from .= "\n" . $additionalFromClause;
6760 // if we are doing a transform, do it here
6761 // use the $from, $where and $having to get the contact ID
6762 if ($this->_displayRelationshipType
) {
6763 $this->filterRelatedContacts($from, $where, $having);
6765 $limit = (!$count && $rowCount) ?
" LIMIT " . CRM_Utils_Type
::escape($offset, 'Int') . ", " . CRM_Utils_Type
::escape($rowCount, 'Int') : '';
6768 'select' => $select,
6771 'order_by' => $order,
6772 'group_by' => $groupBy,
6773 'having' => $having,
6779 * Get the metadata for a given field.
6781 * @param string $fieldName
6785 protected function getMetadataForField($fieldName) {
6786 if ($fieldName === 'contact_a.id') {
6787 // This seems to be the only anomaly.
6790 $pseudoField = isset($this->_pseudoConstantsSelect
[$fieldName]) ?
$this->_pseudoConstantsSelect
[$fieldName] : [];
6791 $field = isset($this->_fields
[$fieldName]) ?
$this->_fields
[$fieldName] : $pseudoField;
6792 $field = array_merge($field, $pseudoField);
6793 if (!empty($field) && empty($field['name'])) {
6794 // standardising field formatting here - over time we can phase out variants.
6795 // all paths using this currently unit tested
6796 $field['name'] = CRM_Utils_Array
::value('field_name', $field, CRM_Utils_Array
::value('idCol', $field, $fieldName));
6802 * Get the metadata for a given field, returning the 'real field' if it is a pseudofield.
6804 * @param string $fieldName
6808 protected function getMetadataForRealField($fieldName) {
6809 $field = $this->getMetadataForField($fieldName);
6810 if (!empty($field['is_pseudofield_for'])) {
6811 $field = $this->getMetadataForField($field['is_pseudofield_for']);
6812 $field['pseudofield_name'] = $fieldName;
6814 elseif (!empty($field['pseudoconstant'])) {
6815 if (!empty($field['pseudoconstant']['optionGroupName'])) {
6816 $field['pseudofield_name'] = $field['pseudoconstant']['optionGroupName'];
6817 if (empty($field['table_name'])) {
6818 if (!empty($field['where'])) {
6819 $field['table_name'] = explode('.', $field['where'])[0];
6822 $field['table_name'] = 'civicrm_contact';
6831 * If we have a field that is better rendered via the pseudoconstant handled them here.
6833 * Rather than joining in the additional table we render the option value on output.
6835 * @todo - so far this applies to a narrow range of pseudocontants. We are adding them
6836 * carefully with test coverage but aim to extend.
6838 * @param string $name
6840 protected function addPseudoconstantFieldToSelect($name) {
6841 $field = $this->getMetadataForRealField($name);
6842 $realFieldName = $field['name'];
6843 $pseudoFieldName = CRM_Utils_Array
::value('pseudofield_name', $field);
6844 if ($pseudoFieldName) {
6845 // @todo - we don't really need to build this array now we have metadata more available with getMetadataForField fn.
6846 $this->_pseudoConstantsSelect
[$pseudoFieldName] = [
6847 'pseudoField' => $pseudoFieldName,
6848 'idCol' => $realFieldName,
6849 'field_name' => $field['name'],
6850 'bao' => $field['bao'],
6851 'pseudoconstant' => $field['pseudoconstant'],
6855 $this->_tables
[$field['table_name']] = 1;
6856 $this->_element
[$realFieldName] = 1;
6857 $this->_select
[$field['name']] = str_replace('civicrm_contact.', 'contact_a.', "{$field['where']} as `$realFieldName`");
6861 * Is this pseudofield a foreign key constraint.
6863 * We are trying to cautiously expand our pseudoconstant handling. This check allows us
6864 * to extend to a narrowly defined type (and then only if the pseudofield is in the fields
6865 * array which is done for contributions which are mostly handled as pseudoconstants.
6871 protected function isPseudoFieldAnFK($fieldSpec) {
6872 if (empty($fieldSpec['FKClassName'])
6873 || CRM_Utils_Array
::value('keyColumn', $fieldSpec['pseudoconstant']) !== 'id'
6874 || CRM_Utils_Array
::value('labelColumn', $fieldSpec['pseudoconstant']) !== 'name') {