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