Exemplo n.º 1
0
 function testPartialUpdate()
 {
     $initialSource = new Search_ContentSource_Static(array('HomePage' => array('data' => 'initial'), 'SomePage' => array('data' => 'initial'), 'Untouchable' => array('data' => 'initial')), array('data' => 'sortable'));
     $finalSource = new Search_ContentSource_Static(array('SomePage' => array('data' => 'final'), 'OtherPage' => array('data' => 'final'), 'Untouchable' => array('data' => 'final')), array('data' => 'sortable'));
     $dir = dirname(__FILE__) . '/test_index';
     $edir = escapeshellarg($dir);
     `rm -Rf {$edir}`;
     $index = new Search_Lucene_Index($dir);
     $indexer = new Search_Indexer($index);
     $indexer->addContentSource('wiki page', $initialSource);
     $indexer->rebuild();
     $indexer = new Search_Indexer($index);
     $indexer->addContentSource('wiki page', $finalSource);
     $indexer->update(array(array('object_type' => 'wiki page', 'object_id' => 'HomePage'), array('object_type' => 'wiki page', 'object_id' => 'SomePage'), array('object_type' => 'wiki page', 'object_id' => 'OtherPage')));
     $query = new Search_Query();
     $query->filterType('wiki page');
     $result = $query->search($index);
     $this->assertEquals(3, count($result));
     $doc0 = $result[0];
     $doc1 = $result[1];
     $doc2 = $result[2];
     $this->assertEquals('Untouchable', $doc0['object_id']);
     $this->assertEquals('initial', $doc0['data']);
     $this->assertEquals('final', $doc1['data']);
     $this->assertEquals('final', $doc2['data']);
     `rm -Rf {$edir}`;
 }
Exemplo n.º 2
0
 function testDocumentTooDifferent()
 {
     $query = new Search_Query();
     $query->filterSimilar('wiki page', 'X');
     $results = $query->search($this->index);
     $this->assertCount(0, $results);
 }
Exemplo n.º 3
0
 function testWeightImpact()
 {
     $query = new Search_Query();
     $query->setWeightCalculator(new Search_Query_WeightCalculator_Field(array('text_field' => 100, 'other_field' => 0.0001)));
     $query->filterContent('foobar', array('text_field', 'other_field'));
     $results = $query->search($this->index);
     $this->assertOrderIs('BA', $results);
 }
Exemplo n.º 4
0
 function build(Search_Query $query, Search_FacetProvider $provider)
 {
     foreach ($this->facets as $facet) {
         if ($real = $provider->getFacet($facet['name'])) {
             $real->setOperator($facet['operator']);
             $query->requestFacet($real);
         }
     }
 }
Exemplo n.º 5
0
 private function buildExpr(array $objectList)
 {
     $query = new Search_Query();
     foreach ($objectList as $object) {
         $object = (array) $object;
         $query->addObject($object['object_type'], $object['object_id']);
     }
     return $query->getExpr();
 }
Exemplo n.º 6
0
 function testRemoveQuery()
 {
     $query = new Search_Query('Hello World');
     $query->store('my_custom_name', $this->index);
     $this->index->unstore('my_custom_name');
     $tf = $this->index->getTypeFactory();
     $names = $this->index->getMatchingQueries(array('object_type' => $tf->identifier('wiki page'), 'object_id' => $tf->identifier('HomePage'), 'contents' => $tf->plaintext('Hello World!')));
     $this->assertEquals(array(), $names);
 }
Exemplo n.º 7
0
 private function addForIndex($query, $indexName, $index)
 {
     $sub = new Search_Query();
     foreach ($index->getTransformations() as $trans) {
         $sub->applyTransform($trans);
     }
     $query->includeForeign($indexName, $sub);
     return $sub;
 }
Exemplo n.º 8
0
 function testIndexProvidesHighlightHelper()
 {
     $query = new Search_Query('foobar or hello');
     $resultSet = $query->search($this->index);
     $plugin = new Search_Formatter_Plugin_WikiTemplate('{display name=highlight}');
     $formatter = new Search_Formatter($plugin);
     $output = $formatter->format($resultSet);
     $this->assertContains('<em>Hello</em>', $output);
     $this->assertNotContains('<body>', $output);
 }
