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