Beispiel #1
0
function wikiplugin_list($data, $params)
{
    $unifiedsearchlib = TikiLib::lib('unifiedsearch');
    $query = new Search_Query();
    $unifiedsearchlib->initQuery($query);
    $matches = WikiParser_PluginMatcher::match($data);
    $builder = new Search_Query_WikiBuilder($query);
    $builder->enableAggregate();
    $builder->apply($matches);
    if (!empty($_REQUEST['sort_mode'])) {
        $query->setOrder($_REQUEST['sort_mode']);
    }
    if (!($index = $unifiedsearchlib->getIndex())) {
        return '';
    }
    $result = $query->search($index);
    $paginationArguments = $builder->getPaginationArguments();
    $resultBuilder = new Search_ResultSet_WikiBuilder($result);
    $resultBuilder->setPaginationArguments($paginationArguments);
    $resultBuilder->apply($matches);
    $builder = new Search_Formatter_Builder();
    $builder->setPaginationArguments($paginationArguments);
    $builder->apply($matches);
    $formatter = $builder->getFormatter();
    $formatter->setDataSource($unifiedsearchlib->getDataSource());
    $out = $formatter->format($result);
    return $out;
}
 function action_list($input)
 {
     global $prefs;
     $unifiedsearchlib = TikiLib::lib('unifiedsearch');
     $index = $unifiedsearchlib->getIndex();
     $dataSource = $unifiedsearchlib->getDataSource();
     $start = 'tracker_field_' . $input->beginField->word();
     $end = 'tracker_field_' . $input->endField->word();
     if ($resource = $input->resourceField->word()) {
         $resource = 'tracker_field_' . $resource;
     }
     if ($coloring = $input->coloringField->word()) {
         $coloring = 'tracker_field_' . $coloring;
     }
     $query = $unifiedsearchlib->buildQuery(array());
     $query->filterRange($input->start->int(), $input->end->int(), array($start, $end));
     $query->setRange(0, $prefs['unified_lucene_max_result']);
     if ($body = $input->filters->none()) {
         $builder = new Search_Query_WikiBuilder($query);
         $builder->apply(WikiParser_PluginMatcher::match($body));
     }
     $result = $query->search($index);
     $result = $dataSource->getInformation($result, array('title', $start, $end));
     $response = array();
     $smarty = TikiLib::lib('smarty');
     $smarty->loadPlugin('smarty_modifier_sefurl');
     foreach ($result as $row) {
         $item = Tracker_Item::fromId($row['object_id']);
         $response[] = array('id' => $row['object_id'], 'trackerId' => isset($row['tracker_id']) ? $row['tracker_id'] : null, 'title' => $row['title'], 'description' => '', 'url' => smarty_modifier_sefurl($row['object_id'], $row['object_type']), 'allDay' => false, 'start' => (int) $row[$start], 'end' => (int) $row[$end], 'editable' => $item->canModify(), 'color' => $this->getColor(isset($row[$coloring]) ? $row[$coloring] : ''), 'textColor' => '#000', 'resource' => $resource && isset($row[$resource]) ? $row[$resource] : '');
     }
     return $response;
 }
