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