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