function wikiplugin_listexecute($data, $params)
{
    $unifiedsearchlib = TikiLib::lib('unifiedsearch');
    $actions = array();
    $factory = new Search_Action_Factory();
    $factory->register(array('change_status' => 'Search_Action_ChangeStatusAction', 'delete' => 'Search_Action_Delete', 'email' => 'Search_Action_EmailAction', 'wiki_approval' => 'Search_Action_WikiApprovalAction', 'tracker_item_modify' => 'Search_Action_TrackerItemModify'));
    $query = new Search_Query();
    $unifiedsearchlib->initQuery($query);
    $matches = WikiParser_PluginMatcher::match($data);
    $builder = new Search_Query_WikiBuilder($query);
    $builder->apply($matches);
    foreach ($matches as $match) {
        $name = $match->getName();
        if ($name == 'action') {
            $action = $factory->fromMatch($match);
            if ($action && $action->isAllowed(Perms::get()->getGroups())) {
                $actions[$action->getName()] = $action;
            }
        }
    }
    if (!empty($_REQUEST['sort_mode'])) {
        $query->setOrder($_REQUEST['sort_mode']);
    }
    $index = $unifiedsearchlib->getIndex();
    $result = $query->search($index);
    $plugin = new Search_Formatter_Plugin_SmartyTemplate('templates/wiki-plugins/wikiplugin_listexecute.tpl');
    $paginationArguments = $builder->getPaginationArguments();
    $dataSource = $unifiedsearchlib->getDataSource();
    $builder = new Search_Formatter_Builder();
    $builder->setPaginationArguments($paginationArguments);
    $builder->apply($matches);
    $builder->setFormatterPlugin($plugin);
    $formatter = $builder->getFormatter();
    $reportSource = new Search_Action_ReportingTransform();
    if (isset($_POST['list_action'], $_POST['objects'])) {
        $action = $_POST['list_action'];
        $objects = (array) $_POST['objects'];
        if (isset($actions[$action])) {
            $tx = TikiDb::get()->begin();
            $action = $actions[$action];
            $plugin->setFields(array_fill_keys($action->getFields(), null));
            $list = $formatter->getPopulatedList($result);
            foreach ($list as $entry) {
                $identifier = "{$entry['object_type']}:{$entry['object_id']}";
                if (in_array($identifier, $objects) || in_array('ALL', $objects)) {
                    $success = $action->execute($entry);
                    $reportSource->setStatus($entry['object_type'], $entry['object_id'], $success);
                }
            }
            $tx->commit();
        }
    }
    $plugin = new Search_Formatter_Plugin_SmartyTemplate('templates/wiki-plugins/wikiplugin_listexecute.tpl');
    $plugin->setFields(array('report_status' => null));
    $plugin->setData(array('actions' => array_keys($actions)));
    $formatter = new Search_Formatter($plugin);
    $result->applyTransform($reportSource);
    return $formatter->format($result);
}
 function action_list($input)
 {
     global $prefs;
     $unifiedsearchlib = TikiLib::lib('unifiedsearch');
     $index = $unifiedsearchlib->getIndex();
     $dataSource = $unifiedsearchlib->getDataSource();
     $start = 'tracker_field_' . $input->beginField->word();
     $end = 'tracker_field_' . $input->endField->word();
     if ($resource = $input->resourceField->word()) {
         $resource = 'tracker_field_' . $resource;
     }
     if ($coloring = $input->coloringField->word()) {
         $coloring = 'tracker_field_' . $coloring;
     }
     $query = $unifiedsearchlib->buildQuery(array());
     $query->filterRange($input->start->int(), $input->end->int(), array($start, $end));
     $query->setRange(0, $prefs['unified_lucene_max_result']);
     if ($body = $input->filters->none()) {
         $builder = new Search_Query_WikiBuilder($query);
         $builder->apply(WikiParser_PluginMatcher::match($body));
     }
     $result = $query->search($index);
     $result = $dataSource->getInformation($result, array('title', $start, $end));
     $response = array();
     $fields = array();
     if ($definition = Tracker_Definition::get($input->trackerId->int())) {
         foreach ($definition->getPopupFields() as $fieldId) {
             if ($field = $definition->getField($fieldId)) {
                 $fields[] = $field;
             }
         }
     }
     $smarty = TikiLib::lib('smarty');
     $smarty->loadPlugin('smarty_modifier_sefurl');
     $trklib = TikiLib::lib('trk');
     foreach ($result as $row) {
         $item = Tracker_Item::fromId($row['object_id']);
         $description = '';
         foreach ($fields as $field) {
             if ($item->canViewField($field['fieldId'])) {
                 $val = trim($trklib->field_render_value(array('field' => $field, 'item' => $item->getData(), 'process' => 'y')));
                 if ($val) {
                     if (count($fields) > 1) {
                         $description .= "<h5>{$field['name']}</h5>";
                     }
                     $description .= $val;
                 }
             }
         }
         $response[] = array('id' => $row['object_id'], 'trackerId' => isset($row['tracker_id']) ? $row['tracker_id'] : null, 'title' => $row['title'], 'description' => $description, 'url' => smarty_modifier_sefurl($row['object_id'], $row['object_type']), 'allDay' => false, 'start' => $this->getTimestamp($row[$start]), 'end' => $this->getTimestamp($row[$end]), 'editable' => $item->canModify(), 'color' => $this->getColor(isset($row[$coloring]) ? $row[$coloring] : ''), 'textColor' => '#000', 'resource' => $resource && isset($row[$resource]) ? strtolower($row[$resource]) : '');
     }
     return $response;
 }
