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 //get the script URL 29 if($conf['basedir']){ 30 $relpath = ''; 31 if($param != 'id') { 32 $relpath = 'lib/exe/'; 33 } 34 $script = $conf['basedir'].$relpath.basename($_SERVER['SCRIPT_FILENAME']); 35 }elseif($_SERVER['DOCUMENT_ROOT'] && $_SERVER['SCRIPT_FILENAME']){ 36 $script = preg_replace ('/^'.preg_quote($_SERVER['DOCUMENT_ROOT'],'/').'/','', 37 $_SERVER['SCRIPT_FILENAME']); 38 $script = '/'.$script; 39 }else{ 40 $script = $_SERVER['SCRIPT_NAME']; 41 } 42 43 //clean script and request (fixes a windows problem) 44 $script = preg_replace('/\/\/+/','/',$script); 45 $request = preg_replace('/\/\/+/','/',$_SERVER['REQUEST_URI']); 46 47 //remove script URL and Querystring to gain the id 48 if(preg_match('/^'.preg_quote($script,'/').'(.*)/',$request, $match)){ 49 $id = preg_replace ('/\?.*/','',$match[1]); 50 } 51 $id = urldecode($id); 52 //strip leading slashes 53 $id = preg_replace('!^/+!','',$id); 54 } 55 56 // Namespace autolinking from URL 57 if(substr($id,-1) == ':' || ($conf['useslash'] && substr($id,-1) == '/')){ 58 if(@file_exists(wikiFN($id.$conf['start']))){ 59 // start page inside namespace 60 $id = $id.$conf['start']; 61 }elseif(@file_exists(wikiFN($id.noNS(cleanID($id))))){ 62 // page named like the NS inside the NS 63 $id = $id.noNS(cleanID($id)); 64 }elseif(@file_exists(wikiFN($id))){ 65 // page like namespace exists 66 $id = substr($id,0,-1); 67 }else{ 68 // fall back to default 69 $id = $id.$conf['start']; 70 } 71 header("Location: ".wl($id,'',true)); 72 } 73 74 if($clean) $id = cleanID($id); 75 if(empty($id) && $param=='id') $id = $conf['start']; 76 77 return $id; 78} 79 80/** 81 * Remove unwanted chars from ID 82 * 83 * Cleans a given ID to only use allowed characters. Accented characters are 84 * converted to unaccented ones 85 * 86 * @author Andreas Gohr <andi@splitbrain.org> 87 * @param string $raw_id The pageid to clean 88 * @param boolean $ascii Force ASCII 89 */ 90function cleanID($raw_id,$ascii=false){ 91 global $conf; 92 global $lang; 93 static $sepcharpat = null; 94 95 global $cache_cleanid; 96 $cache = & $cache_cleanid; 97 98 // check if it's already in the memory cache 99 if (isset($cache[$raw_id])) { 100 return $cache[$raw_id]; 101 } 102 103 $sepchar = $conf['sepchar']; 104 if($sepcharpat == null) // build string only once to save clock cycles 105 $sepcharpat = '#\\'.$sepchar.'+#'; 106 107 $id = trim($raw_id); 108 $id = utf8_strtolower($id); 109 110 //alternative namespace seperator 111 $id = strtr($id,';',':'); 112 if($conf['useslash']){ 113 $id = strtr($id,'/',':'); 114 }else{ 115 $id = strtr($id,'/',$sepchar); 116 } 117 118 if($conf['deaccent'] == 2 || $ascii) $id = utf8_romanize($id); 119 if($conf['deaccent'] || $ascii) $id = utf8_deaccent($id,-1); 120 121 //remove specials 122 $id = utf8_stripspecials($id,$sepchar,'\*'); 123 124 if($ascii) $id = utf8_strip($id); 125 126 //clean up 127 $id = preg_replace($sepcharpat,$sepchar,$id); 128 $id = preg_replace('#:+#',':',$id); 129 $id = trim($id,':._-'); 130 $id = preg_replace('#:[:\._\-]+#',':',$id); 131 132 $cache[$raw_id] = $id; 133 return($id); 134} 135 136/** 137 * Return namespacepart of a wiki ID 138 * 139 * @author Andreas Gohr <andi@splitbrain.org> 140 */ 141function getNS($id){ 142 $pos = strrpos($id,':'); 143 if($pos!==false){ 144 return substr($id,0,$pos); 145 } 146 return false; 147} 148 149/** 150 * Returns the ID without the namespace 151 * 152 * @author Andreas Gohr <andi@splitbrain.org> 153 */ 154function noNS($id) { 155 $pos = strrpos($id, ':'); 156 if ($pos!==false) { 157 return substr($id, $pos+1); 158 } else { 159 return $id; 160 } 161} 162 163/** 164* Returns the current namespace 165* 166* @author Nathan Fritz <fritzn@crown.edu> 167*/ 168function curNS($id) { 169 return noNS(getNS($id)); 170} 171 172/** 173* Returns the ID without the namespace or current namespace for 'start' pages 174* 175* @author Nathan Fritz <fritzn@crown.edu> 176*/ 177function noNSorNS($id) { 178 global $conf; 179 180 $p = noNS($id); 181 if ($p == $conf['start']) { 182 $p = curNS($id); 183 if ($p == false) { 184 return noNS($id); 185 } 186 } 187 return $p; 188} 189 190/** 191 * returns the full path to the datafile specified by ID and 192 * optional revision 193 * 194 * The filename is URL encoded to protect Unicode chars 195 * 196 * @author Andreas Gohr <andi@splitbrain.org> 197 */ 198function wikiFN($raw_id,$rev='',$clean=true){ 199 global $conf; 200 201 global $cache_wikifn; 202 $cache = & $cache_wikifn; 203 204 if (isset($cache[$raw_id]) && isset($cache[$raw_id][$rev])) { 205 return $cache[$raw_id][$rev]; 206 } 207 208 $id = $raw_id; 209 210 if ($clean) $id = cleanID($id); 211 $id = str_replace(':','/',$id); 212 if(empty($rev)){ 213 $fn = $conf['datadir'].'/'.utf8_encodeFN($id).'.txt'; 214 }else{ 215 $fn = $conf['olddir'].'/'.utf8_encodeFN($id).'.'.$rev.'.txt'; 216 if($conf['compression']){ 217 //test for extensions here, we want to read both compressions 218 if (@file_exists($fn . '.gz')){ 219 $fn .= '.gz'; 220 }else if(@file_exists($fn . '.bz2')){ 221 $fn .= '.bz2'; 222 }else{ 223 //file doesnt exist yet, so we take the configured extension 224 $fn .= '.' . $conf['compression']; 225 } 226 } 227 } 228 229 if (!isset($cache[$raw_id])) { $cache[$raw_id] = array(); } 230 $cache[$raw_id][$rev] = $fn; 231 return $fn; 232} 233 234/** 235 * Returns the full path to the file for locking the page while editing. 236 * 237 * @author Ben Coburn <btcoburn@silicodon.net> 238 */ 239function wikiLockFN($id) { 240 global $conf; 241 return $conf['lockdir'].'/'.md5(cleanID($id)).'.lock'; 242} 243 244 245/** 246 * returns the full path to the meta file specified by ID and extension 247 * 248 * The filename is URL encoded to protect Unicode chars 249 * 250 * @author Steven Danz <steven-danz@kc.rr.com> 251 */ 252function metaFN($id,$ext){ 253 global $conf; 254 $id = cleanID($id); 255 $id = str_replace(':','/',$id); 256 $fn = $conf['metadir'].'/'.utf8_encodeFN($id).$ext; 257 return $fn; 258} 259 260/** 261 * returns an array of full paths to all metafiles of a given ID 262 * 263 * @author Esther Brunner <esther@kaffeehaus.ch> 264 */ 265function metaFiles($id){ 266 $name = noNS($id); 267 $dir = metaFN(getNS($id),''); 268 $files = array(); 269 270 $dh = @opendir($dir); 271 if(!$dh) return $files; 272 while(($file = readdir($dh)) !== false){ 273 if(strpos($file,$name.'.') === 0 && !is_dir($dir.$file)) 274 $files[] = $dir.$file; 275 } 276 closedir($dh); 277 278 return $files; 279} 280 281/** 282 * returns the full path to the mediafile specified by ID 283 * 284 * The filename is URL encoded to protect Unicode chars 285 * 286 * @author Andreas Gohr <andi@splitbrain.org> 287 */ 288function mediaFN($id){ 289 global $conf; 290 $id = cleanID($id); 291 $id = str_replace(':','/',$id); 292 $fn = $conf['mediadir'].'/'.utf8_encodeFN($id); 293 return $fn; 294} 295 296/** 297 * Returns the full filepath to a localized textfile if local 298 * version isn't found the english one is returned 299 * 300 * @author Andreas Gohr <andi@splitbrain.org> 301 */ 302function localeFN($id){ 303 global $conf; 304 $file = DOKU_INC.'inc/lang/'.$conf['lang'].'/'.$id.'.txt'; 305 if(!@file_exists($file)){ 306 //fall back to english 307 $file = DOKU_INC.'inc/lang/en/'.$id.'.txt'; 308 } 309 return $file; 310} 311 312/** 313 * Resolve relative paths in IDs 314 * 315 * Do not call directly use resolve_mediaid or resolve_pageid 316 * instead 317 * 318 * Partyly based on a cleanPath function found at 319 * http://www.php.net/manual/en/function.realpath.php#57016 320 * 321 * @author <bart at mediawave dot nl> 322 */ 323function resolve_id($ns,$id,$clean=true){ 324 global $conf; 325 326 // some pre cleaning for useslash: 327 if($conf['useslash']) $id = str_replace('/',':',$id); 328 329 // if the id starts with a dot we need to handle the 330 // relative stuff 331 if($id{0} == '.'){ 332 // normalize initial dots without a colon 333 $id = preg_replace('/^(\.+)(?=[^:\.])/','\1:',$id); 334 // prepend the current namespace 335 $id = $ns.':'.$id; 336 337 // cleanup relatives 338 $result = array(); 339 $pathA = explode(':', $id); 340 if (!$pathA[0]) $result[] = ''; 341 foreach ($pathA AS $key => $dir) { 342 if ($dir == '..') { 343 if (end($result) == '..') { 344 $result[] = '..'; 345 } elseif (!array_pop($result)) { 346 $result[] = '..'; 347 } 348 } elseif ($dir && $dir != '.') { 349 $result[] = $dir; 350 } 351 } 352 if (!end($pathA)) $result[] = ''; 353 $id = implode(':', $result); 354 }elseif($ns !== false && strpos($id,':') === false){ 355 //if link contains no namespace. add current namespace (if any) 356 $id = $ns.':'.$id; 357 } 358 359 if($clean) $id = cleanID($id); 360 return $id; 361} 362 363/** 364 * Returns a full media id 365 * 366 * @author Andreas Gohr <andi@splitbrain.org> 367 */ 368function resolve_mediaid($ns,&$page,&$exists){ 369 $page = resolve_id($ns,$page); 370 $file = mediaFN($page); 371 $exists = @file_exists($file); 372} 373 374/** 375 * Returns a full page id 376 * 377 * @author Andreas Gohr <andi@splitbrain.org> 378 */ 379function resolve_pageid($ns,&$page,&$exists){ 380 global $conf; 381 $exists = false; 382 383 //keep hashlink if exists then clean both parts 384 if (strpos($page,'#')) { 385 list($page,$hash) = split('#',$page,2); 386 } else { 387 $hash = ''; 388 } 389 $hash = cleanID($hash); 390 $page = resolve_id($ns,$page,false); // resolve but don't clean, yet 391 392 // get filename (calls clean itself) 393 $file = wikiFN($page); 394 395 // if ends with colon or slash we have a namespace link 396 if(substr($page,-1) == ':' || ($conf['useslash'] && substr($page,-1) == '/')){ 397 if(@file_exists(wikiFN($page.$conf['start']))){ 398 // start page inside namespace 399 $page = $page.$conf['start']; 400 $exists = true; 401 }elseif(@file_exists(wikiFN($page.noNS(cleanID($page))))){ 402 // page named like the NS inside the NS 403 $page = $page.noNS(cleanID($page)); 404 $exists = true; 405 }elseif(@file_exists(wikiFN($page))){ 406 // page like namespace exists 407 $page = $page; 408 $exists = true; 409 }else{ 410 // fall back to default 411 $page = $page.$conf['start']; 412 } 413 }else{ 414 //check alternative plural/nonplural form 415 if(!@file_exists($file)){ 416 if( $conf['autoplural'] ){ 417 if(substr($page,-1) == 's'){ 418 $try = substr($page,0,-1); 419 }else{ 420 $try = $page.'s'; 421 } 422 if(@file_exists(wikiFN($try))){ 423 $page = $try; 424 $exists = true; 425 } 426 } 427 }else{ 428 $exists = true; 429 } 430 } 431 432 // now make sure we have a clean page 433 $page = cleanID($page); 434 435 //add hash if any 436 if(!empty($hash)) $page .= '#'.$hash; 437} 438 439/** 440 * Returns the name of a cachefile from given data 441 * 442 * The needed directory is created by this function! 443 * 444 * @author Andreas Gohr <andi@splitbrain.org> 445 * 446 * @param string $data This data is used to create a unique md5 name 447 * @param string $ext This is appended to the filename if given 448 * @return string The filename of the cachefile 449 */ 450function getCacheName($data,$ext=''){ 451 global $conf; 452 $md5 = md5($data); 453 $file = $conf['cachedir'].'/'.$md5{0}.'/'.$md5.$ext; 454 io_makeFileDir($file); 455 return $file; 456} 457 458/** 459 * Checks a pageid against $conf['hidepages'] 460 * 461 * @author Andreas Gohr <gohr@cosmocode.de> 462 */ 463function isHiddenPage($id){ 464 global $conf; 465 if(empty($conf['hidepages'])) return false; 466 467 if(preg_match('/'.$conf['hidepages'].'/ui',':'.$id)){ 468 return true; 469 } 470 return false; 471} 472 473/** 474 * Reverse of isHiddenPage 475 * 476 * @author Andreas Gohr <gohr@cosmocode.de> 477 */ 478function isVisiblePage($id){ 479 return !isHiddenPage($id); 480} 481 482/** 483 * Checks and sets HTTP headers for conditional HTTP requests 484 * 485 * @author Simon Willison <swillison@gmail.com> 486 * @link http://simon.incutio.com/archive/2003/04/23/conditionalGet 487 * @param timestamp $timestamp lastmodified time of the cache file 488 * @returns void or void with previously header() commands executed 489 */ 490function http_conditionalRequest($timestamp){ 491 // A PHP implementation of conditional get, see 492 // http://fishbowl.pastiche.org/archives/001132.html 493 $last_modified = substr(gmdate('r', $timestamp), 0, -5).'GMT'; 494 $etag = '"'.md5($last_modified).'"'; 495 // Send the headers 496 header("Last-Modified: $last_modified"); 497 header("ETag: $etag"); 498 // See if the client has provided the required headers 499 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])){ 500 $if_modified_since = stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']); 501 }else{ 502 $if_modified_since = false; 503 } 504 505 if (isset($_SERVER['HTTP_IF_NONE_MATCH'])){ 506 $if_none_match = stripslashes($_SERVER['HTTP_IF_NONE_MATCH']); 507 }else{ 508 $if_none_match = false; 509 } 510 511 if (!$if_modified_since && !$if_none_match){ 512 return; 513 } 514 515 // At least one of the headers is there - check them 516 if ($if_none_match && $if_none_match != $etag) { 517 return; // etag is there but doesn't match 518 } 519 520 if ($if_modified_since && $if_modified_since != $last_modified) { 521 return; // if-modified-since is there but doesn't match 522 } 523 524 // Nothing has changed since their last request - serve a 304 and exit 525 header('HTTP/1.0 304 Not Modified'); 526 exit; 527} 528 529//Setup VIM: ex: et ts=2 enc=utf-8 : 530