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 9if(!defined('DOKU_INC')) die('meh.'); 10require_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 (call_user_func_array($func, array(&$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 call_user_func_array($func, array(&$data,$base,$file,'f',$lvl,$opts)); 53 } 54} 55 56/** 57 * Wrapper around call_user_func_array. 58 * 59 * @deprecated 60 */ 61function search_callback($func,&$data,$base,$file,$type,$lvl,$opts){ 62 return call_user_func_array($func, array(&$data,$base,$file,$type,$lvl,$opts)); 63} 64 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: 71 * 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() 78 * 79 * return values for files are ignored 80 * 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). 86 */ 87 88/** 89 * Searches for pages beginning with the given query 90 * 91 * @author Andreas Gohr <andi@splitbrain.org> 92 */ 93function search_qsearch(&$data,$base,$file,$type,$lvl,$opts){ 94 $opts = array( 95 'idmatch' => '(^|:)'.preg_quote($opts['query'],'/').'/', 96 'listfiles' => true, 97 'pagesonly' => true, 98 ); 99 return search_universal($data,$base,$file,$type,$lvl,$opts); 100} 101 102/** 103 * Build the browsable index of pages 104 * 105 * $opts['ns'] is the current namespace 106 * 107 * @author Andreas Gohr <andi@splitbrain.org> 108 */ 109function search_index(&$data,$base,$file,$type,$lvl,$opts){ 110 global $conf; 111 $return = true; 112 113 $item = array(); 114 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; 121 } 122 123 $id = pathID($file); 124 125 if($type=='d' && $conf['sneaky_index'] && auth_quickaclcheck($id.':') < AUTH_READ){ 126 return false; 127 } 128 129 //check hidden 130 if(isHiddenPage($id)){ 131 return false; 132 } 133 134 //check ACL 135 if($type=='f' && auth_quickaclcheck($id) < AUTH_READ){ 136 return false; 137 } 138 139 $data[]=array( 'id' => $id, 140 'type' => $type, 141 'level' => $lvl, 142 'open' => $return ); 143 return $return; 144} 145 146/** 147 * List all namespaces 148 * 149 * @author Andreas Gohr <andi@splitbrain.org> 150 */ 151function search_namespaces(&$data,$base,$file,$type,$lvl,$opts){ 152 $opts = array( 153 'listdirs' => true, 154 ); 155 return search_universal($data,$base,$file,$type,$lvl,$opts); 156} 157 158/** 159 * List all mediafiles in a namespace 160 * 161 * @author Andreas Gohr <andi@splitbrain.org> 162 */ 163function search_media(&$data,$base,$file,$type,$lvl,$opts){ 164 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; 171 } 172 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 179 } 180 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; 185 } 186 187 //check pattern filter 188 if($opts['pattern'] && !@preg_match($opts['pattern'], $info['id'])){ 189 return false; 190 } 191 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; 202 } 203 if($opts['hash']){ 204 $info['hash'] = md5(io_readFile(wikiFN($info['id']),false)); 205 } 206 207 $data[] = $info; 208 209 return false; 210} 211 212/** 213 * This function just lists documents (for RSS namespace export) 214 * 215 * @author Andreas Gohr <andi@splitbrain.org> 216 */ 217function 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; 226 } 227 $data[]['id'] = $id; 228 } 229 return false; 230} 231 232/** 233 * Quicksearch for searching matching pagenames 234 * 235 * $opts['query'] is the search query 236 * 237 * @author Andreas Gohr <andi@splitbrain.org> 238 */ 239function 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; 244 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; 252 } 253 $data[]['id'] = $id; 254 } 255 } 256 return true; 257} 258 259/** 260 * Just lists all documents 261 * 262 * $opts['depth'] recursion level, 0 for all 263 * $opts['hash'] do md5 sum of content? 264 * $opts['skipacl'] list everything regardless of ACL 265 * 266 * @author Andreas Gohr <andi@splitbrain.org> 267 */ 268function 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; 275 } 276 277 //only search txt files 278 if(substr($file,-4) != '.txt') return true; 279 280 $item['id'] = pathID($file); 281 if(!$opts['skipacl'] && auth_quickaclcheck($item['id']) < AUTH_READ){ 282 return false; 283 } 284 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']))); 290 } 291 292 $data[] = $item; 293 return true; 294} 295 296/** 297 * Search for backlinks to a given page 298 * 299 * $opts['ns'] namespace of the page 300 * $opts['name'] name of the page without namespace 301 * 302 * @author Andreas Gohr <andi@splitbrain.org> 303 * @deprecated Replaced by ft_backlinks() 304 */ 305function 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; 310 311 //absolute search id 312 $sid = cleanID($opts['ns'].':'.$opts['name']); 313 314 //current id and namespace 315 $cid = pathID($file); 316 $cns = getNS($cid); 317 318 //check ACL 319 if(auth_quickaclcheck($cid) < AUTH_READ){ 320 return false; 321 } 322 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; 327 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; 337 } 338 } 339 } 340 341 return false; 342} 343 344/** 345 * Fulltextsearch 346 * 347 * $opts['query'] is the search query 348 * 349 * @author Andreas Gohr <andi@splitbrain.org> 350 * @deprecated - fulltext indexer is used instead 351 */ 352function 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; 357 358 //check ACL 359 $id = pathID($file); 360 if(auth_quickaclcheck($id) < AUTH_READ){ 361 return false; 362 } 363 364 //create regexp from queries 365 $poswords = array(); 366 $negwords = array(); 367 $qpreg = preg_split('/\s+/',$opts['query']); 368 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),'#')); 374 } 375 break; 376 case '+': 377 if(strlen($word) > 1){ // catch single '+' 378 array_push($poswords,preg_quote(substr($word,1),'#')); 379 } 380 break; 381 default: 382 array_push($poswords,preg_quote($word,'#')); 383 break; 384 } 385 } 386 387 // a search without any posword is useless 388 if (!count($poswords)) return true; 389 390 $reg = '^(?=.*?'.join(')(?=.*?',$poswords).')'; 391 $reg .= count($negwords) ? '((?!'.join('|',$negwords).').)*$' : '.*$'; 392 search_regex($data,$base,$file,$reg,$poswords); 393 return true; 394} 395 396/** 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. 403 * 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() 410 * 411 * $opts['query'] is the demanded media file name 412 * 413 * @author Andreas Gohr <andi@splitbrain.org> 414 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> 415 */ 416function search_reference(&$data,$base,$file,$type,$lvl,$opts){ 417 global $conf; 418 419 //we do nothing with directories 420 if($type == 'd') return true; 421 422 //only search txt files 423 if(substr($file,-4) != '.txt') return true; 424 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; 429 430 $reg = '\{\{ *\:?'.$opts['query'].' *(\|.*)?\}\}'; 431 search_regex($data,$base,$file,$reg,array($opts['query'])); 432 return true; 433} 434 435/* ------------- helper functions below -------------- */ 436 437/** 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. 442 * 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 448 * 449 * @author Andreas Gohr <andi@splitbrain.org> 450 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> 451 * 452 * @deprecated - fulltext indexer is used instead 453 */ 454function search_regex(&$data,$base,$file,$reg,$words){ 455 456 //get text 457 $text = io_readfile($base.'/'.$file); 458 //lowercase text (u modifier does not help with case) 459 $lctext = utf8_strtolower($text); 460 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); 475 476 $data[] = array( 477 'id' => pathID($file), 478 'count' => preg_match_all('#'.$mark.'#usi',$lctext,$matches), 479 'poswords' => join(' ',$words), 480 'snippet' => $snippet, 481 ); 482 } 483 484 return true; 485} 486 487 488/** 489 * fulltext sort 490 * 491 * Callback sort function for use with usort to sort the data 492 * structure created by search_fulltext. Sorts descending by count 493 * 494 * @author Andreas Gohr <andi@splitbrain.org> 495 */ 496function 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']); 503 } 504} 505 506/** 507 * translates a document path to an ID 508 * 509 * @author Andreas Gohr <andi@splitbrain.org> 510 * @todo move to pageutils 511 */ 512function 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; 519} 520 521 522/** 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. 526 * 527 * How the function behaves, depends on the options passed in the $opts 528 * array, where the following settings can be used. 529 * 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 547 * 548 * @author Andreas Gohr <gohr@cosmocode.de> 549 */ 550function search_universal(&$data,$base,$file,$type,$lvl,$opts){ 551 $item = array(); 552 $return = true; 553 554 // get ID and check if it is a valid one 555 $item['id'] = pathID($file); 556 if($info['id'] != cleanID($info['id'])){ 557 if($opts['showmsg']) 558 msg(hsc($info['id']).' is not a valid file name for DokuWiki - skipped',-1); 559 return false; // skip non-valid files 560 } 561 $item['ns'] = getNS($item['id']); 562 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; 573 } 574 } 575 if($return && !preg_match('/'.$opts['recmatch'].'/',$file)){ 576 $return = false; // doesn't match 577 } 578 } 579 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 586 } 587 }else{ 588 $item['perm'] = AUTH_DELETE; 589 } 590 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; 604 } 605 606 // still here? prepare the item 607 $item['type'] = $type; 608 $item['lvl'] = $lvl; 609 $item['open'] = $return; 610 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); 618 } 619 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); 623 } 624 625 // finally add the item 626 $data[] = $item; 627 return $return; 628} 629 630//Setup VIM: ex: et ts=4 enc=utf-8 : 631