xref: /dokuwiki/inc/search.php (revision 16905344219a6293705b71cd526fad3ba07b04eb)
1<?php
2/**
3 * DokuWiki search functions
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Andreas Gohr <andi@splitbrain.org>
7 */
8
9if(!defined('DOKU_INC')) die('meh.');
10
11/**
12 * recurse direcory
13 *
14 * This function recurses into a given base directory
15 * and calls the supplied function for each file and directory
16 *
17 * @param   array ref $data The results of the search are stored here
18 * @param   string    $base Where to start the search
19 * @param   callback  $func Callback (function name or arayy with object,method)
20 * @param   string    $dir  Current directory beyond $base
21 * @param   int       $lvl  Recursion Level
22 * @author  Andreas Gohr <andi@splitbrain.org>
23 */
24function search(&$data,$base,$func,$opts,$dir='',$lvl=1){
25    $dirs   = array();
26    $files  = array();
27
28    //read in directories and files
29    $dh = @opendir($base.'/'.$dir);
30    if(!$dh) return;
31    while(($file = readdir($dh)) !== false){
32        if(preg_match('/^[\._]/',$file)) continue; //skip hidden files and upper dirs
33        if(is_dir($base.'/'.$dir.'/'.$file)){
34            $dirs[] = $dir.'/'.$file;
35            continue;
36        }
37        $files[] = $dir.'/'.$file;
38    }
39    closedir($dh);
40    sort($files);
41    sort($dirs);
42
43    //give directories to userfunction then recurse
44    foreach($dirs as $dir){
45        if (call_user_func_array($func, array(&$data,$base,$dir,'d',$lvl,$opts))){
46            search($data,$base,$func,$opts,$dir,$lvl+1);
47        }
48    }
49    //now handle the files
50    foreach($files as $file){
51        call_user_func_array($func, array(&$data,$base,$file,'f',$lvl,$opts));
52    }
53}
54
55/**
56 * Wrapper around call_user_func_array.
57 *
58 * @deprecated
59 */
60function search_callback($func,&$data,$base,$file,$type,$lvl,$opts){
61    return call_user_func_array($func, array(&$data,$base,$file,$type,$lvl,$opts));
62}
63
64/**
65 * The following functions are userfunctions to use with the search
66 * function above. This function is called for every found file or
67 * directory. When a directory is given to the function it has to
68 * decide if this directory should be traversed (true) or not (false)
69 * The function has to accept the following parameters:
70 *
71 * &$data - Reference to the result data structure
72 * $base  - Base usually $conf['datadir']
73 * $file  - current file or directory relative to $base
74 * $type  - Type either 'd' for directory or 'f' for file
75 * $lvl   - Current recursion depht
76 * $opts  - option array as given to search()
77 *
78 * return values for files are ignored
79 *
80 * All functions should check the ACL for document READ rights
81 * namespaces (directories) are NOT checked as this would break
82 * the recursion (You can have an nonreadable dir over a readable
83 * one deeper nested) also make sure to check the file type (for example
84 * in case of lockfiles).
85 */
86
87/**
88 * Searches for pages beginning with the given query
89 *
90 * @author Andreas Gohr <andi@splitbrain.org>
91 */
92function search_qsearch(&$data,$base,$file,$type,$lvl,$opts){
93    $opts = array(
94            'idmatch'   => '(^|:)'.preg_quote($opts['query'],'/').'/',
95            'listfiles' => true,
96            'pagesonly' => true,
97            );
98    return search_universal($data,$base,$file,$type,$lvl,$opts);
99}
100
101/**
102 * Build the browsable index of pages
103 *
104 * $opts['ns'] is the current namespace
105 *
106 * @author  Andreas Gohr <andi@splitbrain.org>
107 */
108function search_index(&$data,$base,$file,$type,$lvl,$opts){
109    global $conf;
110    $return = true;
111
112    $item = array();
113
114    if($type == 'd' && !preg_match('#^'.$file.'(/|$)#','/'.$opts['ns'])){
115        //add but don't recurse
116        $return = false;
117    }elseif($type == 'f' && ($opts['nofiles'] || substr($file,-4) != '.txt')){
118        //don't add
119        return false;
120    }
121
122    $id = pathID($file);
123
124    if($type=='d' && $conf['sneaky_index'] && auth_quickaclcheck($id.':') < AUTH_READ){
125        return false;
126    }
127
128    //check hidden
129    if(isHiddenPage($id)){
130        return false;
131    }
132
133    //check ACL
134    if($type=='f' && auth_quickaclcheck($id) < AUTH_READ){
135        return false;
136    }
137
138    $data[]=array( 'id'    => $id,
139            'type'  => $type,
140            'level' => $lvl,
141            'open'  => $return );
142    return $return;
143}
144
145/**
146 * List all namespaces
147 *
148 * @author  Andreas Gohr <andi@splitbrain.org>
149 */
150function search_namespaces(&$data,$base,$file,$type,$lvl,$opts){
151    $opts = array(
152            'listdirs' => true,
153            );
154    return search_universal($data,$base,$file,$type,$lvl,$opts);
155}
156
157/**
158 * List all mediafiles in a namespace
159 *
160 * @author  Andreas Gohr <andi@splitbrain.org>
161 */
162function search_media(&$data,$base,$file,$type,$lvl,$opts){
163
164    //we do nothing with directories
165    if($type == 'd') {
166        if(!$opts['depth']) return true; // recurse forever
167        $depth = substr_count($file,'/');
168        if($depth >= $opts['depth']) return false; // depth reached
169        return true;
170    }
171
172    $info         = array();
173    $info['id']   = pathID($file,true);
174    if($info['id'] != cleanID($info['id'])){
175        if($opts['showmsg'])
176            msg(hsc($info['id']).' is not a valid file name for DokuWiki - skipped',-1);
177        return false; // skip non-valid files
178    }
179
180    //check ACL for namespace (we have no ACL for mediafiles)
181    $info['perm'] = auth_quickaclcheck(getNS($info['id']).':*');
182    if(!$opts['skipacl'] && $info['perm'] < AUTH_READ){
183        return false;
184    }
185
186    //check pattern filter
187    if($opts['pattern'] && !@preg_match($opts['pattern'], $info['id'])){
188        return false;
189    }
190
191    $info['file']     = basename($file);
192    $info['size']     = filesize($base.'/'.$file);
193    $info['mtime']    = filemtime($base.'/'.$file);
194    $info['writable'] = is_writable($base.'/'.$file);
195    if(preg_match("/\.(jpe?g|gif|png)$/",$file)){
196        $info['isimg'] = true;
197        require_once(DOKU_INC.'inc/JpegMeta.php');
198        $info['meta']  = new JpegMeta($base.'/'.$file);
199    }else{
200        $info['isimg'] = false;
201    }
202    if($opts['hash']){
203        $info['hash'] = md5(io_readFile(wikiFN($info['id']),false));
204    }
205
206    $data[] = $info;
207
208    return false;
209}
210
211/**
212 * This function just lists documents (for RSS namespace export)
213 *
214 * @author  Andreas Gohr <andi@splitbrain.org>
215 */
216function search_list(&$data,$base,$file,$type,$lvl,$opts){
217    //we do nothing with directories
218    if($type == 'd') return false;
219    //only search txt files
220    if(substr($file,-4) == '.txt'){
221        //check ACL
222        $id = pathID($file);
223        if(auth_quickaclcheck($id) < AUTH_READ){
224            return false;
225        }
226        $data[]['id'] = $id;
227    }
228    return false;
229}
230
231/**
232 * Quicksearch for searching matching pagenames
233 *
234 * $opts['query'] is the search query
235 *
236 * @author  Andreas Gohr <andi@splitbrain.org>
237 */
238function search_pagename(&$data,$base,$file,$type,$lvl,$opts){
239    //we do nothing with directories
240    if($type == 'd') return true;
241    //only search txt files
242    if(substr($file,-4) != '.txt') return true;
243
244    //simple stringmatching
245    if (!empty($opts['query'])){
246        if(strpos($file,$opts['query']) !== false){
247            //check ACL
248            $id = pathID($file);
249            if(auth_quickaclcheck($id) < AUTH_READ){
250                return false;
251            }
252            $data[]['id'] = $id;
253        }
254    }
255    return true;
256}
257
258/**
259 * Just lists all documents
260 *
261 * $opts['depth']   recursion level, 0 for all
262 * $opts['hash']    do md5 sum of content?
263 * $opts['skipacl'] list everything regardless of ACL
264 *
265 * @author  Andreas Gohr <andi@splitbrain.org>
266 */
267function search_allpages(&$data,$base,$file,$type,$lvl,$opts){
268    //we do nothing with directories
269    if($type == 'd'){
270        if(!$opts['depth']) return true; // recurse forever
271        $parts = explode('/',ltrim($file,'/'));
272        if(count($parts) == $opts['depth']) return false; // depth reached
273        return true;
274    }
275
276    //only search txt files
277    if(substr($file,-4) != '.txt') return true;
278
279    $item['id']   = pathID($file);
280    if(!$opts['skipacl'] && auth_quickaclcheck($item['id']) < AUTH_READ){
281        return false;
282    }
283
284    $item['rev']   = filemtime($base.'/'.$file);
285    $item['mtime'] = $item['rev'];
286    $item['size']  = filesize($base.'/'.$file);
287    if($opts['hash']){
288        $item['hash'] = md5(trim(rawWiki($item['id'])));
289    }
290
291    $data[] = $item;
292    return true;
293}
294
295/**
296 * Search for backlinks to a given page
297 *
298 * $opts['ns']    namespace of the page
299 * $opts['name']  name of the page without namespace
300 *
301 * @author  Andreas Gohr <andi@splitbrain.org>
302 * @deprecated Replaced by ft_backlinks()
303 */
304function search_backlinks(&$data,$base,$file,$type,$lvl,$opts){
305    //we do nothing with directories
306    if($type == 'd') return true;
307    //only search txt files
308    if(substr($file,-4) != '.txt') return true;
309
310    //absolute search id
311    $sid = cleanID($opts['ns'].':'.$opts['name']);
312
313    //current id and namespace
314    $cid = pathID($file);
315    $cns = getNS($cid);
316
317    //check ACL
318    if(auth_quickaclcheck($cid) < AUTH_READ){
319        return false;
320    }
321
322    //fetch instructions
323    require_once(DOKU_INC.'inc/parserutils.php');
324    $instructions = p_cached_instructions($base.$file,true);
325    if(is_null($instructions)) return false;
326
327    //check all links for match
328    foreach($instructions as $ins){
329        if($ins[0] == 'internallink' || ($conf['camelcase'] && $ins[0] == 'camelcaselink') ){
330            $mid = $ins[1][0];
331            resolve_pageid($cns,$mid,$exists); //exists is not used
332            if($mid == $sid){
333                //we have a match - finish
334                $data[]['id'] = $cid;
335                break;
336            }
337        }
338    }
339
340    return false;
341}
342
343/**
344 * Fulltextsearch
345 *
346 * $opts['query'] is the search query
347 *
348 * @author  Andreas Gohr <andi@splitbrain.org>
349 * @deprecated - fulltext indexer is used instead
350 */
351function search_fulltext(&$data,$base,$file,$type,$lvl,$opts){
352    //we do nothing with directories
353    if($type == 'd') return true;
354    //only search txt files
355    if(substr($file,-4) != '.txt') return true;
356
357    //check ACL
358    $id = pathID($file);
359    if(auth_quickaclcheck($id) < AUTH_READ){
360        return false;
361    }
362
363    //create regexp from queries
364    $poswords = array();
365    $negwords = array();
366    $qpreg = preg_split('/\s+/',$opts['query']);
367
368    foreach($qpreg as $word){
369        switch(substr($word,0,1)){
370            case '-':
371                if(strlen($word) > 1){  // catch single '-'
372                    array_push($negwords,preg_quote(substr($word,1),'#'));
373                }
374                break;
375            case '+':
376                if(strlen($word) > 1){  // catch single '+'
377                    array_push($poswords,preg_quote(substr($word,1),'#'));
378                }
379                break;
380            default:
381                array_push($poswords,preg_quote($word,'#'));
382                break;
383        }
384    }
385
386    // a search without any posword is useless
387    if (!count($poswords)) return true;
388
389    $reg  = '^(?=.*?'.join(')(?=.*?',$poswords).')';
390            $reg .= count($negwords) ? '((?!'.join('|',$negwords).').)*$' : '.*$';
391            search_regex($data,$base,$file,$reg,$poswords);
392            return true;
393            }
394
395            /**
396             * Reference search
397             * This fuction searches for existing references to a given media file
398             * and returns an array with the found pages. It doesn't pay any
399             * attention to ACL permissions to find every reference. The caller
400             * must check if the user has the appropriate rights to see the found
401             * page and eventually have to prevent the result from displaying.
402             *
403             * @param array  $data Reference to the result data structure
404             * @param string $base Base usually $conf['datadir']
405             * @param string $file current file or directory relative to $base
406             * @param char   $type Type either 'd' for directory or 'f' for file
407             * @param int    $lvl  Current recursion depht
408             * @param mixed  $opts option array as given to search()
409             *
410             * $opts['query'] is the demanded media file name
411             *
412             * @author  Andreas Gohr <andi@splitbrain.org>
413             * @author  Matthias Grimm <matthiasgrimm@users.sourceforge.net>
414             */
415function search_reference(&$data,$base,$file,$type,$lvl,$opts){
416    global $conf;
417
418    //we do nothing with directories
419    if($type == 'd') return true;
420
421    //only search txt files
422    if(substr($file,-4) != '.txt') return true;
423
424    //we finish after 'cnt' references found. The return value
425    //'false' will skip subdirectories to speed search up.
426    $cnt = $conf['refshow'] > 0 ? $conf['refshow'] : 1;
427    if(count($data) >= $cnt) return false;
428
429    $reg = '\{\{ *\:?'.$opts['query'].' *(\|.*)?\}\}';
430    search_regex($data,$base,$file,$reg,array($opts['query']));
431    return true;
432}
433
434/* ------------- helper functions below -------------- */
435
436/**
437 * fulltext search helper
438 * searches a text file with a given regular expression
439 * no ACL checks are performed. This have to be done by
440 * the caller if necessary.
441 *
442 * @param array  $data  reference to array for results
443 * @param string $base  base directory
444 * @param string $file  file name to search in
445 * @param string $reg   regular expression to search for
446 * @param array  $words words that should be marked in the results
447 *
448 * @author  Andreas Gohr <andi@splitbrain.org>
449 * @author  Matthias Grimm <matthiasgrimm@users.sourceforge.net>
450 *
451 * @deprecated - fulltext indexer is used instead
452 */
453function search_regex(&$data,$base,$file,$reg,$words){
454
455    //get text
456    $text = io_readfile($base.'/'.$file);
457    //lowercase text (u modifier does not help with case)
458    $lctext = utf8_strtolower($text);
459
460    //do the fulltext search
461    $matches = array();
462    if($cnt = preg_match_all('#'.$reg.'#usi',$lctext,$matches)){
463        //this is not the best way for snippet generation but the fastest I could find
464        $q = $words[0];  //use first word for snippet creation
465        $p = utf8_strpos($lctext,$q);
466        $f = $p - 100;
467        $l = utf8_strlen($q) + 200;
468        if($f < 0) $f = 0;
469        $snippet = '<span class="search_sep"> ... </span>'.
470            htmlspecialchars(utf8_substr($text,$f,$l)).
471            '<span class="search_sep"> ... </span>';
472        $mark    = '('.join('|', $words).')';
473        $snippet = preg_replace('#'.$mark.'#si','<strong class="search_hit">\\1</strong>',$snippet);
474
475        $data[] = array(
476                'id'       => pathID($file),
477                'count'    => preg_match_all('#'.$mark.'#usi',$lctext,$matches),
478                'poswords' => join(' ',$words),
479                'snippet'  => $snippet,
480                );
481    }
482
483    return true;
484}
485
486
487/**
488 * fulltext sort
489 *
490 * Callback sort function for use with usort to sort the data
491 * structure created by search_fulltext. Sorts descending by count
492 *
493 * @author  Andreas Gohr <andi@splitbrain.org>
494 */
495function sort_search_fulltext($a,$b){
496    if($a['count'] > $b['count']){
497        return -1;
498    }elseif($a['count'] < $b['count']){
499        return 1;
500    }else{
501        return strcmp($a['id'],$b['id']);
502    }
503}
504
505/**
506 * translates a document path to an ID
507 *
508 * @author  Andreas Gohr <andi@splitbrain.org>
509 * @todo    move to pageutils
510 */
511function pathID($path,$keeptxt=false){
512    $id = utf8_decodeFN($path);
513    $id = str_replace('/',':',$id);
514    if(!$keeptxt) $id = preg_replace('#\.txt$#','',$id);
515    $id = preg_replace('#^:+#','',$id);
516    $id = preg_replace('#:+$#','',$id);
517    return $id;
518}
519
520
521/**
522 * This is a very universal callback for the search() function, replacing
523 * many of the former individual functions at the cost of a more complex
524 * setup.
525 *
526 * How the function behaves, depends on the options passed in the $opts
527 * array, where the following settings can be used.
528 *
529 * depth      int     recursion depth. 0 for unlimited
530 * keeptxt    bool    keep .txt extension for IDs
531 * listfiles  bool    include files in listing
532 * listdirs   bool    include namespaces in listing
533 * pagesonly  bool    restrict files to pages
534 * skipacl    bool    do not check for READ permission
535 * sneakyacl  bool    don't recurse into nonreadable dirs
536 * hash       bool    create MD5 hash for files
537 * meta       bool    return file metadata
538 * filematch  string  match files against this regexp
539 * idmatch    string  match full ID against this regexp
540 * dirmatch   string  match directory against this regexp when adding
541 * nsmatch    string  match namespace against this regexp when adding
542 * recmatch   string  match directory against this regexp when recursing
543 * showmsg    bool    warn about non-ID files
544 * showhidden bool    show hidden files too
545 * firsthead  bool    return first heading for pages
546 *
547 * @author Andreas Gohr <gohr@cosmocode.de>
548 */
549function search_universal(&$data,$base,$file,$type,$lvl,$opts){
550    $item   = array();
551    $return = true;
552
553    // get ID and check if it is a valid one
554    $item['id'] = pathID($file);
555    if($item['id'] != cleanID($item['id'])){
556        if($opts['showmsg'])
557            msg(hsc($item['id']).' is not a valid file name for DokuWiki - skipped',-1);
558        return false; // skip non-valid files
559    }
560    $item['ns']  = getNS($item['id']);
561
562    if($type == 'd') {
563        // decide if to recursion into this directory is wanted
564        if(!$opts['depth']){
565            $return = true; // recurse forever
566        }else{
567            $depth = substr_count($file,'/');
568            if($depth >= $opts['depth']){
569                $return = false; // depth reached
570            }else{
571                $return = true;
572            }
573        }
574        if($return && !preg_match('/'.$opts['recmatch'].'/',$file)){
575            $return = false; // doesn't match
576        }
577    }
578
579    // check ACL
580    if(!$opts['skipacl']){
581        if($type == 'd'){
582            $item['perm'] = auth_quickaclcheck($item['id'].':*');
583        }else{
584            $item['perm'] = auth_quickaclcheck($item['id']); //FIXME check namespace for media files
585        }
586    }else{
587        $item['perm'] = AUTH_DELETE;
588    }
589
590    // are we done here maybe?
591    if($type == 'd'){
592        if(!$opts['listdirs']) return $return;
593        if(!$opts['skipacl'] && $opts['sneakyacl'] && $item['perm'] < AUTH_READ) return false; //neither list nor recurse
594        if($opts['dirmatch'] && !preg_match('/'.$opts['dirmatch'].'/',$file)) return $return;
595        if($opts['nsmatch'] && !preg_match('/'.$opts['nsmatch'].'/',$item['ns'])) return $return;
596    }else{
597        if(!$opts['listfiles']) return $return;
598        if(!$opts['skipacl'] && $item['perm'] < AUTH_READ) return $return;
599        if($opts['pagesonly'] && (substr($file,-4) != '.txt')) return $return;
600        if(!$conf['showhidden'] && isHiddenPage($id)) return $return;
601        if($opts['filematch'] && !preg_match('/'.$opts['filematch'].'/',$file)) return $return;
602        if($opts['idmatch'] && !preg_match('/'.$opts['idmatch'].'/',$item['id'])) return $return;
603    }
604
605    // still here? prepare the item
606    $item['type']  = $type;
607    $item['level'] = $lvl;
608    $item['open']  = $return;
609
610    if($opts['meta']){
611        $item['file']       = basename($file);
612        $item['size']       = filesize($base.'/'.$file);
613        $item['mtime']      = filemtime($base.'/'.$file);
614        $item['rev']        = $item['mtime'];
615        $item['writable']   = is_writable($base.'/'.$file);
616        $item['executable'] = is_executable($base.'/'.$file);
617    }
618
619    if($type == 'f'){
620        if($opts['hash']) $item['hash'] = md5(io_readFile($base.'/'.$file,false));
621        if($opts['firsthead']) $item['title'] = p_get_first_heading($item['id'],false);
622    }
623
624    // finally add the item
625    $data[] = $item;
626    return $return;
627}
628
629//Setup VIM: ex: et ts=4 enc=utf-8 :
630