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