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