Beispiel #5
0
function wikiplugin_list($data, $params)
{
    global $prefs;
    static $i;
    $i++;
    $unifiedsearchlib = TikiLib::lib('unifiedsearch');
    $query = new Search_Query();
    if (!isset($params['searchable_only']) || $params['searchable_only'] == 1) {
        $query->filterIdentifier('y', 'searchable');
    }
    $unifiedsearchlib->initQuery($query);
    $matches = WikiParser_PluginMatcher::match($data);
    $tsret = applyTablesorter($matches, $query);
    $builder = new Search_Query_WikiBuilder($query);
    $builder->enableAggregate();
    if (!empty($tsret['max']) || !empty($_GET['numrows'])) {
        $max = !empty($_GET['numrows']) ? $_GET['numrows'] : $tsret['max'];
        $builder->wpquery_pagination_max($query, $max);
    }
    $builder->apply($matches);
    $paginationArguments = $builder->getPaginationArguments();
    if (!empty($_REQUEST[$paginationArguments['sort_arg']])) {
        $query->setOrder($_REQUEST[$paginationArguments['sort_arg']]);
    }
    if (!($index = $unifiedsearchlib->getIndex())) {
        return '';
    }
    $result = $query->search($index);
    $result->setId('wplist-' . $i);
    $resultBuilder = new Search_ResultSet_WikiBuilder($result);
    $resultBuilder->setPaginationArguments($paginationArguments);
    $resultBuilder->apply($matches);
    $builder = new Search_Formatter_Builder();
    $builder->setPaginationArguments($paginationArguments);
    $builder->setId('wplist-' . $i);
    $builder->setCount($result->count());
    $builder->setTsOn($tsret['tsOn']);
    $builder->apply($matches);
    $result->setTsSettings($builder->getTsSettings());
    $formatter = $builder->getFormatter();
    $result->setTsOn($tsret['tsOn']);
    $out = $formatter->format($result);
    return $out;
}
Beispiel #6
0
 function evaluate($element)
 {
     $allowed = ['filter'];
     if ($extra = $element->getExtraValues($allowed)) {
         $this->error(tr('Unexpected values: %0', implode(', ', $extra)));
     }
     $searchlib = TikiLib::lib('unifiedsearch');
     $query = new Search_Query();
     // These are absolute counts, so exclude jail and permission checks
     $searchlib->initQueryBase($query, false);
     $builder = new Search_Query_WikiBuilder($query);
     foreach ($element as $topLevel) {
         $arguments = $this->readMap($topLevel);
         $builder->addQueryArgument($topLevel->getType(), $arguments);
     }
     $query->setRange(0, 1);
     $result = $query->search($searchlib->getIndex());
     return count($result);
 }
