xref: /dokuwiki/inc/search.php (revision cde6a01b90b199cd9d42a8e23a61d467992b6d67)
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  if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../').'/');
10  require_once(DOKU_INC.'inc/common.php');
11
12/**
13 * recurse direcory
14 *
15 * This function recurses into a given base directory
16 * and calls the supplied function for each file and directory
17 *
18 * @param   array ref $data The results of the search are stored here
19 * @param   string    $base Where to start the search
20 * @param   callback  $func Callback (function name or arayy with object,method)
21 * @param   string    $dir  Current directory beyond $base
22 * @param   int       $lvl  Recursion Level
23 * @author  Andreas Gohr <andi@splitbrain.org>
24 */
25function search(&$data,$base,$func,$opts,$dir='',$lvl=1){
26  $dirs   = array();
27  $files  = array();
28
29  //read in directories and files
30  $dh = @opendir($base.'/'.$dir);
31  if(!$dh) return;
32  while(($file = readdir($dh)) !== false){
33    if(preg_match('/^[\._]/',$file)) continue; //skip hidden files and upper dirs
34    if(is_dir($base.'/'.$dir.'/'.$file)){
35      $dirs[] = $dir.'/'.$file;
36      continue;
37    }elseif(substr($file,-5) == '.lock'){
38      //skip lockfiles
39      continue;
40    }
41    $files[] = $dir.'/'.$file;
42  }
43  closedir($dh);
44  sort($files);
45  sort($dirs);
46
47  //give directories to userfunction then recurse
48  foreach($dirs as $dir){
49    if (search_callback($func,$data,$base,$dir,'d',$lvl,$opts)){
50      search($data,$base,$func,$opts,$dir,$lvl+1);
51    }
52  }
53  //now handle the files
54  foreach($files as $file){
55    search_callback($func,$data,$base,$file,'f',$lvl,$opts);
56  }
57}
58
59/**
60 * Used to run the a user callback
61 *
62 * Makes sure the $data array is passed by reference (unlike when using
63 * call_user_func())
64 *
65 * @todo If this can be generalized it may be useful elsewhere in the code
66 * @author Andreas Gohr <andi@splitbrain.org>
67 */
68function search_callback($func,&$data,$base,$file,$type,$lvl,$opts){
69  if(is_array($func)){
70    if(is_object($func[0])){
71      // instanciated object
72      return $func[0]->$func[1]($data,$base,$file,$type,$lvl,$opts);
73    }else{
74      // static call
75      $f = $func[0].'::'.$func[1];
76      return $f($data,$base,$file,$type,$lvl,$opts);
77    }
78  }
79  // simple function call
80  return $func($data,$base,$file,$type,$lvl,$opts);
81}
82
83/**
84 * The following functions are userfunctions to use with the search
85 * function above. This function is called for every found file or
86 * directory. When a directory is given to the function it has to
87 * decide if this directory should be traversed (true) or not (false)
88 * The function has to accept the following parameters:
89 *
90 * &$data - Reference to the result data structure
91 * $base  - Base usually $conf['datadir']
92 * $file  - current file or directory relative to $base
93 * $type  - Type either 'd' for directory or 'f' for file
94 * $lvl   - Current recursion depht
95 * $opts  - option array as given to search()
96 *
97 * return values for files are ignored
98 *
99 * All functions should check the ACL for document READ rights
100 * namespaces (directories) are NOT checked as this would break
101 * the recursion (You can have an nonreadable dir over a readable
102 * one deeper nested)
103 */
104
105/**
106 * Searches for pages beginning with the given query
107 *
108 * @author Andreas Gohr <andi@splitbrain.org>
109 */
110function search_qsearch(&$data,$base,$file,$type,$lvl,$opts){
111  $item = array();
112
113  if($type == 'd'){
114    return false; //no handling yet
115  }
116
117  //get id
118  $id = pathID($file);
119
120  //check if it matches the query
121  if(!preg_match('/^'.preg_quote($opts['query'],'/').'/u',$id)){
122    return false;
123  }
124
125  //check ACL
126  if(auth_quickaclcheck($id) < AUTH_READ){
127    return false;
128  }
129
130  $data[]=array( 'id'    => $id,
131                 'type'  => $type,
132                 'level' => 1,
133                 'open'  => true);
134  return true;
135}
136
137/**
138 * Build the browsable index of pages
139 *
140 * $opts['ns'] is the current namespace
141 *
142 * @author  Andreas Gohr <andi@splitbrain.org>
143 */
144function search_index(&$data,$base,$file,$type,$lvl,$opts){
145  $return = true;
146
147  $item = array();
148
149  if($type == 'd' && !preg_match('#^'.$file.'(/|$)#','/'.$opts['ns'])){
150    //add but don't recurse
151    $return = false;
152  }elseif($type == 'f' && ($opts['nofiles'] || !preg_match('#\.txt$#',$file))){
153    //don't add
154    return false;
155  }
156
157  $id = pathID($file);
158
159  //check hidden
160  if(isHiddenPage($id)){
161    return false;
162  }
163
164  //check ACL
165  if($type=='f' && auth_quickaclcheck($id) < AUTH_READ){
166    return false;
167  }
168
169  $data[]=array( 'id'    => $id,
170                 'type'  => $type,
171                 'level' => $lvl,
172                 'open'  => $return );
173  return $return;
174}
175
176/**
177 * List all namespaces
178 *
179 * @author  Andreas Gohr <andi@splitbrain.org>
180 */
181function search_namespaces(&$data,$base,$file,$type,$lvl,$opts){
182  if($type == 'f') return true; //nothing to do on files
183
184  $id = pathID($file);
185  $data[]=array( 'id'    => $id,
186                 'type'  => $type,
187                 'level' => $lvl );
188  return true;
189}
190
191/**
192 * List all mediafiles in a namespace
193 *
194 * @author  Andreas Gohr <andi@splitbrain.org>
195 */
196function search_media(&$data,$base,$file,$type,$lvl,$opts){
197  //we do nothing with directories
198  if($type == 'd') return false;
199
200  $info         = array();
201  $info['id']   = pathID($file,true);
202
203  //check ACL for namespace (we have no ACL for mediafiles)
204  if(auth_quickaclcheck(getNS($info['id']).':*') < AUTH_READ){
205    return false;
206  }
207
208  $info['file'] = basename($file);
209  $info['size'] = filesize($base.'/'.$file);
210  $info['mtime'] = filemtime($base.'/'.$file);
211  $info['writable'] = is_writable($base.'/'.$file);
212  if(preg_match("/\.(jpe?g|gif|png)$/",$file)){
213    $info['isimg'] = true;
214    require_once(DOKU_INC.'inc/JpegMeta.php');
215    $info['meta']  = new JpegMeta($base.'/'.$file);
216  }else{
217    $info['isimg'] = false;
218  }
219  $data[] = $info;
220
221  return false;
222}
223
224/**
225 * This function just lists documents (for RSS namespace export)
226 *
227 * @author  Andreas Gohr <andi@splitbrain.org>
228 */
229function search_list(&$data,$base,$file,$type,$lvl,$opts){
230  //we do nothing with directories
231  if($type == 'd') return false;
232  if(preg_match('#\.txt$#',$file)){
233    //check ACL
234    $id = pathID($file);
235    if(auth_quickaclcheck($id) < AUTH_READ){
236      return false;
237    }
238    $data[]['id'] = $id;;
239  }
240  return false;
241}
242
243/**
244 * Quicksearch for searching matching pagenames
245 *
246 * $opts['query'] is the search query
247 *
248 * @author  Andreas Gohr <andi@splitbrain.org>
249 */
250function search_pagename(&$data,$base,$file,$type,$lvl,$opts){
251  //we do nothing with directories
252  if($type == 'd') return true;
253  //only search txt files
254  if(!preg_match('#\.txt$#',$file)) return true;
255
256  //simple stringmatching
257  if (!empty($opts['query'])){
258    if(strpos($file,$opts['query']) !== false){
259      //check ACL
260      $id = pathID($file);
261      if(auth_quickaclcheck($id) < AUTH_READ){
262        return false;
263      }
264      $data[]['id'] = $id;
265    }
266  }
267  return true;
268}
269
270/**
271 * Just lists all documents
272 *
273 * @author  Andreas Gohr <andi@splitbrain.org>
274 */
275function search_allpages(&$data,$base,$file,$type,$lvl,$opts){
276  //we do nothing with directories
277  if($type == 'd') return true;
278  //only search txt files
279  if(!preg_match('#\.txt$#',$file)) return true;
280
281  $data[]['id'] = pathID($file);
282  return true;
283}
284
285/**
286 * Search for backlinks to a given page
287 *
288 * $opts['ns']    namespace of the page
289 * $opts['name']  name of the page without namespace
290 *
291 * @author  Andreas Gohr <andi@splitbrain.org>
292 * @deprecated Replaced by ft_backlinks()
293 */
294function search_backlinks(&$data,$base,$file,$type,$lvl,$opts){
295  //we do nothing with directories
296  if($type == 'd') return true;;
297  //only search txt files
298  if(!preg_match('#\.txt$#',$file)) return true;;
299
300  //absolute search id
301  $sid = cleanID($opts['ns'].':'.$opts['name']);
302
303  //current id and namespace
304  $cid = pathID($file);
305  $cns = getNS($cid);
306
307  //check ACL
308  if(auth_quickaclcheck($cid) < AUTH_READ){
309    return false;
310  }
311
312  //fetch instructions
313  require_once(DOKU_INC.'inc/parserutils.php');
314  $instructions = p_cached_instructions($base.$file,true);
315  if(is_null($instructions)) return false;
316
317  //check all links for match
318  foreach($instructions as $ins){
319    if($ins[0] == 'internallink' || ($conf['camelcase'] && $ins[0] == 'camelcaselink') ){
320      $mid = $ins[1][0];
321      resolve_pageid($cns,$mid,$exists); //exists is not used
322      if($mid == $sid){
323        //we have a match - finish
324        $data[]['id'] = $cid;
325        break;
326      }
327    }
328  }
329
330  return false;
331}
332
333/**
334 * Fulltextsearch
335 *
336 * $opts['query'] is the search query
337 *
338 * @author  Andreas Gohr <andi@splitbrain.org>
339 * @deprecated - fulltext indexer is used instead
340 */
341function search_fulltext(&$data,$base,$file,$type,$lvl,$opts){
342  //we do nothing with directories
343  if($type == 'd') return true;;
344  //only search txt files
345  if(!preg_match('#\.txt$#',$file)) return true;;
346
347  //check ACL
348  $id = pathID($file);
349  if(auth_quickaclcheck($id) < AUTH_READ){
350    return false;
351  }
352
353  //create regexp from queries
354  $poswords = array();
355  $negwords = array();
356  $qpreg = preg_split('/\s+/',$opts['query']);
357
358  foreach($qpreg as $word){
359    switch(substr($word,0,1)){
360      case '-':
361        if(strlen($word) > 1){  // catch single '-'
362          array_push($negwords,preg_quote(substr($word,1),'#'));
363        }
364        break;
365      case '+':
366        if(strlen($word) > 1){  // catch single '+'
367          array_push($poswords,preg_quote(substr($word,1),'#'));
368        }
369        break;
370      default:
371        array_push($poswords,preg_quote($word,'#'));
372        break;
373    }
374  }
375
376  // a search without any posword is useless
377  if (!count($poswords)) return true;
378
379  $reg  = '^(?=.*?'.join(')(?=.*?',$poswords).')';
380  $reg .= count($negwords) ? '((?!'.join('|',$negwords).').)*$' : '.*$';
381  search_regex($data,$base,$file,$reg,$poswords);
382  return true;
383}
384
385/**
386 * Reference search
387 * This fuction searches for existing references to a given media file
388 * and returns an array with the found pages. It doesn't pay any
389 * attention to ACL permissions to find every reference. The caller
390 * must check if the user has the appropriate rights to see the found
391 * page and eventually have to prevent the result from displaying.
392 *
393 * @param array  $data Reference to the result data structure
394 * @param string $base Base usually $conf['datadir']
395 * @param string $file current file or directory relative to $base
396 * @param char   $type Type either 'd' for directory or 'f' for file
397 * @param int    $lvl  Current recursion depht
398 * @param mixed  $opts option array as given to search()
399 *
400 * $opts['query'] is the demanded media file name
401 *
402 * @author  Andreas Gohr <andi@splitbrain.org>
403 * @author  Matthias Grimm <matthiasgrimm@users.sourceforge.net>
404 */
405function search_reference(&$data,$base,$file,$type,$lvl,$opts){
406  global $conf;
407
408  //we do nothing with directories
409  if($type == 'd') return true;
410
411  //only search txt files
412  if(!preg_match('#\.txt$#',$file)) return true;
413
414  //we finish after 'cnt' references found. The return value
415  //'false' will skip subdirectories to speed search up.
416  $cnt = $conf['refshow'] > 0 ? $conf['refshow'] : 1;
417  if(count($data) >= $cnt) return false;
418
419  $reg = '\{\{ *\:?'.$opts['query'].' *(\|.*)?\}\}';
420  search_regex($data,$base,$file,$reg,array($opts['query']));
421  return true;
422}
423
424/* ------------- helper functions below -------------- */
425
426/**
427 * fulltext search helper
428 * searches a text file with a given regular expression
429 * no ACL checks are performed. This have to be done by
430 * the caller if necessary.
431 *
432 * @param array  $data  reference to array for results
433 * @param string $base  base directory
434 * @param string $file  file name to search in
435 * @param string $reg   regular expression to search for
436 * @param array  $words words that should be marked in the results
437 *
438 * @author  Andreas Gohr <andi@splitbrain.org>
439 * @author  Matthias Grimm <matthiasgrimm@users.sourceforge.net>
440 *
441 * @deprecated - fulltext indexer is used instead
442 */
443function search_regex(&$data,$base,$file,$reg,$words){
444
445  //get text
446  $text = io_readfile($base.'/'.$file);
447  //lowercase text (u modifier does not help with case)
448  $lctext = utf8_strtolower($text);
449
450  //do the fulltext search
451  $matches = array();
452  if($cnt = preg_match_all('#'.$reg.'#usi',$lctext,$matches)){
453    //this is not the best way for snippet generation but the fastest I could find
454    $q = $words[0];  //use first word for snippet creation
455    $p = utf8_strpos($lctext,$q);
456    $f = $p - 100;
457    $l = utf8_strlen($q) + 200;
458    if($f < 0) $f = 0;
459    $snippet = '<span class="search_sep"> ... </span>'.
460               htmlspecialchars(utf8_substr($text,$f,$l)).
461               '<span class="search_sep"> ... </span>';
462    $mark    = '('.join('|', $words).')';
463    $snippet = preg_replace('#'.$mark.'#si','<span class="search_hit">\\1</span>',$snippet);
464
465    $data[] = array(
466      'id'       => pathID($file),
467      'count'    => preg_match_all('#'.$mark.'#usi',$lctext,$matches),
468      'poswords' => join(' ',$words),
469      'snippet'  => $snippet,
470    );
471  }
472
473  return true;
474}
475
476
477/**
478 * fulltext sort
479 *
480 * Callback sort function for use with usort to sort the data
481 * structure created by search_fulltext. Sorts descending by count
482 *
483 * @author  Andreas Gohr <andi@splitbrain.org>
484 */
485function sort_search_fulltext($a,$b){
486  if($a['count'] > $b['count']){
487    return -1;
488  }elseif($a['count'] < $b['count']){
489    return 1;
490  }else{
491    return strcmp($a['id'],$b['id']);
492  }
493}
494
495/**
496 * translates a document path to an ID
497 *
498 * @author  Andreas Gohr <andi@splitbrain.org>
499 * @todo    move to pageutils
500 */
501function pathID($path,$keeptxt=false){
502  $id = utf8_decodeFN($path);
503  $id = str_replace('/',':',$id);
504  if(!$keeptxt) $id = preg_replace('#\.txt$#','',$id);
505  $id = preg_replace('#^:+#','',$id);
506  $id = preg_replace('#:+$#','',$id);
507  return $id;
508}
509
510
511//Setup VIM: ex: et ts=2 enc=utf-8 :
512