Exemplo n.º 9
0
 function testRequireFacet()
 {
     $facet = new Search_Query_Facet_Term('categories');
     $query = new Search_Query();
     $query->filterType('wiki page');
     $query->requestFacet($facet);
     $result = $query->search($this->index);
     $values = $result->getFacet($facet);
     $this->assertEquals(new Search_ResultSet_FacetFilter($facet, array(array('value' => 1, 'count' => 3), array('value' => 2, 'count' => 2), array('value' => 'orphan', 'count' => 1), array('value' => 3, 'count' => 1))), $values);
 }
Exemplo n.º 10
0
 function testCamelCaseNotEnabled()
 {
     $index = new Search_Elastic_Index($this->connection, 'test_index');
     $index->destroy();
     $typeFactory = $index->getTypeFactory();
     $index->addDocument(['object_type' => $typeFactory->identifier('wiki page'), 'object_id' => $typeFactory->identifier('CamelCase Words'), 'title' => $typeFactory->plaintext('CamelCase Words')]);
     $query = new Search_Query();
     $query->filterContent('Camel AND Word', 'title');
     $this->assertEquals(0, count($query->search($index)));
 }
Exemplo n.º 11
0
 function testTransformsApplyPerIndex()
 {
     $query = new Search_Query('Hello');
     $query->applyTransform(new Search\Federated\UrlPrefixTransform('http://foo.example.com'));
     $sub = new Search_Query('Hello');
     $sub->applyTransform(new Search\Federated\UrlPrefixTransform('http://bar.example.com/'));
     $query->includeForeign('test_index_c', $sub);
     $result = $query->search($this->indexA);
     $urls = [$result[0]['url'], $result[1]['url']];
     $this->assertContains('http://foo.example.com/PageA', $urls);
     $this->assertContains('http://bar.example.com/PageC', $urls);
 }
Exemplo n.º 12
0
 /**
  * @expectedException Search_MySql_LimitReachedException
  */
 function testManyIndexes()
 {
     $typeFactory = $this->index->getTypeFactory();
     $document = array('object_type' => $typeFactory->identifier('test'), 'object_id' => $typeFactory->identifier('test'));
     $query = new Search_Query();
     for ($i = 0; 1000 > $i; ++$i) {
         $document['field_' . $i] = $typeFactory->sortable('test');
         $query->filterInitial('test', 'field_' . $i);
     }
     $this->index->addDocument($document);
     $query->search($this->index);
 }
 private function assertResultCorrect($count, $from, $perPage, $first, $last)
 {
     $this->addDocuments($count);
     $query = new Search_Query();
     $query->filterType('article');
     $query->setRange($from, $perPage);
     $result = $query->search($this->index);
     $this->assertEquals($count, count($result), 'total count');
     $real = array();
     foreach ($result as $hit) {
         $real[] = $hit;
     }
     $this->assertEquals($first, $real[0]['object_id'], 'first entry');
     $this->assertEquals($last, $real[count($real) - 1]['object_id'], 'last entry');
 }
Exemplo n.º 14
0
function smarty_block_ifsearchnotexists($params, $content, $smarty, &$repeat)
{
    if (empty($params['type']) || empty($params['id'])) {
        return '';
    }
    TikiLib::lib('access')->check_feature('feature_search');
    $query = new Search_Query();
    $query->addObject($params['type'], $params['id']);
    $index = TikiLib::lib('unifiedsearch')->getIndex();
    $result = $query->search($index);
    if ($result->count() > 0) {
        return '';
    } else {
        return $content;
    }
}
Exemplo n.º 15
0
 private function processObjects($function, $categId, $objects)
 {
     $unifiedsearchlib = TikiLib::lib('unifiedsearch');
     foreach ($objects as $object) {
         $type = $object['type'];
         $id = $object['id'];
         $this->{$function}($categId, $type, $id);
         $unifiedsearchlib->invalidateObject($type, $id);
     }
     $unifiedsearchlib->processUpdateQueue(count($objects) * 2);
     $query = new Search_Query();
     $query->filterCategory((string) $categId);
     $query->filterPermissions(Perms::get()->getGroups());
     $query->setRange(0, 1);
     $result = $query->search($unifiedsearchlib->getIndex());
     return array('categId' => $categId, 'count' => count($result), 'objects' => $objects, 'confirm' => 1);
 }