Beispiel #7
0
 function action_render(JitFilter $request)
 {
     $encoded = $request->stream->none();
     $page = $request->page->int() ?: 1;
     if (!($baseQuery = Tiki_Security::get()->decode($encoded))) {
         throw new Services_Exception_Denied('Invalid request performed.');
     }
     $query = new Search_Query();
     $this->lib->initQuery($query);
     $query->filterType('activity');
     $matches = WikiParser_PluginMatcher::match($baseQuery['body']);
     $builder = new Search_Query_WikiBuilder($query);
     $builder->enableAggregate();
     $builder->apply($matches);
     if ($builder->isNextPossible()) {
         $query->setPage($page);
     }
     $query->setOrder('modification_date_desc');
     if (!($index = $this->lib->getIndex())) {
         throw new Services_Exception_NotAvailable(tr('Activity stream currently unavailable.'));
     }
     $result = $query->search($index);
     $paginationArguments = $builder->getPaginationArguments();
     $resultBuilder = new Search_ResultSet_WikiBuilder($result);
     $resultBuilder->setPaginationArguments($paginationArguments);
     $resultBuilder->apply($matches);
     try {
         $plugin = new Search_Formatter_Plugin_SmartyTemplate('templates/activity/activitystream.tpl');
         $plugin->setFields(array('like_list' => true, 'user_groups' => true, 'contributors' => true));
         $formatter = new Search_Formatter($plugin);
         $formatter->setDataSource($this->lib->getDataSource());
         $out = $formatter->format($result);
     } catch (SmartyException $e) {
         throw new Services_Exception_NotAvailable($e->getMessage());
     }
     return array('autoScroll' => $request->autoscroll->int(), 'pageNumber' => $page, 'nextPossible' => $builder->isNextPossible(), 'stream' => $encoded, 'body' => TikiLib::lib('parser')->parse_data($out, array('is_html' => true)));
 }
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~';
    }
}
function wikiplugin_customsearch($data, $params)
{
    global $prefs;
    if (!isset($params['wiki'])) {
        return tra('Template is not specified');
    } elseif (!TikiLib::lib('tiki')->page_exists($params['wiki'])) {
        return tra('Template page not found');
    }
    if (isset($params['id'])) {
        $id = $params['id'];
    } else {
        $id = '0';
    }
    if (isset($params['recalllastsearch']) && $params['recalllastsearch'] == 1 && (!isset($_REQUEST['forgetlastsearch']) || $_REQUEST['forgetlastsearch'] != 'y')) {
        $recalllastsearch = 1;
    } else {
        $recalllastsearch = 0;
    }
    if (isset($params['searchfadediv'])) {
        $searchfadediv = $params['searchfadediv'];
    } else {
        $searchfadediv = '';
    }
    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'];
    }
    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 = '';
    }
    if (!isset($params['searchonload'])) {
        $params['searchonload'] = 1;
    }
    $definitionKey = md5($data);
    $matches = WikiParser_PluginMatcher::match($data);
    $query = new Search_Query();
    $builder = new Search_Query_WikiBuilder($query);
    $builder->apply($matches);
    $builder = new Search_Formatter_Builder();
    $builder->apply($matches);
    $formatter = $builder->getFormatter();
    $cachelib = TikiLib::lib('cache');
    $cachelib->cacheItem($definitionKey, serialize(array('query' => $query, 'formatter' => $formatter)), 'customsearch');
    $wikitpl = "tplwiki:" . $params['wiki'];
    $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' => $searchfadediv, 'results' => empty($params['destdiv']) ? "#customsearch_{$id}_results" : "#{$params['destdiv']}", 'autosearchdelay' => isset($params['autosearchdelay']) ? max(1500, (int) $params['autosearchdelay']) : 0, 'searchonload' => (int) $params['searchonload']);
    /**
     * 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).modal(cs.options.searchfadetext);\n\n\t\tcs._load(function (data) {\n\t\t\t\$(selector).modal();\n\t\t\t\$(cs.options.results).html(data);\n\t\t\t\$(document).trigger('pageSearchReady');\n\t\t});\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\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\tcustomsearch.load();\n\treturn false;\n});\n\ncustomsearch_{$id} = customsearch;\n";
    $parser = new WikiParser_PluginArgumentParser();
    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']) && $arguments['_filter'] == 'content') {
            $filter = $arguments['_field'];
        } elseif (!empty($arguments['_field']) && $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;
            }
            $match->replaceWith($function($id, $fieldname, $fieldid, $arguments, $default, $script));
        }
    }
    $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);
    }
    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\tpage: " . json_encode($page) . ",\n\t\trecalllastsearch: {$recalllastsearch}\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});\n};\ncustomsearch.sort_mode = " . json_encode($sort_mode) . ";\ncustomsearch.offset = {$offset};\ncustomsearch.maxRecords = {$maxRecords};\ncustomsearch.init();\n";
    TikiLib::lib('header')->add_jq_onready($script);
    $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>';
    }
    return $out;
}