xref: /dokuwiki/inc/search.php (revision 5c967d3d04622c1420313f1a514da5cda99827f3)
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/* ------------- helper functions below -------------- */
277
278/**
279 * fulltext sort
280 *
281 * Callback sort function for use with usort to sort the data
282 * structure created by search_fulltext. Sorts descending by count
283 *
284 * @author  Andreas Gohr <andi@splitbrain.org>
285 */
286function sort_search_fulltext($a,$b){
287    if($a['count'] > $b['count']){
288        return -1;
289    }elseif($a['count'] < $b['count']){
290        return 1;
291    }else{
292        return strcmp($a['id'],$b['id']);
293    }
294}
295
296/**
297 * translates a document path to an ID
298 *
299 * @author  Andreas Gohr <andi@splitbrain.org>
300 * @todo    move to pageutils
301 */
302function pathID($path,$keeptxt=false){
303    $id = utf8_decodeFN($path);
304    $id = str_replace('/',':',$id);
305    if(!$keeptxt) $id = preg_replace('#\.txt$#','',$id);
306    $id = trim($id, ':');
307    return $id;
308}
309
310
311/**
312 * This is a very universal callback for the search() function, replacing
313 * many of the former individual functions at the cost of a more complex
314 * setup.
315 *
316 * How the function behaves, depends on the options passed in the $opts
317 * array, where the following settings can be used.
318 *
319 * depth      int     recursion depth. 0 for unlimited
320 * keeptxt    bool    keep .txt extension for IDs
321 * listfiles  bool    include files in listing
322 * listdirs   bool    include namespaces in listing
323 * pagesonly  bool    restrict files to pages
324 * skipacl    bool    do not check for READ permission
325 * sneakyacl  bool    don't recurse into nonreadable dirs
326 * hash       bool    create MD5 hash for files
327 * meta       bool    return file metadata
328 * filematch  string  match files against this regexp
329 * idmatch    string  match full ID against this regexp
330 * dirmatch   string  match directory against this regexp when adding
331 * nsmatch    string  match namespace against this regexp when adding
332 * recmatch   string  match directory against this regexp when recursing
333 * showmsg    bool    warn about non-ID files
334 * showhidden bool    show hidden files too
335 * firsthead  bool    return first heading for pages
336 *
337 * @author Andreas Gohr <gohr@cosmocode.de>
338 */
339function search_universal(&$data,$base,$file,$type,$lvl,$opts){
340    $item   = array();
341    $return = true;
342
343    // get ID and check if it is a valid one
344    $item['id'] = pathID($file,($type == 'd' || $opts['keeptxt']));
345    if($item['id'] != cleanID($item['id'])){
346        if($opts['showmsg'])
347            msg(hsc($item['id']).' is not a valid file name for DokuWiki - skipped',-1);
348        return false; // skip non-valid files
349    }
350    $item['ns']  = getNS($item['id']);
351
352    if($type == 'd') {
353        // decide if to recursion into this directory is wanted
354        if(!$opts['depth']){
355            $return = true; // recurse forever
356        }else{
357            $depth = substr_count($file,'/');
358            if($depth >= $opts['depth']){
359                $return = false; // depth reached
360            }else{
361                $return = true;
362            }
363        }
364        if($return && !preg_match('/'.$opts['recmatch'].'/',$file)){
365            $return = false; // doesn't match
366        }
367    }
368
369    // check ACL
370    if(!$opts['skipacl']){
371        if($type == 'd'){
372            $item['perm'] = auth_quickaclcheck($item['id'].':*');
373        }else{
374            $item['perm'] = auth_quickaclcheck($item['id']); //FIXME check namespace for media files
375        }
376    }else{
377        $item['perm'] = AUTH_DELETE;
378    }
379
380    // are we done here maybe?
381    if($type == 'd'){
382        if(!$opts['listdirs']) return $return;
383        if(!$opts['skipacl'] && $opts['sneakyacl'] && $item['perm'] < AUTH_READ) return false; //neither list nor recurse
384        if($opts['dirmatch'] && !preg_match('/'.$opts['dirmatch'].'/',$file)) return $return;
385        if($opts['nsmatch'] && !preg_match('/'.$opts['nsmatch'].'/',$item['ns'])) return $return;
386    }else{
387        if(!$opts['listfiles']) return $return;
388        if(!$opts['skipacl'] && $item['perm'] < AUTH_READ) return $return;
389        if($opts['pagesonly'] && (substr($file,-4) != '.txt')) return $return;
390        if(!$opts['showhidden'] && isHiddenPage($item['id'])) return $return;
391        if($opts['filematch'] && !preg_match('/'.$opts['filematch'].'/',$file)) return $return;
392        if($opts['idmatch'] && !preg_match('/'.$opts['idmatch'].'/',$item['id'])) return $return;
393    }
394
395    // still here? prepare the item
396    $item['type']  = $type;
397    $item['level'] = $lvl;
398    $item['open']  = $return;
399
400    if($opts['meta']){
401        $item['file']       = utf8_basename($file);
402        $item['size']       = filesize($base.'/'.$file);
403        $item['mtime']      = filemtime($base.'/'.$file);
404        $item['rev']        = $item['mtime'];
405        $item['writable']   = is_writable($base.'/'.$file);
406        $item['executable'] = is_executable($base.'/'.$file);
407    }
408
409    if($type == 'f'){
410        if($opts['hash']) $item['hash'] = md5(io_readFile($base.'/'.$file,false));
411        if($opts['firsthead']) $item['title'] = p_get_first_heading($item['id'],METADATA_DONT_RENDER);
412    }
413
414    // finally add the item
415    $data[] = $item;
416    return $return;
417}
418
419//Setup VIM: ex: et ts=4 :
420