예제 #1
0
 /**
 * Parses the $query into an SearchQuery Object, and send it to the
 * SearchManager Obect, which prepare and execute the search, and
 * returns the results.
 *
 * Example of returned value:
 *	<pre>
 *	array(
 *		'category' => array (
 *			'amount' => integer
 *			'results' => array ('type' => (string) $markup->type,
 								'path' => (string) $markup->path,
 								'name' => (string) $markup->name,
 								'size' => (string) $markup->size)
 *		)
 *	)
 * </pre>
 *
 * FIXME: to be fixed using a generic Searchresult object.
 *
 *
 * @see SearchQuery
 * @see SearchManager
 * 
 * @param string $query
 * @return array $results
 */
 public function search($query)
 {
     $searchQuery = new SearchQuery();
     $searchQuery->parseQuery($query);
     $searchManager = new SearchManager();
     return $searchManager->search($searchQuery);
 }
예제 #2
0
 /**
  * Adds name/value pair specifying a word phrase and property where it need to be searched.
  *
  * @param string $name The property name
  * @param string|SearchQuery $value The word phrase
  * @param int $match The match type. One of SearchQueryMatch::* values
  * @throws \InvalidArgumentException
  */
 public function item($name, $value, $match = SearchQueryMatch::DEFAULT_MATCH)
 {
     if ($value instanceof SearchQuery && $value->isComplex() && $match != SearchQueryMatch::DEFAULT_MATCH) {
         throw new \InvalidArgumentException('The match argument can be specified only if the value argument is a string or a simple query.');
     }
     if (!$this->searchStringManager->isAcceptableItem($name, $value, $match)) {
         throw new \InvalidArgumentException(sprintf('This combination of arguments are not valid. Name: %s. Value: %s. Match: %d.', $name, is_object($value) ? get_class($value) : $value, $match));
     }
     $this->andOperatorIfNeeded();
     $value = $value instanceof SearchQuery ? $value->getExpression() : $value;
     $this->expr->add(new SearchQueryExprItem($name, $value, $match));
 }
예제 #3
0
 public function sqlForJsonQuery($json)
 {
     global $global;
     include_once 'search_query.inc';
     $searchQueryO = new SearchQuery();
     $searchQueryO->initFromJson($json);
     $queryArray = $searchQueryO->getQueryArray();
     $this->searchQuery = $queryArray;
     //var_dump('searchQuery',$queryArray);
     $this->generateSqlArray();
     $sql = $this->getSql();
     return $sql;
 }
 /**
  * Performs the search against the snippets in the system
  *
  * @param {string} $keywords Keywords to search for
  * @param {int} $languageID Language to filter to
  * @param {int} $folderID Folder to filter to
  * @return {DataList} Data list pointing to the snippets in the results
  */
 public function doSnippetSearch($keywords, $languageID = false, $folderID = false)
 {
     $searchIndex = singleton('CodeBankSolrIndex');
     $searchQuery = new SearchQuery();
     $searchQuery->classes = array(array('class' => 'Snippet', 'includeSubclasses' => true));
     //Add language filtering
     if ($languageID !== false && $languageID > 0) {
         $searchQuery->filter('Snippet_LanguageID', $languageID);
     }
     //Add language filtering
     if ($folderID !== false && $folderID > 0) {
         $searchQuery->filter('Snippet_FolderID', $folderID);
     }
     //Configure search
     $searchQuery->search($keywords, null, array('Snippet_Title' => 2, 'Snippet_Description' => 1));
     return $searchIndex->search($searchQuery, null, null)->Matches->getList();
 }
 public function checkQuery(SearchQuery $obj)
 {
     $queryTokens = $obj->getQueryTokens();
     // if we have some tokens, we check if they are correct or not.
     if ($queryTokens) {
         foreach ($queryTokens as $token => $parameters) {
             $key = array_search($token, $this->validTokens);
             if (is_numeric($key)) {
                 return TRUE;
             }
         }
         return FALSE;
     } else {
         if ($obj->getQueryString()) {
             return TRUE;
         }
     }
 }
 /** These are the API functions */
 function __construct()
 {
     if (self::$missing === null) {
         self::$missing = new stdClass();
     }
     if (self::$present === null) {
         self::$present = new stdClass();
     }
 }
 /**
  * Searches the index for the given search term
  * @return SearchItem[]
  */
 public function Search(SearchQuery $query)
 {
     $terms = $query->GetSanitisedTerms();
     $len = count($terms);
     for ($i = 0; $i < $len; $i++) {
         $terms[$i] = Sql::ProtectString($this->connection, $terms[$i]);
         $terms[$i] = "LIKE '%" . trim($terms[$i], "'") . "%'";
     }
     $sql = "SELECT field_weight, weight_of_type, weight_within_type, weight, url, title, description, related_links_html \n                FROM\n                (\n                    SELECT SUM(field_weight) AS field_weight, weight_of_type, weight_within_type AS weight_within_type,\n                           SUM(field_weight) + weight_of_type + weight_within_type AS weight,\n                           url, title, description, related_links_html \n                    FROM\n                    (\n                        SELECT search_index_id, 500 as field_weight, weight_of_type, weight_within_type, url, title, description, related_links_html \n                        FROM nsa_search_index \n                        WHERE title " . implode(" AND title ", $terms) . " \n                        \n                        UNION\n                        \n                        SELECT search_index_id, 500 as field_weight, weight_of_type, weight_within_type, url, title, description, related_links_html \n                        FROM nsa_search_index \n                        WHERE keywords " . implode(" AND keywords ", $terms) . "  \n                        \n                        UNION\n                        \n                        SELECT search_index_id, 50 as field_weight, weight_of_type, weight_within_type, url, title, description, related_links_html \n                        FROM nsa_search_index \n                        WHERE description " . implode(" AND description ", $terms) . "  \n                        \n                        UNION\n                        \n                        SELECT search_index_id, 1 as field_weight, weight_of_type, weight_within_type, url, title, description, related_links_html \n                        FROM nsa_search_index \n                        WHERE full_text " . implode(" AND full_text ", $terms) . "  \n                    )\n                    AS unsorted_results\n                    GROUP BY search_index_id\n                    ORDER BY SUM(field_weight) DESC, SUM(weight_of_type) DESC, SUM(weight_within_type) DESC\n                ) \n                AS weighted_results\n                ORDER BY weight DESC";
     # Get the total results without paging
     $total = $this->connection->query("SELECT COUNT(*) AS total FROM ({$sql}) AS total");
     $row = $total->fetch();
     $this->total = $row->total;
     # Add paging and get the data
     if ($query->GetFirstResult() && $query->GetPageSize()) {
         $sql .= " LIMIT " . Sql::ProtectNumeric($query->GetFirstResult() - 1, false, false) . "," . Sql::ProtectNumeric($query->GetPageSize(), false, false);
     }
     $query_results = $this->connection->query($sql);
     require_once "search/search-item.class.php";
     $search_results = array();
     while ($row = $query_results->fetch()) {
         $result = new SearchItem();
         $result->Url($row->url);
         $result->Title($row->title);
         $result->Description($row->description);
         $result->RelatedLinksHtml($row->related_links_html);
         $result->WeightOfMatchedField($row->field_weight);
         $result->WeightOfType($row->weight_of_type);
         $result->WeightWithinType($row->weight_within_type);
         $result->Weight($row->weight);
         $search_results[] = $result;
     }
     return $search_results;
 }
 /**
  * Prepares the {@link SearchQuery}. Handles taking request arguments and
  * generating the filters and excludes to manipulate the search query.
  *
  * @return SearchQuery
  */
 protected function prepareQuery()
 {
     $params = $this->getSearchParams();
     $query = new SearchQuery();
     // Filters
     $query->search($params['q']);
     // Permission checks. CanView* checks are really basic, don't check for
     // inheritance or enforce visibility for admins or other logged-in
     // members (based on their many-many relationships).
     $query->exclude('SiteTree_ShowInSearch', false);
     $query->exclude('SiteTree_CanViewType', 'OnlyTheseUsers');
     $query->exclude('SiteTree_CanViewType', 'LoggedInUsers');
     // $query->filter('..', true)
     return $query;
 }
