@since eZ Find 2.0
build a multi field query, basically doing the same as a Lucene MultiField query
not always safe
@param string $searchText
@param array $solrFields
@param string $boostFields a hash array
16090
public function buildMultiFieldQuery( $searchText, $solrFields = array(), $boostFields = array() )
    {
        // simple implode implying an OR functionality
        $multiFieldQuery = '';
        // prepare boostfields arguments if any
        $processedBoostFields = array();
        foreach ( $boostFields as $baseName => $boostValue )
        {
            if ( strpos( $boostValue, ':' ) !== false && is_numeric( $baseName ) )
            {
                // split at the first colon, leave the rest intact
                list( $baseName, $boostValue ) = explode( ':', $boostValue, 2 );
            }
            if ( is_numeric( $boostValue ) )
            {
                // Get internal field name.
                $baseName = eZSolr::getFieldName( $baseName );
                $processedBoostFields[$baseName] = $boostValue;
            }
        }


        foreach ( $solrFields as $field )
        {
            //don't mind the last extra space, it's ignored by Solr
            $multiFieldQuery .= $field . ':(' . $searchText . ')';
            // check if we need to apply a boost
            if ( array_key_exists( $field, $processedBoostFields ) )
            {
                $multiFieldQuery .= '^' . $processedBoostFields[$field];
            }

            $multiFieldQuery .= ' ';

        }
        return $multiFieldQuery;
    }
693554
protected function doASearch($query, $searchRequest): ResponseAdapter
    {
        // the offset mulitplier is page - 1 but not less then zero
        $offsetMultiplier = max(0, $searchRequest->getPage() - 1);
        $offSet = $offsetMultiplier * (int)$searchRequest->getResultsPerPage();

        $response = $this->search->search($query, $offSet, null);
        if($response === null) {
            throw new SolrIncompleteResponseException('The response retrieved from solr was incomplete', 1505989678);
        }

        return $response;
    }
