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