xref: /dokuwiki/inc/search.php (revision 00d58927261c5bed6f093ca4aa2064a18139a228)
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 array with object,method)
20 * @param   string    $dir  Current directory beyond $base
21 * @param   int       $lvl  Recursion Level
22 * @param   mixed     $sort 'natural' to use natural order sorting (default); 'date' to sort by filemtime; leave empty to skip sorting.
23 * @author  Andreas Gohr <andi@splitbrain.org>
24 */
25function search(&$data,$base,$func,$opts,$dir='',$lvl=1,$sort='natural'){
26    $dirs   = array();
27    $files  = array();
28    $filepaths = array();
29
30    //read in directories and files
31    $dh = @opendir($base.'/'.$dir);
32    if(!$dh) return;
33    while(($file = readdir($dh)) !== false){
34        if(preg_match('/^[\._]/',$file)) continue; //skip hidden files and upper dirs
35        if(is_dir($base.'/'.$dir.'/'.$file)){
36            $dirs[] = $dir.'/'.$file;
37            continue;
38        }
39        $files[] = $dir.'/'.$file;
40        $filepaths[] = $base.'/'.$dir.'/'.$file;
41    }
42    closedir($dh);
43    if (!empty($sort)) {
44        if ($sort == 'date') {
45            @array_multisort(array_map('filemtime', $filepaths), SORT_NUMERIC, SORT_DESC, $files);
46        } else /* natural */ {
47            natsort($files);
48        }
49        natsort($dirs);
50    }
51
52    //give directories to userfunction then recurse
53    foreach($dirs as $dir){
54        if (call_user_func_array($func, array(&$data,$base,$dir,'d',$lvl,$opts))){
55            search($data,$base,$func,$opts,$dir,$lvl+1,$sort);
56        }
57    }
58    //now handle the files
59    foreach($files as $file){
60        call_user_func_array($func, array(&$data,$base,$file,'f',$lvl,$opts));
61    }
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('#^'.preg_quote($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']     = utf8_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    if(isset($opts['depth']) && $opts['depth']){
245        $parts = explode('/',ltrim($file,'/'));
246        if(($type == 'd' && count($parts) >= $opts['depth'])
247          || ($type != 'd' && count($parts) > $opts['depth'])){
248            return false; // depth reached
249        }
250    }
251
252    //we do nothing with directories
253    if($type == 'd'){
254        return true;
255    }
256
257    //only search txt files
258    if(substr($file,-4) != '.txt') return true;
259
260    $item['id']   = pathID($file);
261    if(!$opts['skipacl'] && auth_quickaclcheck($item['id']) < AUTH_READ){
262        return false;
263    }
264
265    $item['rev']   = filemtime($base.'/'.$file);
266    $item['mtime'] = $item['rev'];
267    $item['size']  = filesize($base.'/'.$file);
268    if($opts['hash']){
269        $item['hash'] = md5(trim(rawWiki($item['id'])));
270    }
271
272    $data[] = $item;
273    return true;
274}
275
276/**
277 * Reference search
278 * This fuction searches for existing references to a given media file
279 * and returns an array with the found pages. It doesn't pay any
280 * attention to ACL permissions to find every reference. The caller
281 * must check if the user has the appropriate rights to see the found
282 * page and eventually have to prevent the result from displaying.
283 *
284 * @param array  $data Reference to the result data structure
285 * @param string $base Base usually $conf['datadir']
286 * @param string $file current file or directory relative to $base
287 * @param char   $type Type either 'd' for directory or 'f' for file
288 * @param int    $lvl  Current recursion depht
289 * @param mixed  $opts option array as given to search()
290 *
291 * $opts['query'] is the demanded media file name
292 *
293 * @author  Andreas Gohr <andi@splitbrain.org>
294 * @author  Matthias Grimm <matthiasgrimm@users.sourceforge.net>
295 */
296function search_reference(&$data,$base,$file,$type,$lvl,$opts){
297    global $conf;
298
299    //we do nothing with directories
300    if($type == 'd') return true;
301
302    //only search txt files
303    if(substr($file,-4) != '.txt') return true;
304
305    //we finish after 'cnt' references found. The return value
306    //'false' will skip subdirectories to speed search up.
307    $cnt = $conf['refshow'] > 0 ? $conf['refshow'] : 1;
308    if(count($data) >= $cnt) return false;
309
310    $reg = '\{\{ *\:?'.$opts['query'].' *(\|.*)?\}\}';
311    search_regex($data,$base,$file,$reg,array($opts['query']));
312    return true;
313}
314
315/* ------------- helper functions below -------------- */
316
317/**
318 * fulltext sort
319 *
320 * Callback sort function for use with usort to sort the data
321 * structure created by search_fulltext. Sorts descending by count
322 *
323 * @author  Andreas Gohr <andi@splitbrain.org>
324 */
325function sort_search_fulltext($a,$b){
326    if($a['count'] > $b['count']){
327        return -1;
328    }elseif($a['count'] < $b['count']){
329        return 1;
330    }else{
331        return strcmp($a['id'],$b['id']);
332    }
333}
334
335/**
336 * translates a document path to an ID
337 *
338 * @author  Andreas Gohr <andi@splitbrain.org>
339 * @todo    move to pageutils
340 */
341function pathID($path,$keeptxt=false){
342    $id = utf8_decodeFN($path);
343    $id = str_replace('/',':',$id);
344    if(!$keeptxt) $id = preg_replace('#\.txt$#','',$id);
345    $id = trim($id, ':');
346    return $id;
347}
348
349
350/**
351 * This is a very universal callback for the search() function, replacing
352 * many of the former individual functions at the cost of a more complex
353 * setup.
354 *
355 * How the function behaves, depends on the options passed in the $opts
356 * array, where the following settings can be used.
357 *
358 * depth      int     recursion depth. 0 for unlimited
359 * keeptxt    bool    keep .txt extension for IDs
360 * listfiles  bool    include files in listing
361 * listdirs   bool    include namespaces in listing
362 * pagesonly  bool    restrict files to pages
363 * skipacl    bool    do not check for READ permission
364 * sneakyacl  bool    don't recurse into nonreadable dirs
365 * hash       bool    create MD5 hash for files
366 * meta       bool    return file metadata
367 * filematch  string  match files against this regexp
368 * idmatch    string  match full ID against this regexp
369 * dirmatch   string  match directory against this regexp when adding
370 * nsmatch    string  match namespace against this regexp when adding
371 * recmatch   string  match directory against this regexp when recursing
372 * showmsg    bool    warn about non-ID files
373 * showhidden bool    show hidden files too
374 * firsthead  bool    return first heading for pages
375 *
376 * @author Andreas Gohr <gohr@cosmocode.de>
377 */
378function search_universal(&$data,$base,$file,$type,$lvl,$opts){
379    $item   = array();
380    $return = true;
381
382    // get ID and check if it is a valid one
383    $item['id'] = pathID($file,($type == 'd' || $opts['keeptxt']));
384    if($item['id'] != cleanID($item['id'])){
385        if($opts['showmsg'])
386            msg(hsc($item['id']).' is not a valid file name for DokuWiki - skipped',-1);
387        return false; // skip non-valid files
388    }
389    $item['ns']  = getNS($item['id']);
390
391    if($type == 'd') {
392        // decide if to recursion into this directory is wanted
393        if(!$opts['depth']){
394            $return = true; // recurse forever
395        }else{
396            $depth = substr_count($file,'/');
397            if($depth >= $opts['depth']){
398                $return = false; // depth reached
399            }else{
400                $return = true;
401            }
402        }
403        if($return && !preg_match('/'.$opts['recmatch'].'/',$file)){
404            $return = false; // doesn't match
405        }
406    }
407
408    // check ACL
409    if(!$opts['skipacl']){
410        if($type == 'd'){
411            $item['perm'] = auth_quickaclcheck($item['id'].':*');
412        }else{
413            $item['perm'] = auth_quickaclcheck($item['id']); //FIXME check namespace for media files
414        }
415    }else{
416        $item['perm'] = AUTH_DELETE;
417    }
418
419    // are we done here maybe?
420    if($type == 'd'){
421        if(!$opts['listdirs']) return $return;
422        if(!$opts['skipacl'] && $opts['sneakyacl'] && $item['perm'] < AUTH_READ) return false; //neither list nor recurse
423        if($opts['dirmatch'] && !preg_match('/'.$opts['dirmatch'].'/',$file)) return $return;
424        if($opts['nsmatch'] && !preg_match('/'.$opts['nsmatch'].'/',$item['ns'])) return $return;
425    }else{
426        if(!$opts['listfiles']) return $return;
427        if(!$opts['skipacl'] && $item['perm'] < AUTH_READ) return $return;
428        if($opts['pagesonly'] && (substr($file,-4) != '.txt')) return $return;
429        if(!$opts['showhidden'] && isHiddenPage($item['id'])) return $return;
430        if($opts['filematch'] && !preg_match('/'.$opts['filematch'].'/',$file)) return $return;
431        if($opts['idmatch'] && !preg_match('/'.$opts['idmatch'].'/',$item['id'])) return $return;
432    }
433
434    // still here? prepare the item
435    $item['type']  = $type;
436    $item['level'] = $lvl;
437    $item['open']  = $return;
438
439    if($opts['meta']){
440        $item['file']       = utf8_basename($file);
441        $item['size']       = filesize($base.'/'.$file);
442        $item['mtime']      = filemtime($base.'/'.$file);
443        $item['rev']        = $item['mtime'];
444        $item['writable']   = is_writable($base.'/'.$file);
445        $item['executable'] = is_executable($base.'/'.$file);
446    }
447
448    if($type == 'f'){
449        if($opts['hash']) $item['hash'] = md5(io_readFile($base.'/'.$file,false));
450        if($opts['firsthead']) $item['title'] = p_get_first_heading($item['id'],METADATA_DONT_RENDER);
451    }
452
453    // finally add the item
454    $data[] = $item;
455    return $return;
456}
457
458//Setup VIM: ex: et ts=4 :
459