xref: /plugin/sphinxsearch-was/action.php (revision 80:48c7f4fb9fb6)
1<?php
2/**
3 * Script to search in dokuwiki documents
4 *
5 * @author Yaroslav Vorozhko <yaroslav@ivinco.com>
6 */
7
8if(!defined('DOKU_INC')) die();
9if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
10
11require_once(DOKU_INC.'inc/parser/parser.php');
12
13require_once(DOKU_PLUGIN . 'action.php');
14require_once(DOKU_PLUGIN . 'sphinxsearch/sphinxapi.php');
15require_once(DOKU_PLUGIN . 'sphinxsearch/PageMapper.php');
16require_once(DOKU_PLUGIN . 'sphinxsearch/SphinxSearch.php');
17require_once(DOKU_PLUGIN . 'sphinxsearch/functions.php');
18
19
20class action_plugin_sphinxsearch extends DokuWiki_Action_Plugin {
21    var $_search = null;
22
23    /**
24	* return some info
25	*/
26    function getInfo() {
27        return confToHash(dirname(__FILE__).'/plugin.info.txt');
28	}
29
30    /**
31	* Register to the content display event to place the results under it.
32	*/
33    /**
34     * register the eventhandlers
35     */
36    function register(&$controller){
37        $controller->register_hook('TPL_CONTENT_DISPLAY',   'BEFORE', $this, 'handle_act_unknown', array());
38    }
39
40    /**
41     * If our own 'googlesearch' action was given we produce our content here
42     */
43    function handle_act_unknown(&$event, $param){
44        global $ACT;
45        global $QUERY;
46        if($ACT != 'search') return; // nothing to do for us
47
48        // we can handle it -> prevent others
49        $event->stopPropagation();
50        $event->preventDefault();
51
52
53        $this->_search($QUERY,$_REQUEST['start'],$_REQUEST['prev']);
54    }
55
56    /**
57     * do the search and displays the result
58     */
59    function _search($query, $start, $prev) {
60        global $conf;
61
62        $start = (int) $start;
63        if($start < 0){
64            $start = 0;
65        }
66        if(empty($prev)){
67            $prev = 0;
68        }
69
70        $categories = $this->_getCategories($query);
71        $keywords = $this->_getKeywords($query);
72
73        $search = new SphinxSearch($this->getConf('host'), $this->getConf('port'), $this->getConf('index'));
74        $search->setSnippetSize($this->getConf('snippetsize'));
75        $search->setArroundWordsCount($this->getConf('aroundwords'));
76        $search->setTitlePriority($this->getConf('title_priority'));
77        $search->setBodyPriority($this->getConf('body_priority'));
78        $search->setNamespacePriority($this->getConf('namespace_priority'));
79        $search->setPagenamePriority($this->getConf('pagename_priority'));
80
81        if (!empty($keywords) && empty($categories)){
82            $search->setSearchAllQuery($keywords, $categories);
83        } elseif (!empty($keywords)) {
84            $search->setSearchAllQueryWithCategoryFilter($keywords, $categories);
85        } else {
86            echo 'Your search - <strong>' . $query . '</strong> - did not match any documents.';
87            return;
88        }
89        $result = $search->search($start, $this->getConf('maxresults'));
90        $this->_search = $search;
91
92        if (!$result || $search->getError()){
93            echo 'Your search - <strong>' . $query . '</strong> - did not match any documents.';
94            return;
95        }
96
97        $pagesList = $search->getPages($keywords);
98
99        $totalFound = $search->getTotalFound();
100        if(empty($pagesList) || 0 == $totalFound){
101            echo 'Your search - <strong>' . $query . '</strong> - did not match any documents.';
102            return;
103        } else {
104            echo '<style type="text/css">
105                div.dokuwiki .search{
106                    width:1024px;
107                }
108                div.dokuwiki .search_snippet{
109                    color:#000000;
110                    margin-left:0px;
111                    font-size: 13px;
112                }
113                div.dokuwiki .search_result{
114                    width:600px;
115                    float:left;
116                }
117                div.dokuwiki .search_result a.title{
118                    font:16px Arial,Helvetica,sans-serif;
119                }
120                div.dokuwiki .search_result span{
121                    font:12px Arial,Helvetica,sans-serif;
122                }
123                div.dokuwiki .search_sidebar{
124                    width:300px;
125                    float:right;
126                    margin-right: 30px;
127                }
128                div.dokuwiki .search_result_row{
129                    color:#000000;
130                    margin-left:0px;
131                    width:600px;
132                    text-align:left;
133                }
134                div.dokuwiki .search_result_row_child{
135                    color:#000000;
136                    margin-left:30px;
137                    width:600px;
138                    text-align:left;
139                }
140                div.dokuwiki .hide{
141                    display:none;
142                }
143                div.dokuwiki .search_cnt{
144                    color:#909090;
145                    font:12px Arial,Helvetica,sans-serif;
146                }
147                div.dokuwiki .search_nmsp{
148                    font-size: 10px;
149                }
150                div.dokuwiki .sphinxsearch_nav{
151                    clear:both;
152                }
153                </style>
154                <script type="text/javascript">
155function sh(id)
156{
157    var e = document.getElementById(id);
158    if(e.style.display == "block")
159        e.style.display = "none";
160    else
161        e.style.display = "block";
162}
163</script>
164';
165
166            echo '<h2>Found '.$totalFound . ($totalFound == 1  ? ' match ' : ' matches ') . ' for query "' . hsc($query).'"</h2>';
167            echo '<div class="search">';
168            echo '<div class="search_result">';
169            // printout the results
170            $pageListGroupByPage = array();
171            foreach ($pagesList as $row) {
172                $page = $row['page'];
173                if(!isset ($pageListGroupByPage[$page])){
174                    $pageListGroupByPage[$page] = $row;
175                } else {
176                    $pageListGroupByPage[$page]['subpages'][] = $row;
177                }
178            }
179            foreach ($pageListGroupByPage as $row) {
180                $this->_showResult($row, $keywords, false);
181                if(!empty($row['subpages'])){
182                    echo '<div id="more'.$row['page'].'" class="hide">';
183                    foreach($row['subpages'] as $sub){
184                        $this->_showResult($sub, $keywords, true);
185                    }
186                    echo '</div>';
187                }
188
189            }
190            echo '</div>';
191            echo '<div class="search_sidebar">';
192            printNamespacesNew($this->_getMatchingPagenames($keywords, $categories));
193            echo '</div>';
194            echo '<div class="sphinxsearch_nav">';
195            if ($start > 1){
196                if(false !== strpos($prev, ',')){
197                    $prevArry = explode(",", $prev);
198                    $prevNum = $prevArry[count($prevArry)-1];
199                    unset($prevArry[count($prevArry)-1]);
200                    $prevString = implode(",", $prevArry);
201                } else {
202                    $prevNum = 0;
203                }
204
205                echo $this->external_link(wl('',array('do'=>'search','id'=>$query,'start'=>$prevNum, 'prev'=>$prevString),'false','&'),
206                                          'prev','wikilink1 gs_prev',$conf['target']['interwiki']);
207            }
208            echo ' ';
209
210            //if($start + $this->getConf('maxresults') < $totalFound){
211                //$next = $start + $this->getConf('maxresults');
212            if($start + $search->getOffset()< $totalFound){
213                $next = $start + $search->getOffset();
214                if($start > 1){
215                    $prevString = $prev.','.$start;
216                }
217                echo $this->external_link(wl('',array('do'=>'search','id'=>$query,'start'=>$next,'prev'=>$prevString),'false','&'),
218                                          'next','wikilink1 gs_next',$conf['target']['interwiki']);
219            }
220            echo '</div>';
221
222            echo '</div>';
223        }
224
225
226    }
227
228    function _showResult($row, $keywords, $subpages = false)
229    {
230        $page = $row['page'];
231        $bodyExcerpt = $row['bodyExcerpt'];
232        $titleTextExcerpt = $row['titleTextExcerpt'];
233        $hid = $row['hid'];
234
235        $metaData = p_get_metadata($page);
236
237        if (!empty($titleTextExcerpt)){
238            $titleText = $titleTextExcerpt;
239        } elseif(!empty($row['title_text'])){
240            $titleText = $row['title_text'];
241        } elseif(!empty($metaData['title'])){
242            $titleText = hsc($metaData['title']);
243        } else {
244            $titleText = hsc($page);
245        }
246
247        $namespaces = getNsLinks($page, $keywords, $this->_search);
248        $href = !empty($hid) ? (wl($page).'#'.$hid) : wl($page);
249
250        if($subpages){
251            echo '<div class="search_result_row_child">';
252        } else {
253            echo '<div class="search_result_row">';
254        }
255
256        echo '<a class="wikilink1 title" href="'.$href.'" title="" >'.$titleText.'</a><br/>';
257        echo '<div class="search_snippet">';
258        echo strip_tags($bodyExcerpt, '<b>,<strong>');
259        echo '</div>';
260        $sep=':';
261        $i = 0;
262        echo '<span class="search_nmsp">';
263        foreach ($namespaces as $name){
264            $link = $name['link'];
265            $pageTitle = $name['title'];
266            tpl_link($link, $pageTitle);
267            if ($i++ < count($namespaces)-1){
268                echo $sep;
269            }
270        }
271        if (!empty($hid)){
272            echo '#'.$hid;
273        }
274        echo '</span>';
275
276        if (!empty($metaData['last_change']['date'])){
277            echo '<span class="search_cnt"> - Last modified '.date("Y-m-d H:i",$metaData['last_change']['date']).'</span> ';
278        } else if (!empty($metaData['date']['created'])){
279            echo '<span class="search_cnt"> - Last modified '.date("Y-m-d H:i",$metaData['date']['created']).'</span> ';
280        }
281
282        if(!empty($metaData['last_change']['user'])){
283            echo '<span class="search_cnt">by '.$metaData['last_change']['user'].'</span> ';
284        } else if(!empty($metaData['creator'])){
285            echo '<span class="search_cnt">by '.$metaData['creator'].'</span> ';
286        }
287
288        if (!empty($row['subpages'])){
289            echo '<br />';
290            echo '<div style="text-align:right;font:12px Arial,Helvetica,sans-serif;text-decoration:underline;"><a href="javascript:void(0)" onClick="sh('."'more".$page."'".');" >More matches in this document</a></div>';
291        }else {
292            echo '<br />';
293        }
294        echo '<br />';
295        echo '</div>';
296    }
297
298     function searchform(){
299          global $lang;
300          global $ACT;
301          global $QUERY;
302
303          // don't print the search form if search action has been disabled
304          if (!actionOk('search')) return false;
305
306          print '<form action="'.wl().'" accept-charset="utf-8" class="search" id="dw__search"><div class="no">';
307          print '<input type="hidden" name="do" value="search" />';
308          print '<input type="text" ';
309          if($ACT == 'search') print 'value="'.htmlspecialchars($QUERY).'" ';
310          print 'id="qsearch__in" accesskey="f" name="id" class="edit" title="[ALT+F]" />';
311          print '<input type="submit" value="'.$lang['btn_search'].'" class="button" title="'.$lang['btn_search'].'" />';
312          print '</div></form>';
313          return true;
314    }
315
316    function _getCategories($query)
317    {
318        $categories = '';
319        $query = urldecode($query);
320        if (false !== ($pos = strpos($query, "@cat"))){;
321            $categories = substr($query, $pos + strlen("@cat"));
322        }
323        return trim($categories);
324    }
325
326    function _getKeywords($query)
327    {
328        $keywords = $query;
329        $query = urldecode($query);
330        if (false !== ($pos = strpos($query, "-@cat"))){;
331            $keywords = substr($keywords, 0, $pos);
332        }else if (false !== ($pos = strpos($query, "@cat"))){;
333            $keywords = substr($keywords, 0, $pos);
334        }
335        return trim($keywords);
336    }
337
338    function _getMatchingPagenames($keywords, $categories)
339    {
340        $this->_search->setSearchCategoryQuery($keywords, $categories);
341        $this->_search->setNamespacePriority($this->getConf('mp_namespace_priority'));
342        $this->_search->setPagenamePriority($this->getConf('mp_pagename_priority'));
343
344        $res = $this->_search->search(0, 10);
345        if (!$res){
346            return false;
347        }
348        $pageIds = $this->_search->getPagesIds();
349
350        $matchPages = array();
351        foreach($pageIds as $page){
352            $matchPages[$page['page']] = $page['hid'];
353        }
354        return array_unique($matchPages);
355    }
356}
357
358?>
359