Exemplo n.º 16
0
 function update($searchArgument)
 {
     if (is_array($searchArgument)) {
         $query = new Search_Query();
         foreach ($searchArgument as $object) {
             $obj2array = (array) $object;
             $query->addObject($obj2array['object_type'], $obj2array['object_id']);
         }
         $result = $query->invalidate($this->searchIndex);
         $objectList = $searchArgument;
     } elseif ($searchArgument instanceof Search_Query) {
         $objectList = $searchArgument->invalidate($this->searchIndex);
     }
     foreach ($objectList as $object) {
         $obj2array = (array) $object;
         $this->addDocument($obj2array['object_type'], $obj2array['object_id']);
     }
 }
Exemplo n.º 17
0
/**
 * Apply tablesorter is enabled
 *
 * @param WikiParser_PluginMatcher $matches
 * @param Search_Query $query
 * @return array
 */
function applyTablesorter(WikiParser_PluginMatcher $matches, Search_Query $query)
{
    $ret = ['max' => false, 'tsOn' => false];
    $parser = new WikiParser_PluginArgumentParser();
    foreach ($matches as $match) {
        $name = $match->getName();
        if ($name == 'tablesorter') {
            $tsargs = $parser->parse($match->getArguments());
            $ajax = !empty($tsargs['server']) && $tsargs['server'] === 'y';
            $ret['tsOn'] = Table_Check::isEnabled($ajax);
            if (!$ret['tsOn']) {
                TikiLib::lib('errorreport')->report(tra('List plugin: Feature "jQuery Sortable Tables" (tablesorter) is not enabled'));
                return $ret;
            }
            if (isset($tsargs['tsortcolumns'])) {
                $tsc = Table_Check::parseParam($tsargs['tsortcolumns']);
            }
            if (isset($tsargs['tspaginate'])) {
                $tsp = Table_Check::parseParam($tsargs['tspaginate']);
                if (isset($tsp[0]['max']) && $ajax) {
                    $ret['max'] = (int) $tsp[0]['max'];
                }
            }
        }
    }
    foreach ($matches as $match) {
        $name = $match->getName();
        if ($name == 'column') {
            $cols[] = $match;
            $args[] = $parser->parse($match->getArguments());
        }
    }
    if (Table_Check::isSort()) {
        foreach ($_GET['sort'] as $key => $dir) {
            $n = '';
            switch ($tsc[$key]['type']) {
                case 'digit':
                case 'currency':
                case 'percent':
                case 'time':
                case strpos($tsc[$key]['type'], 'date') !== false:
                    $n = 'n';
                    break;
            }
            $query->setOrder($args[$key]['field'] . '_' . $n . Table_Check::$dir[$dir]);
        }
    }
    if (Table_Check::isFilter()) {
        foreach ($_GET['filter'] as $key => $filter) {
            $query->filterContent($filter, $args[$key]['field']);
        }
    }
    return $ret;
}
Exemplo n.º 18
0
 private function assertResultCount($count, $filterMethod, $argument)
 {
     $arguments = func_get_args();
     $arguments = array_slice($arguments, 2);
     $query = new Search_Query();
     call_user_func_array(array($query, $filterMethod), $arguments);
     $this->assertEquals($count, count($query->search($this->index)));
 }
Exemplo n.º 19
0
 function testQueryCloning()
 {
     $query = new Search_Query('Hello World');
     $clone = clone $query;
     $query->filterCategory('1 OR 2');
     $this->assertNotEquals($query, $clone);
 }
