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