예제 #9
0
 public function Save()
 {
     $this->objSearchQuery->DeleteAllQueryConditions();
     foreach ($this->objQueryConditionArray as $intIndex => $objQueryCondition) {
         $lstNode = $this->objForm->GetControl('lstNode' . $intIndex);
         $lstOperation = $this->objForm->GetControl('lstOperation' . $intIndex);
         $pnlValue = $this->objForm->GetControl('pnlValue' . $intIndex);
         $ctlValue = $this->objForm->GetControl('ctlValue' . $intIndex);
         if ($lstNode->SelectedValue) {
             $objQueryCondition = new QueryCondition();
             $objQueryCondition->SearchQuery = $this->objSearchQuery;
             $objQueryCondition->QueryOperationId = $lstOperation->SelectedValue;
             $objQueryCondition->QueryNodeId = $lstNode->SelectedValue;
             if ($ctlValue->Visible) {
                 switch ($this->objNodeArray[$lstNode->SelectedValue]->QueryDataTypeId) {
                     case QueryDataType::DateValue:
                         $objQueryCondition->Value = $ctlValue->DateTime->ToString('YYYY-MM-DD');
                         break;
                     case QueryDataType::IntegerValue:
                     case QueryDataType::StringValue:
                         $objQueryCondition->Value = trim($ctlValue->Text);
                         break;
                     case QueryDataType::BooleanValue:
                         $objQueryCondition->Value = trim($ctlValue->SelectedValue);
                         break;
                     case QueryDataType::TypeValue:
                     case QueryDataType::ObjectValue:
                     case QueryDataType::CustomValue:
                     case QueryDataType::CustomValueOnly:
                         $objQueryCondition->Value = trim($ctlValue->SelectedValue);
                         break;
                     default:
                         throw new Exception('Unhandled QueryDataTypeId');
                 }
             }
             $objQueryCondition->Save();
         }
     }
 }
예제 #10
0
 public function checkTokens(SearchQuery $obj)
 {
     // first, we need to retrive all the available tokens.
     $availableTokens = $this->getAvailableTokens();
     // once we did that, we can analyze each token we've received in
     // queryTokens, and try to find if it matches one of the availables
     // token's module we have.
     $queryTokens = $obj->getQueryTokens();
     if ($queryTokens) {
         foreach ($queryTokens as $token => $parameters) {
             if (array_key_exists($token, $availableTokens)) {
                 $tokenObj = new $availableTokens[$token]($queryTokens[$token]);
                 $tokenObj->checkToken($parameters);
                 if (!$tokenObj->getIsValid()) {
                     unset($queryTokens[$token]);
                 }
             } else {
                 unset($queryTokens[$token]);
             }
         }
         $obj->setQueryTokens($queryTokens);
     }
 }
 /**
  * @param string $keywords
  * @param array  $filters
  * @return array
  */
 public function suggestWithResults($keywords, array $filters = array())
 {
     $limit = (int) ShopSearch::config()->sayt_limit;
     // process the keywords a bit
     $terms = preg_split('/\\s+/', trim(strtolower($keywords)));
     $lastTerm = count($terms) > 0 ? array_pop($terms) : '';
     $prefix = count($terms) > 0 ? implode(' ', $terms) . ' ' : '';
     //$terms[]    = $lastTerm;
     $terms[] = $lastTerm . '*';
     // this allows for partial words to still match
     // convert that to something solr adapater can handle
     $query = new SearchQuery();
     $query->search('+' . implode(' +', $terms));
     $params = array('sort' => 'score desc', 'facet' => 'true', 'facet.field' => '_autocomplete', 'facet.limit' => ShopSearch::config()->suggest_limit, 'facet.prefix' => $lastTerm);
     //		$facetSpec = array(
     //			'_autocomplete' => array(
     //				'Type'      => ShopSearch::FACET_TYPE_LINK,
     //				'Label'     => 'Suggestions',
     //				'Source'    => '_autocomplete',
     //			),
     //		);
     //
     //		Debug::dump($query);
     //
     //		$search     = $this->search($query, 0, $limit, $params, $facetSpec);
     //		Debug::dump($search);
     //		$prodList   = $search->Matches;
     //
     //		$suggestsion = array();
     ////		if ($)
     $service = $this->getService();
     SearchVariant::with(count($query->classes) == 1 ? $query->classes[0]['class'] : null)->call('alterQuery', $query, $this);
     $q = $terms;
     $fq = array();
     // Build the search itself
     //		foreach ($query->search as $search) {
     //			$text = $search['text'];
     //			preg_match_all('/"[^"]*"|\S+/', $text, $parts);
     //
     //			$fuzzy = $search['fuzzy'] ? '~' : '';
     //
     //			foreach ($parts[0] as $part) {
     //				$fields = (isset($search['fields'])) ? $search['fields'] : array();
     //				if(isset($search['boost'])) $fields = array_merge($fields, array_keys($search['boost']));
     //				if ($fields) {
     //					$searchq = array();
     //					foreach ($fields as $field) {
     //						$boost = (isset($search['boost'][$field])) ? '^' . $search['boost'][$field] : '';
     //						$searchq[] = "{$field}:".$part.$fuzzy.$boost;
     //					}
     //					$q[] = '+('.implode(' OR ', $searchq).')';
     //				}
     //				else {
     //					$q[] = '+'.$part.$fuzzy;
     //				}
     //			}
     //		}
     // Filter by class if requested
     $classq = array();
     foreach ($query->classes as $class) {
         if (!empty($class['includeSubclasses'])) {
             $classq[] = 'ClassHierarchy:' . $class['class'];
         } else {
             $classq[] = 'ClassName:' . $class['class'];
         }
     }
     if ($classq) {
         $fq[] = '+(' . implode(' ', $classq) . ')';
     }
     // Filter by filters
     foreach ($query->require as $field => $values) {
         $requireq = array();
         foreach ($values as $value) {
             if ($value === SearchQuery::$missing) {
                 $requireq[] = "(*:* -{$field}:[* TO *])";
             } elseif ($value === SearchQuery::$present) {
                 $requireq[] = "{$field}:[* TO *]";
             } elseif ($value instanceof SearchQuery_Range) {
                 $start = $value->start;
                 if ($start === null) {
                     $start = '*';
                 }
                 $end = $value->end;
                 if ($end === null) {
                     $end = '*';
                 }
                 $requireq[] = "{$field}:[{$start} TO {$end}]";
             } else {
                 $requireq[] = $field . ':"' . $value . '"';
             }
         }
         $fq[] = '+(' . implode(' ', $requireq) . ')';
     }
     foreach ($query->exclude as $field => $values) {
         $excludeq = array();
         $missing = false;
         foreach ($values as $value) {
             if ($value === SearchQuery::$missing) {
                 $missing = true;
             } elseif ($value === SearchQuery::$present) {
                 $excludeq[] = "{$field}:[* TO *]";
             } elseif ($value instanceof SearchQuery_Range) {
                 $start = $value->start;
                 if ($start === null) {
                     $start = '*';
                 }
                 $end = $value->end;
                 if ($end === null) {
                     $end = '*';
                 }
                 $excludeq[] = "{$field}:[{$start} TO {$end}]";
             } else {
                 $excludeq[] = $field . ':"' . $value . '"';
             }
         }
         $fq[] = ($missing ? "+{$field}:[* TO *] " : '') . '-(' . implode(' ', $excludeq) . ')';
     }
     //		if(!headers_sent()) {
     //			if ($q) header('X-Query: '.implode(' ', $q));
     //			if ($fq) header('X-Filters: "'.implode('", "', $fq).'"');
     //		}
     $params = array_merge($params, array('fq' => implode(' ', $fq)));
     $res = $service->search(implode(' ', $q), 0, $limit, $params, Apache_Solr_Service::METHOD_POST);
     $results = new ArrayList();
     if ($res->getHttpStatus() >= 200 && $res->getHttpStatus() < 300) {
         foreach ($res->response->docs as $doc) {
             $result = DataObject::get_by_id($doc->ClassName, $doc->ID);
             if ($result) {
                 $results->push($result);
             }
         }
         $numFound = $res->response->numFound;
     } else {
         $numFound = 0;
     }
     $ret = array();
     $ret['products'] = new PaginatedList($results);
     $ret['products']->setLimitItems(false);
     $ret['products']->setTotalItems($numFound);
     $ret['products']->setPageStart(0);
     $ret['products']->setPageLength($limit);
     // Facets (this is how we're doing suggestions for now...
     $ret['suggestions'] = array();
     if (isset($res->facet_counts->facet_fields->_autocomplete)) {
         foreach ($res->facet_counts->facet_fields->_autocomplete as $term => $count) {
             $ret['suggestions'][] = $prefix . $term;
         }
     }
     // Suggestions (requires custom setup, assumes spellcheck.collate=true)
     //		if(isset($res->spellcheck->suggestions->collation)) {
     //			$ret['Suggestion'] = $res->spellcheck->suggestions->collation;
     //		}
     return $ret;
 }
