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