Exemplo n.º 20
0
function wikiplugin_customsearch($data, $params)
{
    global $prefs;
    static $instance_id = null;
    if (empty($params['wiki']) && empty($params['tpl'])) {
        return tra('Template is not specified');
    } elseif (!empty($params['wiki']) && !TikiLib::lib('tiki')->page_exists($params['wiki'])) {
        return tra('Template page not found');
    }
    if (isset($params['id'])) {
        $id = $params['id'];
    } else {
        if ($instance_id === null) {
            $instance_id = 0;
        } else {
            $instance_id++;
        }
        $id = (string) $instance_id;
    }
    if (isset($params['recalllastsearch']) && $params['recalllastsearch'] == 1 && (!isset($_REQUEST['forgetlastsearch']) || $_REQUEST['forgetlastsearch'] != 'y')) {
        $recalllastsearch = 1;
    } else {
        $recalllastsearch = 0;
    }
    $defaults = array();
    $plugininfo = wikiplugin_customsearch_info();
    foreach ($plugininfo['params'] as $key => $param) {
        $defaults["{$key}"] = $param['default'];
    }
    $params = array_merge($defaults, $params);
    if (!isset($_REQUEST["offset"])) {
        $offset = 0;
    } else {
        $offset = (int) $_REQUEST["offset"];
    }
    if (isset($_REQUEST['maxRecords'])) {
        $maxRecords = (int) $_REQUEST['maxRecords'];
    } elseif ($recalllastsearch && !empty($_SESSION["customsearch_{$id}"]['maxRecords'])) {
        $maxRecords = (int) $_SESSION["customsearch_{$id}"]['maxRecords'];
    } else {
        $maxRecords = (int) $prefs['maxRecords'];
        $maxDefault = true;
    }
    if (!empty($_REQUEST['sort_mode'])) {
        $sort_mode = $_REQUEST['sort_mode'];
    } elseif ($recalllastsearch && !empty($_SESSION["customsearch_{$id}"]['sort_mode'])) {
        $sort_mode = $_SESSION["customsearch_{$id}"]['sort_mode'];
    } else {
        $sort_mode = '';
    }
    $definitionKey = md5($data);
    $matches = WikiParser_PluginMatcher::match($data);
    $query = new Search_Query();
    if (!isset($params['searchable_only']) || $params['searchable_only'] == 1) {
        $query->filterIdentifier('y', 'searchable');
    }
    $builder = new Search_Query_WikiBuilder($query);
    $builder->apply($matches);
    $paginationArguments = $builder->getPaginationArguments();
    // Use maxRecords set in LIST parameters rather then global default if set.
    if (isset($maxDefault) && $maxDefault) {
        if (!empty($paginationArguments['max'])) {
            $maxRecords = $paginationArguments['max'];
        }
    }
    // setup AJAX pagination
    $paginationArguments['offset_jsvar'] = "customsearch_{$id}.offset";
    $paginationArguments['sort_jsvar'] = "customsearch_{$id}.sort_mode";
    $paginationArguments['_onclick'] = "\$('#customsearch_{$id}').submit();return false;";
    $builder = new Search_Formatter_Builder();
    $builder->setPaginationArguments($paginationArguments);
    $builder->apply($matches);
    $formatter = $builder->getFormatter();
    $facets = new Search_Query_FacetWikiBuilder();
    $facets->apply($matches);
    $cachelib = TikiLib::lib('cache');
    $cachelib->cacheItem($definitionKey, serialize(array('query' => $query, 'formatter' => $formatter, 'facets' => $facets)), 'customsearch');
    if (!empty($params['wiki'])) {
        $wikitpl = "tplwiki:" . $params['wiki'];
    } else {
        $wikitpl = $params['tpl'];
    }
    $wikicontent = TikiLib::lib('smarty')->fetch($wikitpl);
    TikiLib::lib('parser')->parse_wiki_argvariable($wikicontent);
    $matches = WikiParser_PluginMatcher::match($wikicontent);
    $fingerprint = md5($wikicontent);
    $sessionprint = "customsearch_{$id}_{$fingerprint}";
    if (isset($_SESSION[$sessionprint]) && $_SESSION[$sessionprint] != $fingerprint) {
        unset($_SESSION["customsearch_{$id}"]);
    }
    $_SESSION[$sessionprint] = $fingerprint;
    // important that offset from session is set after fingerprint check otherwise blank page might show
    if ($recalllastsearch && !isset($_REQUEST['offset']) && !empty($_SESSION["customsearch_{$id}"]["offset"])) {
        $offset = (int) $_SESSION["customsearch_{$id}"]["offset"];
    }
    $options = array('searchfadetext' => tr('Loading...'), 'searchfadediv' => $params['searchfadediv'], 'results' => empty($params['destdiv']) ? "#customsearch_{$id}_results" : "#{$params['destdiv']}", 'autosearchdelay' => isset($params['autosearchdelay']) ? max(1500, (int) $params['autosearchdelay']) : 0, 'searchonload' => (int) $params['searchonload'], 'requireinput' => (bool) $params['requireinput'], 'origrequireinput' => (bool) $params['requireinput'], 'forcesortmode' => (bool) $params['forcesortmode']);
    /**
     * NOTES: Search Execution
     *
     * There is a global delay on execution of 1 second. This makes sure
     * multiple submissions will never trigger multiple requests.
     *
     * There is an additional autosearchdelay configuration that can trigger the search
     * on field change rather than explicit request. Explicit requests will still work.
     */
    $script = "\nvar customsearch = {\n\toptions: " . json_encode($options) . ",\n\tid: " . json_encode($id) . ",\n\toffset: 0,\n\tsearchdata: {},\n\tdefinition: " . json_encode((string) $definitionKey) . ",\n\tautoTimeout: null,\n\tadd: function (fieldId, filter) {\n\t\tthis.searchdata[fieldId] = filter;\n\t\tthis.auto();\n\t},\n\tremove: function (fieldId) {\n\t\tdelete this.searchdata[fieldId];\n\t\tthis.auto();\n\t},\n\tload: function () {\n\t\tthis._executor(this);\n\t},\n\tauto: function () {\n\t},\n\t_executor: delayedExecutor(1000, function (cs) {\n\t\tvar selector = '#' + cs.options.searchfadediv;\n\t\tif (cs.options.searchfadediv.length <= 1 && \$(selector).length === 0) {\n\t\t\tselector = '#customsearch_' + cs.id;\n\t\t}\n\n\t\t\$(selector).tikiModal(cs.options.searchfadetext);\n\n\t\tcs._load(function (data) {\n\t\t\t\$(selector).tikiModal();\n\t\t\t\$(cs.options.results).html(data);\n\t\t\t\$(document).trigger('pageSearchReady');\n\t\t});\n\t\tcs.store_query = '';\n\t}),\n\tinit: function () {\n\t\tvar that = this;\n\t\tif (that.options.searchonload) {\n\t\t\tthat.load();\n\t\t}\n\n\t\tif (that.options.autosearchdelay) {\n\t\t\tthat.auto = delayedExecutor(that.options.autosearchdelay, function () {\n\t\t\t\tif (that.options.requireinput && (!\$('#customsearch_{$id}').find(':text').val() || \$('#customsearch_{$id}').find(':text').val().indexOf('...') > 0)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tthat.load();\n\t\t\t});\n\t\t}\n\t}\n};\n\$('#customsearch_{$id}').click(function() {\n\tcustomsearch.offset = 0;\n});\n\$('#customsearch_{$id}').submit(function() {\n\tif (customsearch.options.requireinput && (!\$(this).find(':text').val() || \$(this).find(':text').val().indexOf('...') > 0)) {\n\t\talert(tr('Please enter a search query'));\n\t\treturn false;\n\t}\n\tif (customsearch.options.origrequireinput != customsearch.options.requireinput) {\n\t\tcustomsearch.options.requireinput = customsearch.options.origrequireinput;\n\t}\n\tcustomsearch.load();\n\treturn false;\n});\n\nwindow.customsearch_{$id} = customsearch;\n\$(document).trigger('formSearchReady');\n";
    $parser = new WikiParser_PluginArgumentParser();
    $dr = 0;
    foreach ($matches as $match) {
        $name = $match->getName();
        $arguments = $parser->parse($match->getArguments());
        $key = $match->getInitialStart();
        $fieldid = "customsearch_{$id}_{$key}";
        if (isset($arguments['id'])) {
            $fieldid = $arguments['id'];
        }
        if ($name == 'sort' && !empty($arguments['mode']) && empty($sort_mode)) {
            $sort_mode = $arguments['mode'];
            $match->replaceWith('');
            continue;
        }
        if (!empty($arguments['_field']) && !empty($arguments['_filter']) && $arguments['_filter'] == 'content') {
            $filter = $arguments['_field'];
        } elseif (empty($arguments['_field']) && !empty($arguments['_filter']) && $arguments['_filter'] == 'content') {
            $filter = 'content';
        } else {
            $filter = '';
        }
        if ($filter && !empty($_REQUEST['default'][$filter])) {
            $default = $_REQUEST['default'][$filter];
        } elseif ($recalllastsearch && isset($_SESSION["customsearch_{$id}"][$fieldid])) {
            $default = $_SESSION["customsearch_{$id}"][$fieldid];
        } elseif (!empty($arguments['_default'])) {
            if (strpos($arguments['_default'], ',') !== false) {
                $default = explode(',', $arguments['_default']);
            } else {
                $default = $arguments['_default'];
            }
        } else {
            $default = '';
        }
        if ($name == 'categories') {
            $parent = $arguments['_parent'];
            if (!empty($_REQUEST['defaultcat'][$parent])) {
                $default = $_REQUEST['defaultcat'][$parent];
            }
        }
        $function = "cs_design_{$name}";
        if (function_exists($function)) {
            if (isset($arguments['_group'])) {
                $fieldname = "customsearch_{$id}_gr" . $arguments['_group'];
            } elseif (isset($arguments['_textrange'])) {
                $fieldname = "customsearch_{$id}_textrange" . $arguments['_textrange'];
            } elseif (isset($arguments['_daterange'])) {
                $fieldname = "customsearch_{$id}_daterange" . $arguments['_daterange'];
            } else {
                $fieldname = $fieldid;
            }
            $html = $function($id, $fieldname, $fieldid, $arguments, $default, $script);
            if ($params['trimlinefeeds']) {
                $html = trim($html);
            }
            $match->replaceWith($html);
        }
        if ($name == 'daterange') {
            $dr++;
        }
    }
    $callbackScript = null;
    if (!empty($params['callbackscript']) && TikiLib::lib('tiki')->page_exists($params['callbackscript'])) {
        $callbackscript_tpl = "wiki:" . $params['callbackscript'];
        $callbackScript = TikiLib::lib('smarty')->fetch($callbackscript_tpl);
    }
    //get iconset icon if daterange is one of the fields
    if ($dr) {
        $smarty = TikiLib::lib('smarty');
        $smarty->loadPlugin('smarty_function_js_insert_icon');
        $iconinsert = smarty_function_js_insert_icon(['type' => 'jscalendar', 'return' => 'y'], $smarty);
    } else {
        $iconinsert = '';
    }
    global $page;
    $script .= "\ncustomsearch._load = function (receive) {\n\tvar datamap = {\n\t\tdefinition: this.definition,\n\t\tadddata: \$.toJSON(this.searchdata),\n\t\tsearchid: this.id,\n\t\toffset: customsearch.offset,\n\t\tmaxRecords: this.maxRecords,\n\t\tstore_query: this.store_query,\n\t\tpage: " . json_encode($page) . ",\n\t\trecalllastsearch: {$recalllastsearch}\n\t};\n\tif (!customsearch.options.forcesortmode && \$('#customsearch_{$id}').find(':text').val() && \$('#customsearch_{$id}').find(':text').val().indexOf('...') <= 0) {\n\t\tcustomsearch.sort_mode = 'score_desc';\n\t}\n\tif (customsearch.sort_mode) {\n\t\t// blank sort_mode is not allowed by Tiki input filter\n\t\tdatamap.sort_mode = customsearch.sort_mode;\n\t}\n\t\$.ajax({\n\t\ttype: 'POST',\n\t\turl: \$.service('search_customsearch', 'customsearch'),\n\t\tdata: datamap,\n\t\tdataType: 'html',\n\t\tsuccess: function(data) {\n\t\t\treceive(data);\n\t\t\t{$callbackScript};\n\t\t},\n\t\terror: function ( jqXHR, textStatus, errorThrown ) {\n\t\t\tvar selector = '#' + customsearch.options.searchfadediv;\n\t\t\tif (customsearch.options.searchfadediv.length <= 1 && \$(selector).length === 0) {\n\t\t\t\tselector = '#customsearch_' + customsearch.id;\n\t\t\t}\n\t\t\t\$(selector).tikiModal();\n\n\t\t\t\$('#customsearch_{$id}').showError(jqXHR)\n\t\t}\n\t});\n};\ncustomsearch.sort_mode = " . json_encode($sort_mode) . ";\ncustomsearch.offset = {$offset};\ncustomsearch.maxRecords = {$maxRecords};\ncustomsearch.store_query ='';\ncustomsearch.init();\n{$iconinsert}";
    TikiLib::lib('header')->add_jq_onready($script);
    if ($params['customsearchjs']) {
        TikiLib::lib('header')->add_jsfile('lib/jquery_tiki/customsearch.js');
    }
    $out = '<div id="customsearch_' . $id . '_form"><form id="customsearch_' . $id . '">' . $matches->getText() . '</form></div>';
    if (empty($params['destdiv'])) {
        $out .= '<div id="customsearch_' . $id . '_results"></div>';
    }
    if (!empty($params['wiki'])) {
        return $out;
    } else {
        // If using smarty tpl should assume it's all HTML
        $out = str_replace('~np~', '', $out);
        $out = str_replace('~/np~', '', $out);
        return '~np~' . $out . '~/np~';
    }
}
Exemplo n.º 21
0
 function applySimilarConditions(\Search_Query $query, $type, $object)
 {
     $query->filterSimilar($type, $object, 'file');
 }
