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 $item = array(); 95 96 if($type == 'd'){ 97 return false; //no handling yet 98 } 99 100 //only search txt files 101 if(substr($file,-4) != '.txt') return false; 102 103 //get id 104 $id = pathID($file); 105 106 //check if it matches the query 107 if(!preg_match('/^'.preg_quote($opts['query'],'/').'/u',$id)){ 108 return false; 109 } 110 111 //check ACL 112 if(auth_quickaclcheck($id) < AUTH_READ){ 113 return false; 114 } 115 116 $data[]=array( 'id' => $id, 117 'type' => $type, 118 'level' => 1, 119 'open' => true); 120 return true; 121} 122 123/** 124 * Build the browsable index of pages 125 * 126 * $opts['ns'] is the current namespace 127 * 128 * @author Andreas Gohr <andi@splitbrain.org> 129 */ 130function search_index(&$data,$base,$file,$type,$lvl,$opts){ 131 global $conf; 132 $return = true; 133 134 $item = array(); 135 136 if($type == 'd' && !preg_match('#^'.$file.'(/|$)#','/'.$opts['ns'])){ 137 //add but don't recurse 138 $return = false; 139 }elseif($type == 'f' && ($opts['nofiles'] || substr($file,-4) != '.txt')){ 140 //don't add 141 return false; 142 } 143 144 $id = pathID($file); 145 146 if($type=='d' && $conf['sneaky_index'] && auth_quickaclcheck($id.':') < AUTH_READ){ 147 return false; 148 } 149 150 //check hidden 151 if(isHiddenPage($id)){ 152 return false; 153 } 154 155 //check ACL 156 if($type=='f' && auth_quickaclcheck($id) < AUTH_READ){ 157 return false; 158 } 159 160 $data[]=array( 'id' => $id, 161 'type' => $type, 162 'level' => $lvl, 163 'open' => $return ); 164 return $return; 165} 166 167/** 168 * List all namespaces 169 * 170 * @author Andreas Gohr <andi@splitbrain.org> 171 */ 172function search_namespaces(&$data,$base,$file,$type,$lvl,$opts){ 173 if($type == 'f') return true; //nothing to do on files 174 175 $id = pathID($file); 176 $data[]=array( 'id' => $id, 177 'type' => $type, 178 'level' => $lvl ); 179 return true; 180} 181 182/** 183 * List all mediafiles in a namespace 184 * 185 * @author Andreas Gohr <andi@splitbrain.org> 186 */ 187function search_media(&$data,$base,$file,$type,$lvl,$opts){ 188 189 //we do nothing with directories 190 if($type == 'd') { 191 if(!$opts['depth']) return true; // recurse forever 192 $depth = substr_count($file,'/'); 193 if($depth >= $opts['depth']) return false; // depth reached 194 return true; 195 } 196 197 $info = array(); 198 $info['id'] = pathID($file,true); 199 if($info['id'] != cleanID($info['id'])){ 200 if($opts['showmsg']) 201 msg(hsc($info['id']).' is not a valid file name for DokuWiki - skipped',-1); 202 return false; // skip non-valid files 203 } 204 205 //check ACL for namespace (we have no ACL for mediafiles) 206 $info['perm'] = auth_quickaclcheck(getNS($info['id']).':*'); 207 if(!$opts['skipacl'] && $info['perm'] < AUTH_READ){ 208 return false; 209 } 210 211 //check pattern filter 212 if($opts['pattern'] && !@preg_match($opts['pattern'], $info['id'])){ 213 return false; 214 } 215 216 $info['file'] = basename($file); 217 $info['size'] = filesize($base.'/'.$file); 218 $info['mtime'] = filemtime($base.'/'.$file); 219 $info['writable'] = is_writable($base.'/'.$file); 220 if(preg_match("/\.(jpe?g|gif|png)$/",$file)){ 221 $info['isimg'] = true; 222 require_once(DOKU_INC.'inc/JpegMeta.php'); 223 $info['meta'] = new JpegMeta($base.'/'.$file); 224 }else{ 225 $info['isimg'] = false; 226 } 227 if($opts['hash']){ 228 $info['hash'] = md5(io_readFile(wikiFN($info['id']),false)); 229 } 230 231 $data[] = $info; 232 233 return false; 234} 235 236/** 237 * This function just lists documents (for RSS namespace export) 238 * 239 * @author Andreas Gohr <andi@splitbrain.org> 240 */ 241function search_list(&$data,$base,$file,$type,$lvl,$opts){ 242 //we do nothing with directories 243 if($type == 'd') return false; 244 //only search txt files 245 if(substr($file,-4) == '.txt'){ 246 //check ACL 247 $id = pathID($file); 248 if(auth_quickaclcheck($id) < AUTH_READ){ 249 return false; 250 } 251 $data[]['id'] = $id; 252 } 253 return false; 254} 255 256/** 257 * Quicksearch for searching matching pagenames 258 * 259 * $opts['query'] is the search query 260 * 261 * @author Andreas Gohr <andi@splitbrain.org> 262 */ 263function search_pagename(&$data,$base,$file,$type,$lvl,$opts){ 264 //we do nothing with directories 265 if($type == 'd') return true; 266 //only search txt files 267 if(substr($file,-4) != '.txt') return true; 268 269 //simple stringmatching 270 if (!empty($opts['query'])){ 271 if(strpos($file,$opts['query']) !== false){ 272 //check ACL 273 $id = pathID($file); 274 if(auth_quickaclcheck($id) < AUTH_READ){ 275 return false; 276 } 277 $data[]['id'] = $id; 278 } 279 } 280 return true; 281} 282 283/** 284 * Just lists all documents 285 * 286 * $opts['depth'] recursion level, 0 for all 287 * $opts['hash'] do md5 sum of content? 288 * $opts['skipacl'] list everything regardless of ACL 289 * 290 * @author Andreas Gohr <andi@splitbrain.org> 291 */ 292function search_allpages(&$data,$base,$file,$type,$lvl,$opts){ 293 //we do nothing with directories 294 if($type == 'd'){ 295 if(!$opts['depth']) return true; // recurse forever 296 $parts = explode('/',ltrim($file,'/')); 297 if(count($parts) == $opts['depth']) return false; // depth reached 298 return true; 299 } 300 301 //only search txt files 302 if(substr($file,-4) != '.txt') return true; 303 304 $item['id'] = pathID($file); 305 if(!$opts['skipacl'] && auth_quickaclcheck($item['id']) < AUTH_READ){ 306 return false; 307 } 308 309 $item['rev'] = filemtime($base.'/'.$file); 310 $item['mtime'] = $item['rev']; 311 $item['size'] = filesize($base.'/'.$file); 312 if($opts['hash']){ 313 $item['hash'] = md5(trim(rawWiki($item['id']))); 314 } 315 316 $data[] = $item; 317 return true; 318} 319 320/** 321 * Search for backlinks to a given page 322 * 323 * $opts['ns'] namespace of the page 324 * $opts['name'] name of the page without namespace 325 * 326 * @author Andreas Gohr <andi@splitbrain.org> 327 * @deprecated Replaced by ft_backlinks() 328 */ 329function search_backlinks(&$data,$base,$file,$type,$lvl,$opts){ 330 //we do nothing with directories 331 if($type == 'd') return true; 332 //only search txt files 333 if(substr($file,-4) != '.txt') return true; 334 335 //absolute search id 336 $sid = cleanID($opts['ns'].':'.$opts['name']); 337 338 //current id and namespace 339 $cid = pathID($file); 340 $cns = getNS($cid); 341 342 //check ACL 343 if(auth_quickaclcheck($cid) < AUTH_READ){ 344 return false; 345 } 346 347 //fetch instructions 348 require_once(DOKU_INC.'inc/parserutils.php'); 349 $instructions = p_cached_instructions($base.$file,true); 350 if(is_null($instructions)) return false; 351 352 //check all links for match 353 foreach($instructions as $ins){ 354 if($ins[0] == 'internallink' || ($conf['camelcase'] && $ins[0] == 'camelcaselink') ){ 355 $mid = $ins[1][0]; 356 resolve_pageid($cns,$mid,$exists); //exists is not used 357 if($mid == $sid){ 358 //we have a match - finish 359 $data[]['id'] = $cid; 360 break; 361 } 362 } 363 } 364 365 return false; 366} 367 368/** 369 * Fulltextsearch 370 * 371 * $opts['query'] is the search query 372 * 373 * @author Andreas Gohr <andi@splitbrain.org> 374 * @deprecated - fulltext indexer is used instead 375 */ 376function search_fulltext(&$data,$base,$file,$type,$lvl,$opts){ 377 //we do nothing with directories 378 if($type == 'd') return true; 379 //only search txt files 380 if(substr($file,-4) != '.txt') return true; 381 382 //check ACL 383 $id = pathID($file); 384 if(auth_quickaclcheck($id) < AUTH_READ){ 385 return false; 386 } 387 388 //create regexp from queries 389 $poswords = array(); 390 $negwords = array(); 391 $qpreg = preg_split('/\s+/',$opts['query']); 392 393 foreach($qpreg as $word){ 394 switch(substr($word,0,1)){ 395 case '-': 396 if(strlen($word) > 1){ // catch single '-' 397 array_push($negwords,preg_quote(substr($word,1),'#')); 398 } 399 break; 400 case '+': 401 if(strlen($word) > 1){ // catch single '+' 402 array_push($poswords,preg_quote(substr($word,1),'#')); 403 } 404 break; 405 default: 406 array_push($poswords,preg_quote($word,'#')); 407 break; 408 } 409 } 410 411 // a search without any posword is useless 412 if (!count($poswords)) return true; 413 414 $reg = '^(?=.*?'.join(')(?=.*?',$poswords).')'; 415 $reg .= count($negwords) ? '((?!'.join('|',$negwords).').)*$' : '.*$'; 416 search_regex($data,$base,$file,$reg,$poswords); 417 return true; 418} 419 420/** 421 * Reference search 422 * This fuction searches for existing references to a given media file 423 * and returns an array with the found pages. It doesn't pay any 424 * attention to ACL permissions to find every reference. The caller 425 * must check if the user has the appropriate rights to see the found 426 * page and eventually have to prevent the result from displaying. 427 * 428 * @param array $data Reference to the result data structure 429 * @param string $base Base usually $conf['datadir'] 430 * @param string $file current file or directory relative to $base 431 * @param char $type Type either 'd' for directory or 'f' for file 432 * @param int $lvl Current recursion depht 433 * @param mixed $opts option array as given to search() 434 * 435 * $opts['query'] is the demanded media file name 436 * 437 * @author Andreas Gohr <andi@splitbrain.org> 438 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> 439 */ 440function search_reference(&$data,$base,$file,$type,$lvl,$opts){ 441 global $conf; 442 443 //we do nothing with directories 444 if($type == 'd') return true; 445 446 //only search txt files 447 if(substr($file,-4) != '.txt') return true; 448 449 //we finish after 'cnt' references found. The return value 450 //'false' will skip subdirectories to speed search up. 451 $cnt = $conf['refshow'] > 0 ? $conf['refshow'] : 1; 452 if(count($data) >= $cnt) return false; 453 454 $reg = '\{\{ *\:?'.$opts['query'].' *(\|.*)?\}\}'; 455 search_regex($data,$base,$file,$reg,array($opts['query'])); 456 return true; 457} 458 459/* ------------- helper functions below -------------- */ 460 461/** 462 * fulltext search helper 463 * searches a text file with a given regular expression 464 * no ACL checks are performed. This have to be done by 465 * the caller if necessary. 466 * 467 * @param array $data reference to array for results 468 * @param string $base base directory 469 * @param string $file file name to search in 470 * @param string $reg regular expression to search for 471 * @param array $words words that should be marked in the results 472 * 473 * @author Andreas Gohr <andi@splitbrain.org> 474 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> 475 * 476 * @deprecated - fulltext indexer is used instead 477 */ 478function search_regex(&$data,$base,$file,$reg,$words){ 479 480 //get text 481 $text = io_readfile($base.'/'.$file); 482 //lowercase text (u modifier does not help with case) 483 $lctext = utf8_strtolower($text); 484 485 //do the fulltext search 486 $matches = array(); 487 if($cnt = preg_match_all('#'.$reg.'#usi',$lctext,$matches)){ 488 //this is not the best way for snippet generation but the fastest I could find 489 $q = $words[0]; //use first word for snippet creation 490 $p = utf8_strpos($lctext,$q); 491 $f = $p - 100; 492 $l = utf8_strlen($q) + 200; 493 if($f < 0) $f = 0; 494 $snippet = '<span class="search_sep"> ... </span>'. 495 htmlspecialchars(utf8_substr($text,$f,$l)). 496 '<span class="search_sep"> ... </span>'; 497 $mark = '('.join('|', $words).')'; 498 $snippet = preg_replace('#'.$mark.'#si','<strong class="search_hit">\\1</strong>',$snippet); 499 500 $data[] = array( 501 'id' => pathID($file), 502 'count' => preg_match_all('#'.$mark.'#usi',$lctext,$matches), 503 'poswords' => join(' ',$words), 504 'snippet' => $snippet, 505 ); 506 } 507 508 return true; 509} 510 511 512/** 513 * fulltext sort 514 * 515 * Callback sort function for use with usort to sort the data 516 * structure created by search_fulltext. Sorts descending by count 517 * 518 * @author Andreas Gohr <andi@splitbrain.org> 519 */ 520function sort_search_fulltext($a,$b){ 521 if($a['count'] > $b['count']){ 522 return -1; 523 }elseif($a['count'] < $b['count']){ 524 return 1; 525 }else{ 526 return strcmp($a['id'],$b['id']); 527 } 528} 529 530/** 531 * translates a document path to an ID 532 * 533 * @author Andreas Gohr <andi@splitbrain.org> 534 * @todo move to pageutils 535 */ 536function pathID($path,$keeptxt=false){ 537 $id = utf8_decodeFN($path); 538 $id = str_replace('/',':',$id); 539 if(!$keeptxt) $id = preg_replace('#\.txt$#','',$id); 540 $id = preg_replace('#^:+#','',$id); 541 $id = preg_replace('#:+$#','',$id); 542 return $id; 543} 544 545 546/** 547 * This is a very universal callback for the search() function, replacing 548 * many of the former individual functions at the cost of a more complex 549 * setup. 550 * 551 * How the function behaves, depends on the options passed in the $opts 552 * array, where the following settings can be used. 553 * 554 * depth int recursion depth. 0 for unlimited 555 * keeptxt bool keep .txt extension for IDs 556 * listfiles bool include files in listing 557 * listdirs bool include namespaces in listing 558 * pagesonly bool restrict files to pages 559 * skipacl bool do not check for READ permission 560 * sneakyacl bool don't recurse into nonreadable dirs 561 * hash bool create MD5 hash for files 562 * meta bool return file metadata 563 * filematch string match files against this regexp 564 * dirmatch string match namespaces against this regexp when adding 565 * recmatch string match namespaces against this regexp when recursing 566 * showmsg bool warn about non-ID files 567 * showhidden bool show hidden files too 568 * firsthead bool return first heading for pages 569 * 570 * @author Andreas Gohr <gohr@cosmocode.de> 571 */ 572function search_universal(&$data,$base,$file,$type,$lvl,$opts){ 573 $item = array(); 574 $return = true; 575 576 // get ID and check if it is a valid one 577 $item['id'] = pathID($file); 578 if($info['id'] != cleanID($info['id'])){ 579 if($opts['showmsg']) 580 msg(hsc($info['id']).' is not a valid file name for DokuWiki - skipped',-1); 581 return false; // skip non-valid files 582 } 583 584 if($type == 'd') { 585 // decide if to recursion into this directory is wanted 586 if(!$opts['depth']){ 587 $return = true; // recurse forever 588 }else{ 589 $depth = substr_count($file,'/'); 590 if($depth >= $opts['depth']){ 591 $return = false; // depth reached 592 }else{ 593 $return = true; 594 } 595 } 596 if($return && !preg_match('/'.$opts['recmatch'].'/',$file)){ 597 $return = false; // doesn't match 598 } 599 } 600 601 // check ACL 602 if(!$opts['skipacl']){ 603 if($type == 'd'){ 604 $item['perm'] = auth_quickaclcheck($item['id'].':*'); 605 }else{ 606 $item['perm'] = auth_quickaclcheck($item['id']); //FIXME check namespace for media files 607 } 608 }else{ 609 $item['perm'] = AUTH_DELETE; 610 } 611 612 // are we done here maybe? 613 if($type == 'd'){ 614 if(!$opts['listdirs']) return $return; 615 if(!$opts['skipacl'] && $opts['sneakyacl'] && $item['perm'] < AUTH_READ) return false; //neither list nor recurse 616 if($opts['dirmatch'] && !preg_match('/'.$opts['dirmatch'].'/',$file)) return $return; 617 }else{ 618 if(!$opts['listfiles']) return $return; 619 if(!$opts['skipacl'] && $item['perm'] < AUTH_READ) return $return; 620 if($opts['pagesonly'] && (substr($file,-4) != '.txt')) return $return; 621 if(!$conf['showhidden'] && isHiddenPage($id)) return $return; 622 if($opts['filematch'] && !preg_match('/'.$opts['filematch'].'/',$file)) return $return; 623 } 624 625 // still here? prepare the item 626 $item['type'] = $type; 627 $item['lvl'] = $lvl; 628 $item['open'] = $return; 629 630 if($opts['meta']){ 631 $item['file'] = basename($file); 632 $item['size'] = filesize($base.'/'.$file); 633 $item['mtime'] = filemtime($base.'/'.$file); 634 $item['rev'] = $item['mtime']; 635 $item['writable'] = is_writable($base.'/'.$file); 636 $item['executable'] = is_executable($base.'/'.$file); 637 } 638 639 if($type == 'f'){ 640 if($opts['hash']) $item['hash'] = md5(io_readFile($base.'/'.$file,false)); 641 if($opts['firsthead']) $item['title'] = p_get_first_heading($item['id'],false); 642 } 643 644 // finally add the item 645 $data[] = $item; 646 return $return; 647} 648 649//Setup VIM: ex: et ts=4 enc=utf-8 : 650