예제 #12
0
    // create author search string
    if (strlen(trim($adv->author)) > 0) {
        $query_string .= " +{$authorstr}:" . implode(" +{$authorstr}:", preg_split("/[\\s,;]+/", $adv->author));
    }
    // save our options if the query is valid
    if (!empty($query_string)) {
        $_SESSION['search_advanced_query'] = serialize($adv);
    }
}
// normalise page number
if ($page_number < 1) {
    $page_number = 1;
}
//run the query against the index ensuring internal coding works in UTF-8
Zend_Search_Lucene_Analysis_Analyzer::setDefault(new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8_CaseInsensitive());
$sq = new SearchQuery($query_string, $page_number, 10, false);
if (!($site = get_site())) {
    redirect("index.php");
}
$strsearch = get_string('search', 'search');
$strquery = get_string('enteryoursearchquery', 'search');
//    if ($CFG->version < 2007032200){ NOT RELIABLE
if (!function_exists('build_navigation')) {
    print_header("{$site->shortname}: {$strsearch}: {$strquery}", "{$site->fullname}", "<a href=\"index.php\">{$strsearch}</a> -> {$strquery}");
} else {
    $navlinks[] = array('name' => $strsearch, 'link' => "index.php", 'type' => 'misc');
    $navlinks[] = array('name' => $strquery, 'link' => null, 'type' => 'misc');
    $navigation = build_navigation($navlinks);
    $site = get_site();
    print_header("{$strsearch}", "{$site->fullname}", $navigation, "", "", true, "&nbsp;", navmenu($site));
}
 public function search(SearchQuery $obj)
 {
     if (AdvancedPathLib::getCurrentOS() == AdvancedPathLib::OS_WINDOWS) {
         return array(0, array());
     }
     $this->results = array();
     // setting the queryString to the variable.
     $searchArray = explode(' ', $obj->getQueryString());
     foreach ($searchArray as $word) {
         $this->searchQuery .= 'filename:' . $word . '* ';
     }
     // setting the queryTokens to the variable.
     $queryTokens = $obj->getQueryTokens();
     // for each valid token, we add the token and its parameters to the $searchQuery variable.
     if ($queryTokens) {
         foreach ($queryTokens as $token => $parameters) {
             if (in_array($token, $this->getValidTokens())) {
                 foreach ($parameters as $count => $value) {
                     $this->searchQuery .= $token . ':' . $value;
                     if ($count < count($parameters) - 1) {
                         $this->searchQuery .= ' OR ';
                     } else {
                         $this->searchQuery .= ' ';
                     }
                 }
                 $this->searchQuery .= 'AND ';
             }
         }
         // searching for an AND at the end of the searchQuery, if it's there we delete it
         // to conform the query to the recoll standards.
         // ( by the way, an AND at the end of a query does not make any sense, do it? :P )
         $pos = strpos($this->searchQuery, 'AND', strlen($this->searchQuery) - 4);
         $this->searchQuery = substr($this->searchQuery, 0, $pos - 1);
     }
     $user = ProcManager::getInstance()->getCurrentProcess()->getLoginContext()->getEyeosUser()->getName();
     $recollDirPath = UMManager::getEyeosUserDirectory($user) . '/' . USERS_CONF_DIR . '/' . FRAMEWORK_SEARCH_RECOLL_DIR;
     $result = shell_exec(AdvancedPathLib::realpath(FRAMEWORK_SEARCH_UTILS_PATH) . '/XmlBuilder.pl ' . escapeshellarg(AdvancedPathLib::realpath($recollDirPath)) . ' ' . escapeshellarg($this->searchQuery));
     $xmlResult = simplexml_load_string($result);
     if ($xmlResult) {
         $path = realpath(UMManager::getEyeosUserDirectory($user)) . '/files/';
         foreach ($xmlResult as $node => $markup) {
             if ($node == 'file') {
                 $cleanPath = utf8_substr($markup->path, 7);
                 $cleanPath = 'home://~' . $user . '/' . utf8_substr($cleanPath, strlen($path));
                 $tempFile = array('type' => (string) $markup->type, 'path' => (string) $cleanPath, 'name' => (string) $markup->name, 'size' => (string) $markup->size);
                 $this->results[] = $tempFile;
             } else {
                 if ($node == 'files') {
                     $this->totalFiles = $markup;
                 }
             }
         }
     }
     return array($this->totalFiles, $this->results);
 }