Exemplo n.º 22
0
 private function assertResultCount($count, $argument)
 {
     $query = new Search_Query();
     $query->filterContent($argument);
     $this->assertEquals($count, count($query->search($this->index)));
 }
Exemplo n.º 23
0
 function initQuery(Search_Query $query)
 {
     global $prefs;
     $query->setWeightCalculator($this->getWeightCalculator());
     $query->setIdentifierFields($prefs['unified_identifier_fields']);
     if (!Perms::get()->admin) {
         $query->filterPermissions(Perms::get()->getGroups());
     }
     $categlib = TikiLib::lib('categ');
     if ($jail = $categlib->get_jail()) {
         $query->filterCategory(implode(' or ', $jail), true);
     }
 }
Exemplo n.º 24
0
 function testHebrewString()
 {
     $query = new Search_Query();
     $query->filterContent('מחשב', 'hebrew');
     $this->assertEquals(1, count($query->search($this->index)));
 }
Exemplo n.º 25
0
 function testSubQueryCreatesOrStatement()
 {
     $index = new Search_Index_Memory();
     $query = new Search_Query();
     $query->getSubQuery('abc')->filterContent('hello');
     $query->getSubQuery('abc')->filterCategory('1 and 2');
     $query->filterPermissions(array('Registered'));
     $query->search($index);
     $expr = new Search_Expr_And(array(new Search_Expr_Or(array(new Search_Expr_Token('hello', 'plaintext', 'contents'), new Search_Expr_And(array(new Search_Expr_Token('1', 'multivalue', 'categories'), new Search_Expr_Token('2', 'multivalue', 'categories'))))), new Search_Expr_Or(array(new Search_Expr_Token('Registered', 'multivalue', 'allowed_groups')))));
     $this->assertEquals($expr, $index->getLastQuery());
     $this->assertEquals(array('hello'), $query->getTerms());
 }
