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