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