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