1<?php 2/** 3 * Utilities for handling pagenames 4 * 5 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) 6 * @author Andreas Gohr <andi@splitbrain.org> 7 * @todo Combine similar functions like {wiki,media,meta}FN() 8 */ 9 10/** 11 * Fetch the an ID from request 12 * 13 * Uses either standard $_REQUEST variable or extracts it from 14 * the full request URI when userewrite is set to 2 15 * 16 * For $param='id' $conf['start'] is returned if no id was found. 17 * If the second parameter is true (default) the ID is cleaned. 18 * 19 * @author Andreas Gohr <andi@splitbrain.org> 20 */ 21function getID($param='id',$clean=true){ 22 global $conf; 23 24 $id = isset($_REQUEST[$param]) ? $_REQUEST[$param] : null; 25 26 //construct page id from request URI 27 if(empty($id) && $conf['userewrite'] == 2){ 28 $request = $_SERVER['REQUEST_URI']; 29 $script = ''; 30 31 //get the script URL 32 if($conf['basedir']){ 33 $relpath = ''; 34 if($param != 'id') { 35 $relpath = 'lib/exe/'; 36 } 37 $script = $conf['basedir'].$relpath.basename($_SERVER['SCRIPT_FILENAME']); 38 39 }elseif($_SERVER['PATH_INFO']){ 40 $request = $_SERVER['PATH_INFO']; 41 }elseif($_SERVER['SCRIPT_NAME']){ 42 $script = $_SERVER['SCRIPT_NAME']; 43 }elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){ 44 $script = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','', 45 $_SERVER['SCRIPT_FILENAME']); 46 $script = '/'.$script; 47 } 48 49 //clean script and request (fixes a windows problem) 50 $script = preg_replace('/\/\/+/','/',$script); 51 $request = preg_replace('/\/\/+/','/',$request); 52 53 //remove script URL and Querystring to gain the id 54 if(preg_match('/^'.preg_quote($script,'/').'(.*)/',$request, $match)){ 55 $id = preg_replace ('/\?.*/','',$match[1]); 56 } 57 $id = urldecode($id); 58 //strip leading slashes 59 $id = preg_replace('!^/+!','',$id); 60 } 61 62 // Namespace autolinking from URL 63 if(substr($id,-1) == ':' || ($conf['useslash'] && substr($id,-1) == '/')){ 64 if(page_exists($id.$conf['start'])){ 65 // start page inside namespace 66 $id = $id.$conf['start']; 67 }elseif(page_exists($id.noNS(cleanID($id)))){ 68 // page named like the NS inside the NS 69 $id = $id.noNS(cleanID($id)); 70 }elseif(page_exists($id)){ 71 // page like namespace exists 72 $id = substr($id,0,-1); 73 }else{ 74 // fall back to default 75 $id = $id.$conf['start']; 76 } 77 send_redirect(wl($id,'',true)); 78 } 79 80 if($clean) $id = cleanID($id); 81 if(empty($id) && $param=='id') $id = $conf['start']; 82 83 return $id; 84} 85 86/** 87 * Remove unwanted chars from ID 88 * 89 * Cleans a given ID to only use allowed characters. Accented characters are 90 * converted to unaccented ones 91 * 92 * @author Andreas Gohr <andi@splitbrain.org> 93 * @param string $raw_id The pageid to clean 94 * @param boolean $ascii Force ASCII 95 * @param boolean $media Allow leading or trailing _ for media files 96 */ 97function cleanID($raw_id,$ascii=false,$media=false){ 98 global $conf; 99 static $sepcharpat = null; 100 101 global $cache_cleanid; 102 $cache = & $cache_cleanid; 103 104 // check if it's already in the memory cache 105 if (isset($cache[(string)$raw_id])) { 106 return $cache[(string)$raw_id]; 107 } 108 109 $sepchar = $conf['sepchar']; 110 if($sepcharpat == null) // build string only once to save clock cycles 111 $sepcharpat = '#\\'.$sepchar.'+#'; 112 113 $id = trim((string)$raw_id); 114 $id = utf8_strtolower($id); 115 116 //alternative namespace seperator 117 $id = strtr($id,';',':'); 118 if($conf['useslash']){ 119 $id = strtr($id,'/',':'); 120 }else{ 121 $id = strtr($id,'/',$sepchar); 122 } 123 124 if($conf['deaccent'] == 2 || $ascii) $id = utf8_romanize($id); 125 if($conf['deaccent'] || $ascii) $id = utf8_deaccent($id,-1); 126 127 //remove specials 128 $id = utf8_stripspecials($id,$sepchar,'\*'); 129 130 if($ascii) $id = utf8_strip($id); 131 132 //clean up 133 $id = preg_replace($sepcharpat,$sepchar,$id); 134 $id = preg_replace('#:+#',':',$id); 135 $id = ($media ? trim($id,':.-') : trim($id,':._-')); 136 $id = preg_replace('#:[:\._\-]+#',':',$id); 137 138 $cache[(string)$raw_id] = $id; 139 return($id); 140} 141 142/** 143 * Return namespacepart of a wiki ID 144 * 145 * @author Andreas Gohr <andi@splitbrain.org> 146 */ 147function getNS($id){ 148 $pos = strrpos((string)$id,':'); 149 if($pos!==false){ 150 return substr((string)$id,0,$pos); 151 } 152 return false; 153} 154 155/** 156 * Returns the ID without the namespace 157 * 158 * @author Andreas Gohr <andi@splitbrain.org> 159 */ 160function noNS($id) { 161 $pos = strrpos($id, ':'); 162 if ($pos!==false) { 163 return substr($id, $pos+1); 164 } else { 165 return $id; 166 } 167} 168 169/** 170 * Returns the current namespace 171 * 172 * @author Nathan Fritz <fritzn@crown.edu> 173 */ 174function curNS($id) { 175 return noNS(getNS($id)); 176} 177 178/** 179 * Returns the ID without the namespace or current namespace for 'start' pages 180 * 181 * @author Nathan Fritz <fritzn@crown.edu> 182 */ 183function noNSorNS($id) { 184 global $conf; 185 186 $p = noNS($id); 187 if ($p == $conf['start'] || $p == false) { 188 $p = curNS($id); 189 if ($p == false) { 190 return $conf['start']; 191 } 192 } 193 return $p; 194} 195 196/** 197 * Creates a XHTML valid linkid from a given headline title 198 * 199 * @param string $title The headline title 200 * @param array $check Existing IDs (title => number) 201 * @author Andreas Gohr <andi@splitbrain.org> 202 */ 203function sectionID($title,&$check) { 204 $title = str_replace(array(':','.'),'',cleanID($title)); 205 $new = ltrim($title,'0123456789_-'); 206 if(empty($new)){ 207 $title = 'section'.preg_replace('/[^0-9]+/','',$title); //keep numbers from headline 208 }else{ 209 $title = $new; 210 } 211 212 if(is_array($check)){ 213 // make sure tiles are unique 214 if (!array_key_exists ($title,$check)) { 215 $check[$title] = 0; 216 } else { 217 $title .= ++ $check[$title]; 218 } 219 } 220 221 return $title; 222} 223 224 225/** 226 * Wiki page existence check 227 * 228 * parameters as for wikiFN 229 * 230 * @author Chris Smith <chris@jalakai.co.uk> 231 */ 232function page_exists($id,$rev='',$clean=true) { 233 return @file_exists(wikiFN($id,$rev,$clean)); 234} 235 236/** 237 * returns the full path to the datafile specified by ID and optional revision 238 * 239 * The filename is URL encoded to protect Unicode chars 240 * 241 * @param $raw_id string id of wikipage 242 * @param $rev string page revision, empty string for current 243 * @param $clean bool flag indicating that $raw_id should be cleaned. Only set to false 244 * when $id is guaranteed to have been cleaned already. 245 * 246 * @author Andreas Gohr <andi@splitbrain.org> 247 */ 248function wikiFN($raw_id,$rev='',$clean=true){ 249 global $conf; 250 251 global $cache_wikifn; 252 $cache = & $cache_wikifn; 253 254 if (isset($cache[$raw_id]) && isset($cache[$raw_id][$rev])) { 255 return $cache[$raw_id][$rev]; 256 } 257 258 $id = $raw_id; 259 260 if ($clean) $id = cleanID($id); 261 $id = str_replace(':','/',$id); 262 if(empty($rev)){ 263 $fn = $conf['datadir'].'/'.utf8_encodeFN($id).'.txt'; 264 }else{ 265 $fn = $conf['olddir'].'/'.utf8_encodeFN($id).'.'.$rev.'.txt'; 266 if($conf['compression']){ 267 //test for extensions here, we want to read both compressions 268 if (@file_exists($fn . '.gz')){ 269 $fn .= '.gz'; 270 }else if(@file_exists($fn . '.bz2')){ 271 $fn .= '.bz2'; 272 }else{ 273 //file doesnt exist yet, so we take the configured extension 274 $fn .= '.' . $conf['compression']; 275 } 276 } 277 } 278 279 if (!isset($cache[$raw_id])) { $cache[$raw_id] = array(); } 280 $cache[$raw_id][$rev] = $fn; 281 return $fn; 282} 283 284/** 285 * Returns the full path to the file for locking the page while editing. 286 * 287 * @author Ben Coburn <btcoburn@silicodon.net> 288 */ 289function wikiLockFN($id) { 290 global $conf; 291 return $conf['lockdir'].'/'.md5(cleanID($id)).'.lock'; 292} 293 294 295/** 296 * returns the full path to the meta file specified by ID and extension 297 * 298 * The filename is URL encoded to protect Unicode chars 299 * 300 * @author Steven Danz <steven-danz@kc.rr.com> 301 */ 302function metaFN($id,$ext){ 303 global $conf; 304 $id = cleanID($id); 305 $id = str_replace(':','/',$id); 306 $fn = $conf['metadir'].'/'.utf8_encodeFN($id).$ext; 307 return $fn; 308} 309 310/** 311 * returns an array of full paths to all metafiles of a given ID 312 * 313 * @author Esther Brunner <esther@kaffeehaus.ch> 314 */ 315function metaFiles($id){ 316 $name = noNS($id); 317 $ns = getNS($id); 318 $dir = ($ns) ? metaFN($ns,'').'/' : metaFN($ns,''); 319 $files = array(); 320 $files = glob($dir.$name.'.*'); 321 return $files; 322} 323 324/** 325 * returns the full path to the mediafile specified by ID 326 * 327 * The filename is URL encoded to protect Unicode chars 328 * 329 * @author Andreas Gohr <andi@splitbrain.org> 330 */ 331function mediaFN($id){ 332 global $conf; 333 $id = cleanID($id); 334 $id = str_replace(':','/',$id); 335 $fn = $conf['mediadir'].'/'.utf8_encodeFN($id); 336 return $fn; 337} 338 339/** 340 * Returns the full filepath to a localized textfile if local 341 * version isn't found the english one is returned 342 * 343 * @author Andreas Gohr <andi@splitbrain.org> 344 */ 345function localeFN($id){ 346 global $conf; 347 $file = DOKU_CONF.'/lang/'.$conf['lang'].'/'.$id.'.txt'; 348 if(!@file_exists($file)){ 349 $file = DOKU_INC.'inc/lang/'.$conf['lang'].'/'.$id.'.txt'; 350 if(!@file_exists($file)){ 351 //fall back to english 352 $file = DOKU_INC.'inc/lang/en/'.$id.'.txt'; 353 } 354 } 355 return $file; 356} 357 358/** 359 * Resolve relative paths in IDs 360 * 361 * Do not call directly use resolve_mediaid or resolve_pageid 362 * instead 363 * 364 * Partyly based on a cleanPath function found at 365 * http://www.php.net/manual/en/function.realpath.php#57016 366 * 367 * @author <bart at mediawave dot nl> 368 */ 369function resolve_id($ns,$id,$clean=true){ 370 global $conf; 371 372 // some pre cleaning for useslash: 373 if($conf['useslash']) $id = str_replace('/',':',$id); 374 375 // if the id starts with a dot we need to handle the 376 // relative stuff 377 if($id{0} == '.'){ 378 // normalize initial dots without a colon 379 $id = preg_replace('/^(\.+)(?=[^:\.])/','\1:',$id); 380 // prepend the current namespace 381 $id = $ns.':'.$id; 382 383 // cleanup relatives 384 $result = array(); 385 $pathA = explode(':', $id); 386 if (!$pathA[0]) $result[] = ''; 387 foreach ($pathA AS $key => $dir) { 388 if ($dir == '..') { 389 if (end($result) == '..') { 390 $result[] = '..'; 391 } elseif (!array_pop($result)) { 392 $result[] = '..'; 393 } 394 } elseif ($dir && $dir != '.') { 395 $result[] = $dir; 396 } 397 } 398 if (!end($pathA)) $result[] = ''; 399 $id = implode(':', $result); 400 }elseif($ns !== false && strpos($id,':') === false){ 401 //if link contains no namespace. add current namespace (if any) 402 $id = $ns.':'.$id; 403 } 404 405 if($clean) $id = cleanID($id); 406 return $id; 407} 408 409/** 410 * Returns a full media id 411 * 412 * @author Andreas Gohr <andi@splitbrain.org> 413 */ 414function resolve_mediaid($ns,&$page,&$exists){ 415 $page = resolve_id($ns,$page); 416 $file = mediaFN($page); 417 $exists = @file_exists($file); 418} 419 420/** 421 * Returns a full page id 422 * 423 * @author Andreas Gohr <andi@splitbrain.org> 424 */ 425function resolve_pageid($ns,&$page,&$exists){ 426 global $conf; 427 $exists = false; 428 429 //keep hashlink if exists then clean both parts 430 if (strpos($page,'#')) { 431 list($page,$hash) = explode('#',$page,2); 432 } else { 433 $hash = ''; 434 } 435 $hash = cleanID($hash); 436 $page = resolve_id($ns,$page,false); // resolve but don't clean, yet 437 438 // get filename (calls clean itself) 439 $file = wikiFN($page); 440 441 // if ends with colon or slash we have a namespace link 442 if(in_array(substr($page,-1), array(':', ';')) || 443 ($conf['useslash'] && substr($page,-1) == '/')){ 444 if(page_exists($page.$conf['start'])){ 445 // start page inside namespace 446 $page = $page.$conf['start']; 447 $exists = true; 448 }elseif(page_exists($page.noNS(cleanID($page)))){ 449 // page named like the NS inside the NS 450 $page = $page.noNS(cleanID($page)); 451 $exists = true; 452 }elseif(page_exists($page)){ 453 // page like namespace exists 454 $page = $page; 455 $exists = true; 456 }else{ 457 // fall back to default 458 $page = $page.$conf['start']; 459 } 460 }else{ 461 //check alternative plural/nonplural form 462 if(!@file_exists($file)){ 463 if( $conf['autoplural'] ){ 464 if(substr($page,-1) == 's'){ 465 $try = substr($page,0,-1); 466 }else{ 467 $try = $page.'s'; 468 } 469 if(page_exists($try)){ 470 $page = $try; 471 $exists = true; 472 } 473 } 474 }else{ 475 $exists = true; 476 } 477 } 478 479 // now make sure we have a clean page 480 $page = cleanID($page); 481 482 //add hash if any 483 if(!empty($hash)) $page .= '#'.$hash; 484} 485 486/** 487 * Returns the name of a cachefile from given data 488 * 489 * The needed directory is created by this function! 490 * 491 * @author Andreas Gohr <andi@splitbrain.org> 492 * 493 * @param string $data This data is used to create a unique md5 name 494 * @param string $ext This is appended to the filename if given 495 * @return string The filename of the cachefile 496 */ 497function getCacheName($data,$ext=''){ 498 global $conf; 499 $md5 = md5($data); 500 $file = $conf['cachedir'].'/'.$md5{0}.'/'.$md5.$ext; 501 io_makeFileDir($file); 502 return $file; 503} 504 505/** 506 * Checks a pageid against $conf['hidepages'] 507 * 508 * @author Andreas Gohr <gohr@cosmocode.de> 509 */ 510function isHiddenPage($id){ 511 global $conf; 512 global $ACT; 513 if(empty($conf['hidepages'])) return false; 514 if($ACT == 'admin') return false; 515 516 if(preg_match('/'.$conf['hidepages'].'/ui',':'.$id)){ 517 return true; 518 } 519 return false; 520} 521 522/** 523 * Reverse of isHiddenPage 524 * 525 * @author Andreas Gohr <gohr@cosmocode.de> 526 */ 527function isVisiblePage($id){ 528 return !isHiddenPage($id); 529} 530 531/** 532 * Format an id for output to a user 533 * 534 * Namespaces are denoted by a trailing “:*”. The root namespace is 535 * “*”. Output is escaped. 536 * 537 * @author Adrian Lang <lang@cosmocode.de> 538 */ 539 540function prettyprint_id($id) { 541 if (!$id || $id === ':') { 542 return '*'; 543 } 544 if ((substr($id, -1, 1) === ':')) { 545 $id .= '*'; 546 } 547 return hsc($id); 548} 549 550/** 551 * Encode a UTF-8 filename to use on any filesystem 552 * 553 * Uses the 'fnencode' option to determine encoding 554 * 555 * When the second parameter is true the string will 556 * be encoded only if non ASCII characters are detected - 557 * This makes it safe to run it multiple times on the 558 * same string (default is true) 559 * 560 * @author Andreas Gohr <andi@splitbrain.org> 561 * @see urlencode 562 */ 563function utf8_encodeFN($file,$safe=true){ 564 global $conf; 565 if($conf['fnencode'] == 'utf-8') return $file; 566 567 if($safe && preg_match('#^[a-zA-Z0-9/_\-\.%]+$#',$file)){ 568 return $file; 569 } 570 571 if($conf['fnencode'] == 'safe'){ 572 return SafeFN::encode($file); 573 } 574 575 $file = urlencode($file); 576 $file = str_replace('%2F','/',$file); 577 return $file; 578} 579 580/** 581 * Decode a filename back to UTF-8 582 * 583 * Uses the 'fnencode' option to determine encoding 584 * 585 * @author Andreas Gohr <andi@splitbrain.org> 586 * @see urldecode 587 */ 588function utf8_decodeFN($file){ 589 global $conf; 590 if($conf['fnencode'] == 'utf-8') return $file; 591 592 if($conf['fnencode'] == 'safe'){ 593 return SafeFN::decode($file); 594 } 595 596 return urldecode($file); 597} 598 599