Exemplo n.º 26
0
 function testMoreLikeThisThroughAbstraction()
 {
     $builder = new QueryBuilder();
     $builder->setDocumentReader(function ($type, $object) {
         return array('object_type' => $type, 'object_id' => $object, 'contents' => 'hello world');
     });
     $q = new Search_Query();
     $q->filterSimilar('wiki page', 'A');
     $query = $builder->build($q->getExpr());
     $this->assertEquals(array('bool' => array('must' => array(array('more_like_this' => array('fields' => array('contents'), 'like_text' => 'hello world', 'boost' => 1.0))), 'must_not' => array(array('bool' => array('must' => array(array("match" => array("object_type" => array("query" => "wiki page"))), array("match" => array("object_id" => array("query" => "A"))))))))), $query['query']);
 }
Exemplo n.º 27
0
 private function assertResultFound($word, $index, $count = 1)
 {
     $query = new Search_Query($word);
     $result = $query->search($index);
     $this->assertEquals($count, count($result));
 }
Exemplo n.º 28
0
 private function cs_dataappend_daterange(Search_Query $query, $config, $value)
 {
     if ($vals = preg_split('/,/', $value)) {
         if (count($vals) == 2) {
             $from = $vals[0];
             $to = $vals[1];
             if (!empty($config['_field'])) {
                 $field = $config['_field'];
             } else {
                 $field = 'modification_date';
             }
             $query->filterRange($from, $to, $field);
         }
     }
 }
