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