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