xref: /dokuwiki/inc/pageutils.php (revision 58332f92e599b579dcdc7f655b9bc34711e0dcb1)
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 * @param bool $clean
400 *
401 * @return string full path
402 */
403function mediaFN($id, $rev='', $clean=true){
404    global $conf;
405    if ($clean) $id = cleanID($id);
406    $id = str_replace(':','/',$id);
407    if(empty($rev)){
408        $fn = $conf['mediadir'].'/'.utf8_encodeFN($id);
409    }else{
410        $ext = mimetype($id);
411        $name = substr($id,0, -1*strlen($ext[0])-1);
412        $fn = $conf['mediaolddir'].'/'.utf8_encodeFN($name .'.'.( (int) $rev ).'.'.$ext[0]);
413    }
414    return $fn;
415}
416
417/**
418 * Returns the full filepath to a localized file if local
419 * version isn't found the english one is returned
420 *
421 * @param  string $id  The id of the local file
422 * @param  string $ext The file extension (usually txt)
423 * @return string full filepath to localized file
424 *
425 * @author Andreas Gohr <andi@splitbrain.org>
426 */
427function localeFN($id,$ext='txt'){
428    global $conf;
429    $file = DOKU_CONF.'lang/'.$conf['lang'].'/'.$id.'.'.$ext;
430    if(!file_exists($file)){
431        $file = DOKU_INC.'inc/lang/'.$conf['lang'].'/'.$id.'.'.$ext;
432        if(!file_exists($file)){
433            //fall back to english
434            $file = DOKU_INC.'inc/lang/en/'.$id.'.'.$ext;
435        }
436    }
437    return $file;
438}
439
440/**
441 * Resolve relative paths in IDs
442 *
443 * Do not call directly use resolve_mediaid or resolve_pageid
444 * instead
445 *
446 * Partyly based on a cleanPath function found at
447 * http://php.net/manual/en/function.realpath.php#57016
448 *
449 * @author <bart at mediawave dot nl>
450 *
451 * @param string $ns     namespace which is context of id
452 * @param string $id     relative id
453 * @param bool   $clean  flag indicating that id should be cleaned
454 * @return string
455 */
456function resolve_id($ns,$id,$clean=true){
457    global $conf;
458
459    // some pre cleaning for useslash:
460    if($conf['useslash']) $id = str_replace('/',':',$id);
461
462    // if the id starts with a dot we need to handle the
463    // relative stuff
464    if($id && $id{0} == '.'){
465        // normalize initial dots without a colon
466        $id = preg_replace('/^(\.+)(?=[^:\.])/','\1:',$id);
467        // prepend the current namespace
468        $id = $ns.':'.$id;
469
470        // cleanup relatives
471        $result = array();
472        $pathA  = explode(':', $id);
473        if (!$pathA[0]) $result[] = '';
474        foreach ($pathA AS $key => $dir) {
475            if ($dir == '..') {
476                if (end($result) == '..') {
477                    $result[] = '..';
478                } elseif (!array_pop($result)) {
479                    $result[] = '..';
480                }
481            } elseif ($dir && $dir != '.') {
482                $result[] = $dir;
483            }
484        }
485        if (!end($pathA)) $result[] = '';
486        $id = implode(':', $result);
487    }elseif($ns !== false && strpos($id,':') === false){
488        //if link contains no namespace. add current namespace (if any)
489        $id = $ns.':'.$id;
490    }
491
492    if($clean) $id = cleanID($id);
493    return $id;
494}
495
496/**
497 * Returns a full media 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 media id, updated to resolved id
503 * @param bool &$exists (reference) updated with existance of media
504 * @param int|string $rev
505 * @param bool $date_at
506 */
507function resolve_mediaid($ns,&$page,&$exists,$rev='',$date_at=false){
508    $page   = resolve_id($ns,$page);
509    if($rev !== '' &&  $date_at){
510        $medialog = new MediaChangeLog($page);
511        $medialog_rev = $medialog->getLastRevisionAt($rev);
512        if($medialog_rev !== false) {
513            $rev = $medialog_rev;
514        }
515    }
516
517    $file   = mediaFN($page,$rev);
518    $exists = file_exists($file);
519}
520
521/**
522 * Returns a full page id
523 *
524 * @author Andreas Gohr <andi@splitbrain.org>
525 *
526 * @param string $ns namespace which is context of id
527 * @param string &$page (reference) relative page id, updated to resolved id
528 * @param bool &$exists (reference) updated with existance of media
529 * @param string $rev
530 * @param bool $date_at
531 */
532function resolve_pageid($ns,&$page,&$exists,$rev='',$date_at=false ){
533    global $conf;
534    global $ID;
535    $exists = false;
536
537    //empty address should point to current page
538    if ($page === "") {
539        $page = $ID;
540    }
541
542    //keep hashlink if exists then clean both parts
543    if (strpos($page,'#')) {
544        list($page,$hash) = explode('#',$page,2);
545    } else {
546        $hash = '';
547    }
548    $hash = cleanID($hash);
549    $page = resolve_id($ns,$page,false); // resolve but don't clean, yet
550
551    // get filename (calls clean itself)
552    if($rev !== '' && $date_at) {
553        $pagelog = new PageChangeLog($page);
554        $pagelog_rev = $pagelog->getLastRevisionAt($rev);
555        if($pagelog_rev !== false)//something found
556           $rev  = $pagelog_rev;
557    }
558    $file = wikiFN($page,$rev);
559
560    // if ends with colon or slash we have a namespace link
561    if(in_array(substr($page,-1), array(':', ';')) ||
562       ($conf['useslash'] && substr($page,-1) == '/')){
563        if(page_exists($page.$conf['start'],$rev,true,$date_at)){
564            // start page inside namespace
565            $page = $page.$conf['start'];
566            $exists = true;
567        }elseif(page_exists($page.noNS(cleanID($page)),$rev,true,$date_at)){
568            // page named like the NS inside the NS
569            $page = $page.noNS(cleanID($page));
570            $exists = true;
571        }elseif(page_exists($page,$rev,true,$date_at)){
572            // page like namespace exists
573            $page = $page;
574            $exists = true;
575        }else{
576            // fall back to default
577            $page = $page.$conf['start'];
578        }
579    }else{
580        //check alternative plural/nonplural form
581        if(!file_exists($file)){
582            if( $conf['autoplural'] ){
583                if(substr($page,-1) == 's'){
584                    $try = substr($page,0,-1);
585                }else{
586                    $try = $page.'s';
587                }
588                if(page_exists($try,$rev,true,$date_at)){
589                    $page   = $try;
590                    $exists = true;
591                }
592            }
593        }else{
594            $exists = true;
595        }
596    }
597
598    // now make sure we have a clean page
599    $page = cleanID($page);
600
601    //add hash if any
602    if(!empty($hash)) $page .= '#'.$hash;
603}
604
605/**
606 * Returns the name of a cachefile from given data
607 *
608 * The needed directory is created by this function!
609 *
610 * @author Andreas Gohr <andi@splitbrain.org>
611 *
612 * @param string $data  This data is used to create a unique md5 name
613 * @param string $ext   This is appended to the filename if given
614 * @return string       The filename of the cachefile
615 */
616function getCacheName($data,$ext=''){
617    global $conf;
618    $md5  = md5($data);
619    $file = $conf['cachedir'].'/'.$md5{0}.'/'.$md5.$ext;
620    io_makeFileDir($file);
621    return $file;
622}
623
624/**
625 * Checks a pageid against $conf['hidepages']
626 *
627 * @author Andreas Gohr <gohr@cosmocode.de>
628 *
629 * @param string $id page id
630 * @return bool
631 */
632function isHiddenPage($id){
633    $data = array(
634        'id' => $id,
635        'hidden' => false
636    );
637    trigger_event('PAGEUTILS_ID_HIDEPAGE', $data, '_isHiddenPage');
638    return $data['hidden'];
639}
640
641/**
642 * callback checks if page is hidden
643 *
644 * @param array $data event data    - see isHiddenPage()
645 */
646function _isHiddenPage(&$data) {
647    global $conf;
648    global $ACT;
649
650    if ($data['hidden']) return;
651    if(empty($conf['hidepages'])) return;
652    if($ACT == 'admin') return;
653
654    if(preg_match('/'.$conf['hidepages'].'/ui',':'.$data['id'])){
655        $data['hidden'] = true;
656    }
657}
658
659/**
660 * Reverse of isHiddenPage
661 *
662 * @author Andreas Gohr <gohr@cosmocode.de>
663 *
664 * @param string $id page id
665 * @return bool
666 */
667function isVisiblePage($id){
668    return !isHiddenPage($id);
669}
670
671/**
672 * Format an id for output to a user
673 *
674 * Namespaces are denoted by a trailing “:*”. The root namespace is
675 * “*”. Output is escaped.
676 *
677 * @author Adrian Lang <lang@cosmocode.de>
678 *
679 * @param string $id page id
680 * @return string
681 */
682function prettyprint_id($id) {
683    if (!$id || $id === ':') {
684        return '*';
685    }
686    if ((substr($id, -1, 1) === ':')) {
687        $id .= '*';
688    }
689    return hsc($id);
690}
691
692/**
693 * Encode a UTF-8 filename to use on any filesystem
694 *
695 * Uses the 'fnencode' option to determine encoding
696 *
697 * When the second parameter is true the string will
698 * be encoded only if non ASCII characters are detected -
699 * This makes it safe to run it multiple times on the
700 * same string (default is true)
701 *
702 * @author Andreas Gohr <andi@splitbrain.org>
703 * @see    urlencode
704 *
705 * @param string $file file name
706 * @param bool   $safe if true, only encoded when non ASCII characters detected
707 * @return string
708 */
709function utf8_encodeFN($file,$safe=true){
710    global $conf;
711    if($conf['fnencode'] == 'utf-8') return $file;
712
713    if($safe && preg_match('#^[a-zA-Z0-9/_\-\.%]+$#',$file)){
714        return $file;
715    }
716
717    if($conf['fnencode'] == 'safe'){
718        return SafeFN::encode($file);
719    }
720
721    $file = urlencode($file);
722    $file = str_replace('%2F','/',$file);
723    return $file;
724}
725
726/**
727 * Decode a filename back to UTF-8
728 *
729 * Uses the 'fnencode' option to determine encoding
730 *
731 * @author Andreas Gohr <andi@splitbrain.org>
732 * @see    urldecode
733 *
734 * @param string $file file name
735 * @return string
736 */
737function utf8_decodeFN($file){
738    global $conf;
739    if($conf['fnencode'] == 'utf-8') return $file;
740
741    if($conf['fnencode'] == 'safe'){
742        return SafeFN::decode($file);
743    }
744
745    return urldecode($file);
746}
747
748/**
749 * Find a page in the current namespace (determined from $ID) or any
750 * higher namespace that can be accessed by the current user,
751 * this condition can be overriden by an optional parameter.
752 *
753 * Used for sidebars, but can be used other stuff as well
754 *
755 * @todo   add event hook
756 *
757 * @param  string $page the pagename you're looking for
758 * @param bool $useacl only return pages readable by the current user, false to ignore ACLs
759 * @return false|string the full page id of the found page, false if any
760 */
761function page_findnearest($page, $useacl = true){
762    if (!$page) return false;
763    global $ID;
764
765    $ns = $ID;
766    do {
767        $ns = getNS($ns);
768        $pageid = cleanID("$ns:$page");
769        if(page_exists($pageid) && (!$useacl || auth_quickaclcheck($pageid) >= AUTH_READ)){
770            return $pageid;
771        }
772    } while($ns);
773
774    return false;
775}
776