297611
public static function search_contacts($searchtext, $onlymycourses = false) {
        global $CFG, $USER, $PAGE;
        require_once($CFG->dirroot . '/user/lib.php');

        // Check if messaging is enabled.
        if (empty($CFG->messaging)) {
            throw new moodle_exception('disabled', 'message');
        }

        require_once($CFG->libdir . '/enrollib.php');

        $params = array('searchtext' => $searchtext, 'onlymycourses' => $onlymycourses);
        $params = self::validate_parameters(self::search_contacts_parameters(), $params);

        // Extra validation, we do not allow empty queries.
        if ($params['searchtext'] === '') {
            throw new moodle_exception('querystringcannotbeempty');
        }

        $courseids = array();
        if ($params['onlymycourses']) {
            $mycourses = enrol_get_my_courses(array('id'));
            foreach ($mycourses as $mycourse) {
                $courseids[] = $mycourse->id;
            }
        } else {
            $courseids[] = SITEID;
        }

        // Retrieving the users matching the query.
        $users = message_search_users($courseids, $params['searchtext']);
        $results = array();
        foreach ($users as $user) {
            $results[$user->id] = $user;
        }

        // Reorganising information.
        foreach ($results as &$user) {
            $newuser = array(
                'id' => $user->id,
                'fullname' => fullname($user)
            );

            // Avoid undefined property notice as phone not specified.
            $user->phone1 = null;
            $user->phone2 = null;

            $userpicture = new user_picture($user);
            $userpicture->size = 1; // Size f1.
            $newuser['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
            $userpicture->size = 0; // Size f2.
            $newuser['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);

            $user = $newuser;
        }

        return $results;
    }
780332
public function search( $searchText, $params = array(), $searchTypes = array() )
    {
        $searchText = trim( $searchText );

        if ( empty( $searchText ) )
        {
            return array(
                'SearchResult' => array(),
                'SearchCount' => 0,
                'StopWordArray' => array()
            );
        }

        $doFullText = true;
        $query = new LocationQuery();

        $criteria = array();

        if ( isset( $params['SearchDate'] ) && (int)$params['SearchDate'] > 0 )
        {
            $currentTimestamp = time();
            $dateSearchType = (int)$params['SearchDate'];

            $fromTimestamp = 0;
            if ( $dateSearchType === 1 )
            {
                // Last day
                $fromTimestamp = $currentTimestamp - 86400;
            }
            else if ( $dateSearchType === 2 )
            {
                // Last week
                $fromTimestamp = $currentTimestamp - ( 7 * 86400 );
            }
            else if ( $dateSearchType === 3 )
            {
                // Last month
                $fromTimestamp = $currentTimestamp - ( 30 * 86400 );
            }
            else if ( $dateSearchType === 4 )
            {
                // Last three months
                $fromTimestamp = $currentTimestamp - ( 3 * 30 * 86400 );
            }
            else if ( $dateSearchType === 5 )
            {
                // Last year
                $fromTimestamp = $currentTimestamp - ( 365 * 86400 );
            }

            $criteria[] = new Criterion\DateMetadata(
                Criterion\DateMetadata::CREATED,
                Criterion\Operator::GTE,
                $fromTimestamp
            );
        }

        if ( isset( $params['SearchSectionID'] ) && (int)$params['SearchSectionID'] > 0 )
        {
            $criteria[] = new Criterion\SectionId( (int)$params['SearchSectionID'] );
        }

        if ( isset( $params['SearchContentClassID'] ) && !is_array( $params['SearchContentClassID'] ) && (int)$params['SearchContentClassID'] > 0 )
        {
            $criteria[] = new Criterion\ContentTypeId( (int)$params['SearchContentClassID'] );

            if ( isset( $params['SearchContentClassAttributeID'] ) && (int)$params['SearchContentClassAttributeID'] > 0 )
            {
                $classAttribute = eZContentClassAttribute::fetch( $params['SearchContentClassAttributeID'] );
                if ( $classAttribute instanceof eZContentClassAttribute )
                {
                    $criteria[] = new Criterion\Field(
                        $classAttribute->attribute( 'identifier' ),
                        Criterion\Operator::LIKE,
                        $searchText
                    );

                    $doFullText = false;
                }
            }
        }
        else if ( isset( $params['SearchContentClassID'] ) && is_array( $params['SearchContentClassID'] ) )
        {
            $contentTypeIDs = array_map(
                function ($contentClassID)
                {
                    return (int)$contentClassID;
                },
                $params['SearchContentClassID']
            );

            $criteria[] = new Criterion\ContentTypeId( $contentTypeIDs );
        }

        if ( isset( $params['SearchSubTreeArray'] ) && !empty( $params['SearchSubTreeArray'] ) )
        {
            $subTreeArrayCriteria = array();
            foreach ( $params['SearchSubTreeArray'] as $nodeId )
            {
                $node = eZContentObjectTreeNode::fetch( $nodeId );
                $subTreeArrayCriteria[] = $node->attribute( 'path_string' );
            }

            $criteria[] = new Criterion\Subtree( $subTreeArrayCriteria );
        }

        if ( $doFullText )
        {
            $query->query = new Criterion\FullText( $searchText );
        }

        if ( !empty( $criteria ) )
        {
            $query->filter = new Criterion\LogicalAnd( $criteria );
        }

        $query->limit = isset( $params['SearchLimit'] ) ? (int)$params['SearchLimit'] : 10;
        $query->offset = isset( $params['SearchOffset'] ) ? (int)$params['SearchOffset'] : 0;

        $useLocationSearch = $this->iniConfig->variable( 'SearchSettings', 'UseLocationSearch' ) === 'true';

        if ( $useLocationSearch )
        {
            $searchResult = $this->repository->getSearchService()->findLocations( $query );
        }
        else
        {
            $searchResult = $this->repository->getSearchService()->findContentInfo( $query );
        }

        $nodeIds = array();
        foreach ( $searchResult->searchHits as $searchHit )
        {
            $nodeIds[] = $useLocationSearch ?
                $searchHit->valueObject->id :
                $searchHit->valueObject->mainLocationId;
        }

        $resultNodes = array();
        if ( !empty( $nodeIds ) )
        {
            $resultNodes = eZContentObjectTreeNode::fetch( $nodeIds );
            if ( $resultNodes instanceof eZContentObjectTreeNode )
            {
                $resultNodes = array( $resultNodes );
            }
            else if ( is_array( $resultNodes ) )
            {
                $nodeIds = array_flip( $nodeIds );

                usort(
                    $resultNodes,
                    function ( eZContentObjectTreeNode $node1, eZContentObjectTreeNode $node2 ) use ( $nodeIds )
                    {
                        if ( $node1->attribute( 'node_id' ) === $node2->attribute( 'node_id' ) )
                        {
                            return 0;
                        }

                        return ( $nodeIds[$node1->attribute( 'node_id' )] < $nodeIds[$node2->attribute( 'node_id' )] ) ? -1 : 1;
                    }
                );
            }
        }

        return array(
            'SearchResult' => $resultNodes,
            'SearchCount' => $searchResult->totalCount,
            'StopWordArray' => array()
        );
    }
1177423
public void setSearchRoots(List<String> searchRoots) {

        if ((searchRoots != null) && !searchRoots.isEmpty()) {
            addFilterQuery(CmsSearchField.FIELD_PARENT_FOLDERS, searchRoots, false, true);
        }
    }
956521
public function searchFields(array $fields, $mode = self::SEARCH_MODE_PATTERN, $boost = 1, $phraseBoost = 2) {
		foreach($fields as $field) {
			$this->searchField($field, $mode, $boost, $phraseBoost);
		}
		return $this;
	}
824189
public String findTextByQueryReplyAndQueryField(QueryReply queryReply, QueryField queryField) {
    EntityManager entityManager = getEntityManager();

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<String> criteria = criteriaBuilder.createQuery(String.class);
    Root<QueryQuestionOptionAnswer> root = criteria.from(QueryQuestionOptionAnswer.class);
    Join<QueryQuestionOptionAnswer, QueryOptionFieldOption> option = root.join(QueryQuestionOptionAnswer_.option);
    
    criteria.select(option.get(QueryOptionFieldOption_.text));
    
    criteria.where(
      criteriaBuilder.and(
        criteriaBuilder.equal(root.get(QueryQuestionOptionAnswer_.queryField), queryField),
        criteriaBuilder.equal(root.get(QueryQuestionOptionAnswer_.queryReply), queryReply)
      )
    );
    
    return getSingleResult(entityManager.createQuery(criteria));
  }
1058485
public function search( $searchText, $params = array(), $searchTypes = array() )
    {
        if ( count( $searchTypes ) == 0 )
        {
            $searchTypes['general'] = array();
            $searchTypes['subtype'] = array();
            $searchTypes['and'] = array();
        }
        else if ( !isset( $searchTypes['general'] ) )
        {
            $searchTypes['general'] = array();
        }
        $allowSearch = true;
        if ( trim( $searchText ) == '' )
        {
            $ini = eZINI::instance();
            if ( $ini->variable( 'SearchSettings', 'AllowEmptySearch' ) != 'enabled' )
                $allowSearch = false;
            if ( isset( $params['AllowEmptySearch'] ) )
                $allowSearch = $params['AllowEmptySearch'];
        }
        if ( $allowSearch )
        {
            $searchText = $this->normalizeText( $searchText, false );
            $db = eZDB::instance();

            $nonExistingWordArray = array();
            $searchTypeMap = array( 'class' => 'SearchContentClassID',
                                    'publishdate' => 'SearchDate',
                                    'subtree' => 'SearchSubTreeArray' );

            foreach ( $searchTypes['general'] as $searchType )
            {
                $params[$searchTypeMap[$searchType['subtype']]] = $searchType['value'];
            }

            if ( isset( $params['SearchOffset'] ) )
                $searchOffset = $params['SearchOffset'];
            else
                $searchOffset = 0;

            if ( isset( $params['SearchLimit'] ) )
                $searchLimit = $params['SearchLimit'];
            else
                $searchLimit = 10;

            if ( isset( $params['SearchContentClassID'] ) )
                $searchContentClassID = $params['SearchContentClassID'];
            else
                $searchContentClassID = -1;

            if ( isset( $params['SearchSectionID'] ) )
                $searchSectionID = $params['SearchSectionID'];
            else
                $searchSectionID = -1;

            if ( isset( $params['SearchDate'] ) )
                $searchDate = $params['SearchDate'];
            else
                $searchDate = -1;

            if ( isset( $params['SearchTimestamp'] ) )
                $searchTimestamp = $params['SearchTimestamp'];
            else
                $searchTimestamp = false;

            if ( isset( $params['SearchContentClassAttributeID'] ) )
                $searchContentClassAttributeID = $params['SearchContentClassAttributeID'];
            else
                $searchContentClassAttributeID = -1;

            if ( isset( $params['SearchSubTreeArray'] ) )
                $subTreeArray = $params['SearchSubTreeArray'];
            else
                $subTreeArray = array();

            if ( isset( $params['SortArray'] ) )
                $sortArray = $params['SortArray'];
            else
                $sortArray = array();

            $ignoreVisibility = isset( $params['IgnoreVisibility'] ) ? $params['IgnoreVisibility'] : false;

            // strip multiple spaces
            $searchText = preg_replace( "(\s+)", " ", $searchText );

            // find the phrases
/*            $numQuotes = substr_count( $searchText, "\"" );

            $phraseTextArray = array();
            $fullText = $searchText;
            $nonPhraseText ='';
//            $fullText = '';
            $postPhraseText = $fullText;
            $pos = 0;
            if ( ( $numQuotes > 0 ) and ( ( $numQuotes % 2 ) == 0 ) )
            {
                for ( $i = 0; $i < ( $numQuotes / 2 ); $i ++ )
                {
                    $quotePosStart = strpos( $searchText, '"',  $pos );
                    $quotePosEnd = strpos( $searchText, '"',  $quotePosStart + 1 );

                    $prePhraseText = substr( $searchText, $pos, $quotePosStart - $pos );
                    $postPhraseText = substr( $searchText, $quotePosEnd +1 );
                    $phraseText = substr( $searchText, $quotePosStart + 1, $quotePosEnd - $quotePosStart - 1 );

                    $phraseTextArray[] = $phraseText;
//                    $fullText .= $prePhraseText;
                    $nonPhraseText .= $prePhraseText;
                    $pos = $quotePosEnd + 1;
                }
            }
            $nonPhraseText .= $postPhraseText;
*/
            $phrasesResult = $this->getPhrases( $searchText );
            $phraseTextArray = $phrasesResult['phrases'];
            $nonPhraseText = $phrasesResult['nonPhraseText'];
            $fullText = $phrasesResult['fullText'];

            $sectionQuery = '';
            if ( is_numeric( $searchSectionID ) and  $searchSectionID > 0 )
            {
                $sectionQuery = "ezsearch_object_word_link.section_id = '" . (int)$searchSectionID . "' AND ";
            }
            else if ( is_array( $searchSectionID ) )
            {
                // Build query for searching in an array of sections
                $sectionQuery = $db->generateSQLINStatement( array_map( 'intval', $searchSectionID ), 'ezsearch_object_word_link.section_id', false, false, 'int' ) . " AND ";
            }

            $searchDateQuery = '';
            if ( ( is_numeric( $searchDate ) and  $searchDate > 0 ) or
                 $searchTimestamp )
            {
                $date = new eZDateTime();
                $timestamp = $date->timeStamp();
                $day = $date->attribute('day');
                $month = $date->attribute('month');
                $year = $date->attribute('year');
                $publishedDateStop = false;
                if ( $searchTimestamp )
                {
                    if ( is_array( $searchTimestamp ) )
                    {
                        $publishedDate = (int) $searchTimestamp[0];
                        $publishedDateStop = (int) $searchTimestamp[1];
                    }
                    else
                        $publishedDate = (int) $searchTimestamp;
                }
                else
                {
                    switch ( $searchDate )
                    {
                        case 1:
                        {
                            $adjustment = 24*60*60; //seconds for one day
                            $publishedDate = $timestamp - $adjustment;
                        } break;
                        case 2:
                        {
                            $adjustment = 7*24*60*60; //seconds for one week
                            $publishedDate = $timestamp - $adjustment;
                        } break;
                        case 3:
                        {
                            $adjustment = 31*24*60*60; //seconds for one month
                            $publishedDate = $timestamp - $adjustment;
                        } break;
                        case 4:
                        {
                            $adjustment = 3*31*24*60*60; //seconds for three months
                            $publishedDate = $timestamp - $adjustment;
                        } break;
                        case 5:
                        {
                            $adjustment = 365*24*60*60; //seconds for one year
                            $publishedDate = $timestamp - $adjustment;
                        } break;
                        default:
                        {
                            $publishedDate = $date->timeStamp();
                        }
                    }
                }
                $searchDateQuery = "ezsearch_object_word_link.published >= '$publishedDate' AND ";
                if ( $publishedDateStop )
                    $searchDateQuery .= "ezsearch_object_word_link.published <= '$publishedDateStop' AND ";
                $this->GeneralFilter['searchDateQuery'] = $searchDateQuery;
            }

            $classQuery = "";
            if ( is_numeric( $searchContentClassID ) and $searchContentClassID > 0 )
            {
                // Build query for searching in one class
                $classQuery = "ezsearch_object_word_link.contentclass_id = '" . (int)$searchContentClassID . "' AND ";
                $this->GeneralFilter['classAttributeQuery'] = $classQuery;
            }
            else if ( is_array( $searchContentClassID ) )
            {
                // Build query for searching in a number of classes
                $classString = $db->generateSQLINStatement( array_map( 'intval', $searchContentClassID ), 'ezsearch_object_word_link.contentclass_id', false, false, 'int' );
                $classQuery = "$classString AND ";
                $this->GeneralFilter['classAttributeQuery'] = $classQuery;
            }

            $classAttributeQuery = "";
            if ( is_numeric( $searchContentClassAttributeID ) and  $searchContentClassAttributeID > 0 )
            {
                $classAttributeQuery = "ezsearch_object_word_link.contentclass_attribute_id = '$searchContentClassAttributeID' AND ";
            }
            else if ( is_array( $searchContentClassAttributeID ) )
            {
                // Build query for searching in a number of attributes
                $classAttributeQuery = $db->generateSQLINStatement( array_map( 'intval', $searchContentClassAttributeID ), 'ezsearch_object_word_link.contentclass_attribute_id', false, false, 'int' ) . ' AND ';
            }

            // Get the total number of objects
            $totalObjectCount = $this->fetchTotalObjectCount();

            $searchPartsArray = array();
            $wordIDHash = array();
            $wildCardCount = 0;
            if ( trim( $searchText ) != '' )
            {
                $wordIDArrays = $this->prepareWordIDArrays( $searchText );
                $wordIDArray = $wordIDArrays['wordIDArray'];
                $wordIDHash = $wordIDArrays['wordIDHash'];
                $wildIDArray = $wordIDArrays['wildIDArray'];
                $wildCardCount = $wordIDArrays['wildCardCount'];
                $searchPartsArray = $this->buildSearchPartArray( $phraseTextArray, $nonPhraseText, $wordIDHash, $wildIDArray );
            }

            /// OR search, not used in this version
            $doOrSearch = false;

            if ( $doOrSearch == true )
            {
                // build fulltext search SQL part
                $searchWordArray = $this->splitString( $fullText );
                $fullTextSQL = "";
                if ( count( $searchWordArray ) > 0 )
                {
                    $i = 0;
                    // Build the word query string
                    foreach ( $searchWordArray as $searchWord )
                    {
                        $wordID = null;
                        if ( isset( $wordIDHash[$searchWord] ) )
                            $wordID = $wordIDHash[$searchWord]['id'];

                        if ( is_numeric( $wordID ) and ( $wordID > 0 ) )
                        {
                            if ( $i == 0 )
                                $fullTextSQL .= "ezsearch_object_word_link.word_id='$wordID' ";
                            else
                                $fullTextSQL .= " OR ezsearch_object_word_link.word_id='$wordID' ";
                        }
                        else
                        {
                            $nonExistingWordArray[] = $searchWord;
                        }
                        $i++;
                    }
                    $fullTextSQL = " ( $fullTextSQL ) AND ";
                }
            }

            // Search only in specific sub trees
            $subTreeSQL = "";
            $subTreeTable = "";
            if ( count( $subTreeArray ) > 0 )
            {
                // Fetch path_string value to use when searching subtrees
                $i = 0;
                $doSubTreeSearch = false;
                $subTreeNodeSQL = '';
                foreach ( $subTreeArray as $nodeID )
                {
                    if ( is_numeric( $nodeID ) and ( $nodeID > 0 ) )
                    {
                        $subTreeNodeSQL .= " $nodeID";

                        if ( isset( $subTreeArray[$i + 1] ) and
                             is_numeric( $subTreeArray[$i + 1] ) )
                            $subTreeNodeSQL .= ", ";

                        $doSubTreeSearch = true;
                    }
                    $i++;
                }

                if ( $doSubTreeSearch == true )
                {

                    $subTreeNodeSQL = "( " . $subTreeNodeSQL;
//                    $subTreeTable = ", ezcontentobject_tree ";
                    $subTreeTable = '';
                    $subTreeNodeSQL .= " ) ";
                    $nodeQuery = "SELECT node_id, path_string FROM ezcontentobject_tree WHERE node_id IN $subTreeNodeSQL";

                    // Build SQL subtre search query
                    $subTreeSQL = " ( ";

                    $nodeArray = $db->arrayQuery( $nodeQuery );
                    $i = 0;
                    foreach ( $nodeArray as $node )
                    {
                        $pathString = $node['path_string'];
                        $subTreeSQL .= " ezcontentobject_tree.path_string like '$pathString%' ";

                        if ( $i < ( count( $nodeArray ) -1 ) )
                            $subTreeSQL .= " OR ";
                        $i++;
                    }
                    $subTreeSQL .= " ) AND ";
                    $this->GeneralFilter['subTreeTable'] = $subTreeTable;
                    $this->GeneralFilter['subTreeSQL'] = $subTreeSQL;

                }
            }

            $limitation = false;
            if ( isset( $params['Limitation'] ) )
            {
                $limitation = $params['Limitation'];
            }

            $limitationList = eZContentObjectTreeNode::getLimitationList( $limitation );
            $sqlPermissionChecking = eZContentObjectTreeNode::createPermissionCheckingSQL( $limitationList );
            $this->GeneralFilter['sqlPermissionChecking'] = $sqlPermissionChecking;

            $versionNameJoins = " AND " . eZContentLanguage::sqlFilter( 'ezcontentobject_name', 'ezcontentobject' );

            /// Only support AND search at this time
            // build fulltext search SQL part
            $searchWordArray = $this->splitString( $fullText );
            $searchWordCount = count( $searchWordArray );
            $fullTextSQL = "";
            $stopWordArray = array( );
            $ini = eZINI::instance();

            $tmpTableCount = 0;
            $i = 0;
            foreach ( $searchTypes['and'] as $searchType )
            {
                $methodName = $this->constructMethodName( $searchType );
                $intermediateResult = $this->callMethod( $methodName, array( $searchType ) );
                if ( $intermediateResult == false )
                {
                    // cleanup temp tables
                    $db->dropTempTableList( $sqlPermissionChecking['temp_tables'] );

                    return array( "SearchResult" => array(),
                                  "SearchCount" => 0,
                                  "StopWordArray" => array() );
                }
            }

            // Do not execute search if site.ini:[SearchSettings]->AllowEmptySearch is enabled, but no conditions are set.
            if ( !$searchDateQuery &&
                 !$sectionQuery &&
                 !$classQuery &&
                 !$classAttributeQuery &&
                 !$searchPartsArray &&
                 !$subTreeSQL )
            {
                // cleanup temp tables
                $db->dropTempTableList( $sqlPermissionChecking['temp_tables'] );

                return array( "SearchResult" => array(),
                              "SearchCount" => 0,
                              "StopWordArray" => array() );
            }

            $i = $this->TempTablesCount;

            // Loop every word and insert result in temporary table

            // Determine whether we should search invisible nodes.
            $showInvisibleNodesCond = eZContentObjectTreeNode::createShowInvisibleSQLString( !$ignoreVisibility );

            foreach ( $searchPartsArray as $searchPart )
            {
                $stopWordThresholdValue = 100;
                if ( $ini->hasVariable( 'SearchSettings', 'StopWordThresholdValue' ) )
                    $stopWordThresholdValue = $ini->variable( 'SearchSettings', 'StopWordThresholdValue' );

                $stopWordThresholdPercent = 60;
                if ( $ini->hasVariable( 'SearchSettings', 'StopWordThresholdPercent' ) )
                    $stopWordThresholdPercent = $ini->variable( 'SearchSettings', 'StopWordThresholdPercent' );

                $searchThresholdValue = $totalObjectCount;
                if ( $totalObjectCount > $stopWordThresholdValue )
                {
                    $searchThresholdValue = (int)( $totalObjectCount * ( $stopWordThresholdPercent / 100 ) );
                }

                // do not search words that are too frequent
                if ( $searchPart['object_count'] < $searchThresholdValue )
                {
                    $tmpTableCount++;
                    $searchPartText = $searchPart['sql_part'];
                    if ( $i == 0 )
                    {
                        $table = $db->generateUniqueTempTableName( 'ezsearch_tmp_%', 0 );
                        $this->saveCreatedTempTableName( 0, $table );
                        $db->createTempTable( "CREATE TEMPORARY TABLE $table ( contentobject_id int primary key not null, published int )" );
                        $db->query( "INSERT INTO $table SELECT DISTINCT ezsearch_object_word_link.contentobject_id, ezsearch_object_word_link.published
                                         FROM ezcontentobject
                                              INNER JOIN ezsearch_object_word_link ON (ezsearch_object_word_link.contentobject_id = ezcontentobject.id)
                                              $subTreeTable
                                              INNER JOIN ezcontentclass ON (ezcontentclass.id = ezcontentobject.contentclass_id)
                                              INNER JOIN ezcontentobject_tree ON (ezcontentobject_tree.contentobject_id = ezcontentobject.id)
                                              $sqlPermissionChecking[from]
                                         WHERE
                                               $searchDateQuery
                                               $sectionQuery
                                               $classQuery
                                               $classAttributeQuery
                                               $searchPartText
                                               $subTreeSQL
                                         ezcontentclass.version = '0' AND
                                         ezcontentobject_tree.node_id = ezcontentobject_tree.main_node_id
                                         $showInvisibleNodesCond
                                         $sqlPermissionChecking[where]",
                                    eZDBInterface::SERVER_SLAVE );
                    }
                    else
                    {
                        $table = $db->generateUniqueTempTableName( 'ezsearch_tmp_%', $i );
                        $this->saveCreatedTempTableName( $i, $table );

                        $tmpTable0 = $this->getSavedTempTableName( 0 );
                        $db->createTempTable( "CREATE TEMPORARY TABLE $table ( contentobject_id int primary key not null, published int )" );
                        $db->query( "INSERT INTO $table SELECT DISTINCT ezsearch_object_word_link.contentobject_id, ezsearch_object_word_link.published
                                         FROM
                                             ezcontentobject
                                             INNER JOIN ezsearch_object_word_link ON (ezsearch_object_word_link.contentobject_id = ezcontentobject.id)
                                             $subTreeTable
                                             INNER JOIN ezcontentclass ON (ezcontentclass.id = ezcontentobject.contentclass_id)
                                             INNER JOIN ezcontentobject_tree ON (ezcontentobject_tree.contentobject_id = ezcontentobject.id)
                                             INNER JOIN $tmpTable0 ON ($tmpTable0.contentobject_id = ezsearch_object_word_link.contentobject_id)
                                             $sqlPermissionChecking[from]
                                          WHERE
                                          $searchDateQuery
                                          $sectionQuery
                                          $classQuery
                                          $classAttributeQuery
                                          $searchPartText
                                          $subTreeSQL
                                          ezcontentclass.version = '0' AND
                                          ezcontentobject_tree.node_id = ezcontentobject_tree.main_node_id
                                          $showInvisibleNodesCond
                                          $sqlPermissionChecking[where]",
                                    eZDBInterface::SERVER_SLAVE );
                    }
                    $i++;
                }
                else
                {
                    $stopWordArray[] = array( 'word' => $searchPart['text'] );
                }
            }

            if ( count( $searchPartsArray ) === 0 && $this->TempTablesCount == 0 )
            {
                 $table = $db->generateUniqueTempTableName( 'ezsearch_tmp_%', 0 );
                 $this->saveCreatedTempTableName( 0, $table );
                 $db->createTempTable( "CREATE TEMPORARY TABLE $table ( contentobject_id int primary key not null, published int )" );
                 $db->query( "INSERT INTO $table SELECT DISTINCT ezsearch_object_word_link.contentobject_id, ezsearch_object_word_link.published
                                     FROM ezcontentobject
                                          INNER JOIN ezsearch_object_word_link ON (ezsearch_object_word_link.contentobject_id = ezcontentobject.id)
                                          $subTreeTable
                                          INNER JOIN ezcontentclass ON (ezcontentclass.id = ezcontentobject.contentclass_id)
                                          INNER JOIN ezcontentobject_tree ON (ezcontentobject_tree.contentobject_id = ezcontentobject.id)
                                          $sqlPermissionChecking[from]
                                     WHERE
                                          $searchDateQuery
                                          $sectionQuery
                                          $classQuery
                                          $classAttributeQuery
                                          $subTreeSQL
                                          ezcontentclass.version = '0' AND
                                          ezcontentobject_tree.node_id = ezcontentobject_tree.main_node_id
                                          $showInvisibleNodesCond
                                          $sqlPermissionChecking[where]",
                             eZDBInterface::SERVER_SLAVE );
                 $this->TempTablesCount = 1;
                 $i = $this->TempTablesCount;
            }

            $nonExistingWordCount = count( array_unique( $searchWordArray ) ) - count( $wordIDHash ) - $wildCardCount;
            $excludeWordCount = $searchWordCount - count( $stopWordArray );

            if ( ( count( $stopWordArray ) + $nonExistingWordCount ) == $searchWordCount && $this->TempTablesCount == 0 )
            {
                // No words to search for, return empty result

                // cleanup temp tables
                $db->dropTempTableList( $sqlPermissionChecking['temp_tables'] );
                $db->dropTempTableList( $this->getSavedTempTablesList() );

                return array( "SearchResult" => array(),
                          "SearchCount" => 0,
                          "StopWordArray" => $stopWordArray );
            }
            $tmpTablesFrom = "";
            $tmpTablesWhere = "";
            /// tmp tables
            $tmpTableCount = $i;
            for ( $i = 0; $i < $tmpTableCount; $i++ )
            {
                $tmpTablesFrom .= $this->getSavedTempTableName( $i );
                if ( $i < ( $tmpTableCount - 1 ) )
                    $tmpTablesFrom .= ", ";

            }
            $tmpTablesSeparator = '';
            if ( $tmpTableCount > 0 )
            {
                $tmpTablesSeparator = ', ';
            }

            $tmpTable0 = $this->getSavedTempTableName( 0 );
            for ( $i = 1; $i < $tmpTableCount; $i++ )
            {
                $tmpTableI = $this->getSavedTempTableName( $i );
                $tmpTablesWhere .= " $tmpTable0.contentobject_id=$tmpTableI.contentobject_id  ";
                if ( $i < ( $tmpTableCount - 1 ) )
                    $tmpTablesWhere .= " AND ";
            }
            $tmpTablesWhereExtra = '';
            if ( $tmpTableCount > 0 )
            {
                $tmpTablesWhereExtra = "ezcontentobject.id=$tmpTable0.contentobject_id AND";
            }

            $and = "";
            if ( $tmpTableCount > 1 )
                $and = " AND ";

            // Generate ORDER BY SQL
            $orderBySQLArray = $this->buildSortSQL( $sortArray );
            $orderByFieldsSQL = $orderBySQLArray['sortingFields'];
            $sortWhereSQL = $orderBySQLArray['whereSQL'];
            $sortFromSQL = $orderBySQLArray['fromSQL'];
            $sortSelectSQL = $orderBySQLArray['selectSQL'];

            // Fetch data from table
            $searchQuery = "SELECT DISTINCT " .
            "ezcontentobject.contentclass_id, ezcontentobject.current_version, ezcontentobject.id, ezcontentobject.initial_language_id, ezcontentobject.language_mask, " .
            "ezcontentobject.modified, ezcontentobject.name, ezcontentobject.owner_id, ezcontentobject.published, ezcontentobject.remote_id AS object_remote_id, ezcontentobject.section_id, " .
            "ezcontentobject.status, ezcontentobject_tree.contentobject_is_published, ezcontentobject_tree.contentobject_version, ezcontentobject_tree.depth, ezcontentobject_tree.is_hidden, " .
            "ezcontentobject_tree.is_invisible, ezcontentobject_tree.main_node_id, ezcontentobject_tree.modified_subnode, ezcontentobject_tree.node_id, ezcontentobject_tree.parent_node_id, " .
            "ezcontentobject_tree.path_identification_string, ezcontentobject_tree.path_string, ezcontentobject_tree.priority, ezcontentobject_tree.remote_id, ezcontentobject_tree.sort_field, " .
            "ezcontentobject_tree.sort_order, ezcontentclass.serialized_name_list as class_serialized_name_list, ezcontentobject_name.name as name, " .
            "ezcontentobject_name.real_translation $sortSelectSQL " .
            "FROM " .
            "$tmpTablesFrom $tmpTablesSeparator " .
            "ezcontentobject " .
            "INNER JOIN ezcontentclass ON (ezcontentclass.id = ezcontentobject.contentclass_id ) " .
            "INNER JOIN ezcontentobject_tree ON (ezcontentobject_tree.contentobject_id = ezcontentobject.id) " .
            "INNER JOIN ezcontentobject_name ON ( " .
            "    ezcontentobject_name.contentobject_id = ezcontentobject_tree.contentobject_id AND " .
            "    ezcontentobject_name.content_version = ezcontentobject_tree.contentobject_version " .
            ") " .
            $sortFromSQL . " " .
            "WHERE " .
            "$tmpTablesWhere $and " .
            $tmpTablesWhereExtra . " " .
            "ezcontentclass.version = '0' AND " .
            "ezcontentobject_tree.node_id = ezcontentobject_tree.main_node_id AND " .
            "" . eZContentLanguage::sqlFilter( 'ezcontentobject_name', 'ezcontentobject' ) . " " .
            $showInvisibleNodesCond . " " .
            $sortWhereSQL . " " .
            "ORDER BY $orderByFieldsSQL";

            // Count query
            $languageCond = eZContentLanguage::languagesSQLFilter( 'ezcontentobject' );
            if ( $tmpTableCount == 0 )
            {
                $searchCountQuery = "SELECT count( DISTINCT ezcontentobject.id ) AS count
                        FROM
                           ezcontentobject,
                           ezcontentobject_tree
                        WHERE
                        ezcontentobject.id = ezcontentobject_tree.contentobject_id and
                        ezcontentobject_tree.node_id = ezcontentobject_tree.main_node_id
                        AND $languageCond
                        $showInvisibleNodesCond";
            }
            else
            {
                $searchCountQuery = "SELECT count( DISTINCT ezcontentobject.id ) AS count
                        FROM $tmpTablesFrom $tmpTablesSeparator
                             ezcontentobject
                        WHERE $tmpTablesWhere $and
                            $tmpTablesWhereExtra
                            $languageCond";
            }

            $objectRes = array();
            $searchCount = 0;

            if ( $nonExistingWordCount <= 0 )
            {
                // execute search query
                $objectResArray = $db->arrayQuery( $searchQuery, array( "limit" => $searchLimit, "offset" => $searchOffset ), eZDBInterface::SERVER_SLAVE );
                // execute search count query
                $objectCountRes = $db->arrayQuery( $searchCountQuery, array(), eZDBInterface::SERVER_SLAVE );
                $objectRes = eZContentObjectTreeNode::makeObjectsArray( $objectResArray );
                $searchCount = $objectCountRes[0]['count'];
            }
            else
                $objectRes = array();

            // Drop tmp tables
            $db->dropTempTableList( $sqlPermissionChecking['temp_tables'] );
            $db->dropTempTableList( $this->getSavedTempTablesList() );

            return array( "SearchResult" => $objectRes,
                          "SearchCount" => $searchCount,
                          "StopWordArray" => $stopWordArray );
        }
        else
        {
            return array( "SearchResult" => array(),
                          "SearchCount" => 0,
                          "StopWordArray" => array() );
        }
    }
1249299
private function extractLanguageCodesFromSolrResult( $solrResults )
    {
        $languages = array();

        if ( isset( $solrResults['response']['docs'] ) )
        {
            foreach ( $solrResults['response']['docs'] as $doc )
            {
                if ( isset( $doc['meta_language_code_ms'] ) )
                {
                    $languages[] = $doc['meta_language_code_ms'];
                }
            }
        }

        return $languages;
    }
182621
private String logAndGetQueryText(FieldSearchQuery query,
                                      String[] resultFields) //2004.05.02 wdn5e
            throws SQLException, QueryParseException {
        StringBuffer queryText = new StringBuffer("SELECT");
        if (query.getType() == FieldSearchQuery.TERMS_TYPE) {
            queryText.append(" doFields.pid FROM doFields"
                    + getWhereClause(query.getTerms()));
        } else {
            StringBuffer resultFieldsString = new StringBuffer();
            if (resultFields.length > 0) {
                String delimiter = " ";
                for (String element : resultFields) {
                    String dbColumn = "doFields." + dcFixup(element);
                    resultFieldsString.append(delimiter + dbColumn);
                    delimiter = ", ";
                }
            }
            queryText.append(resultFieldsString);
            queryText.append(" FROM doFields");
            queryText.append(getWhereClause(query.getConditions()));
            // disabled sorting: see bug 78
            //            queryText.append(" ORDER BY");
            //            queryText.append(resultFieldsString);

        }
        String qt = queryText.toString();
        logger.debug(qt);
        return qt;
    }
604067
static function search( $searchText, $params, $searchTypes = array() )
    {
        $searchEngine = eZSearch::getEngine();

        if ( $searchEngine instanceof ezpSearchEngine )
        {
            return $searchEngine->search( $searchText, $params, $searchTypes );
        }
    }
1177544
function _abstract_solr_filter_template(filters){
	
	var allbuf = new Array();
	for( var filter_key in filters ){

	    var filter_val = filters[filter_key];

	    // If the value looks like an array, iterate over it and
	    // collect.
	    if( filter_val &&
		filter_val != null &&
		typeof filter_val == 'object' &&
		filter_val.length ){

		    for( var i = 0; i < filter_val.length; i++ ){
			var minibuffer = new Array();
			var try_val = filter_val[i];
			if( typeof(try_val) != 'undefined' &&
			try_val != '' ){
			    minibuffer.push('fq=');
			    minibuffer.push(filter_key);
			    minibuffer.push(':');
			    minibuffer.push('"');
			    minibuffer.push(filter_val[i]);
			    minibuffer.push('"');
			    allbuf.push(minibuffer.join(''));
			}
		    }		    
		}else{
		    var minibuf = new Array();
		    if( typeof(filter_val) != 'undefined' &&
			filter_val != '' ){
			    minibuf.push('fq=');
			    minibuf.push(filter_key);
			    minibuf.push(':');
			    minibuf.push('"');
			    minibuf.push(filter_val);
			    minibuf.push('"');
			    allbuf.push(minibuf.join(''));
			}
		}
	}
	return allbuf.join('&');
    }
1278992
private String createTextQuery(String text) {

        if (m_textSearchFields.isEmpty()) {
            m_textSearchFields.add(CmsSearchField.FIELD_TEXT);
        }
        String q = "{!q.op=OR type=" + getRequestHandler() + " qf=";
        boolean first = true;
        for (String textField : m_textSearchFields) {
            if (!first) {
                q += " ";
            }
            q += textField;
        }
        q += "}" + text;
        return q;
    }
1139223
public function termDocs(Zend_Search_Lucene_Index_Term $term, $docsFilter = null)
    {
        if ($docsFilter != null) {
            include_once 'Zend/Search/Lucene/Exception.php';
            throw new Zend_Search_Lucene_Exception('Document filters could not used with multi-searcher');
        }

        $docsList = array();

        $indexShift = 0;
        foreach ($this->_indices as $index) {
            $docs = $index->termDocs($term);

            if ($indexShift != 0) {
                foreach ($docs as $id => $docId) {
                    $docs[$id] += $indexShift;
                }
            }

            $indexShift += $index->count();
            $docsList[] = $docs;
        }

        return call_user_func_array('array_merge', $docsList);
    }
244617
public function findAll($searchFields = array())
    {
        // Cannot have an array as the root object
        // in a JSON document
        $data = $searchFields === array() ? (object)array() : $searchFields;
        $results = $this
            ->doRequest($data, array(
                'verb'     => 'POST',
                'endpoint' => 'searchCustomers',
            ));

        return $this->hydrateSearchResults($results, 'HpsPayPlanCustomer');
    }
1375049
private function whereSearch(Builder $query, $field, array $search_terms): void
    {
        if ($field instanceof Expression) {
            $field = $field->getValue();
        }

        foreach ($search_terms as $search_term) {
            $query->whereContains(DB::raw($field), $search_term);
        }
    }
1150221
@Override
	public <T extends SolrDataQuery> T setHighlightOptions(HighlightOptions highlightOptions) {
		return query.setHighlightOptions(highlightOptions);
	}