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