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