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