xref: /dokuwiki/inc/pageutils.php (revision 42ea7f447f39fbc2f79eaaec31f8c10ede59c5d0)
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/**
248 * Wiki page existence check
249 *
250 * parameters as for wikiFN
251 *
252 * @author Chris Smith <chris@jalakai.co.uk>
253 *
254 * @param string     $id     page id
255 * @param string|int $rev    empty or revision timestamp
256 * @param bool       $clean  flag indicating that $id should be cleaned (see wikiFN as well)
257 * @return bool exists?
258 */
259function page_exists($id,$rev='',$clean=true) {
260    return @file_exists(wikiFN($id,$rev,$clean));
261}
262
263/**
264 * returns the full path to the datafile specified by ID and optional revision
265 *
266 * The filename is URL encoded to protect Unicode chars
267 *
268 * @param  $raw_id  string   id of wikipage
269 * @param  $rev     int|string   page revision, empty string for current
270 * @param  $clean   bool     flag indicating that $raw_id should be cleaned.  Only set to false
271 *                           when $id is guaranteed to have been cleaned already.
272 * @return string full path
273 *
274 * @author Andreas Gohr <andi@splitbrain.org>
275 */
276function wikiFN($raw_id,$rev='',$clean=true){
277    global $conf;
278
279    global $cache_wikifn;
280    $cache = & $cache_wikifn;
281
282    if (isset($cache[$raw_id]) && isset($cache[$raw_id][$rev])) {
283        return $cache[$raw_id][$rev];
284    }
285
286    $id = $raw_id;
287
288    if ($clean) $id = cleanID($id);
289    $id = str_replace(':','/',$id);
290    if(empty($rev)){
291        $fn = $conf['datadir'].'/'.utf8_encodeFN($id).'.txt';
292    }else{
293        $fn = $conf['olddir'].'/'.utf8_encodeFN($id).'.'.$rev.'.txt';
294        if($conf['compression']){
295            //test for extensions here, we want to read both compressions
296            if (@file_exists($fn . '.gz')){
297                $fn .= '.gz';
298            }else if(@file_exists($fn . '.bz2')){
299                $fn .= '.bz2';
300            }else{
301                //file doesnt exist yet, so we take the configured extension
302                $fn .= '.' . $conf['compression'];
303            }
304        }
305    }
306
307    if (!isset($cache[$raw_id])) { $cache[$raw_id] = array(); }
308    $cache[$raw_id][$rev] = $fn;
309    return $fn;
310}
311
312/**
313 * Returns the full path to the file for locking the page while editing.
314 *
315 * @author Ben Coburn <btcoburn@silicodon.net>
316 *
317 * @param string $id page id
318 * @return string full path
319 */
320function wikiLockFN($id) {
321    global $conf;
322    return $conf['lockdir'].'/'.md5(cleanID($id)).'.lock';
323}
324
325
326/**
327 * returns the full path to the meta file specified by ID and extension
328 *
329 * @author Steven Danz <steven-danz@kc.rr.com>
330 *
331 * @param string $id   page id
332 * @param string $ext  file extension
333 * @return string full path
334 */
335function metaFN($id,$ext){
336    global $conf;
337    $id = cleanID($id);
338    $id = str_replace(':','/',$id);
339    $fn = $conf['metadir'].'/'.utf8_encodeFN($id).$ext;
340    return $fn;
341}
342
343/**
344 * returns the full path to the media's meta file specified by ID and extension
345 *
346 * @author Kate Arzamastseva <pshns@ukr.net>
347 *
348 * @param string $id   media id
349 * @param string $ext  extension of media
350 * @return string
351 */
352function mediaMetaFN($id,$ext){
353    global $conf;
354    $id = cleanID($id);
355    $id = str_replace(':','/',$id);
356    $fn = $conf['mediametadir'].'/'.utf8_encodeFN($id).$ext;
357    return $fn;
358}
359
360/**
361 * returns an array of full paths to all metafiles of a given ID
362 *
363 * @author Esther Brunner <esther@kaffeehaus.ch>
364 * @author Michael Hamann <michael@content-space.de>
365 *
366 * @param string $id page id
367 * @return array
368 */
369function metaFiles($id){
370    $basename = metaFN($id, '');
371    $files    = glob($basename.'.*', GLOB_MARK);
372    // filter files like foo.bar.meta when $id == 'foo'
373    return    $files ? preg_grep('/^'.preg_quote($basename, '/').'\.[^.\/]*$/u', $files) : array();
374}
375
376/**
377 * returns the full path to the mediafile specified by ID
378 *
379 * The filename is URL encoded to protect Unicode chars
380 *
381 * @author Andreas Gohr <andi@splitbrain.org>
382 * @author Kate Arzamastseva <pshns@ukr.net>
383 *
384 * @param string     $id  media id
385 * @param string|int $rev empty string or revision timestamp
386 * @return string full path
387 */
388function mediaFN($id, $rev=''){
389    global $conf;
390    $id = cleanID($id);
391    $id = str_replace(':','/',$id);
392    if(empty($rev)){
393        $fn = $conf['mediadir'].'/'.utf8_encodeFN($id);
394    }else{
395        $ext = mimetype($id);
396        $name = substr($id,0, -1*strlen($ext[0])-1);
397        $fn = $conf['mediaolddir'].'/'.utf8_encodeFN($name .'.'.( (int) $rev ).'.'.$ext[0]);
398    }
399    return $fn;
400}
401
402/**
403 * Returns the full filepath to a localized file if local
404 * version isn't found the english one is returned
405 *
406 * @param  string $id  The id of the local file
407 * @param  string $ext The file extension (usually txt)
408 * @return string full filepath to localized file
409 *
410 * @author Andreas Gohr <andi@splitbrain.org>
411 */
412function localeFN($id,$ext='txt'){
413    global $conf;
414    $file = DOKU_CONF.'lang/'.$conf['lang'].'/'.$id.'.'.$ext;
415    if(!@file_exists($file)){
416        $file = DOKU_INC.'inc/lang/'.$conf['lang'].'/'.$id.'.'.$ext;
417        if(!@file_exists($file)){
418            //fall back to english
419            $file = DOKU_INC.'inc/lang/en/'.$id.'.'.$ext;
420        }
421    }
422    return $file;
423}
424
425/**
426 * Resolve relative paths in IDs
427 *
428 * Do not call directly use resolve_mediaid or resolve_pageid
429 * instead
430 *
431 * Partyly based on a cleanPath function found at
432 * http://www.php.net/manual/en/function.realpath.php#57016
433 *
434 * @author <bart at mediawave dot nl>
435 *
436 * @param string $ns     namespace which is context of id
437 * @param string $id     relative id
438 * @param bool   $clean  flag indicating that id should be cleaned
439 * @return string
440 */
441function resolve_id($ns,$id,$clean=true){
442    global $conf;
443
444    // some pre cleaning for useslash:
445    if($conf['useslash']) $id = str_replace('/',':',$id);
446
447    // if the id starts with a dot we need to handle the
448    // relative stuff
449    if($id && $id{0} == '.'){
450        // normalize initial dots without a colon
451        $id = preg_replace('/^(\.+)(?=[^:\.])/','\1:',$id);
452        // prepend the current namespace
453        $id = $ns.':'.$id;
454
455        // cleanup relatives
456        $result = array();
457        $pathA  = explode(':', $id);
458        if (!$pathA[0]) $result[] = '';
459        foreach ($pathA AS $key => $dir) {
460            if ($dir == '..') {
461                if (end($result) == '..') {
462                    $result[] = '..';
463                } elseif (!array_pop($result)) {
464                    $result[] = '..';
465                }
466            } elseif ($dir && $dir != '.') {
467                $result[] = $dir;
468            }
469        }
470        if (!end($pathA)) $result[] = '';
471        $id = implode(':', $result);
472    }elseif($ns !== false && strpos($id,':') === false){
473        //if link contains no namespace. add current namespace (if any)
474        $id = $ns.':'.$id;
475    }
476
477    if($clean) $id = cleanID($id);
478    return $id;
479}
480
481/**
482 * Returns a full media id
483 *
484 * @author Andreas Gohr <andi@splitbrain.org>
485 *
486 * @param string  $ns     namespace which is context of id
487 * @param string &$page   (reference) relative media id, updated to resolved id
488 * @param bool   &$exists (reference) updated with existance of media
489 */
490function resolve_mediaid($ns,&$page,&$exists){
491    $page   = resolve_id($ns,$page);
492    $file   = mediaFN($page);
493    $exists = @file_exists($file);
494}
495
496/**
497 * Returns a full page id
498 *
499 * @author Andreas Gohr <andi@splitbrain.org>
500 *
501 * @param string  $ns     namespace which is context of id
502 * @param string &$page   (reference) relative page id, updated to resolved id
503 * @param bool   &$exists (reference) updated with existance of media
504 */
505function resolve_pageid($ns,&$page,&$exists){
506    global $conf;
507    global $ID;
508    $exists = false;
509
510    //empty address should point to current page
511    if ($page === "") {
512        $page = $ID;
513    }
514
515    //keep hashlink if exists then clean both parts
516    if (strpos($page,'#')) {
517        list($page,$hash) = explode('#',$page,2);
518    } else {
519        $hash = '';
520    }
521    $hash = cleanID($hash);
522    $page = resolve_id($ns,$page,false); // resolve but don't clean, yet
523
524    // get filename (calls clean itself)
525    $file = wikiFN($page);
526
527    // if ends with colon or slash we have a namespace link
528    if(in_array(substr($page,-1), array(':', ';')) ||
529       ($conf['useslash'] && substr($page,-1) == '/')){
530        if(page_exists($page.$conf['start'])){
531            // start page inside namespace
532            $page = $page.$conf['start'];
533            $exists = true;
534        }elseif(page_exists($page.noNS(cleanID($page)))){
535            // page named like the NS inside the NS
536            $page = $page.noNS(cleanID($page));
537            $exists = true;
538        }elseif(page_exists($page)){
539            // page like namespace exists
540            $page = $page;
541            $exists = true;
542        }else{
543            // fall back to default
544            $page = $page.$conf['start'];
545        }
546    }else{
547        //check alternative plural/nonplural form
548        if(!@file_exists($file)){
549            if( $conf['autoplural'] ){
550                if(substr($page,-1) == 's'){
551                    $try = substr($page,0,-1);
552                }else{
553                    $try = $page.'s';
554                }
555                if(page_exists($try)){
556                    $page   = $try;
557                    $exists = true;
558                }
559            }
560        }else{
561            $exists = true;
562        }
563    }
564
565    // now make sure we have a clean page
566    $page = cleanID($page);
567
568    //add hash if any
569    if(!empty($hash)) $page .= '#'.$hash;
570}
571
572/**
573 * Returns the name of a cachefile from given data
574 *
575 * The needed directory is created by this function!
576 *
577 * @author Andreas Gohr <andi@splitbrain.org>
578 *
579 * @param string $data  This data is used to create a unique md5 name
580 * @param string $ext   This is appended to the filename if given
581 * @return string       The filename of the cachefile
582 */
583function getCacheName($data,$ext=''){
584    global $conf;
585    $md5  = md5($data);
586    $file = $conf['cachedir'].'/'.$md5{0}.'/'.$md5.$ext;
587    io_makeFileDir($file);
588    return $file;
589}
590
591/**
592 * Checks a pageid against $conf['hidepages']
593 *
594 * @author Andreas Gohr <gohr@cosmocode.de>
595 *
596 * @param string $id page id
597 * @return bool
598 */
599function isHiddenPage($id){
600    $data = array(
601        'id' => $id,
602        'hidden' => false
603    );
604    trigger_event('PAGEUTILS_ID_HIDEPAGE', $data, '_isHiddenPage');
605    return $data['hidden'];
606}
607
608/**
609 * callback checks if page is hidden
610 *
611 * @param array $data event data    - see isHiddenPage()
612 */
613function _isHiddenPage(&$data) {
614    global $conf;
615    global $ACT;
616
617    if ($data['hidden']) return;
618    if(empty($conf['hidepages'])) return;
619    if($ACT == 'admin') return;
620
621    if(preg_match('/'.$conf['hidepages'].'/ui',':'.$data['id'])){
622        $data['hidden'] = true;
623    }
624}
625
626/**
627 * Reverse of isHiddenPage
628 *
629 * @author Andreas Gohr <gohr@cosmocode.de>
630 *
631 * @param string $id page id
632 * @return bool
633 */
634function isVisiblePage($id){
635    return !isHiddenPage($id);
636}
637
638/**
639 * Format an id for output to a user
640 *
641 * Namespaces are denoted by a trailing “:*”. The root namespace is
642 * “*”. Output is escaped.
643 *
644 * @author Adrian Lang <lang@cosmocode.de>
645 *
646 * @param string $id page id
647 * @return string
648 */
649function prettyprint_id($id) {
650    if (!$id || $id === ':') {
651        return '*';
652    }
653    if ((substr($id, -1, 1) === ':')) {
654        $id .= '*';
655    }
656    return hsc($id);
657}
658
659/**
660 * Encode a UTF-8 filename to use on any filesystem
661 *
662 * Uses the 'fnencode' option to determine encoding
663 *
664 * When the second parameter is true the string will
665 * be encoded only if non ASCII characters are detected -
666 * This makes it safe to run it multiple times on the
667 * same string (default is true)
668 *
669 * @author Andreas Gohr <andi@splitbrain.org>
670 * @see    urlencode
671 *
672 * @param string $file file name
673 * @param bool   $safe if true, only encoded when non ASCII characters detected
674 * @return string
675 */
676function utf8_encodeFN($file,$safe=true){
677    global $conf;
678    if($conf['fnencode'] == 'utf-8') return $file;
679
680    if($safe && preg_match('#^[a-zA-Z0-9/_\-\.%]+$#',$file)){
681        return $file;
682    }
683
684    if($conf['fnencode'] == 'safe'){
685        return SafeFN::encode($file);
686    }
687
688    $file = urlencode($file);
689    $file = str_replace('%2F','/',$file);
690    return $file;
691}
692
693/**
694 * Decode a filename back to UTF-8
695 *
696 * Uses the 'fnencode' option to determine encoding
697 *
698 * @author Andreas Gohr <andi@splitbrain.org>
699 * @see    urldecode
700 *
701 * @param string $file file name
702 * @return string
703 */
704function utf8_decodeFN($file){
705    global $conf;
706    if($conf['fnencode'] == 'utf-8') return $file;
707
708    if($conf['fnencode'] == 'safe'){
709        return SafeFN::decode($file);
710    }
711
712    return urldecode($file);
713}
714
715/**
716 * Find a page in the current namespace (determined from $ID) or any
717 * higher namespace
718 *
719 * Used for sidebars, but can be used other stuff as well
720 *
721 * @todo   add event hook
722 *
723 * @param  string $page the pagename you're looking for
724 * @return string|false the full page id of the found page, false if any
725 */
726function page_findnearest($page){
727    if (!$page) return false;
728    global $ID;
729
730    $ns = $ID;
731    do {
732        $ns = getNS($ns);
733        $pageid = ltrim("$ns:$page",':');
734        if(page_exists($pageid)){
735            return $pageid;
736        }
737    } while($ns);
738
739    return false;
740}
741