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