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 //we do nothing with directories 189 if($type == 'd') { 190 if(!$opts['depth']) return true; // recurse forever 191 $parts = explode('/',ltrim($file,'/')); 192 if(count($parts) == $opts['depth']) return false; // depth reached 193 return true; 194 } 195 196 $info = array(); 197 $info['id'] = pathID($file,true); 198 if($info['id'] != cleanID($info['id'])){ 199 if($opts['showmsg']) 200 msg(hsc($info['id']).' is not a valid file name for DokuWiki - skipped',-1); 201 return false; // skip non-valid files 202 } 203 204 //check ACL for namespace (we have no ACL for mediafiles) 205 $info['perm'] = auth_quickaclcheck(getNS($info['id']).':*'); 206 if(!$opts['skipacl'] && $info['perm'] < AUTH_READ){ 207 return false; 208 } 209 210 //check pattern filter 211 if($opts['pattern'] && !@preg_match($opts['pattern'], $info['id'])){ 212 return false; 213 } 214 215 $info['file'] = basename($file); 216 $info['size'] = filesize($base.'/'.$file); 217 $info['mtime'] = filemtime($base.'/'.$file); 218 $info['writable'] = is_writable($base.'/'.$file); 219 if(preg_match("/\.(jpe?g|gif|png)$/",$file)){ 220 $info['isimg'] = true; 221 require_once(DOKU_INC.'inc/JpegMeta.php'); 222 $info['meta'] = new JpegMeta($base.'/'.$file); 223 }else{ 224 $info['isimg'] = false; 225 } 226 if($opts['hash']){ 227 $info['hash'] = md5(io_readFile(wikiFN($info['id']),false)); 228 } 229 230 $data[] = $info; 231 232 return false; 233} 234 235/** 236 * This function just lists documents (for RSS namespace export) 237 * 238 * @author Andreas Gohr <andi@splitbrain.org> 239 */ 240function search_list(&$data,$base,$file,$type,$lvl,$opts){ 241 //we do nothing with directories 242 if($type == 'd') return false; 243 //only search txt files 244 if(substr($file,-4) == '.txt'){ 245 //check ACL 246 $id = pathID($file); 247 if(auth_quickaclcheck($id) < AUTH_READ){ 248 return false; 249 } 250 $data[]['id'] = $id; 251 } 252 return false; 253} 254 255/** 256 * Quicksearch for searching matching pagenames 257 * 258 * $opts['query'] is the search query 259 * 260 * @author Andreas Gohr <andi@splitbrain.org> 261 */ 262function search_pagename(&$data,$base,$file,$type,$lvl,$opts){ 263 //we do nothing with directories 264 if($type == 'd') return true; 265 //only search txt files 266 if(substr($file,-4) != '.txt') return true; 267 268 //simple stringmatching 269 if (!empty($opts['query'])){ 270 if(strpos($file,$opts['query']) !== false){ 271 //check ACL 272 $id = pathID($file); 273 if(auth_quickaclcheck($id) < AUTH_READ){ 274 return false; 275 } 276 $data[]['id'] = $id; 277 } 278 } 279 return true; 280} 281 282/** 283 * Just lists all documents 284 * 285 * $opts['depth'] recursion level, 0 for all 286 * $opts['hash'] do md5 sum of content? 287 * $opts['skipacl'] list everything regardless of ACL 288 * 289 * @author Andreas Gohr <andi@splitbrain.org> 290 */ 291function search_allpages(&$data,$base,$file,$type,$lvl,$opts){ 292 //we do nothing with directories 293 if($type == 'd'){ 294 if(!$opts['depth']) return true; // recurse forever 295 $parts = explode('/',ltrim($file,'/')); 296 if(count($parts) == $opts['depth']) return false; // depth reached 297 return true; 298 } 299 300 //only search txt files 301 if(substr($file,-4) != '.txt') return true; 302 303 $item['id'] = pathID($file); 304 if(!$opts['skipacl'] && auth_quickaclcheck($item['id']) < AUTH_READ){ 305 return false; 306 } 307 308 $item['rev'] = filemtime($base.'/'.$file); 309 $item['mtime'] = $item['rev']; 310 $item['size'] = filesize($base.'/'.$file); 311 if($opts['hash']){ 312 $item['hash'] = md5(trim(rawWiki($item['id']))); 313 } 314 315 $data[] = $item; 316 return true; 317} 318 319/** 320 * Search for backlinks to a given page 321 * 322 * $opts['ns'] namespace of the page 323 * $opts['name'] name of the page without namespace 324 * 325 * @author Andreas Gohr <andi@splitbrain.org> 326 * @deprecated Replaced by ft_backlinks() 327 */ 328function search_backlinks(&$data,$base,$file,$type,$lvl,$opts){ 329 //we do nothing with directories 330 if($type == 'd') return true; 331 //only search txt files 332 if(substr($file,-4) != '.txt') return true; 333 334 //absolute search id 335 $sid = cleanID($opts['ns'].':'.$opts['name']); 336 337 //current id and namespace 338 $cid = pathID($file); 339 $cns = getNS($cid); 340 341 //check ACL 342 if(auth_quickaclcheck($cid) < AUTH_READ){ 343 return false; 344 } 345 346 //fetch instructions 347 require_once(DOKU_INC.'inc/parserutils.php'); 348 $instructions = p_cached_instructions($base.$file,true); 349 if(is_null($instructions)) return false; 350 351 //check all links for match 352 foreach($instructions as $ins){ 353 if($ins[0] == 'internallink' || ($conf['camelcase'] && $ins[0] == 'camelcaselink') ){ 354 $mid = $ins[1][0]; 355 resolve_pageid($cns,$mid,$exists); //exists is not used 356 if($mid == $sid){ 357 //we have a match - finish 358 $data[]['id'] = $cid; 359 break; 360 } 361 } 362 } 363 364 return false; 365} 366 367/** 368 * Fulltextsearch 369 * 370 * $opts['query'] is the search query 371 * 372 * @author Andreas Gohr <andi@splitbrain.org> 373 * @deprecated - fulltext indexer is used instead 374 */ 375function search_fulltext(&$data,$base,$file,$type,$lvl,$opts){ 376 //we do nothing with directories 377 if($type == 'd') return true; 378 //only search txt files 379 if(substr($file,-4) != '.txt') return true; 380 381 //check ACL 382 $id = pathID($file); 383 if(auth_quickaclcheck($id) < AUTH_READ){ 384 return false; 385 } 386 387 //create regexp from queries 388 $poswords = array(); 389 $negwords = array(); 390 $qpreg = preg_split('/\s+/',$opts['query']); 391 392 foreach($qpreg as $word){ 393 switch(substr($word,0,1)){ 394 case '-': 395 if(strlen($word) > 1){ // catch single '-' 396 array_push($negwords,preg_quote(substr($word,1),'#')); 397 } 398 break; 399 case '+': 400 if(strlen($word) > 1){ // catch single '+' 401 array_push($poswords,preg_quote(substr($word,1),'#')); 402 } 403 break; 404 default: 405 array_push($poswords,preg_quote($word,'#')); 406 break; 407 } 408 } 409 410 // a search without any posword is useless 411 if (!count($poswords)) return true; 412 413 $reg = '^(?=.*?'.join(')(?=.*?',$poswords).')'; 414 $reg .= count($negwords) ? '((?!'.join('|',$negwords).').)*$' : '.*$'; 415 search_regex($data,$base,$file,$reg,$poswords); 416 return true; 417} 418 419/** 420 * Reference search 421 * This fuction searches for existing references to a given media file 422 * and returns an array with the found pages. It doesn't pay any 423 * attention to ACL permissions to find every reference. The caller 424 * must check if the user has the appropriate rights to see the found 425 * page and eventually have to prevent the result from displaying. 426 * 427 * @param array $data Reference to the result data structure 428 * @param string $base Base usually $conf['datadir'] 429 * @param string $file current file or directory relative to $base 430 * @param char $type Type either 'd' for directory or 'f' for file 431 * @param int $lvl Current recursion depht 432 * @param mixed $opts option array as given to search() 433 * 434 * $opts['query'] is the demanded media file name 435 * 436 * @author Andreas Gohr <andi@splitbrain.org> 437 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> 438 */ 439function search_reference(&$data,$base,$file,$type,$lvl,$opts){ 440 global $conf; 441 442 //we do nothing with directories 443 if($type == 'd') return true; 444 445 //only search txt files 446 if(substr($file,-4) != '.txt') return true; 447 448 //we finish after 'cnt' references found. The return value 449 //'false' will skip subdirectories to speed search up. 450 $cnt = $conf['refshow'] > 0 ? $conf['refshow'] : 1; 451 if(count($data) >= $cnt) return false; 452 453 $reg = '\{\{ *\:?'.$opts['query'].' *(\|.*)?\}\}'; 454 search_regex($data,$base,$file,$reg,array($opts['query'])); 455 return true; 456} 457 458/* ------------- helper functions below -------------- */ 459 460/** 461 * fulltext search helper 462 * searches a text file with a given regular expression 463 * no ACL checks are performed. This have to be done by 464 * the caller if necessary. 465 * 466 * @param array $data reference to array for results 467 * @param string $base base directory 468 * @param string $file file name to search in 469 * @param string $reg regular expression to search for 470 * @param array $words words that should be marked in the results 471 * 472 * @author Andreas Gohr <andi@splitbrain.org> 473 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> 474 * 475 * @deprecated - fulltext indexer is used instead 476 */ 477function search_regex(&$data,$base,$file,$reg,$words){ 478 479 //get text 480 $text = io_readfile($base.'/'.$file); 481 //lowercase text (u modifier does not help with case) 482 $lctext = utf8_strtolower($text); 483 484 //do the fulltext search 485 $matches = array(); 486 if($cnt = preg_match_all('#'.$reg.'#usi',$lctext,$matches)){ 487 //this is not the best way for snippet generation but the fastest I could find 488 $q = $words[0]; //use first word for snippet creation 489 $p = utf8_strpos($lctext,$q); 490 $f = $p - 100; 491 $l = utf8_strlen($q) + 200; 492 if($f < 0) $f = 0; 493 $snippet = '<span class="search_sep"> ... </span>'. 494 htmlspecialchars(utf8_substr($text,$f,$l)). 495 '<span class="search_sep"> ... </span>'; 496 $mark = '('.join('|', $words).')'; 497 $snippet = preg_replace('#'.$mark.'#si','<strong class="search_hit">\\1</strong>',$snippet); 498 499 $data[] = array( 500 'id' => pathID($file), 501 'count' => preg_match_all('#'.$mark.'#usi',$lctext,$matches), 502 'poswords' => join(' ',$words), 503 'snippet' => $snippet, 504 ); 505 } 506 507 return true; 508} 509 510 511/** 512 * fulltext sort 513 * 514 * Callback sort function for use with usort to sort the data 515 * structure created by search_fulltext. Sorts descending by count 516 * 517 * @author Andreas Gohr <andi@splitbrain.org> 518 */ 519function sort_search_fulltext($a,$b){ 520 if($a['count'] > $b['count']){ 521 return -1; 522 }elseif($a['count'] < $b['count']){ 523 return 1; 524 }else{ 525 return strcmp($a['id'],$b['id']); 526 } 527} 528 529/** 530 * translates a document path to an ID 531 * 532 * @author Andreas Gohr <andi@splitbrain.org> 533 * @todo move to pageutils 534 */ 535function pathID($path,$keeptxt=false){ 536 $id = utf8_decodeFN($path); 537 $id = str_replace('/',':',$id); 538 if(!$keeptxt) $id = preg_replace('#\.txt$#','',$id); 539 $id = preg_replace('#^:+#','',$id); 540 $id = preg_replace('#:+$#','',$id); 541 return $id; 542} 543 544 545//Setup VIM: ex: et ts=2 enc=utf-8 : 546