Exemplo n.º 29
0
 function applySimilarConditions(\Search_Query $query, $type, $object)
 {
     $query->filterSimilar($type, $object);
     $this->applyRaw($query);
 }
Exemplo n.º 30
0
function wikiplugin_list($data, $params)
{
	$unifiedsearchlib = TikiLib::lib('unifiedsearch');

	$alternate = null;
	$output = null;
	$subPlugins = array();

	$query = new Search_Query;
	$query->setWeightCalculator($unifiedsearchlib->getWeightCalculator());

	if (isset($_REQUEST['maxRecords'])) {
		if (isset($_REQUEST['offset'])) {
			$query->setRange($_REQUEST['offset'], $_REQUEST['maxRecords']);
		} else {
			$query->setRange(0, $_REQUEST['maxRecords']);
		}
	} elseif (isset($_REQUEST['offset'])) {
		$query->setRange($_REQUEST['offset']);
	}

	$matches = WikiParser_PluginMatcher::match($data);
	$argumentParser = new WikiParser_PluginArgumentParser;

	$onclick = '';
	$offset_jsvar = '';

	foreach ($matches as $match) {
		$name = $match->getName();
		$arguments = $argumentParser->parse($match->getArguments());

		foreach ($arguments as $key => $value) {
			$function = "wpquery_{$name}_{$key}";

			if (function_exists($function)) {
				$function($query, $value, $arguments);
			}

			$function = "wpformat_{$name}_{$key}";

			if (function_exists($function)) {
				$function($subPlugins, $value, $match->getBody());
			}
		}

		if ($name == 'output') {
			$output = $match;
		}

		if ($name == 'alternate') {
			$alternate = $match->getBody();
		}

		if ($name == 'pagination' && isset($arguments['onclick'])) {
			$onclick = $arguments['onclick'];
		}
		if ($name == 'pagination' && isset($arguments['offset_jsvar'])) {
			$offset_jsvar = $arguments['offset_jsvar'];
		}
	}

	if (! Perms::get()->admin) {
		$query->filterPermissions(Perms::get()->getGroups());
	}

	if (!empty($_REQUEST['sort_mode'])) {
		$query->setOrder($_REQUEST['sort_mode']);
	}

	$index = $unifiedsearchlib->getIndex();

	$result = $query->search($index);

	if (count($result)) {
		if (!empty($output)) {
			$arguments = $argumentParser->parse($output->getArguments());

			if (isset($arguments['template'])) {
				if ($arguments['template'] == 'table') {
					$arguments['template'] = dirname(__FILE__) . '/../../templates/table.tpl';
				} else if (!file_exists($arguments['template'])) {
					TikiLib::lib('errorreport')->report(tr('Missing template "%0"', $arguments['template']));
					return '';
				}
				$builder = new Search_Formatter_ArrayBuilder;
				$templateData = $builder->getData($output->getBody());

				$plugin = new Search_Formatter_Plugin_SmartyTemplate($arguments['template']);
				$plugin->setData($templateData);
				$plugin->setFields(wp_list_findfields($templateData));
			} elseif (isset($arguments['wiki']) && TikiLib::lib('tiki')->page_exists($arguments['wiki'])) {	
				$wikitpl = "tplwiki:" . $arguments['wiki'];
				$wikicontent = TikiLib::lib('smarty')->fetch($wikitpl);
				$plugin = new Search_Formatter_Plugin_WikiTemplate($wikicontent);
			} else {
				$plugin = new Search_Formatter_Plugin_WikiTemplate($output->getBody());
			}

			if (isset($arguments['pagination'])) {
				$plugin = new WikiPlugin_List_AppendPagination($plugin, $onclick, $offset_jsvar);
			}
		} else {
			$plugin = new Search_Formatter_Plugin_WikiTemplate("* {display name=title format=objectlink}\n");
		}

		$formatter = new Search_Formatter($plugin);
		$formatter->setDataSource($unifiedsearchlib->getDataSource());

		foreach ($subPlugins as $key => $plugin) {
			$formatter->addSubFormatter($key, $plugin);
		}

		$out = $formatter->format($result);
	} elseif (!empty($alternate)) {
		$out = $alternate;
	} else {
		$out = '^' . tra('No results for query.') . '^';
	}

	return $out;
}