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 = $id; 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 // if the id starts with a dot we need to handle the 325 // relative stuff 326 if($id{0} == '.'){ 327 // normalize initial dots without a colon 328 $id = preg_replace('/^(\.+)(?=[^:\.])/','\1:',$id); 329 // prepend the current namespace 330 $id = $ns.':'.$id; 331 332 // cleanup relatives 333 $result = array(); 334 $pathA = explode(':', $id); 335 if (!$pathA[0]) $result[] = ''; 336 foreach ($pathA AS $key => $dir) { 337 if ($dir == '..') { 338 if (end($result) == '..') { 339 $result[] = '..'; 340 } elseif (!array_pop($result)) { 341 $result[] = '..'; 342 } 343 } elseif ($dir && $dir != '.') { 344 $result[] = $dir; 345 } 346 } 347 if (!end($pathA)) $result[] = ''; 348 $id = implode(':', $result); 349 }elseif($ns !== false && strpos($id,':') === false){ 350 //if link contains no namespace. add current namespace (if any) 351 $id = $ns.':'.$id; 352 } 353 354 if($clean) $id = cleanID($id); 355 return $id; 356} 357 358/** 359 * Returns a full media id 360 * 361 * @author Andreas Gohr <andi@splitbrain.org> 362 */ 363function resolve_mediaid($ns,&$page,&$exists){ 364 $page = resolve_id($ns,$page); 365 $file = mediaFN($page); 366 $exists = @file_exists($file); 367} 368 369/** 370 * Returns a full page id 371 * 372 * @author Andreas Gohr <andi@splitbrain.org> 373 */ 374function resolve_pageid($ns,&$page,&$exists){ 375 global $conf; 376 $exists = false; 377 378 //keep hashlink if exists then clean both parts 379 if (strpos($page,'#')) { 380 list($page,$hash) = split('#',$page,2); 381 } else { 382 $hash = ''; 383 } 384 $hash = cleanID($hash); 385 $page = resolve_id($ns,$page,false); // resolve but don't clean, yet 386 387 // get filename (calls clean itself) 388 $file = wikiFN($page); 389 390 // if ends with colon or slash we have a namespace link 391 if(substr($page,-1) == ':' || ($conf['useslash'] && substr($page,-1) == '/')){ 392 if(@file_exists(wikiFN($page.$conf['start']))){ 393 // start page inside namespace 394 $page = $page.$conf['start']; 395 $exists = true; 396 }elseif(@file_exists(wikiFN($page.noNS(cleanID($page))))){ 397 // page named like the NS inside the NS 398 $page = $page.noNS(cleanID($page)); 399 $exists = true; 400 }elseif(@file_exists(wikiFN($page))){ 401 // page like namespace exists 402 $page = $page; 403 $exists = true; 404 }else{ 405 // fall back to default 406 $page = $page.$conf['start']; 407 } 408 }else{ 409 //check alternative plural/nonplural form 410 if(!@file_exists($file)){ 411 if( $conf['autoplural'] ){ 412 if(substr($page,-1) == 's'){ 413 $try = substr($page,0,-1); 414 }else{ 415 $try = $page.'s'; 416 } 417 if(@file_exists(wikiFN($try))){ 418 $page = $try; 419 $exists = true; 420 } 421 } 422 }else{ 423 $exists = true; 424 } 425 } 426 427 // now make sure we have a clean page 428 $page = cleanID($page); 429 430 //add hash if any 431 if(!empty($hash)) $page .= '#'.$hash; 432} 433 434/** 435 * Returns the name of a cachefile from given data 436 * 437 * The needed directory is created by this function! 438 * 439 * @author Andreas Gohr <andi@splitbrain.org> 440 * 441 * @param string $data This data is used to create a unique md5 name 442 * @param string $ext This is appended to the filename if given 443 * @return string The filename of the cachefile 444 */ 445function getCacheName($data,$ext=''){ 446 global $conf; 447 $md5 = md5($data); 448 $file = $conf['cachedir'].'/'.$md5{0}.'/'.$md5.$ext; 449 io_makeFileDir($file); 450 return $file; 451} 452 453/** 454 * Checks a pageid against $conf['hidepages'] 455 * 456 * @author Andreas Gohr <gohr@cosmocode.de> 457 */ 458function isHiddenPage($id){ 459 global $conf; 460 if(empty($conf['hidepages'])) return false; 461 462 if(preg_match('/'.$conf['hidepages'].'/ui',':'.$id)){ 463 return true; 464 } 465 return false; 466} 467 468/** 469 * Reverse of isHiddenPage 470 * 471 * @author Andreas Gohr <gohr@cosmocode.de> 472 */ 473function isVisiblePage($id){ 474 return !isHiddenPage($id); 475} 476 477/** 478 * Checks and sets HTTP headers for conditional HTTP requests 479 * 480 * @author Simon Willison <swillison@gmail.com> 481 * @link http://simon.incutio.com/archive/2003/04/23/conditionalGet 482 * @param timestamp $timestamp lastmodified time of the cache file 483 * @returns void or void with previously header() commands executed 484 */ 485function http_conditionalRequest($timestamp){ 486 // A PHP implementation of conditional get, see 487 // http://fishbowl.pastiche.org/archives/001132.html 488 $last_modified = substr(gmdate('r', $timestamp), 0, -5).'GMT'; 489 $etag = '"'.md5($last_modified).'"'; 490 // Send the headers 491 header("Last-Modified: $last_modified"); 492 header("ETag: $etag"); 493 // See if the client has provided the required headers 494 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])){ 495 $if_modified_since = stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']); 496 }else{ 497 $if_modified_since = false; 498 } 499 500 if (isset($_SERVER['HTTP_IF_NONE_MATCH'])){ 501 $if_none_match = stripslashes($_SERVER['HTTP_IF_NONE_MATCH']); 502 }else{ 503 $if_none_match = false; 504 } 505 506 if (!$if_modified_since && !$if_none_match){ 507 return; 508 } 509 510 // At least one of the headers is there - check them 511 if ($if_none_match && $if_none_match != $etag) { 512 return; // etag is there but doesn't match 513 } 514 515 if ($if_modified_since && $if_modified_since != $last_modified) { 516 return; // if-modified-since is there but doesn't match 517 } 518 519 // Nothing has changed since their last request - serve a 304 and exit 520 header('HTTP/1.0 304 Not Modified'); 521 exit; 522} 523 524//Setup VIM: ex: et ts=2 enc=utf-8 : 525