French language update
[dokuwiki/radio.git] / inc / search.php
blob2b9a51fb36b107006c20a100c5823e37181008ec
1 <?php
2 /**
3 * DokuWiki search functions
5 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author Andreas Gohr <andi@splitbrain.org>
7 */
9 if(!defined('DOKU_INC')) die('meh.');
10 require_once(DOKU_INC.'inc/common.php');
12 /**
13 * recurse direcory
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){
26 $dirs = array();
27 $files = array();
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;
38 $files[] = $dir.'/'.$file;
40 closedir($dh);
41 sort($files);
42 sort($dirs);
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));
56 /**
57 * Wrapper around call_user_func_array.
59 * @deprecated
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));
65 /**
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).
88 /**
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){
94 $opts = array(
95 'idmatch' => '(^|:)'.preg_quote($opts['query'],'/').'/',
96 'listfiles' => true,
97 'pagesonly' => true,
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){
110 global $conf;
111 $return = true;
113 $item = array();
115 if($type == 'd' && !preg_match('#^'.$file.'(/|$)#','/'.$opts['ns'])){
116 //add but don't recurse
117 $return = false;
118 }elseif($type == 'f' && ($opts['nofiles'] || substr($file,-4) != '.txt')){
119 //don't add
120 return false;
123 $id = pathID($file);
125 if($type=='d' && $conf['sneaky_index'] && auth_quickaclcheck($id.':') < AUTH_READ){
126 return false;
129 //check hidden
130 if(isHiddenPage($id)){
131 return false;
134 //check ACL
135 if($type=='f' && auth_quickaclcheck($id) < AUTH_READ){
136 return false;
139 $data[]=array( 'id' => $id,
140 'type' => $type,
141 'level' => $lvl,
142 'open' => $return );
143 return $return;
147 * List all namespaces
149 * @author Andreas Gohr <andi@splitbrain.org>
151 function search_namespaces(&$data,$base,$file,$type,$lvl,$opts){
152 $opts = array(
153 'listdirs' => true,
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
166 if($type == 'd') {
167 if(!$opts['depth']) return true; // recurse forever
168 $depth = substr_count($file,'/');
169 if($depth >= $opts['depth']) return false; // depth reached
170 return true;
173 $info = array();
174 $info['id'] = pathID($file,true);
175 if($info['id'] != cleanID($info['id'])){
176 if($opts['showmsg'])
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){
184 return false;
187 //check pattern filter
188 if($opts['pattern'] && !@preg_match($opts['pattern'], $info['id'])){
189 return false;
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);
200 }else{
201 $info['isimg'] = false;
203 if($opts['hash']){
204 $info['hash'] = md5(io_readFile(wikiFN($info['id']),false));
207 $data[] = $info;
209 return 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'){
222 //check ACL
223 $id = pathID($file);
224 if(auth_quickaclcheck($id) < AUTH_READ){
225 return false;
227 $data[]['id'] = $id;
229 return false;
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){
248 //check ACL
249 $id = pathID($file);
250 if(auth_quickaclcheck($id) < AUTH_READ){
251 return false;
253 $data[]['id'] = $id;
256 return true;
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
270 if($type == 'd'){
271 if(!$opts['depth']) return true; // recurse forever
272 $parts = explode('/',ltrim($file,'/'));
273 if(count($parts) == $opts['depth']) return false; // depth reached
274 return true;
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){
282 return false;
285 $item['rev'] = filemtime($base.'/'.$file);
286 $item['mtime'] = $item['rev'];
287 $item['size'] = filesize($base.'/'.$file);
288 if($opts['hash']){
289 $item['hash'] = md5(trim(rawWiki($item['id'])));
292 $data[] = $item;
293 return true;
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;
311 //absolute search id
312 $sid = cleanID($opts['ns'].':'.$opts['name']);
314 //current id and namespace
315 $cid = pathID($file);
316 $cns = getNS($cid);
318 //check ACL
319 if(auth_quickaclcheck($cid) < AUTH_READ){
320 return false;
323 //fetch instructions
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') ){
331 $mid = $ins[1][0];
332 resolve_pageid($cns,$mid,$exists); //exists is not used
333 if($mid == $sid){
334 //we have a match - finish
335 $data[]['id'] = $cid;
336 break;
341 return false;
345 * Fulltextsearch
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;
358 //check ACL
359 $id = pathID($file);
360 if(auth_quickaclcheck($id) < AUTH_READ){
361 return false;
364 //create regexp from queries
365 $poswords = array();
366 $negwords = array();
367 $qpreg = preg_split('/\s+/',$opts['query']);
369 foreach($qpreg as $word){
370 switch(substr($word,0,1)){
371 case '-':
372 if(strlen($word) > 1){ // catch single '-'
373 array_push($negwords,preg_quote(substr($word,1),'#'));
375 break;
376 case '+':
377 if(strlen($word) > 1){ // catch single '+'
378 array_push($poswords,preg_quote(substr($word,1),'#'));
380 break;
381 default:
382 array_push($poswords,preg_quote($word,'#'));
383 break;
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);
393 return true;
397 * Reference search
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){
417 global $conf;
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']));
432 return true;
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){
456 //get text
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
462 $matches = array();
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);
467 $f = $p - 100;
468 $l = utf8_strlen($q) + 200;
469 if($f < 0) $f = 0;
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);
476 $data[] = array(
477 'id' => pathID($file),
478 'count' => preg_match_all('#'.$mark.'#usi',$lctext,$matches),
479 'poswords' => join(' ',$words),
480 'snippet' => $snippet,
484 return true;
489 * fulltext sort
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']){
498 return -1;
499 }elseif($a['count'] < $b['count']){
500 return 1;
501 }else{
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);
518 return $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
525 * setup.
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){
551 $item = array();
552 $return = true;
554 // get ID and check if it is a valid one
555 $item['id'] = pathID($file);
556 if($item['id'] != cleanID($item['id'])){
557 if($opts['showmsg'])
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']);
563 if($type == 'd') {
564 // decide if to recursion into this directory is wanted
565 if(!$opts['depth']){
566 $return = true; // recurse forever
567 }else{
568 $depth = substr_count($file,'/');
569 if($depth >= $opts['depth']){
570 $return = false; // depth reached
571 }else{
572 $return = true;
575 if($return && !preg_match('/'.$opts['recmatch'].'/',$file)){
576 $return = false; // doesn't match
580 // check ACL
581 if(!$opts['skipacl']){
582 if($type == 'd'){
583 $item['perm'] = auth_quickaclcheck($item['id'].':*');
584 }else{
585 $item['perm'] = auth_quickaclcheck($item['id']); //FIXME check namespace for media files
587 }else{
588 $item['perm'] = AUTH_DELETE;
591 // are we done here maybe?
592 if($type == 'd'){
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;
597 }else{
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;
611 if($opts['meta']){
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);
620 if($type == 'f'){
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
626 $data[] = $item;
627 return $return;
630 //Setup VIM: ex: et ts=4 enc=utf-8 :