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.');
10 require_once(DOKU_INC
.'inc/common.php');
15 * This function recurses into a given base directory
16 * and calls the supplied function for each file and directory
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>
25 function search(&$data,$base,$func,$opts,$dir='',$lvl=1){
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;
44 //give directories to userfunction then recurse
45 foreach($dirs as $dir){
46 if (call_user_func_array($func, array(&$data,$base,$dir,'d',$lvl,$opts))){
47 search($data,$base,$func,$opts,$dir,$lvl+
1);
50 //now handle the files
51 foreach($files as $file){
52 call_user_func_array($func, array(&$data,$base,$file,'f',$lvl,$opts));
57 * Wrapper around call_user_func_array.
61 function search_callback($func,&$data,$base,$file,$type,$lvl,$opts){
62 return call_user_func_array($func, array(&$data,$base,$file,$type,$lvl,$opts));
66 * The following functions are userfunctions to use with the search
67 * function above. This function is called for every found file or
68 * directory. When a directory is given to the function it has to
69 * decide if this directory should be traversed (true) or not (false)
70 * The function has to accept the following parameters:
72 * &$data - Reference to the result data structure
73 * $base - Base usually $conf['datadir']
74 * $file - current file or directory relative to $base
75 * $type - Type either 'd' for directory or 'f' for file
76 * $lvl - Current recursion depht
77 * $opts - option array as given to search()
79 * return values for files are ignored
81 * All functions should check the ACL for document READ rights
82 * namespaces (directories) are NOT checked as this would break
83 * the recursion (You can have an nonreadable dir over a readable
84 * one deeper nested) also make sure to check the file type (for example
85 * in case of lockfiles).
89 * Searches for pages beginning with the given query
91 * @author Andreas Gohr <andi@splitbrain.org>
93 function search_qsearch(&$data,$base,$file,$type,$lvl,$opts){
95 'idmatch' => '(^|:)'.preg_quote($opts['query'],'/').'/',
99 return search_universal($data,$base,$file,$type,$lvl,$opts);
103 * Build the browsable index of pages
105 * $opts['ns'] is the current namespace
107 * @author Andreas Gohr <andi@splitbrain.org>
109 function search_index(&$data,$base,$file,$type,$lvl,$opts){
115 if($type == 'd' && !preg_match('#^'.$file.'(/|$)#','/'.$opts['ns'])){
116 //add but don't recurse
118 }elseif($type == 'f' && ($opts['nofiles'] ||
substr($file,-4) != '.txt')){
125 if($type=='d' && $conf['sneaky_index'] && auth_quickaclcheck($id.':') < AUTH_READ
){
130 if(isHiddenPage($id)){
135 if($type=='f' && auth_quickaclcheck($id) < AUTH_READ
){
139 $data[]=array( 'id' => $id,
147 * List all namespaces
149 * @author Andreas Gohr <andi@splitbrain.org>
151 function search_namespaces(&$data,$base,$file,$type,$lvl,$opts){
155 return search_universal($data,$base,$file,$type,$lvl,$opts);
159 * List all mediafiles in a namespace
161 * @author Andreas Gohr <andi@splitbrain.org>
163 function search_media(&$data,$base,$file,$type,$lvl,$opts){
165 //we do nothing with directories
167 if(!$opts['depth']) return true; // recurse forever
168 $depth = substr_count($file,'/');
169 if($depth >= $opts['depth']) return false; // depth reached
174 $info['id'] = pathID($file,true);
175 if($info['id'] != cleanID($info['id'])){
177 msg(hsc($info['id']).' is not a valid file name for DokuWiki - skipped',-1);
178 return false; // skip non-valid files
181 //check ACL for namespace (we have no ACL for mediafiles)
182 $info['perm'] = auth_quickaclcheck(getNS($info['id']).':*');
183 if(!$opts['skipacl'] && $info['perm'] < AUTH_READ
){
187 //check pattern filter
188 if($opts['pattern'] && !@preg_match
($opts['pattern'], $info['id'])){
192 $info['file'] = basename($file);
193 $info['size'] = filesize($base.'/'.$file);
194 $info['mtime'] = filemtime($base.'/'.$file);
195 $info['writable'] = is_writable($base.'/'.$file);
196 if(preg_match("/\.(jpe?g|gif|png)$/",$file)){
197 $info['isimg'] = true;
198 require_once(DOKU_INC
.'inc/JpegMeta.php');
199 $info['meta'] = new JpegMeta($base.'/'.$file);
201 $info['isimg'] = false;
204 $info['hash'] = md5(io_readFile(wikiFN($info['id']),false));
213 * This function just lists documents (for RSS namespace export)
215 * @author Andreas Gohr <andi@splitbrain.org>
217 function search_list(&$data,$base,$file,$type,$lvl,$opts){
218 //we do nothing with directories
219 if($type == 'd') return false;
220 //only search txt files
221 if(substr($file,-4) == '.txt'){
224 if(auth_quickaclcheck($id) < AUTH_READ
){
233 * Quicksearch for searching matching pagenames
235 * $opts['query'] is the search query
237 * @author Andreas Gohr <andi@splitbrain.org>
239 function search_pagename(&$data,$base,$file,$type,$lvl,$opts){
240 //we do nothing with directories
241 if($type == 'd') return true;
242 //only search txt files
243 if(substr($file,-4) != '.txt') return true;
245 //simple stringmatching
246 if (!empty($opts['query'])){
247 if(strpos($file,$opts['query']) !== false){
250 if(auth_quickaclcheck($id) < AUTH_READ
){
260 * Just lists all documents
262 * $opts['depth'] recursion level, 0 for all
263 * $opts['hash'] do md5 sum of content?
264 * $opts['skipacl'] list everything regardless of ACL
266 * @author Andreas Gohr <andi@splitbrain.org>
268 function search_allpages(&$data,$base,$file,$type,$lvl,$opts){
269 //we do nothing with directories
271 if(!$opts['depth']) return true; // recurse forever
272 $parts = explode('/',ltrim($file,'/'));
273 if(count($parts) == $opts['depth']) return false; // depth reached
277 //only search txt files
278 if(substr($file,-4) != '.txt') return true;
280 $item['id'] = pathID($file);
281 if(!$opts['skipacl'] && auth_quickaclcheck($item['id']) < AUTH_READ
){
285 $item['rev'] = filemtime($base.'/'.$file);
286 $item['mtime'] = $item['rev'];
287 $item['size'] = filesize($base.'/'.$file);
289 $item['hash'] = md5(trim(rawWiki($item['id'])));
297 * Search for backlinks to a given page
299 * $opts['ns'] namespace of the page
300 * $opts['name'] name of the page without namespace
302 * @author Andreas Gohr <andi@splitbrain.org>
303 * @deprecated Replaced by ft_backlinks()
305 function search_backlinks(&$data,$base,$file,$type,$lvl,$opts){
306 //we do nothing with directories
307 if($type == 'd') return true;
308 //only search txt files
309 if(substr($file,-4) != '.txt') return true;
312 $sid = cleanID($opts['ns'].':'.$opts['name']);
314 //current id and namespace
315 $cid = pathID($file);
319 if(auth_quickaclcheck($cid) < AUTH_READ
){
324 require_once(DOKU_INC
.'inc/parserutils.php');
325 $instructions = p_cached_instructions($base.$file,true);
326 if(is_null($instructions)) return false;
328 //check all links for match
329 foreach($instructions as $ins){
330 if($ins[0] == 'internallink' ||
($conf['camelcase'] && $ins[0] == 'camelcaselink') ){
332 resolve_pageid($cns,$mid,$exists); //exists is not used
334 //we have a match - finish
335 $data[]['id'] = $cid;
347 * $opts['query'] is the search query
349 * @author Andreas Gohr <andi@splitbrain.org>
350 * @deprecated - fulltext indexer is used instead
352 function search_fulltext(&$data,$base,$file,$type,$lvl,$opts){
353 //we do nothing with directories
354 if($type == 'd') return true;
355 //only search txt files
356 if(substr($file,-4) != '.txt') return true;
360 if(auth_quickaclcheck($id) < AUTH_READ
){
364 //create regexp from queries
367 $qpreg = preg_split('/\s+/',$opts['query']);
369 foreach($qpreg as $word){
370 switch(substr($word,0,1)){
372 if(strlen($word) > 1){ // catch single '-'
373 array_push($negwords,preg_quote(substr($word,1),'#'));
377 if(strlen($word) > 1){ // catch single '+'
378 array_push($poswords,preg_quote(substr($word,1),'#'));
382 array_push($poswords,preg_quote($word,'#'));
387 // a search without any posword is useless
388 if (!count($poswords)) return true;
390 $reg = '^(?=.*?'.join(')(?=.*?',$poswords).')';
391 $reg .= count($negwords) ?
'((?!'.join('|',$negwords).').)*$' : '.*$';
392 search_regex($data,$base,$file,$reg,$poswords);
398 * This fuction searches for existing references to a given media file
399 * and returns an array with the found pages. It doesn't pay any
400 * attention to ACL permissions to find every reference. The caller
401 * must check if the user has the appropriate rights to see the found
402 * page and eventually have to prevent the result from displaying.
404 * @param array $data Reference to the result data structure
405 * @param string $base Base usually $conf['datadir']
406 * @param string $file current file or directory relative to $base
407 * @param char $type Type either 'd' for directory or 'f' for file
408 * @param int $lvl Current recursion depht
409 * @param mixed $opts option array as given to search()
411 * $opts['query'] is the demanded media file name
413 * @author Andreas Gohr <andi@splitbrain.org>
414 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
416 function search_reference(&$data,$base,$file,$type,$lvl,$opts){
419 //we do nothing with directories
420 if($type == 'd') return true;
422 //only search txt files
423 if(substr($file,-4) != '.txt') return true;
425 //we finish after 'cnt' references found. The return value
426 //'false' will skip subdirectories to speed search up.
427 $cnt = $conf['refshow'] > 0 ?
$conf['refshow'] : 1;
428 if(count($data) >= $cnt) return false;
430 $reg = '\{\{ *\:?'.$opts['query'].' *(\|.*)?\}\}';
431 search_regex($data,$base,$file,$reg,array($opts['query']));
435 /* ------------- helper functions below -------------- */
438 * fulltext search helper
439 * searches a text file with a given regular expression
440 * no ACL checks are performed. This have to be done by
441 * the caller if necessary.
443 * @param array $data reference to array for results
444 * @param string $base base directory
445 * @param string $file file name to search in
446 * @param string $reg regular expression to search for
447 * @param array $words words that should be marked in the results
449 * @author Andreas Gohr <andi@splitbrain.org>
450 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
452 * @deprecated - fulltext indexer is used instead
454 function search_regex(&$data,$base,$file,$reg,$words){
457 $text = io_readfile($base.'/'.$file);
458 //lowercase text (u modifier does not help with case)
459 $lctext = utf8_strtolower($text);
461 //do the fulltext search
463 if($cnt = preg_match_all('#'.$reg.'#usi',$lctext,$matches)){
464 //this is not the best way for snippet generation but the fastest I could find
465 $q = $words[0]; //use first word for snippet creation
466 $p = utf8_strpos($lctext,$q);
468 $l = utf8_strlen($q) +
200;
470 $snippet = '<span class="search_sep"> ... </span>'.
471 htmlspecialchars(utf8_substr($text,$f,$l)).
472 '<span class="search_sep"> ... </span>';
473 $mark = '('.join('|', $words).')';
474 $snippet = preg_replace('#'.$mark.'#si','<strong class="search_hit">\\1</strong>',$snippet);
477 'id' => pathID($file),
478 'count' => preg_match_all('#'.$mark.'#usi',$lctext,$matches),
479 'poswords' => join(' ',$words),
480 'snippet' => $snippet,
491 * Callback sort function for use with usort to sort the data
492 * structure created by search_fulltext. Sorts descending by count
494 * @author Andreas Gohr <andi@splitbrain.org>
496 function sort_search_fulltext($a,$b){
497 if($a['count'] > $b['count']){
499 }elseif($a['count'] < $b['count']){
502 return strcmp($a['id'],$b['id']);
507 * translates a document path to an ID
509 * @author Andreas Gohr <andi@splitbrain.org>
510 * @todo move to pageutils
512 function pathID($path,$keeptxt=false){
513 $id = utf8_decodeFN($path);
514 $id = str_replace('/',':',$id);
515 if(!$keeptxt) $id = preg_replace('#\.txt$#','',$id);
516 $id = preg_replace('#^:+#','',$id);
517 $id = preg_replace('#:+$#','',$id);
523 * This is a very universal callback for the search() function, replacing
524 * many of the former individual functions at the cost of a more complex
527 * How the function behaves, depends on the options passed in the $opts
528 * array, where the following settings can be used.
530 * depth int recursion depth. 0 for unlimited
531 * keeptxt bool keep .txt extension for IDs
532 * listfiles bool include files in listing
533 * listdirs bool include namespaces in listing
534 * pagesonly bool restrict files to pages
535 * skipacl bool do not check for READ permission
536 * sneakyacl bool don't recurse into nonreadable dirs
537 * hash bool create MD5 hash for files
538 * meta bool return file metadata
539 * filematch string match files against this regexp
540 * idmatch string match full ID against this regexp
541 * dirmatch string match directory against this regexp when adding
542 * nsmatch string match namespace against this regexp when adding
543 * recmatch string match directory against this regexp when recursing
544 * showmsg bool warn about non-ID files
545 * showhidden bool show hidden files too
546 * firsthead bool return first heading for pages
548 * @author Andreas Gohr <gohr@cosmocode.de>
550 function search_universal(&$data,$base,$file,$type,$lvl,$opts){
554 // get ID and check if it is a valid one
555 $item['id'] = pathID($file);
556 if($item['id'] != cleanID($item['id'])){
558 msg(hsc($item['id']).' is not a valid file name for DokuWiki - skipped',-1);
559 return false; // skip non-valid files
561 $item['ns'] = getNS($item['id']);
564 // decide if to recursion into this directory is wanted
566 $return = true; // recurse forever
568 $depth = substr_count($file,'/');
569 if($depth >= $opts['depth']){
570 $return = false; // depth reached
575 if($return && !preg_match('/'.$opts['recmatch'].'/',$file)){
576 $return = false; // doesn't match
581 if(!$opts['skipacl']){
583 $item['perm'] = auth_quickaclcheck($item['id'].':*');
585 $item['perm'] = auth_quickaclcheck($item['id']); //FIXME check namespace for media files
588 $item['perm'] = AUTH_DELETE
;
591 // are we done here maybe?
593 if(!$opts['listdirs']) return $return;
594 if(!$opts['skipacl'] && $opts['sneakyacl'] && $item['perm'] < AUTH_READ
) return false; //neither list nor recurse
595 if($opts['dirmatch'] && !preg_match('/'.$opts['dirmatch'].'/',$file)) return $return;
596 if($opts['nsmatch'] && !preg_match('/'.$opts['nsmatch'].'/',$item['ns'])) return $return;
598 if(!$opts['listfiles']) return $return;
599 if(!$opts['skipacl'] && $item['perm'] < AUTH_READ
) return $return;
600 if($opts['pagesonly'] && (substr($file,-4) != '.txt')) return $return;
601 if(!$conf['showhidden'] && isHiddenPage($id)) return $return;
602 if($opts['filematch'] && !preg_match('/'.$opts['filematch'].'/',$file)) return $return;
603 if($opts['idmatch'] && !preg_match('/'.$opts['idmatch'].'/',$item['id'])) return $return;
606 // still here? prepare the item
607 $item['type'] = $type;
608 $item['level'] = $lvl;
609 $item['open'] = $return;
612 $item['file'] = basename($file);
613 $item['size'] = filesize($base.'/'.$file);
614 $item['mtime'] = filemtime($base.'/'.$file);
615 $item['rev'] = $item['mtime'];
616 $item['writable'] = is_writable($base.'/'.$file);
617 $item['executable'] = is_executable($base.'/'.$file);
621 if($opts['hash']) $item['hash'] = md5(io_readFile($base.'/'.$file,false));
622 if($opts['firsthead']) $item['title'] = p_get_first_heading($item['id'],false);
625 // finally add the item
630 //Setup VIM: ex: et ts=4 enc=utf-8 :