예제 #14
0
 public function testSearchFileRecollPlugin()
 {
     $query = "filename:*foo* filename:*lol* type:pdf OR type:xml AND ext:html OR ext:xml";
     $searchQuery = new SearchQuery();
     $searchQuery->setQueryString($this->query);
     $searchQuery->setQueryTokens($this->tokens);
     // we want to check if the SearchManager is well working,
     // means if it is able to load all the required library.
     $searchManager = new SearchManager();
     $searchManager->search($searchQuery);
     // we also want to check if the parsing process
     // gives us a well formatted string.
     $recollPlugin = new SearchFileRecollPlugin();
     $recollPlugin->search($searchQuery);
     $this->assertEquals($query, $recollPlugin->getSearchQuery());
     // FileSearchListener::fileCreated()
     $this->assertFalse(is_file($this->fixture_file_path));
     $this->assertTrue($this->fixture_file->createNewFile());
     $this->assertTrue(is_file($this->fixture_file_path));
     $searchQuery->setQueryString('testFile');
     $searchQuery->setQueryTokens(null);
     $recollPlugin->resetSearchQuery();
     $recollPlugin->search($searchQuery);
     $results = $recollPlugin->getResults();
     $this->assertEquals($results[0]['name'], 'testFile.txt');
     // FileSearchListener::fileDeleted()
     $this->assertTrue(is_file($this->fixture_file_path));
     $this->assertTrue($this->fixture_file->delete());
     $this->assertFalse(is_file($this->fixture_file_path));
     $searchQuery->setQueryString('testFile');
     $searchQuery->setQueryTokens(null);
     $recollPlugin->resetSearchQuery();
     $recollPlugin->search($searchQuery);
     $results = $recollPlugin->getResults();
     $this->assertTrue(empty($results));
     // FileSearchListener::directoryCreated()
     $this->assertFalse(is_dir($this->fixture_dir_path));
     $this->assertTrue($this->fixture_dir->mkdir());
     $this->assertTrue(is_dir($this->fixture_dir_path));
     $searchQuery->setQueryString('testDir');
     $searchQuery->setQueryTokens(null);
     $recollPlugin->resetSearchQuery();
     $recollPlugin->search($searchQuery);
     $results = $recollPlugin->getResults();
     $this->assertEquals($results[0]['name'], 'testDir');
     // FileSearchListener::fileMoved()
     $this->assertFalse(is_file($this->fixture_file_path));
     $this->assertTrue($this->fixture_file->createNewFile());
     $this->assertTrue(is_file($this->fixture_file_path));
     $newFile = FSI::getFile('home://~fakeUser/testDir/testFile2.txt');
     $this->assertTrue($this->fixture_file->moveTo($newFile));
     $this->assertTrue(is_file($this->fixture_newFile_path));
     $this->assertFalse(is_file($this->fixture_file_path));
     $searchQuery->setQueryString('testFile2');
     $searchQuery->setQueryTokens(null);
     $recollPlugin->resetSearchQuery();
     $recollPlugin->search($searchQuery);
     $results = $recollPlugin->getResults();
     $this->assertEquals($results[0]['name'], 'testFile2.txt');
     $searchQuery->setQueryString('testFile');
     $searchQuery->setQueryTokens(null);
     $recollPlugin->resetSearchQuery();
     $recollPlugin->search($searchQuery);
     $results = $recollPlugin->getResults();
     $this->assertNotEquals($results[0]['name'], 'testFile.txt');
     $newFile->delete();
     // FileSearchListener::fileRenamed()
     $this->assertFalse(is_file($this->fixture_file_path));
     $this->assertTrue($this->fixture_file->createNewFile());
     $this->assertTrue(is_file($this->fixture_file_path));
     $this->assertTrue($this->fixture_file->renameTo('testFileRenamed.txt'));
     $searchQuery->setQueryString('testFile');
     $searchQuery->setQueryTokens(null);
     $recollPlugin->resetSearchQuery();
     $recollPlugin->search($searchQuery);
     $results = $recollPlugin->getResults();
     $this->assertNotEquals($results[0]['name'], 'testFile.txt');
     $this->assertEquals($results[0]['name'], 'testFileRenamed.txt');
     // FileSearchListener::fileWritten()
     $this->fixture_file->putContents('take it easy!');
     // TODO: check if the content's file is up to date.
 }
