xref: /dokuwiki/inc/search.php (revision 3f4a342befbede62946481d36e02a2a7b211c309)
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
9/**
10 * Recurse directory
11 *
12 * This function recurses into a given base directory
13 * and calls the supplied function for each file and directory
14 *
15 * @param   array    &$data The results of the search are stored here
16 * @param   string    $base Where to start the search
17 * @param   callback  $func Callback (function name or array with object,method)
18 * @param   array     $opts option array will be given to the Callback
19 * @param   string    $dir  Current directory beyond $base
20 * @param   int       $lvl  Recursion Level
21 * @param   mixed     $sort 'natural' to use natural order sorting (default);
22 *                          '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{
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 *
98 * @param array $data
99 * @param string $base
100 * @param string $file
101 * @param string $type
102 * @param integer $lvl
103 * @param array $opts
104 *
105 * @return bool
106 */
107function search_qsearch(&$data, $base, $file, $type, $lvl, $opts)
108{
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{
135    global $conf;
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, '#').'(/|$)#','/'.$opts['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{
164    $opts = array(
165            'listdirs' => true,
166            );
167    return search_universal($data, $base, $file, $type, $lvl, $opts);
168}
169
170/**
171 * List all mediafiles in a namespace
172 *   $opts['depth']     recursion level, 0 for all
173 *   $opts['showmsg']   shows message if invalid media id is used
174 *   $opts['skipacl']   skip acl checking
175 *   $opts['pattern']   check given pattern
176 *   $opts['hash']      add hashes to result list
177 *
178 * @author  Andreas Gohr <andi@splitbrain.org>
179 *
180 * @param array $data
181 * @param string $base
182 * @param string $file
183 * @param string $type
184 * @param integer $lvl
185 * @param array $opts
186 *
187 * @return bool
188 */
189function search_media(&$data, $base, $file, $type, $lvl, $opts)
190{
191    //we do nothing with directories
192    if ($type == 'd') {
193        if (empty($opts['depth'])) return true; // recurse forever
194        $depth = substr_count($file,'/');
195        if ($depth >= $opts['depth']) return false; // depth reached
196        return true;
197    }
198
199    $info         = array();
200    $info['id']   = pathID($file, true);
201    if ($info['id'] != cleanID($info['id'])) {
202        if ($opts['showmsg'])
203            msg(hsc($info['id']).' is not a valid file name for DokuWiki - skipped',-1);
204        return false; // skip non-valid files
205    }
206
207    //check ACL for namespace (we have no ACL for mediafiles)
208    $info['perm'] = auth_quickaclcheck(getNS($info['id']).':*');
209    if (empty($opts['skipacl']) && $info['perm'] < AUTH_READ) {
210        return false;
211    }
212
213    //check pattern filter
214    if (!empty($opts['pattern']) && !@preg_match($opts['pattern'], $info['id'])) {
215        return false;
216    }
217
218    $info['file']     = \dokuwiki\Utf8\PhpString::basename($file);
219    $info['size']     = filesize($base.'/'.$file);
220    $info['mtime']    = filemtime($base.'/'.$file);
221    $info['writable'] = is_writable($base.'/'.$file);
222    if (preg_match("/\.(jpe?g|gif|png)$/", $file)) {
223        $info['isimg'] = true;
224        $info['meta']  = new JpegMeta($base.'/'.$file);
225    } else {
226        $info['isimg'] = false;
227    }
228    if (!empty($opts['hash'])) {
229        $info['hash'] = md5(io_readFile(mediaFN($info['id']), false));
230    }
231
232    $data[] = $info;
233
234    return false;
235}
236
237/**
238 * This function just lists documents (for RSS namespace export)
239 *
240 * @author  Andreas Gohr <andi@splitbrain.org>
241 *
242 * @param array $data
243 * @param string $base
244 * @param string $file
245 * @param string $type
246 * @param integer $lvl
247 * @param array $opts
248 *
249 * @return bool
250 */
251function search_list(&$data, $base, $file, $type, $lvl, $opts)
252{
253    //we do nothing with directories
254    if ($type == 'd') return false;
255    //only search txt files
256    if (substr($file, -4) == '.txt') {
257        //check ACL
258        $id = pathID($file);
259        if (auth_quickaclcheck($id) < AUTH_READ) {
260            return false;
261        }
262        $data[]['id'] = $id;
263    }
264    return false;
265}
266
267/**
268 * Quicksearch for searching matching pagenames
269 *
270 * $opts['query'] is the search query
271 *
272 * @author  Andreas Gohr <andi@splitbrain.org>
273 *
274 * @param array $data
275 * @param string $base
276 * @param string $file
277 * @param string $type
278 * @param integer $lvl
279 * @param array $opts
280 *
281 * @return bool
282 */
283function search_pagename(&$data, $base, $file, $type, $lvl, $opts)
284{
285    //we do nothing with directories
286    if ($type == 'd') return true;
287    //only search txt files
288    if (substr($file, -4) != '.txt') return true;
289
290    //simple stringmatching
291    if (!empty($opts['query'])) {
292        if (strpos($file, $opts['query']) !== false) {
293            //check ACL
294            $id = pathID($file);
295            if (auth_quickaclcheck($id) < AUTH_READ) {
296                return false;
297            }
298            $data[]['id'] = $id;
299        }
300    }
301    return true;
302}
303
304/**
305 * Just lists all documents
306 *
307 * $opts['depth']   recursion level, 0 for all
308 * $opts['hash']    do md5 sum of content?
309 * $opts['skipacl'] list everything regardless of ACL
310 *
311 * @author  Andreas Gohr <andi@splitbrain.org>
312 *
313 * @param array $data
314 * @param string $base
315 * @param string $file
316 * @param string $type
317 * @param integer $lvl
318 * @param array $opts
319 *
320 * @return bool
321 */
322function search_allpages(&$data, $base, $file, $type, $lvl, $opts)
323{
324    if (isset($opts['depth']) && $opts['depth']) {
325        $parts = explode('/',ltrim($file, '/'));
326        if (($type == 'd' && count($parts) >= $opts['depth'])
327            || ($type != 'd' && count($parts) > $opts['depth'])
328        ){
329            return false; // depth reached
330        }
331    }
332
333    //we do nothing with directories
334    if ($type == 'd') {
335        return true;
336    }
337
338    //only search txt files
339    if (substr($file, -4) != '.txt') return true;
340
341    $item = array();
342    $item['id']   = pathID($file);
343    if (empty($opts['skipacl']) && auth_quickaclcheck($item['id']) < AUTH_READ) {
344        return false;
345    }
346
347    $item['rev']   = filemtime($base.'/'.$file);
348    $item['mtime'] = $item['rev'];
349    $item['size']  = filesize($base.'/'.$file);
350    if (!empty($opts['hash'])) {
351        $item['hash'] = md5(trim(rawWiki($item['id'])));
352    }
353
354    $data[] = $item;
355    return true;
356}
357
358/* ------------- helper functions below -------------- */
359
360/**
361 * fulltext sort
362 *
363 * Callback sort function for use with usort to sort the data
364 * structure created by search_fulltext. Sorts descending by count
365 *
366 * @author  Andreas Gohr <andi@splitbrain.org>
367 *
368 * @param array $a
369 * @param array $b
370 *
371 * @return int
372 */
373function sort_search_fulltext($a, $b)
374{
375    if ($a['count'] > $b['count']) {
376        return -1;
377    } elseif ($a['count'] < $b['count']) {
378        return 1;
379    } else {
380        return strcmp($a['id'], $b['id']);
381    }
382}
383
384/**
385 * translates a document path to an ID
386 *
387 * @author  Andreas Gohr <andi@splitbrain.org>
388 * @todo    move to pageutils
389 *
390 * @param string $path
391 * @param bool $keeptxt
392 *
393 * @return mixed|string
394 */
395function pathID($path, $keeptxt=false)
396{
397    $id = utf8_decodeFN($path);
398    $id = str_replace('/', ':', $id);
399    if (!$keeptxt) $id = preg_replace('#\.txt$#', '', $id);
400    $id = trim($id, ':');
401    return $id;
402}
403
404
405/**
406 * This is a very universal callback for the search() function, replacing
407 * many of the former individual functions at the cost of a more complex
408 * setup.
409 *
410 * How the function behaves, depends on the options passed in the $opts
411 * array, where the following settings can be used.
412 *
413 * depth      int     recursion depth. 0 for unlimited                       (default: 0)
414 * keeptxt    bool    keep .txt extension for IDs                            (default: false)
415 * listfiles  bool    include files in listing                               (default: false)
416 * listdirs   bool    include namespaces in listing                          (default: false)
417 * pagesonly  bool    restrict files to pages                                (default: false)
418 * skipacl    bool    do not check for READ permission                       (default: false)
419 * sneakyacl  bool    don't recurse into nonreadable dirs                    (default: false)
420 * hash       bool    create MD5 hash for files                              (default: false)
421 * meta       bool    return file metadata                                   (default: false)
422 * filematch  string  match files against this regexp                        (default: '', so accept everything)
423 * idmatch    string  match full ID against this regexp                      (default: '', so accept everything)
424 * dirmatch   string  match directory against this regexp when adding        (default: '', so accept everything)
425 * nsmatch    string  match namespace against this regexp when adding        (default: '', so accept everything)
426 * recmatch   string  match directory against this regexp when recursing     (default: '', so accept everything)
427 * showmsg    bool    warn about non-ID files                                (default: false)
428 * showhidden bool    show hidden files(e.g. by hidepages config) too        (default: false)
429 * firsthead  bool    return first heading for pages                         (default: false)
430 *
431 * @param array &$data  - Reference to the result data structure
432 * @param string $base  - Base usually $conf['datadir']
433 * @param string $file  - current file or directory relative to $base
434 * @param string $type  - Type either 'd' for directory or 'f' for file
435 * @param int    $lvl   - Current recursion depht
436 * @param array  $opts  - option array as given to search()
437 * @return bool if this directory should be traversed (true) or not (false)
438 *              return value is ignored for files
439 *
440 * @author Andreas Gohr <gohr@cosmocode.de>
441 */
442function search_universal(&$data, $base, $file, $type, $lvl, $opts)
443{
444    $item   = array();
445    $return = true;
446
447    // get ID and check if it is a valid one
448    $item['id'] = pathID($file, ($type == 'd' || !empty($opts['keeptxt'])));
449    if ($item['id'] != cleanID($item['id'])){
450        if (!empty($opts['showmsg'])) {
451            msg(hsc($item['id']).' is not a valid file name for DokuWiki - skipped',-1);
452        }
453        return false; // skip non-valid files
454    }
455    $item['ns']  = getNS($item['id']);
456
457    if ($type == 'd') {
458        // decide if to recursion into this directory is wanted
459        if (empty($opts['depth'])) {
460            $return = true; // recurse forever
461        } else {
462            $depth = substr_count($file,'/');
463            if ($depth >= $opts['depth']) {
464                $return = false; // depth reached
465            } else {
466                $return = true;
467            }
468        }
469
470        if ($return) {
471            $match = empty($opts['recmatch']) || preg_match('/'.$opts['recmatch'].'/', $file);
472            if (!$match) {
473                return false; // doesn't match
474            }
475        }
476    }
477
478    // check ACL
479    if (empty($opts['skipacl'])) {
480        if ($type == 'd') {
481            $item['perm'] = auth_quickaclcheck($item['id'].':*');
482        } else {
483            $item['perm'] = auth_quickaclcheck($item['id']); //FIXME check namespace for media files
484        }
485    } else {
486        $item['perm'] = AUTH_DELETE;
487    }
488
489    // are we done here maybe?
490    if ($type == 'd') {
491        if (empty($opts['listdirs'])) return $return;
492        //neither list nor recurse forbidden items:
493        if (empty($opts['skipacl']) && !empty($opts['sneakyacl']) && $item['perm'] < AUTH_READ) return false;
494        if (!empty($opts['dirmatch']) && !preg_match('/'.$opts['dirmatch'].'/', $file)) return $return;
495        if (!empty($opts['nsmatch']) && !preg_match('/'.$opts['nsmatch'].'/', $item['ns'])) return $return;
496    } else {
497        if (empty($opts['listfiles'])) return $return;
498        if (empty($opts['skipacl']) && $item['perm'] < AUTH_READ) return $return;
499        if (!empty($opts['pagesonly']) && (substr($file, -4) != '.txt')) return $return;
500        if (empty($opts['showhidden']) && isHiddenPage($item['id'])) return $return;
501        if (!empty($opts['filematch']) && !preg_match('/'.$opts['filematch'].'/', $file)) return $return;
502        if (!empty($opts['idmatch']) && !preg_match('/'.$opts['idmatch'].'/', $item['id'])) return $return;
503    }
504
505    // still here? prepare the item
506    $item['type']  = $type;
507    $item['level'] = $lvl;
508    $item['open']  = $return;
509
510    if (!empty($opts['meta'])) {
511        $item['file']       = \dokuwiki\Utf8\PhpString::basename($file);
512        $item['size']       = filesize($base.'/'.$file);
513        $item['mtime']      = filemtime($base.'/'.$file);
514        $item['rev']        = $item['mtime'];
515        $item['writable']   = is_writable($base.'/'.$file);
516        $item['executable'] = is_executable($base.'/'.$file);
517    }
518
519    if ($type == 'f') {
520        if (!empty($opts['hash'])) $item['hash'] = md5(io_readFile($base.'/'.$file, false));
521        if (!empty($opts['firsthead'])) {
522            $item['title'] = p_get_first_heading($item['id'], METADATA_DONT_RENDER);
523        }
524    }
525
526    // finally add the item
527    $data[] = $item;
528    return $return;
529}
530
531//Setup VIM: ex: et ts=4 :
532