1<?php
2/**
3 * DokuWiki Plugin searchform (Action Component)
4 *
5 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
6 * @author  Gerrit Uitslag <klapinklapin@gmail.com>
7 */
8
9use dokuwiki\Extension\ActionPlugin;
10use dokuwiki\Extension\Event;
11use dokuwiki\Extension\EventHandler;
12
13/**
14 * Class action_plugin_searchform
15 */
16class action_plugin_searchform extends ActionPlugin {
17
18    /**
19     * Registers a callback function for a given event
20     *
21     * @param EventHandler $controller DokuWiki's event controller object
22     * @return void
23     */
24    public function register(EventHandler $controller) {
25        $controller->register_hook('DOKUWIKI_STARTED', 'AFTER',  $this, 'changeQuery');
26    }
27
28    /**
29     * Restrict the global query to namespace given as url parameter
30     *
31     * @param Event $event event object by reference
32     * @param mixed $param [the parameters passed as fifth argument to register_hook() when this
33     *                     handler was registered]
34     * @return void
35     */
36    public function changeQuery(Event $event, $param) {
37        global $QUERY;
38        global $ACT;
39
40        if($ACT != 'search'){
41            return;
42        }
43        $this->addNamespaceToQuery($QUERY);
44    }
45
46    /**
47     * Extend query string with namespace, if it doesn't contain a namespace expression
48     *
49     * @param string &$query (reference) search query string
50     */
51    private function addNamespaceToQuery(&$query) {
52        global $INPUT;
53
54        $ns = cleanID($INPUT->str('ns'));
55        if($ns) {
56            //add namespace if user hasn't already provide one
57            if(!preg_match('/(?:^| )(?:\^|@|-ns:|ns:)[\w:]+/u', $query, $matches)) {
58                $query .= ' @' . $ns;
59            }
60        }
61        $notns = cleanID($INPUT->str('-ns'));
62        if($notns) {
63            //add namespace if user hasn't already provide one
64            if(!preg_match('/(?:^| )(?:\^|@|-ns:|ns:)[\w:]+/u', $query, $matches)) {
65                $query .= ' ^' . $notns;
66            }
67        }
68    }
69
70}
71