3 * DokuWiki search functions
5 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author Andreas Gohr <andi@splitbrain.org>
9 if(!defined('DOKU_INC')) die('meh.');
14 * This function recurses into a given base directory
15 * and calls the supplied function for each file and directory
17 * @param array ref $data The results of the search are stored here
18 * @param string $base Where to start the search
19 * @param callback $func Callback (function name or arayy with object,method)
20 * @param string $dir Current directory beyond $base
21 * @param int $lvl Recursion Level
22 * @author Andreas Gohr <andi@splitbrain.org>
24 function search(&$data,$base,$func,$opts,$dir='',$lvl=1,$sort=false){
29 //read in directories and files
30 $dh = @opendir($base.'/'.$dir);
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;
38 $files[] = $dir.'/'.$file;
39 $filepaths[] = $base.'/'.$dir.'/'.$file;
42 if ($sort == 'date') {
43 @array_multisort(array_map('filemtime', $filepaths), SORT_NUMERIC, SORT_DESC, $files);
49 //give directories to userfunction then recurse
50 foreach($dirs as $dir){
51 if (call_user_func_array($func, array(&$data,$base,$dir,'d',$lvl,$opts))){
52 search($data,$base,$func,$opts,$dir,$lvl+1);
55 //now handle the files
56 foreach($files as $file){
57 call_user_func_array($func, array(&$data,$base,$file,'f',$lvl,$opts));
62 * Wrapper around call_user_func_array.
66 function search_callback($func,&$data,$base,$file,$type,$lvl,$opts){
67 return call_user_func_array($func, array(&$data,$base,$file,$type,$lvl,$opts));
71 * The following functions are userfunctions to use with the search
72 * function above. This function is called for every found file or
73 * directory. When a directory is given to the function it has to
74 * decide if this directory should be traversed (true) or not (false)
75 * The function has to accept the following parameters:
77 * &$data - Reference to the result data structure
78 * $base - Base usually $conf['datadir']
79 * $file - current file or directory relative to $base
80 * $type - Type either 'd' for directory or 'f' for file
81 * $lvl - Current recursion depht
82 * $opts - option array as given to search()
84 * return values for files are ignored
86 * All functions should check the ACL for document READ rights
87 * namespaces (directories) are NOT checked (when sneaky_index is 0) as this
88 * would break the recursion (You can have an nonreadable dir over a readable
89 * one deeper nested) also make sure to check the file type (for example
90 * in case of lockfiles).
94 * Searches for pages beginning with the given query
96 * @author Andreas Gohr <andi@splitbrain.org>
98 function search_qsearch(&$data,$base,$file,$type,$lvl,$opts){
100 'idmatch' => '(^|:)'.preg_quote($opts['query'],'/').'/',
104 return search_universal($data,$base,$file,$type,$lvl,$opts);
108 * Build the browsable index of pages
110 * $opts['ns'] is the currently viewed namespace
112 * @author Andreas Gohr <andi@splitbrain.org>
114 function search_index(&$data,$base,$file,$type,$lvl,$opts){
119 'listfiles' => !$opts['nofiles'],
120 'sneakyacl' => $conf['sneaky_index'],
121 // Hacky, should rather use recmatch
122 'depth' => preg_match('#^'.preg_quote($file, '#').'(/|$)#','/'.$opts['ns']) ? 0 : -1
125 return search_universal($data, $base, $file, $type, $lvl, $opts);
129 * List all namespaces
131 * @author Andreas Gohr <andi@splitbrain.org>
133 function search_namespaces(&$data,$base,$file,$type,$lvl,$opts){
137 return search_universal($data,$base,$file,$type,$lvl,$opts);
141 * List all mediafiles in a namespace
143 * @author Andreas Gohr <andi@splitbrain.org>
145 function search_media(&$data,$base,$file,$type,$lvl,$opts){
147 //we do nothing with directories
149 if(!$opts['depth']) return true; // recurse forever
150 $depth = substr_count($file,'/');
151 if($depth >= $opts['depth']) return false; // depth reached
156 $info['id'] = pathID($file,true);
157 if($info['id'] != cleanID($info['id'])){
159 msg(hsc($info['id']).' is not a valid file name for DokuWiki - skipped',-1);
160 return false; // skip non-valid files
163 //check ACL for namespace (we have no ACL for mediafiles)
164 $info['perm'] = auth_quickaclcheck(getNS($info['id']).':*');
165 if(!$opts['skipacl'] && $info['perm'] < AUTH_READ){
169 //check pattern filter
170 if($opts['pattern'] && !@preg_match($opts['pattern'], $info['id'])){
174 $info['file'] = utf8_basename($file);
175 $info['size'] = filesize($base.'/'.$file);
176 $info['mtime'] = filemtime($base.'/'.$file);
177 $info['writable'] = is_writable($base.'/'.$file);
178 if(preg_match("/\.(jpe?g|gif|png)$/",$file)){
179 $info['isimg'] = true;
180 $info['meta'] = new JpegMeta($base.'/'.$file);
182 $info['isimg'] = false;
185 $info['hash'] = md5(io_readFile(mediaFN($info['id']),false));
194 * This function just lists documents (for RSS namespace export)
196 * @author Andreas Gohr <andi@splitbrain.org>
198 function search_list(&$data,$base,$file,$type,$lvl,$opts){
199 //we do nothing with directories
200 if($type == 'd') return false;
201 //only search txt files
202 if(substr($file,-4) == '.txt'){
205 if(auth_quickaclcheck($id) < AUTH_READ){
214 * Quicksearch for searching matching pagenames
216 * $opts['query'] is the search query
218 * @author Andreas Gohr <andi@splitbrain.org>
220 function search_pagename(&$data,$base,$file,$type,$lvl,$opts){
221 //we do nothing with directories
222 if($type == 'd') return true;
223 //only search txt files
224 if(substr($file,-4) != '.txt') return true;
226 //simple stringmatching
227 if (!empty($opts['query'])){
228 if(strpos($file,$opts['query']) !== false){
231 if(auth_quickaclcheck($id) < AUTH_READ){
241 * Just lists all documents
243 * $opts['depth'] recursion level, 0 for all
244 * $opts['hash'] do md5 sum of content?
245 * $opts['skipacl'] list everything regardless of ACL
247 * @author Andreas Gohr <andi@splitbrain.org>
249 function search_allpages(&$data,$base,$file,$type,$lvl,$opts){
250 //we do nothing with directories
252 if(!$opts['depth']) return true; // recurse forever
253 $parts = explode('/',ltrim($file,'/'));
254 if(count($parts) == $opts['depth']) return false; // depth reached
258 //only search txt files
259 if(substr($file,-4) != '.txt') return true;
261 $item['id'] = pathID($file);
262 if(!$opts['skipacl'] && auth_quickaclcheck($item['id']) < AUTH_READ){
266 $item['rev'] = filemtime($base.'/'.$file);
267 $item['mtime'] = $item['rev'];
268 $item['size'] = filesize($base.'/'.$file);
270 $item['hash'] = md5(trim(rawWiki($item['id'])));
278 * Search for backlinks to a given page
280 * $opts['ns'] namespace of the page
281 * $opts['name'] name of the page without namespace
283 * @author Andreas Gohr <andi@splitbrain.org>
284 * @deprecated Replaced by ft_backlinks()
286 function search_backlinks(&$data,$base,$file,$type,$lvl,$opts){
287 //we do nothing with directories
288 if($type == 'd') return true;
289 //only search txt files
290 if(substr($file,-4) != '.txt') return true;
293 $sid = cleanID($opts['ns'].':'.$opts['name']);
295 //current id and namespace
296 $cid = pathID($file);
300 if(auth_quickaclcheck($cid) < AUTH_READ){
305 $instructions = p_cached_instructions($base.$file,true);
306 if(is_null($instructions)) return false;
309 //check all links for match
310 foreach($instructions as $ins){
311 if($ins[0] == 'internallink' || ($conf['camelcase'] && $ins[0] == 'camelcaselink') ){
313 resolve_pageid($cns,$mid,$exists); //exists is not used
315 //we have a match - finish
316 $data[]['id'] = $cid;
328 * $opts['query'] is the search query
330 * @author Andreas Gohr <andi@splitbrain.org>
331 * @deprecated - fulltext indexer is used instead
333 function search_fulltext(&$data,$base,$file,$type,$lvl,$opts){
334 //we do nothing with directories
335 if($type == 'd') return true;
336 //only search txt files
337 if(substr($file,-4) != '.txt') return true;
341 if(auth_quickaclcheck($id) < AUTH_READ){
345 //create regexp from queries
348 $qpreg = preg_split('/\s+/',$opts['query']);
350 foreach($qpreg as $word){
351 switch(substr($word,0,1)){
353 if(strlen($word) > 1){ // catch single '-'
354 array_push($negwords,preg_quote(substr($word,1),'#'));
358 if(strlen($word) > 1){ // catch single '+'
359 array_push($poswords,preg_quote(substr($word,1),'#'));
363 array_push($poswords,preg_quote($word,'#'));
368 // a search without any posword is useless
369 if (!count($poswords)) return true;
371 $reg = '^(?=.*?'.join(')(?=.*?',$poswords).')';
372 $reg .= count($negwords) ? '((?!'.join('|',$negwords).').)*$' : '.*$';
373 search_regex($data,$base,$file,$reg,$poswords);
379 * This fuction searches for existing references to a given media file
380 * and returns an array with the found pages. It doesn't pay any
381 * attention to ACL permissions to find every reference. The caller
382 * must check if the user has the appropriate rights to see the found
383 * page and eventually have to prevent the result from displaying.
385 * @param array $data Reference to the result data structure
386 * @param string $base Base usually $conf['datadir']
387 * @param string $file current file or directory relative to $base
388 * @param char $type Type either 'd' for directory or 'f' for file
389 * @param int $lvl Current recursion depht
390 * @param mixed $opts option array as given to search()
392 * $opts['query'] is the demanded media file name
394 * @author Andreas Gohr <andi@splitbrain.org>
395 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
397 function search_reference(&$data,$base,$file,$type,$lvl,$opts){
400 //we do nothing with directories
401 if($type == 'd') return true;
403 //only search txt files
404 if(substr($file,-4) != '.txt') return true;
406 //we finish after 'cnt' references found. The return value
407 //'false' will skip subdirectories to speed search up.
408 $cnt = $conf['refshow'] > 0 ? $conf['refshow'] : 1;
409 if(count($data) >= $cnt) return false;
411 $reg = '\{\{ *\:?'.$opts['query'].' *(\|.*)?\}\}';
412 search_regex($data,$base,$file,$reg,array($opts['query']));
416 /* ------------- helper functions below -------------- */
419 * fulltext search helper
420 * searches a text file with a given regular expression
421 * no ACL checks are performed. This have to be done by
422 * the caller if necessary.
424 * @param array $data reference to array for results
425 * @param string $base base directory
426 * @param string $file file name to search in
427 * @param string $reg regular expression to search for
428 * @param array $words words that should be marked in the results
430 * @author Andreas Gohr <andi@splitbrain.org>
431 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
433 * @deprecated - fulltext indexer is used instead
435 function search_regex(&$data,$base,$file,$reg,$words){
438 $text = io_readfile($base.'/'.$file);
439 //lowercase text (u modifier does not help with case)
440 $lctext = utf8_strtolower($text);
442 //do the fulltext search
444 if($cnt = preg_match_all('#'.$reg.'#usi',$lctext,$matches)){
445 //this is not the best way for snippet generation but the fastest I could find
446 $q = $words[0]; //use first word for snippet creation
447 $p = utf8_strpos($lctext,$q);
449 $l = utf8_strlen($q) + 200;
451 $snippet = '<span class="search_sep"> ... </span>'.
452 htmlspecialchars(utf8_substr($text,$f,$l)).
453 '<span class="search_sep"> ... </span>';
454 $mark = '('.join('|', $words).')';
455 $snippet = preg_replace('#'.$mark.'#si','<strong class="search_hit">\\1</strong>',$snippet);
458 'id' => pathID($file),
459 'count' => preg_match_all('#'.$mark.'#usi',$lctext,$matches),
460 'poswords' => join(' ',$words),
461 'snippet' => $snippet,
472 * Callback sort function for use with usort to sort the data
473 * structure created by search_fulltext. Sorts descending by count
475 * @author Andreas Gohr <andi@splitbrain.org>
477 function sort_search_fulltext($a,$b){
478 if($a['count'] > $b['count']){
480 }elseif($a['count'] < $b['count']){
483 return strcmp($a['id'],$b['id']);
488 * translates a document path to an ID
490 * @author Andreas Gohr <andi@splitbrain.org>
491 * @todo move to pageutils
493 function pathID($path,$keeptxt=false){
494 $id = utf8_decodeFN($path);
495 $id = str_replace('/',':',$id);
496 if(!$keeptxt) $id = preg_replace('#\.txt$#','',$id);
497 $id = trim($id, ':');
503 * This is a very universal callback for the search() function, replacing
504 * many of the former individual functions at the cost of a more complex
507 * How the function behaves, depends on the options passed in the $opts
508 * array, where the following settings can be used.
510 * depth int recursion depth. 0 for unlimited
511 * keeptxt bool keep .txt extension for IDs
512 * listfiles bool include files in listing
513 * listdirs bool include namespaces in listing
514 * pagesonly bool restrict files to pages
515 * skipacl bool do not check for READ permission
516 * sneakyacl bool don't recurse into nonreadable dirs
517 * hash bool create MD5 hash for files
518 * meta bool return file metadata
519 * filematch string match files against this regexp
520 * idmatch string match full ID against this regexp
521 * dirmatch string match directory against this regexp when adding
522 * nsmatch string match namespace against this regexp when adding
523 * recmatch string match directory against this regexp when recursing
524 * showmsg bool warn about non-ID files
525 * showhidden bool show hidden files too
526 * firsthead bool return first heading for pages
528 * @author Andreas Gohr <gohr@cosmocode.de>
530 function search_universal(&$data,$base,$file,$type,$lvl,$opts){
534 // get ID and check if it is a valid one
535 $item['id'] = pathID($file,($type == 'd' || $opts['keeptxt']));
536 if($item['id'] != cleanID($item['id'])){
538 msg(hsc($item['id']).' is not a valid file name for DokuWiki - skipped',-1);
539 return false; // skip non-valid files
541 $item['ns'] = getNS($item['id']);
544 // decide if to recursion into this directory is wanted
546 $return = true; // recurse forever
548 $depth = substr_count($file,'/');
549 if($depth >= $opts['depth']){
550 $return = false; // depth reached
555 if($return && !preg_match('/'.$opts['recmatch'].'/',$file)){
556 $return = false; // doesn't match
561 if(!$opts['skipacl']){
563 $item['perm'] = auth_quickaclcheck($item['id'].':*');
565 $item['perm'] = auth_quickaclcheck($item['id']); //FIXME check namespace for media files
568 $item['perm'] = AUTH_DELETE;
571 // are we done here maybe?
573 if(!$opts['listdirs']) return $return;
574 if(!$opts['skipacl'] && $opts['sneakyacl'] && $item['perm'] < AUTH_READ) return false; //neither list nor recurse
575 if($opts['dirmatch'] && !preg_match('/'.$opts['dirmatch'].'/',$file)) return $return;
576 if($opts['nsmatch'] && !preg_match('/'.$opts['nsmatch'].'/',$item['ns'])) return $return;
578 if(!$opts['listfiles']) return $return;
579 if(!$opts['skipacl'] && $item['perm'] < AUTH_READ) return $return;
580 if($opts['pagesonly'] && (substr($file,-4) != '.txt')) return $return;
581 if(!$opts['showhidden'] && isHiddenPage($item['id'])) return $return;
582 if($opts['filematch'] && !preg_match('/'.$opts['filematch'].'/',$file)) return $return;
583 if($opts['idmatch'] && !preg_match('/'.$opts['idmatch'].'/',$item['id'])) return $return;
586 // still here? prepare the item
587 $item['type'] = $type;
588 $item['level'] = $lvl;
589 $item['open'] = $return;
592 $item['file'] = utf8_basename($file);
593 $item['size'] = filesize($base.'/'.$file);
594 $item['mtime'] = filemtime($base.'/'.$file);
595 $item['rev'] = $item['mtime'];
596 $item['writable'] = is_writable($base.'/'.$file);
597 $item['executable'] = is_executable($base.'/'.$file);
601 if($opts['hash']) $item['hash'] = md5(io_readFile($base.'/'.$file,false));
602 if($opts['firsthead']) $item['title'] = p_get_first_heading($item['id'],METADATA_DONT_RENDER);
605 // finally add the item
610 //Setup VIM: ex: et ts=4 :