xref: /dokuwiki/inc/search.php (revision 1eadd9e86a740ac0a4e8284ca14a40b58ad39994)
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
9use dokuwiki\Utf8\Sort;
10
11/**
12 * Recurse directory
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    &$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 array with object,method)
20 * @param   array     $opts option array will be given to the Callback
21 * @param   string    $dir  Current directory beyond $base
22 * @param   int       $lvl  Recursion Level
23 * @param   mixed     $sort 'natural' to use natural order sorting (default);
24 *                          'date' to sort by filemtime; leave empty to skip sorting.
25 * @author  Andreas Gohr <andi@splitbrain.org>
26 */
27function search(&$data,$base,$func,$opts,$dir='',$lvl=1,$sort='natural'){
28    $dirs   = array();
29    $files  = array();
30    $filepaths = array();
31
32    // safeguard against runaways #1452
33    if($base == '' || $base == '/') {
34        throw new RuntimeException('No valid $base passed to search() - possible misconfiguration or bug');
35    }
36
37    //read in directories and files
38    $dh = @opendir($base.'/'.$dir);
39    if(!$dh) return;
40    while(($file = readdir($dh)) !== false){
41        if(preg_match('/^[\._]/',$file)) continue; //skip hidden files and upper dirs
42        if(is_dir($base.'/'.$dir.'/'.$file)){
43            $dirs[] = $dir.'/'.$file;
44            continue;
45        }
46        $files[] = $dir.'/'.$file;
47        $filepaths[] = $base.'/'.$dir.'/'.$file;
48    }
49    closedir($dh);
50    if (!empty($sort)) {
51        if ($sort == 'date') {
52            @array_multisort(array_map('filemtime', $filepaths), SORT_NUMERIC, SORT_DESC, $files);
53        } else /* natural */ {
54            Sort::asortFN($files);
55        }
56        Sort::asortFN($dirs);
57    }
58
59    //give directories to userfunction then recurse
60    foreach($dirs as $dir){
61        if (call_user_func_array($func, array(&$data,$base,$dir,'d',$lvl,$opts))){
62            search($data,$base,$func,$opts,$dir,$lvl+1,$sort);
63        }
64    }
65    //now handle the files
66    foreach($files as $file){
67        call_user_func_array($func, array(&$data,$base,$file,'f',$lvl,$opts));
68    }
69}
70
71/**
72 * The following functions are userfunctions to use with the search
73 * function above. This function is called for every found file or
74 * directory. When a directory is given to the function it has to
75 * decide if this directory should be traversed (true) or not (false)
76 * The function has to accept the following parameters:
77 *
78 * array &$data  - Reference to the result data structure
79 * string $base  - Base usually $conf['datadir']
80 * string $file  - current file or directory relative to $base
81 * string $type  - Type either 'd' for directory or 'f' for file
82 * int    $lvl   - Current recursion depht
83 * array  $opts  - option array as given to search()
84 *
85 * return values for files are ignored
86 *
87 * All functions should check the ACL for document READ rights
88 * namespaces (directories) are NOT checked (when sneaky_index is 0) as this
89 * would break the recursion (You can have an nonreadable dir over a readable
90 * one deeper nested) also make sure to check the file type (for example
91 * in case of lockfiles).
92 */
93
94/**
95 * Searches for pages beginning with the given query
96 *
97 * @author Andreas Gohr <andi@splitbrain.org>
98 *
99 * @param array $data
100 * @param string $base
101 * @param string $file
102 * @param string $type
103 * @param integer $lvl
104 * @param array $opts
105 *
106 * @return bool
107 */
108function search_qsearch(&$data,$base,$file,$type,$lvl,$opts){
109    $opts = array(
110            'idmatch'   => '(^|:)'.preg_quote($opts['query'],'/').'/',
111            'listfiles' => true,
112            'pagesonly' => true,
113            );
114    return search_universal($data,$base,$file,$type,$lvl,$opts);
115}
116
117/**
118 * Build the browsable index of pages
119 *
120 * $opts['ns'] is the currently viewed namespace
121 *
122 * @author  Andreas Gohr <andi@splitbrain.org>
123 *
124 * @param array $data
125 * @param string $base
126 * @param string $file
127 * @param string $type
128 * @param integer $lvl
129 * @param array $opts
130 *
131 * @return bool
132 */
133function search_index(&$data,$base,$file,$type,$lvl,$opts){
134    global $conf;
135    $ns = isset($opts['ns']) ? $opts['ns'] : '';
136    $opts = array(
137        'pagesonly' => true,
138        'listdirs' => true,
139        'listfiles' => empty($opts['nofiles']),
140        'sneakyacl' => $conf['sneaky_index'],
141        // Hacky, should rather use recmatch
142        'depth' => preg_match('#^'.preg_quote($file, '#').'(/|$)#','/'.$ns) ? 0 : -1
143    );
144
145    return search_universal($data, $base, $file, $type, $lvl, $opts);
146}
147
148/**
149 * List all namespaces
150 *
151 * @author  Andreas Gohr <andi@splitbrain.org>
152 *
153 * @param array $data
154 * @param string $base
155 * @param string $file
156 * @param string $type
157 * @param integer $lvl
158 * @param array $opts
159 *
160 * @return bool
161 */
162function search_namespaces(&$data,$base,$file,$type,$lvl,$opts){
163    $opts = array(
164            'listdirs' => true,
165            );
166    return search_universal($data,$base,$file,$type,$lvl,$opts);
167}
168
169/**
170 * List all mediafiles in a namespace
171 *   $opts['depth']     recursion level, 0 for all
172 *   $opts['showmsg']   shows message if invalid media id is used
173 *   $opts['skipacl']   skip acl checking
174 *   $opts['pattern']   check given pattern
175 *   $opts['hash']      add hashes to result list
176 *
177 * @author  Andreas Gohr <andi@splitbrain.org>
178 *
179 * @param array $data
180 * @param string $base
181 * @param string $file
182 * @param string $type
183 * @param integer $lvl
184 * @param array $opts
185 *
186 * @return bool
187 */
188function search_media(&$data,$base,$file,$type,$lvl,$opts){
189
190    //we do nothing with directories
191    if($type == 'd') {
192        if(empty($opts['depth'])) return true; // recurse forever
193        $depth = substr_count($file,'/');
194        if($depth >= $opts['depth']) return false; // depth reached
195        return true;
196    }
197
198    $info         = array();
199    $info['id']   = pathID($file,true);
200    if($info['id'] != cleanID($info['id'])){
201        if($opts['showmsg'])
202            msg(hsc($info['id']).' is not a valid file name for DokuWiki - skipped',-1);
203        return false; // skip non-valid files
204    }
205
206    //check ACL for namespace (we have no ACL for mediafiles)
207    $info['perm'] = auth_quickaclcheck(getNS($info['id']).':*');
208    if(empty($opts['skipacl']) && $info['perm'] < AUTH_READ){
209        return false;
210    }
211
212    //check pattern filter
213    if(!empty($opts['pattern']) && !@preg_match($opts['pattern'], $info['id'])){
214        return false;
215    }
216
217    $info['file']     = \dokuwiki\Utf8\PhpString::basename($file);
218    $info['size']     = filesize($base.'/'.$file);
219    $info['mtime']    = filemtime($base.'/'.$file);
220    $info['writable'] = is_writable($base.'/'.$file);
221    if(preg_match("/\.(jpe?g|gif|png)$/",$file)){
222        $info['isimg'] = true;
223        $info['meta']  = new JpegMeta($base.'/'.$file);
224    }else{
225        $info['isimg'] = false;
226    }
227    if(!empty($opts['hash'])){
228        $info['hash'] = md5(io_readFile(mediaFN($info['id']),false));
229    }
230
231    $data[] = $info;
232
233    return false;
234}
235
236/**
237 * This function just lists documents (for RSS namespace export)
238 *
239 * @author  Andreas Gohr <andi@splitbrain.org>
240 *
241 * @param array $data
242 * @param string $base
243 * @param string $file
244 * @param string $type
245 * @param integer $lvl
246 * @param array $opts
247 *
248 * @return bool
249 */
250function search_list(&$data,$base,$file,$type,$lvl,$opts){
251    //we do nothing with directories
252    if($type == 'd') return false;
253    //only search txt files
254    if(substr($file,-4) == '.txt'){
255        //check ACL
256        $id = pathID($file);
257        if(auth_quickaclcheck($id) < AUTH_READ){
258            return false;
259        }
260        $data[]['id'] = $id;
261    }
262    return false;
263}
264
265/**
266 * Quicksearch for searching matching pagenames
267 *
268 * $opts['query'] is the search query
269 *
270 * @author  Andreas Gohr <andi@splitbrain.org>
271 *
272 * @param array $data
273 * @param string $base
274 * @param string $file
275 * @param string $type
276 * @param integer $lvl
277 * @param array $opts
278 *
279 * @return bool
280 */
281function search_pagename(&$data,$base,$file,$type,$lvl,$opts){
282    //we do nothing with directories
283    if($type == 'd') return true;
284    //only search txt files
285    if(substr($file,-4) != '.txt') return true;
286
287    //simple stringmatching
288    if (!empty($opts['query'])){
289        if(strpos($file,$opts['query']) !== false){
290            //check ACL
291            $id = pathID($file);
292            if(auth_quickaclcheck($id) < AUTH_READ){
293                return false;
294            }
295            $data[]['id'] = $id;
296        }
297    }
298    return true;
299}
300
301/**
302 * Just lists all documents
303 *
304 * $opts['depth']   recursion level, 0 for all
305 * $opts['hash']    do md5 sum of content?
306 * $opts['skipacl'] list everything regardless of ACL
307 *
308 * @author  Andreas Gohr <andi@splitbrain.org>
309 *
310 * @param array $data
311 * @param string $base
312 * @param string $file
313 * @param string $type
314 * @param integer $lvl
315 * @param array $opts
316 *
317 * @return bool
318 */
319function search_allpages(&$data,$base,$file,$type,$lvl,$opts){
320    if(isset($opts['depth']) && $opts['depth']){
321        $parts = explode('/',ltrim($file,'/'));
322        if(($type == 'd' && count($parts) >= $opts['depth'])
323          || ($type != 'd' && count($parts) > $opts['depth'])){
324            return false; // depth reached
325        }
326    }
327
328    //we do nothing with directories
329    if($type == 'd'){
330        return true;
331    }
332
333    //only search txt files
334    if(substr($file,-4) != '.txt') return true;
335
336    $item = array();
337    $item['id']   = pathID($file);
338    if(empty($opts['skipacl']) && auth_quickaclcheck($item['id']) < AUTH_READ){
339        return false;
340    }
341
342    $item['rev']   = filemtime($base.'/'.$file);
343    $item['mtime'] = $item['rev'];
344    $item['size']  = filesize($base.'/'.$file);
345    if(!empty($opts['hash'])){
346        $item['hash'] = md5(trim(rawWiki($item['id'])));
347    }
348
349    $data[] = $item;
350    return true;
351}
352
353/* ------------- helper functions below -------------- */
354
355/**
356 * fulltext sort
357 *
358 * Callback sort function for use with usort to sort the data
359 * structure created by search_fulltext. Sorts descending by count
360 *
361 * @author  Andreas Gohr <andi@splitbrain.org>
362 *
363 * @param array $a
364 * @param array $b
365 *
366 * @return int
367 */
368function sort_search_fulltext($a,$b){
369    if($a['count'] > $b['count']){
370        return -1;
371    }elseif($a['count'] < $b['count']){
372        return 1;
373    }else{
374        return Sort::strcmp($a['id'],$b['id']);
375    }
376}
377
378/**
379 * translates a document path to an ID
380 *
381 * @author  Andreas Gohr <andi@splitbrain.org>
382 * @todo    move to pageutils
383 *
384 * @param string $path
385 * @param bool $keeptxt
386 *
387 * @return mixed|string
388 */
389function pathID($path,$keeptxt=false){
390    $id = utf8_decodeFN($path);
391    $id = str_replace('/',':',$id);
392    if(!$keeptxt) $id = preg_replace('#\.txt$#','',$id);
393    $id = trim($id, ':');
394    return $id;
395}
396
397
398/**
399 * This is a very universal callback for the search() function, replacing
400 * many of the former individual functions at the cost of a more complex
401 * setup.
402 *
403 * How the function behaves, depends on the options passed in the $opts
404 * array, where the following settings can be used.
405 *
406 * depth      int     recursion depth. 0 for unlimited                       (default: 0)
407 * keeptxt    bool    keep .txt extension for IDs                            (default: false)
408 * listfiles  bool    include files in listing                               (default: false)
409 * listdirs   bool    include namespaces in listing                          (default: false)
410 * pagesonly  bool    restrict files to pages                                (default: false)
411 * skipacl    bool    do not check for READ permission                       (default: false)
412 * sneakyacl  bool    don't recurse into nonreadable dirs                    (default: false)
413 * hash       bool    create MD5 hash for files                              (default: false)
414 * meta       bool    return file metadata                                   (default: false)
415 * filematch  string  match files against this regexp                        (default: '', so accept everything)
416 * idmatch    string  match full ID against this regexp                      (default: '', so accept everything)
417 * dirmatch   string  match directory against this regexp when adding        (default: '', so accept everything)
418 * nsmatch    string  match namespace against this regexp when adding        (default: '', so accept everything)
419 * recmatch   string  match directory against this regexp when recursing     (default: '', so accept everything)
420 * showmsg    bool    warn about non-ID files                                (default: false)
421 * showhidden bool    show hidden files(e.g. by hidepages config) too        (default: false)
422 * firsthead  bool    return first heading for pages                         (default: false)
423 *
424 * @param array &$data  - Reference to the result data structure
425 * @param string $base  - Base usually $conf['datadir']
426 * @param string $file  - current file or directory relative to $base
427 * @param string $type  - Type either 'd' for directory or 'f' for file
428 * @param int    $lvl   - Current recursion depht
429 * @param array  $opts  - option array as given to search()
430 * @return bool if this directory should be traversed (true) or not (false)
431 *              return value is ignored for files
432 *
433 * @author Andreas Gohr <gohr@cosmocode.de>
434 */
435function search_universal(&$data,$base,$file,$type,$lvl,$opts){
436    $item   = array();
437    $return = true;
438
439    // get ID and check if it is a valid one
440    $item['id'] = pathID($file,($type == 'd' || !empty($opts['keeptxt'])));
441    if($item['id'] != cleanID($item['id'])){
442        if(!empty($opts['showmsg'])){
443            msg(hsc($item['id']).' is not a valid file name for DokuWiki - skipped',-1);
444        }
445        return false; // skip non-valid files
446    }
447    $item['ns']  = getNS($item['id']);
448
449    if($type == 'd') {
450        // decide if to recursion into this directory is wanted
451        if(empty($opts['depth'])){
452            $return = true; // recurse forever
453        }else{
454            $depth = substr_count($file,'/');
455            if($depth >= $opts['depth']){
456                $return = false; // depth reached
457            }else{
458                $return = true;
459            }
460        }
461
462        if ($return) {
463            $match = empty($opts['recmatch']) || preg_match('/'.$opts['recmatch'].'/',$file);
464            if (!$match) {
465                return false; // doesn't match
466            }
467        }
468    }
469
470    // check ACL
471    if(empty($opts['skipacl'])){
472        if($type == 'd'){
473            $item['perm'] = auth_quickaclcheck($item['id'].':*');
474        }else{
475            $item['perm'] = auth_quickaclcheck($item['id']); //FIXME check namespace for media files
476        }
477    }else{
478        $item['perm'] = AUTH_DELETE;
479    }
480
481    // are we done here maybe?
482    if($type == 'd'){
483        if(empty($opts['listdirs'])) return $return;
484        //neither list nor recurse forbidden items:
485        if(empty($opts['skipacl']) && !empty($opts['sneakyacl']) && $item['perm'] < AUTH_READ) return false;
486        if(!empty($opts['dirmatch']) && !preg_match('/'.$opts['dirmatch'].'/',$file)) return $return;
487        if(!empty($opts['nsmatch']) && !preg_match('/'.$opts['nsmatch'].'/',$item['ns'])) return $return;
488    }else{
489        if(empty($opts['listfiles'])) return $return;
490        if(empty($opts['skipacl']) && $item['perm'] < AUTH_READ) return $return;
491        if(!empty($opts['pagesonly']) && (substr($file,-4) != '.txt')) return $return;
492        if(empty($opts['showhidden']) && isHiddenPage($item['id'])) return $return;
493        if(!empty($opts['filematch']) && !preg_match('/'.$opts['filematch'].'/',$file)) return $return;
494        if(!empty($opts['idmatch']) && !preg_match('/'.$opts['idmatch'].'/',$item['id'])) return $return;
495    }
496
497    // still here? prepare the item
498    $item['type']  = $type;
499    $item['level'] = $lvl;
500    $item['open']  = $return;
501
502    if(!empty($opts['meta'])){
503        $item['file']       = \dokuwiki\Utf8\PhpString::basename($file);
504        $item['size']       = filesize($base.'/'.$file);
505        $item['mtime']      = filemtime($base.'/'.$file);
506        $item['rev']        = $item['mtime'];
507        $item['writable']   = is_writable($base.'/'.$file);
508        $item['executable'] = is_executable($base.'/'.$file);
509    }
510
511    if($type == 'f'){
512        if(!empty($opts['hash'])) $item['hash'] = md5(io_readFile($base.'/'.$file,false));
513        if(!empty($opts['firsthead'])) $item['title'] = p_get_first_heading($item['id'],METADATA_DONT_RENDER);
514    }
515
516    // finally add the item
517    $data[] = $item;
518    return $return;
519}
520
521//Setup VIM: ex: et ts=4 :
522