xref: /dokuwiki/inc/search.php (revision b54f94e00cd0f1a818dd79fb2ce3bca7117e243e)
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  if($type=='d' && auth_quickaclcheck($id.':') < AUTH_READ){
160	  return false;
161  }
162
163  //check hidden
164  if(isHiddenPage($id)){
165    return false;
166  }
167
168  //check ACL
169  if($type=='f' && auth_quickaclcheck($id) < AUTH_READ){
170    return false;
171  }
172
173  $data[]=array( 'id'    => $id,
174                 'type'  => $type,
175                 'level' => $lvl,
176                 'open'  => $return );
177  return $return;
178}
179
180/**
181 * List all namespaces
182 *
183 * @author  Andreas Gohr <andi@splitbrain.org>
184 */
185function search_namespaces(&$data,$base,$file,$type,$lvl,$opts){
186  if($type == 'f') return true; //nothing to do on files
187
188  $id = pathID($file);
189  $data[]=array( 'id'    => $id,
190                 'type'  => $type,
191                 'level' => $lvl );
192  return true;
193}
194
195/**
196 * List all mediafiles in a namespace
197 *
198 * @author  Andreas Gohr <andi@splitbrain.org>
199 */
200function search_media(&$data,$base,$file,$type,$lvl,$opts){
201  //we do nothing with directories
202  if($type == 'd') return false;
203
204  $info         = array();
205  $info['id']   = pathID($file,true);
206
207  //check ACL for namespace (we have no ACL for mediafiles)
208  if(auth_quickaclcheck(getNS($info['id']).':*') < AUTH_READ){
209    return false;
210  }
211
212  $info['file'] = basename($file);
213  $info['size'] = filesize($base.'/'.$file);
214  $info['mtime'] = filemtime($base.'/'.$file);
215  $info['writable'] = is_writable($base.'/'.$file);
216  if(preg_match("/\.(jpe?g|gif|png)$/",$file)){
217    $info['isimg'] = true;
218    require_once(DOKU_INC.'inc/JpegMeta.php');
219    $info['meta']  = new JpegMeta($base.'/'.$file);
220  }else{
221    $info['isimg'] = false;
222  }
223  $data[] = $info;
224
225  return false;
226}
227
228/**
229 * This function just lists documents (for RSS namespace export)
230 *
231 * @author  Andreas Gohr <andi@splitbrain.org>
232 */
233function search_list(&$data,$base,$file,$type,$lvl,$opts){
234  //we do nothing with directories
235  if($type == 'd') return false;
236  if(preg_match('#\.txt$#',$file)){
237    //check ACL
238    $id = pathID($file);
239    if(auth_quickaclcheck($id) < AUTH_READ){
240      return false;
241    }
242    $data[]['id'] = $id;;
243  }
244  return false;
245}
246
247/**
248 * Quicksearch for searching matching pagenames
249 *
250 * $opts['query'] is the search query
251 *
252 * @author  Andreas Gohr <andi@splitbrain.org>
253 */
254function search_pagename(&$data,$base,$file,$type,$lvl,$opts){
255  //we do nothing with directories
256  if($type == 'd') return true;
257  //only search txt files
258  if(!preg_match('#\.txt$#',$file)) return true;
259
260  //simple stringmatching
261  if (!empty($opts['query'])){
262    if(strpos($file,$opts['query']) !== false){
263      //check ACL
264      $id = pathID($file);
265      if(auth_quickaclcheck($id) < AUTH_READ){
266        return false;
267      }
268      $data[]['id'] = $id;
269    }
270  }
271  return true;
272}
273
274/**
275 * Just lists all documents
276 *
277 * @author  Andreas Gohr <andi@splitbrain.org>
278 */
279function search_allpages(&$data,$base,$file,$type,$lvl,$opts){
280  //we do nothing with directories
281  if($type == 'd') return true;
282  //only search txt files
283  if(!preg_match('#\.txt$#',$file)) return true;
284
285  $data[]['id'] = pathID($file);
286  return true;
287}
288
289/**
290 * Search for backlinks to a given page
291 *
292 * $opts['ns']    namespace of the page
293 * $opts['name']  name of the page without namespace
294 *
295 * @author  Andreas Gohr <andi@splitbrain.org>
296 * @deprecated Replaced by ft_backlinks()
297 */
298function search_backlinks(&$data,$base,$file,$type,$lvl,$opts){
299  //we do nothing with directories
300  if($type == 'd') return true;;
301  //only search txt files
302  if(!preg_match('#\.txt$#',$file)) return true;;
303
304  //absolute search id
305  $sid = cleanID($opts['ns'].':'.$opts['name']);
306
307  //current id and namespace
308  $cid = pathID($file);
309  $cns = getNS($cid);
310
311  //check ACL
312  if(auth_quickaclcheck($cid) < AUTH_READ){
313    return false;
314  }
315
316  //fetch instructions
317  require_once(DOKU_INC.'inc/parserutils.php');
318  $instructions = p_cached_instructions($base.$file,true);
319  if(is_null($instructions)) return false;
320
321  //check all links for match
322  foreach($instructions as $ins){
323    if($ins[0] == 'internallink' || ($conf['camelcase'] && $ins[0] == 'camelcaselink') ){
324      $mid = $ins[1][0];
325      resolve_pageid($cns,$mid,$exists); //exists is not used
326      if($mid == $sid){
327        //we have a match - finish
328        $data[]['id'] = $cid;
329        break;
330      }
331    }
332  }
333
334  return false;
335}
336
337/**
338 * Fulltextsearch
339 *
340 * $opts['query'] is the search query
341 *
342 * @author  Andreas Gohr <andi@splitbrain.org>
343 * @deprecated - fulltext indexer is used instead
344 */
345function search_fulltext(&$data,$base,$file,$type,$lvl,$opts){
346  //we do nothing with directories
347  if($type == 'd') return true;;
348  //only search txt files
349  if(!preg_match('#\.txt$#',$file)) return true;;
350
351  //check ACL
352  $id = pathID($file);
353  if(auth_quickaclcheck($id) < AUTH_READ){
354    return false;
355  }
356
357  //create regexp from queries
358  $poswords = array();
359  $negwords = array();
360  $qpreg = preg_split('/\s+/',$opts['query']);
361
362  foreach($qpreg as $word){
363    switch(substr($word,0,1)){
364      case '-':
365        if(strlen($word) > 1){  // catch single '-'
366          array_push($negwords,preg_quote(substr($word,1),'#'));
367        }
368        break;
369      case '+':
370        if(strlen($word) > 1){  // catch single '+'
371          array_push($poswords,preg_quote(substr($word,1),'#'));
372        }
373        break;
374      default:
375        array_push($poswords,preg_quote($word,'#'));
376        break;
377    }
378  }
379
380  // a search without any posword is useless
381  if (!count($poswords)) return true;
382
383  $reg  = '^(?=.*?'.join(')(?=.*?',$poswords).')';
384  $reg .= count($negwords) ? '((?!'.join('|',$negwords).').)*$' : '.*$';
385  search_regex($data,$base,$file,$reg,$poswords);
386  return true;
387}
388
389/**
390 * Reference search
391 * This fuction searches for existing references to a given media file
392 * and returns an array with the found pages. It doesn't pay any
393 * attention to ACL permissions to find every reference. The caller
394 * must check if the user has the appropriate rights to see the found
395 * page and eventually have to prevent the result from displaying.
396 *
397 * @param array  $data Reference to the result data structure
398 * @param string $base Base usually $conf['datadir']
399 * @param string $file current file or directory relative to $base
400 * @param char   $type Type either 'd' for directory or 'f' for file
401 * @param int    $lvl  Current recursion depht
402 * @param mixed  $opts option array as given to search()
403 *
404 * $opts['query'] is the demanded media file name
405 *
406 * @author  Andreas Gohr <andi@splitbrain.org>
407 * @author  Matthias Grimm <matthiasgrimm@users.sourceforge.net>
408 */
409function search_reference(&$data,$base,$file,$type,$lvl,$opts){
410  global $conf;
411
412  //we do nothing with directories
413  if($type == 'd') return true;
414
415  //only search txt files
416  if(!preg_match('#\.txt$#',$file)) return true;
417
418  //we finish after 'cnt' references found. The return value
419  //'false' will skip subdirectories to speed search up.
420  $cnt = $conf['refshow'] > 0 ? $conf['refshow'] : 1;
421  if(count($data) >= $cnt) return false;
422
423  $reg = '\{\{ *\:?'.$opts['query'].' *(\|.*)?\}\}';
424  search_regex($data,$base,$file,$reg,array($opts['query']));
425  return true;
426}
427
428/* ------------- helper functions below -------------- */
429
430/**
431 * fulltext search helper
432 * searches a text file with a given regular expression
433 * no ACL checks are performed. This have to be done by
434 * the caller if necessary.
435 *
436 * @param array  $data  reference to array for results
437 * @param string $base  base directory
438 * @param string $file  file name to search in
439 * @param string $reg   regular expression to search for
440 * @param array  $words words that should be marked in the results
441 *
442 * @author  Andreas Gohr <andi@splitbrain.org>
443 * @author  Matthias Grimm <matthiasgrimm@users.sourceforge.net>
444 *
445 * @deprecated - fulltext indexer is used instead
446 */
447function search_regex(&$data,$base,$file,$reg,$words){
448
449  //get text
450  $text = io_readfile($base.'/'.$file);
451  //lowercase text (u modifier does not help with case)
452  $lctext = utf8_strtolower($text);
453
454  //do the fulltext search
455  $matches = array();
456  if($cnt = preg_match_all('#'.$reg.'#usi',$lctext,$matches)){
457    //this is not the best way for snippet generation but the fastest I could find
458    $q = $words[0];  //use first word for snippet creation
459    $p = utf8_strpos($lctext,$q);
460    $f = $p - 100;
461    $l = utf8_strlen($q) + 200;
462    if($f < 0) $f = 0;
463    $snippet = '<span class="search_sep"> ... </span>'.
464               htmlspecialchars(utf8_substr($text,$f,$l)).
465               '<span class="search_sep"> ... </span>';
466    $mark    = '('.join('|', $words).')';
467    $snippet = preg_replace('#'.$mark.'#si','<span class="search_hit">\\1</span>',$snippet);
468
469    $data[] = array(
470      'id'       => pathID($file),
471      'count'    => preg_match_all('#'.$mark.'#usi',$lctext,$matches),
472      'poswords' => join(' ',$words),
473      'snippet'  => $snippet,
474    );
475  }
476
477  return true;
478}
479
480
481/**
482 * fulltext sort
483 *
484 * Callback sort function for use with usort to sort the data
485 * structure created by search_fulltext. Sorts descending by count
486 *
487 * @author  Andreas Gohr <andi@splitbrain.org>
488 */
489function sort_search_fulltext($a,$b){
490  if($a['count'] > $b['count']){
491    return -1;
492  }elseif($a['count'] < $b['count']){
493    return 1;
494  }else{
495    return strcmp($a['id'],$b['id']);
496  }
497}
498
499/**
500 * translates a document path to an ID
501 *
502 * @author  Andreas Gohr <andi@splitbrain.org>
503 * @todo    move to pageutils
504 */
505function pathID($path,$keeptxt=false){
506  $id = utf8_decodeFN($path);
507  $id = str_replace('/',':',$id);
508  if(!$keeptxt) $id = preg_replace('#\.txt$#','',$id);
509  $id = preg_replace('#^:+#','',$id);
510  $id = preg_replace('#:+$#','',$id);
511  return $id;
512}
513
514
515//Setup VIM: ex: et ts=2 enc=utf-8 :
516