예제 #15
0
    /**
     * Deletes all associated SearchQueries
     * @return void
     */
    public function DeleteAllSearchQueries()
    {
        if (is_null($this->intId)) {
            throw new QUndefinedPrimaryKeyException('Unable to call UnassociateSearchQuery on this unsaved Person.');
        }
        // Get the Database Object for this Class
        $objDatabase = Person::GetDatabase();
        // Journaling
        if ($objDatabase->JournalingDatabase) {
            foreach (SearchQuery::LoadArrayByPersonId($this->intId) as $objSearchQuery) {
                $objSearchQuery->Journal('DELETE');
            }
        }
        // Perform the SQL Query
        $objDatabase->NonQuery('
				DELETE FROM
					`search_query`
				WHERE
					`person_id` = ' . $objDatabase->SqlVariable($this->intId) . '
			');
    }
 /**
  * Refresh this MetaControl with Data from the local QueryCondition object.
  * @param boolean $blnReload reload QueryCondition from the database
  * @return void
  */
 public function Refresh($blnReload = false)
 {
     if ($blnReload) {
         $this->objQueryCondition->Reload();
     }
     if ($this->lblId) {
         if ($this->blnEditMode) {
             $this->lblId->Text = $this->objQueryCondition->Id;
         }
     }
     if ($this->lstSearchQuery) {
         $this->lstSearchQuery->RemoveAllItems();
         $this->lstSearchQuery->AddItem(QApplication::Translate('- Select One -'), null);
         $objSearchQueryArray = SearchQuery::LoadAll();
         if ($objSearchQueryArray) {
             foreach ($objSearchQueryArray as $objSearchQuery) {
                 $objListItem = new QListItem($objSearchQuery->__toString(), $objSearchQuery->Id);
                 if ($this->objQueryCondition->SearchQuery && $this->objQueryCondition->SearchQuery->Id == $objSearchQuery->Id) {
                     $objListItem->Selected = true;
                 }
                 $this->lstSearchQuery->AddItem($objListItem);
             }
         }
     }
     if ($this->lblSearchQueryId) {
         $this->lblSearchQueryId->Text = $this->objQueryCondition->SearchQuery ? $this->objQueryCondition->SearchQuery->__toString() : null;
     }
     if ($this->lstOrQueryCondition) {
         $this->lstOrQueryCondition->RemoveAllItems();
         $this->lstOrQueryCondition->AddItem(QApplication::Translate('- Select One -'), null);
         $objOrQueryConditionArray = QueryCondition::LoadAll();
         if ($objOrQueryConditionArray) {
             foreach ($objOrQueryConditionArray as $objOrQueryCondition) {
                 $objListItem = new QListItem($objOrQueryCondition->__toString(), $objOrQueryCondition->Id);
                 if ($this->objQueryCondition->OrQueryCondition && $this->objQueryCondition->OrQueryCondition->Id == $objOrQueryCondition->Id) {
                     $objListItem->Selected = true;
                 }
                 $this->lstOrQueryCondition->AddItem($objListItem);
             }
         }
     }
     if ($this->lblOrQueryConditionId) {
         $this->lblOrQueryConditionId->Text = $this->objQueryCondition->OrQueryCondition ? $this->objQueryCondition->OrQueryCondition->__toString() : null;
     }
     if ($this->lstQueryOperation) {
         $this->lstQueryOperation->RemoveAllItems();
         if (!$this->blnEditMode) {
             $this->lstQueryOperation->AddItem(QApplication::Translate('- Select One -'), null);
         }
         $objQueryOperationArray = QueryOperation::LoadAll();
         if ($objQueryOperationArray) {
             foreach ($objQueryOperationArray as $objQueryOperation) {
                 $objListItem = new QListItem($objQueryOperation->__toString(), $objQueryOperation->Id);
                 if ($this->objQueryCondition->QueryOperation && $this->objQueryCondition->QueryOperation->Id == $objQueryOperation->Id) {
                     $objListItem->Selected = true;
                 }
                 $this->lstQueryOperation->AddItem($objListItem);
             }
         }
     }
     if ($this->lblQueryOperationId) {
         $this->lblQueryOperationId->Text = $this->objQueryCondition->QueryOperation ? $this->objQueryCondition->QueryOperation->__toString() : null;
     }
     if ($this->lstQueryNode) {
         $this->lstQueryNode->RemoveAllItems();
         if (!$this->blnEditMode) {
             $this->lstQueryNode->AddItem(QApplication::Translate('- Select One -'), null);
         }
         $objQueryNodeArray = QueryNode::LoadAll();
         if ($objQueryNodeArray) {
             foreach ($objQueryNodeArray as $objQueryNode) {
                 $objListItem = new QListItem($objQueryNode->__toString(), $objQueryNode->Id);
                 if ($this->objQueryCondition->QueryNode && $this->objQueryCondition->QueryNode->Id == $objQueryNode->Id) {
                     $objListItem->Selected = true;
                 }
                 $this->lstQueryNode->AddItem($objListItem);
             }
         }
     }
     if ($this->lblQueryNodeId) {
         $this->lblQueryNodeId->Text = $this->objQueryCondition->QueryNode ? $this->objQueryCondition->QueryNode->__toString() : null;
     }
     if ($this->txtValue) {
         $this->txtValue->Text = $this->objQueryCondition->Value;
     }
     if ($this->lblValue) {
         $this->lblValue->Text = $this->objQueryCondition->Value;
     }
     if ($this->lstQueryConditionAsOr) {
         $this->lstQueryConditionAsOr->RemoveAllItems();
         $this->lstQueryConditionAsOr->AddItem(QApplication::Translate('- Select One -'), null);
         $objQueryConditionArray = QueryCondition::LoadAll();
         if ($objQueryConditionArray) {
             foreach ($objQueryConditionArray as $objQueryCondition) {
                 $objListItem = new QListItem($objQueryCondition->__toString(), $objQueryCondition->Id);
                 if ($objQueryCondition->OrQueryConditionId == $this->objQueryCondition->Id) {
                     $objListItem->Selected = true;
                 }
                 $this->lstQueryConditionAsOr->AddItem($objListItem);
             }
         }
     }
     if ($this->lblQueryConditionAsOr) {
         $this->lblQueryConditionAsOr->Text = $this->objQueryCondition->QueryConditionAsOr ? $this->objQueryCondition->QueryConditionAsOr->__toString() : null;
     }
 }
function get_elastic_crp_posts($args = array())
{
    global $post;
    // Are we matching only the title or the post content as well?
    $match_fields = array('post_title');
    $match_fields_content = array($post->post_title);
    if ($args['match_content']) {
        $match_fields[] = 'post_content';
        $match_fields_content[] = crp_excerpt($post->ID, $args['match_content_words'], false);
    }
    // Limit the related posts by time
    $current_time = current_time('timestamp', 0);
    $from_date = $current_time - $args['daily_range'] * DAY_IN_SECONDS;
    $from_date = gmdate('Y-m-d H:i:s', $from_date);
    $limit = $args['strict_limit'] ? $args['limit'] : $args['limit'] * 3;
    $client = \Grupoadslzone\Singletons\ElasticSearchClient::i();
    /*$clientBuilder = Elasticsearch\ClientBuilder::create();
      $clientBuilder->setHosts(array('http://127.0.0.1:9200'));
      $client = $clientBuilder->build();*/
    require_once plugin_dir_path(__FILE__) . 'includes/SearchQuery.php';
    $search_query = new SearchQuery();
    $search_query->setParamsByWPPost($post);
    $params = ['index' => ep_get_index_name(), 'type' => 'post', 'body' => ['_source' => 'post_id', 'query' => ['more_like_this' => ["fields" => $search_query->getFields(), "like_text" => $search_query->getSearchQuery(), "min_term_freq" => $search_query->getMinTermFreq(), "max_query_terms" => $search_query->getMaxQueryTerms(), "min_word_length" => 2, "minimum_should_match" => $search_query->getMinimumShouldMatch(), "boost" => 9, "boost_terms" => 4]], 'filter' => ["bool" => ["should" => ['range' => ['post_date' => ['from' => $from_date]]], 'must_not' => ['term' => ["post.post_id" => $post->ID]]]], 'from' => 0, 'size' => $limit]];
    //$ret = json_encode($params['body']);
    $response = $client->search($params);
    $results = $response['hits']['hits'];
    return $results;
}
예제 #18
0
파일: search.php 프로젝트: rebe100x/YAKREP
<?php

require_once 'init.php';
require_once 'SearchClient.php';
// $searchClient = SearchClient::createSearchClient("http://reddmz011.prod.exalead.com:12100/searchV10", '4.6');
$searchClient = SearchClient::createSearchClient("http://reddmz011.prod:10600/search/xml/v10", '4.6');
// $searchClient = SearchClient::createSearchClient("http://reddmz011.prod:19200/search-api/search", '5.0');
// $searchClient = SearchClient::createSearchClient("http://reddmz012.prod:31010/search-api/search", '5.0');
// $searchClient = SearchClient::createSearchClient("http://api.exalead.com/search/web?output=searchv10", 'APIFRONT');
$searchQuery = new SearchQuery();
foreach ($_GET as $key => $value) {
    $searchParameters = $searchQuery->addParameter($key, $value);
}
try {
    $answer = $searchClient->getResultsAsSimplifiedObject($searchQuery);
} catch (Exception $e) {
    $error = $e->getMessage() . $e->getTraceAsString();
}
if ($answer) {
    $query = clean($_GET['q']);
    // remove html entities, etc.
    $answerInfos = $answer->getInfos();
    if ($answerInfos['context']) {
        unset($_GET);
        $_GET['q'] = $query;
        $_GET[SearchParameter::$CONTEXT] = $answerInfos['context'];
    }
    if (count($answer->getHits())) {
        /* Render the Refines template into the sidebar_right container */
        $templates['sidebar_right'] = 'refines.phtml';
    }
 /**
  * Filters a list of element IDs by a given search query.
  *
  * @param array $elementIds   The list of element IDs to filter by the search query.
  * @param mixed $query        The search query (either a string or a SearchQuery instance)
  * @param bool  $scoreResults Whether to order the results based on how closely they match the query.
  * @param mixed $localeId     The locale to filter by.
  * @param bool  $returnScores Whether the search scores should be included in the results. If true, results will be returned as `element ID => score`.
  *
  * @return array The filtered list of element IDs.
  */
 public function filterElementIdsByQuery($elementIds, $query, $scoreResults = true, $localeId = null, $returnScores = false)
 {
     if (is_string($query)) {
         $query = new SearchQuery($query, craft()->config->get('defaultSearchTermOptions'));
     } else {
         if (is_array($query)) {
             $options = $query;
             $query = $options['query'];
             unset($options['query']);
             $query = new SearchQuery($query, $options);
         }
     }
     // Get tokens for query
     $this->_tokens = $query->getTokens();
     $this->_terms = array();
     $this->_groups = array();
     // Set Terms and Groups based on tokens
     foreach ($this->_tokens as $obj) {
         if ($obj instanceof SearchQueryTermGroup) {
             $this->_groups[] = $obj->terms;
         } else {
             $this->_terms[] = $obj;
         }
     }
     // Get where clause from tokens, bail out if no valid query is there
     $where = $this->_getWhereClause();
     if (!$where) {
         return array();
     }
     // Add any locale restrictions
     if ($localeId) {
         $where .= sprintf(' AND %s = %s', craft()->db->quoteColumnName('locale'), craft()->db->quoteValue($localeId));
     }
     // Begin creating SQL
     $sql = sprintf('SELECT * FROM %s WHERE %s', craft()->db->quoteTableName(craft()->db->addTablePrefix('searchindex')), $where);
     // Append elementIds to QSL
     if ($elementIds) {
         $sql .= sprintf(' AND %s IN (%s)', craft()->db->quoteColumnName('elementId'), implode(',', $elementIds));
     }
     // Execute the sql
     $results = craft()->db->createCommand()->setText($sql)->queryAll();
     // Are we scoring the results?
     if ($scoreResults) {
         $scoresByElementId = array();
         // Loop through results and calculate score per element
         foreach ($results as $row) {
             $elementId = $row['elementId'];
             $score = $this->_scoreRow($row);
             if (!isset($scoresByElementId[$elementId])) {
                 $scoresByElementId[$elementId] = $score;
             } else {
                 $scoresByElementId[$elementId] += $score;
             }
         }
         // Sort found elementIds by score
         arsort($scoresByElementId);
         if ($returnScores) {
             return $scoresByElementId;
         } else {
             // Just return the ordered element IDs
             return array_keys($scoresByElementId);
         }
     } else {
         // Don't apply score, just return the IDs
         $elementIds = array();
         foreach ($results as $row) {
             $elementIds[] = $row['elementId'];
         }
         return array_unique($elementIds);
     }
 }
예제 #20
0
 /**
  * Builds a search query from a give search term.
  * @return SearchQuery
  */
 protected function getSearchQuery($keywords)
 {
     $categoryIDs = array();
     $categoryFilterID = $this->request->requestVar(self::$search_category_key);
     $categories = $this->Categories();
     if ($categories->count() == 0) {
         $categories = FAQ::getRootCategory()->Children();
     }
     $filterCategory = $categories->filter('ID', $categoryFilterID)->first();
     $categoryIDs = array();
     if ($filterCategory && $filterCategory->exists()) {
         $categoryIDs = $this->getSelectedIDs(array($filterCategory));
     } else {
         $categoryIDs = $this->Categories()->column('ID');
     }
     $query = new SearchQuery();
     $query->classes = self::$classes_to_search;
     if (count($categoryIDs) > 0) {
         $query->filter('FAQ_Category_ID', array_filter($categoryIDs, 'intval'));
     }
     $query->search($keywords);
     // Artificially lower the amount of results to prevent too high resource usage.
     // on subsequent canView check loop.
     $query->limit(100);
     return $query;
 }
예제 #21
0
 /**
  * Filters a list of element IDs by a given search query.
  *
  * @param array  $elementIds The list of element IDs to filter by the search query.
  * @param mixed  $query      The search query (either a string or a SearchQuery instance)
  * @param bool   $scoreResults Whether to order the results based on how closely they match the query.
  * @return array The filtered list of element IDs.
  */
 public function filterElementIdsByQuery($elementIds, $query, $scoreResults = true)
 {
     if (is_string($query)) {
         $query = new SearchQuery($query);
     }
     // Get tokens for query
     $this->_tokens = $query->getTokens();
     $this->_terms = array();
     $this->_groups = array();
     $this->_results = array();
     // Set Terms and Groups based on tokens
     foreach ($this->_tokens as $obj) {
         if ($obj instanceof SearchQueryTermGroup) {
             $this->_groups[] = $obj->terms;
         } else {
             $this->_terms[] = $obj;
         }
     }
     // Get where clause from tokens, bail out if no valid query is there
     $where = $this->_getWhereClause();
     if (!$where) {
         return array();
     }
     // Begin creating SQL
     $sql = sprintf('SELECT * FROM %s WHERE %s', craft()->db->quoteTableName(DbHelper::addTablePrefix('searchindex')), $where);
     // Append elementIds to QSL
     if ($elementIds) {
         $sql .= sprintf(' AND %s IN (%s)', craft()->db->quoteColumnName('elementId'), implode(',', $elementIds));
     }
     // Execute the sql
     $results = craft()->db->createCommand()->setText($sql)->queryAll();
     // Are we scoring the results?
     if ($scoreResults) {
         // Loop through results and calculate score per element
         foreach ($results as $row) {
             $eId = $row['elementId'];
             $score = $this->_scoreRow($row);
             if (!isset($this->_results[$eId])) {
                 $this->_results[$eId] = $score;
             } else {
                 $this->_results[$eId] += $score;
             }
         }
         // Sort found elementIds by score
         asort($this->_results);
         // Store entry ids in return value
         $elementIds = array_keys($this->_results);
     } else {
         // Don't apply score, just return the IDs
         $elementIds = array();
         foreach ($results as $row) {
             $elementIds[] = $row['elementId'];
         }
         $elementIds = array_unique($elementIds);
     }
     // Return elementIds
     return $elementIds;
 }
예제 #22
0
 /**
  * Static Helper Method to Create using PK arguments
  * You must pass in the PK arguments on an object to load, or leave it blank to create a new one.
  * If you want to load via QueryString or PathInfo, use the CreateFromQueryString or CreateFromPathInfo
  * static helper methods.  Finally, specify a CreateType to define whether or not we are only allowed to 
  * edit, or if we are also allowed to create a new one, etc.
  * 
  * @param mixed $objParentObject QForm or QPanel which will be using this SearchQueryMetaControl
  * @param integer $intId primary key value
  * @param QMetaControlCreateType $intCreateType rules governing SearchQuery object creation - defaults to CreateOrEdit
  * @return SearchQueryMetaControl
  */
 public static function Create($objParentObject, $intId = null, $intCreateType = QMetaControlCreateType::CreateOrEdit)
 {
     // Attempt to Load from PK Arguments
     if (strlen($intId)) {
         $objSearchQuery = SearchQuery::Load($intId);
         // SearchQuery was found -- return it!
         if ($objSearchQuery) {
             return new SearchQueryMetaControl($objParentObject, $objSearchQuery);
         } else {
             if ($intCreateType != QMetaControlCreateType::CreateOnRecordNotFound) {
                 throw new QCallerException('Could not find a SearchQuery object with PK arguments: ' . $intId);
             }
         }
         // If EditOnly is specified, throw an exception
     } else {
         if ($intCreateType == QMetaControlCreateType::EditOnly) {
             throw new QCallerException('No PK arguments specified');
         }
     }
     // If we are here, then we need to create a new record
     return new SearchQueryMetaControl($objParentObject, new SearchQuery());
 }
예제 #23
0
 /**
  * Override method to perform a property "Get"
  * This will get the value of $strName
  *
  * @param string $strName Name of the property to get
  * @return mixed
  */
 public function __get($strName)
 {
     switch ($strName) {
         ///////////////////
         // Member Variables
         ///////////////////
         case 'GroupId':
             // Gets the value for intGroupId (PK)
             // @return integer
             return $this->intGroupId;
         case 'Query':
             // Gets the value for strQuery
             // @return string
             return $this->strQuery;
         case 'DateRefreshed':
             // Gets the value for dttDateRefreshed
             // @return QDateTime
             return $this->dttDateRefreshed;
         case 'ProcessTimeMs':
             // Gets the value for intProcessTimeMs
             // @return integer
             return $this->intProcessTimeMs;
             ///////////////////
             // Member Objects
             ///////////////////
         ///////////////////
         // Member Objects
         ///////////////////
         case 'Group':
             // Gets the value for the Group object referenced by intGroupId (PK)
             // @return Group
             try {
                 if (!$this->objGroup && !is_null($this->intGroupId)) {
                     $this->objGroup = Group::Load($this->intGroupId);
                 }
                 return $this->objGroup;
             } catch (QCallerException $objExc) {
                 $objExc->IncrementOffset();
                 throw $objExc;
             }
         case 'SearchQuery':
             // Gets the value for the SearchQuery object that uniquely references this SmartGroup
             // by objSearchQuery (Unique)
             // @return SearchQuery
             try {
                 if ($this->objSearchQuery === false) {
                     // We've attempted early binding -- and the reverse reference object does not exist
                     return null;
                 }
                 if (!$this->objSearchQuery) {
                     $this->objSearchQuery = SearchQuery::LoadBySmartGroupId($this->intGroupId);
                 }
                 return $this->objSearchQuery;
             } catch (QCallerException $objExc) {
                 $objExc->IncrementOffset();
                 throw $objExc;
             }
             ////////////////////////////
             // Virtual Object References (Many to Many and Reverse References)
             // (If restored via a "Many-to" expansion)
             ////////////////////////////
         ////////////////////////////
         // Virtual Object References (Many to Many and Reverse References)
         // (If restored via a "Many-to" expansion)
         ////////////////////////////
         case '__Restored':
             return $this->__blnRestored;
         default:
             try {
                 return parent::__get($strName);
             } catch (QCallerException $objExc) {
                 $objExc->IncrementOffset();
                 throw $objExc;
             }
     }
 }
예제 #24
0
        }
        // create author search string
        if (strlen(trim($adv->author)) > 0) {
            $query_string .= " +{$authorstr}:" . implode(" +{$authorstr}:", preg_split("/[\\s,;]+/", $adv->author));
        }
        // save our options if the query is valid
        if (!empty($query_string)) {
            $_SESSION['search_advanced_query'] = serialize($adv);
        }
    }
    // normalise page number
    if ($page_number < 1) {
        $page_number = 1;
    }
    //run the query against the index
    $sq = new SearchQuery($query_string, $page_number, 10, false);
}
if (!($site = get_site())) {
    redirect("index.php");
}
$strsearch = get_string('search', 'search');
$strquery = get_string('enteryoursearchquery', 'search');
$navlinks[] = array('name' => $strsearch, 'link' => "index.php", 'type' => 'misc');
$navlinks[] = array('name' => $strquery, 'link' => null, 'type' => 'misc');
$navigation = build_navigation($navlinks);
$site = get_site();
print_header("{$strsearch}", "{$site->fullname}", $navigation, "", "", true, "&nbsp;", user_login_string($course) . '<hr style="width:95%">' . navmenu($site));
//keep things pretty, even if php5 isn't available
if (!$check) {
    print_heading(search_check_php5(true));
    print_footer();
예제 #25
0
 protected function getResults(SearchQuery $query)
 {
     $i = 0;
     $params = $query->getParameters();
     $xmlReq = "<Query xmlns='exa:com.exalead.search.v10'><args>";
     foreach ($params as $param) {
         $name = $param->getName();
         $value = $param->getValue();
         $xmlReq .= "<Arg xmlns='exa:com.exalead.xmlapplication' name='" . $name . "' value='" . htmlspecialchars(stripslashes($value), ENT_QUOTES, 'UTF-8') . "'/>";
     }
     $xmlReq .= "</args></Query>";
     //        echo str_replace("<", "&lt;", $xmlReq);
     $ch = curl_init($this->url);
     curl_setopt_array($ch, array(CURLOPT_HTTPHEADER => array('Content-type: text/xml'), CURLOPT_FOLLOWLOCATION => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $xmlReq));
     if (($result = curl_exec($ch)) !== false && curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200) {
         $this->xmlResponse = str_replace("xmlns=", "ns=", $result);
         echo str_replace("<", "&lt;", $this->xmlResponse);
     } else {
         throw new SearchClientException('Error: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE) . "\n" . curl_error($ch));
     }
     curl_close($ch);
 }
예제 #26
0
 /**
  * This will save this object's SmartGroup instance,
  * updating only the fields which have had a control created for it.
  */
 public function SaveSmartGroup()
 {
     try {
         // Update any fields for controls that have been created
         if ($this->lstGroup) {
             $this->objSmartGroup->GroupId = $this->lstGroup->SelectedValue;
         }
         if ($this->txtQuery) {
             $this->objSmartGroup->Query = $this->txtQuery->Text;
         }
         if ($this->calDateRefreshed) {
             $this->objSmartGroup->DateRefreshed = $this->calDateRefreshed->DateTime;
         }
         if ($this->txtProcessTimeMs) {
             $this->objSmartGroup->ProcessTimeMs = $this->txtProcessTimeMs->Text;
         }
         // Update any UniqueReverseReferences (if any) for controls that have been created for it
         if ($this->lstSearchQuery) {
             $this->objSmartGroup->SearchQuery = SearchQuery::Load($this->lstSearchQuery->SelectedValue);
         }
         // Save the SmartGroup object
         $this->objSmartGroup->Save();
         // Finally, update any ManyToManyReferences (if any)
     } catch (QCallerException $objExc) {
         $objExc->IncrementOffset();
         throw $objExc;
     }
 }
 function testHighlightQueryOnBoost()
 {
     $serviceMock = $this->getServiceMock();
     Phockito::when($serviceMock)->search(anything(), anything(), anything(), anything(), anything())->return($this->getFakeRawSolrResponse());
     $index = new SolrIndexTest_FakeIndex();
     $index->setService($serviceMock);
     // Search without highlighting
     $query = new SearchQuery();
     $query->search('term', null, array('Field1' => 1.5, 'HasOneObject_Field1' => 3));
     $index->search($query);
     Phockito::verify($serviceMock)->search('+(Field1:term^1.5 OR HasOneObject_Field1:term^3)', anything(), anything(), not(hasKeyInArray('hl.q')), anything());
     // Search with highlighting
     $query = new SearchQuery();
     $query->search('term', null, array('Field1' => 1.5, 'HasOneObject_Field1' => 3));
     $index->search($query, -1, -1, array('hl' => true));
     Phockito::verify($serviceMock)->search('+(Field1:term^1.5 OR HasOneObject_Field1:term^3)', anything(), anything(), hasKeyInArray('hl.q'), anything());
 }
예제 #28
0
파일: ste.php 프로젝트: homberghp/peerweb
 /**
  * Process the user response from $_GET, $_POST or $_SESSION.
  * @return void
  */
 function processResponse()
 {
     global $PHP_SELF;
     global $_SESSION;
     global $validator_clearance;
     global $system_settings;
     $this->list_query = '';
     // declare list query
     $this->ste_query = '';
     // declare main query
     $this->menu = new ExtendedMenu($this->itemValidator, $this->page);
     if (isset($this->rawNames)) {
         $this->menu->setRawNames($this->rawNames);
     }
     $this->menu->setFieldPrefix('veld');
     $this->menu->setItemDefQuery("select column_name,data_type,item_length," . "edit_type,query,capability,precision,placeholder,regex_name\n" . "from menu_item_defs where menu_name='{$this->menuName}'");
     $this->menu->setDBConn($this->dbConn);
     /*  let the menu learn about its content */
     $this->menu->setMenuName($this->menuName);
     $this->menu->setSubRel($this->subRel);
     $this->menu->setSubRelJoinColumns($this->subRelJoinColumns);
     /* now menu knows its columns, process the inputs */
     if (!empty($_SESSION['list_query']) && $PHP_SELF == $_SESSION['ste_referer']) {
         $this->list_query = $_SESSION['list_query'];
     }
     /* pick up potential key values from $_GET */
     $this->keyValues = $this->getKeyValues($_GET);
     //    $this->dbConn->log('keyValues={'.bvar_dump($this->keyValues).'}<br/>');
     /* pick up the _POST inputs such as the submit values */
     //    echo '<br><span style="color:red;"> _POST=',bvar_dump($_POST).'</span><br>';
     if (count($_POST) > 0) {
         if (isset($_POST['Clear'])) {
             /*
              * L E E G
              */
             /* throw away any old search result, i.e. the query */
             /* by kicking it out of the $_GET array */
             //	  echo '<span style="color:red;">Meuk it<br><br></span>';
             $_GET = array();
             $_POST = array();
             $this->list_query = '';
             $this->keyValues = array();
             /* meuk */
             unset($_SESSION['list_query']);
             unset($_SESSION['ste_query']);
             $this->list_query = '';
             $this->ste_query = '';
             /* THATS all folks, empty results etc */
             return;
         }
         /* load only  if request is not LEEG */
         $this->setMenuValues($_POST);
         if ($validator_clearance) {
             // save edit values to session.
             if (isset($system_settings['edit_to_session'])) {
                 $save = explode(',', $system_settings['edit_to_session']);
                 foreach ($save as $s) {
                     list($k, $d) = split('=', $s);
                     $v = $d;
                     if (isset($_POST[$k]) && $_POST[$k] !== '') {
                         $v = $_POST[$k];
                     }
                     $_SESSION[$k] = $v;
                 }
             }
             if (isset($_POST['Search'])) {
                 /*
                  * S E A R C H
                  */
                 /** build a query from the $_POST data */
                 $sq = new SearchQuery($this->dbConn, $this->relation);
                 $sq->setKeyColumns($this->keyColumns);
                 $sq->setNameExpression($this->nameExpression);
                 if (isset($this->listRowTemplate)) {
                     $sq->setAuxColNames($this->listRowTemplate);
                 }
                 $sq->setQueryExtension($this->listQueryExtension);
                 $sq->setOrderList($this->orderList);
                 $sq->setSubmitValueSet($_POST);
                 $this->list_query = $sq->setSubRel($this->subRel)->setSubRelJoinColumns($this->subRelJoinColumns)->getExtendedQuery();
                 // test if must show searchquery through log
                 //$this->dbMessage .="\n<br/>list_query=[" . $this->list_query . "]=list_query\n";
                 $this->addLogQuery($sq->getLog());
                 $this->ste_query = $sq->getAllQuery();
                 $this->spreadSheetWriter->setQuery($this->ste_query);
                 if ($this->showQuery) {
                     $this->dbConn->log("<br/>\nste query=" . $this->ste_query . "<br/>");
                 }
                 //$this->dbMessage .= "\nste query=".$this->ste_query;
                 $rs = $this->dbConnExecute($this->ste_query);
                 if ($rs !== false && !$rs->EOF) {
                     /* if search succeeded, load the first hit */
                     $this->setMenuValues($rs->fields);
                     $this->keyValues = $this->getKeyValues($rs->fields);
                 } else {
                     /* reload screen from _POST data */
                     $this->setMenuValues($_POST);
                     $this->dbMessage .= "\nNothing found";
                 }
             } else {
                 if ($this->allowIUD && isset($_POST['Insert'])) {
                     /*
                      * I N S E R T
                      */
                     $this->doInsert();
                 } else {
                     if ($this->allowIUD && isset($_POST['Update'])) {
                         $this->doUpdate();
                     } else {
                         if ($this->allowIUD && isset($_POST['Delete'])) {
                             /*
                              * D E L E T E
                              */
                             $this->doDelete();
                         } else {
                             if (isset($_POST['Reset'])) {
                                 /*
                                  * reset is handled by the browser
                                  */
                             }
                         }
                     }
                 }
             }
         } else {
             // redisplay input
             $this->setMenuValues($_POST);
         }
     }
     /*
      * use _GET to determine the key columns
      */
     $sq = new SearchQuery($this->dbConn, $this->relation);
     $sq->setKeyColumns($this->keyColumns);
     $sq->setNameExpression($this->nameExpression);
     $sq->setOrderList($this->orderList)->setSubRel($this->subRel)->setSubRelJoinColumns($this->subRelJoinColumns);
     $sq->setSubmitValueSet($_GET);
     $this->dbMessage .= $sq->getQuery();
     if ($sq->areKeyColumnsSet()) {
         $sql = $sq->getAllQuery();
         $arr = array();
         $rs = $this->dbConnExecute($sql);
         if ($this->showQuery) {
             $this->dbConn->log('query ' . $sql);
         }
         $this->addLogQuery("<pre>all=[{$sql}]=all</pre><br/>");
         if ($rs !== false && !$rs->EOF) {
             $this->setMenuValues($rs->fields);
             $this->dbConn->log("<pre>" . print_r($rs->fields, true) . "</pre><br>");
             $this->keyValues = $this->getKeyValues($rs->fields);
         } else {
             $this->dbMessage .= "\n Found nothing " . $this->dbConn->ErrorMsg() . ' ' . $sql;
         }
     }
     /* end of else branch if (count($_POST)) */
 }
예제 #29
0
 public static function GetSoapObjectFromObject($objObject, $blnBindRelatedObjects)
 {
     if ($objObject->objSearchQuery) {
         $objObject->objSearchQuery = SearchQuery::GetSoapObjectFromObject($objObject->objSearchQuery, false);
     } else {
         if (!$blnBindRelatedObjects) {
             $objObject->intSearchQueryId = null;
         }
     }
     if ($objObject->objOrQueryCondition) {
         $objObject->objOrQueryCondition = QueryCondition::GetSoapObjectFromObject($objObject->objOrQueryCondition, false);
     } else {
         if (!$blnBindRelatedObjects) {
             $objObject->intOrQueryConditionId = null;
         }
     }
     if ($objObject->objQueryOperation) {
         $objObject->objQueryOperation = QueryOperation::GetSoapObjectFromObject($objObject->objQueryOperation, false);
     } else {
         if (!$blnBindRelatedObjects) {
             $objObject->intQueryOperationId = null;
         }
     }
     if ($objObject->objQueryNode) {
         $objObject->objQueryNode = QueryNode::GetSoapObjectFromObject($objObject->objQueryNode, false);
     } else {
         if (!$blnBindRelatedObjects) {
             $objObject->intQueryNodeId = null;
         }
     }
     return $objObject;
 }
예제 #30
0
 function getSubRelData()
 {
     if (!isset($this->subRel) || !isset($this->subRelJoinColumns)) {
         // return empty result.
         return array();
     }
     $query = new SearchQuery($this->dbConn, $this->relation);
     $query->setSubRel($this->subRel)->setSubRelJoinColumns($this->subRelJoinColumns);
     $sql = $query->getSubRelQuery();
     $this->logString .= 'subrel:' . $sql;
     return $this->dbConn->Execute($sql)->fields;
 }