xref: /dokuwiki/inc/pageutils.php (revision 54611a7a6e7af290525dd263f03b7293f20df91a)
1b625487dSandi<?php
2b625487dSandi/**
3b625487dSandi * Utilities for handling pagenames
4b625487dSandi *
5b625487dSandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6b625487dSandi * @author     Andreas Gohr <andi@splitbrain.org>
71380fc45SAndreas Gohr * @todo       Combine similar functions like {wiki,media,meta}FN()
8b625487dSandi */
9b625487dSandi
100c3a5702SAndreas Gohruse dokuwiki\ChangeLog\MediaChangeLog;
110c3a5702SAndreas Gohruse dokuwiki\ChangeLog\PageChangeLog;
125c844bb3SAndreas Gohruse dokuwiki\Utils\MediaResolver;
135c844bb3SAndreas Gohruse dokuwiki\Utils\PageResolver;
140c3a5702SAndreas Gohr
156c7843b5Sandi/**
166de3759aSAndreas Gohr * Fetch the an ID from request
176c7843b5Sandi *
186c7843b5Sandi * Uses either standard $_REQUEST variable or extracts it from
196c7843b5Sandi * the full request URI when userewrite is set to 2
206c7843b5Sandi *
2142905504SAndreas Gohr * For $param='id' $conf['start'] is returned if no id was found.
2242905504SAndreas Gohr * If the second parameter is true (default) the ID is cleaned.
236c7843b5Sandi *
246c7843b5Sandi * @author Andreas Gohr <andi@splitbrain.org>
2584657ea2SGerrit Uitslag *
2684657ea2SGerrit Uitslag * @param string $param  the $_REQUEST variable name, default 'id'
2784657ea2SGerrit Uitslag * @param bool   $clean  if true, ID is cleaned
2842ea7f44SGerrit Uitslag * @return string
296c7843b5Sandi */
3042905504SAndreas Gohrfunction getID($param='id',$clean=true){
31585bf44eSChristopher Smith    /** @var Input $INPUT */
327d01a0eaSTom N Harris    global $INPUT;
336c7843b5Sandi    global $conf;
344e90caaaSMichael Hamann    global $ACT;
356c7843b5Sandi
367d01a0eaSTom N Harris    $id = $INPUT->str($param);
3748665d38SAndreas Gohr
386c7843b5Sandi    //construct page id from request URI
396c7843b5Sandi    if(empty($id) && $conf['userewrite'] == 2){
40585bf44eSChristopher Smith        $request = $INPUT->server->str('REQUEST_URI');
4106368e4dSMichael Hamann        $script = '';
4206368e4dSMichael Hamann
436c7843b5Sandi        //get the script URL
446c7843b5Sandi        if($conf['basedir']){
4581124000Sjan            $relpath = '';
4681124000Sjan            if($param != 'id') {
4781124000Sjan                $relpath = 'lib/exe/';
4881124000Sjan            }
496ce3e5f8SAndreas Gohr            $script = $conf['basedir'] . $relpath .
506ce3e5f8SAndreas Gohr                \dokuwiki\Utf8\PhpString::basename($INPUT->server->str('SCRIPT_FILENAME'));
517d71d4b7SAndreas Gohr
52585bf44eSChristopher Smith        }elseif($INPUT->server->str('PATH_INFO')){
53585bf44eSChristopher Smith            $request = $INPUT->server->str('PATH_INFO');
54585bf44eSChristopher Smith        }elseif($INPUT->server->str('SCRIPT_NAME')){
55585bf44eSChristopher Smith            $script = $INPUT->server->str('SCRIPT_NAME');
56585bf44eSChristopher Smith        }elseif($INPUT->server->str('DOCUMENT_ROOT') && $INPUT->server->str('SCRIPT_FILENAME')){
57585bf44eSChristopher Smith            $script = preg_replace ('/^'.preg_quote($INPUT->server->str('DOCUMENT_ROOT'),'/').'/','',
58585bf44eSChristopher Smith                    $INPUT->server->str('SCRIPT_FILENAME'));
596c7843b5Sandi            $script = '/'.$script;
606c7843b5Sandi        }
616c7843b5Sandi
6252339126Sandi        //clean script and request (fixes a windows problem)
6352339126Sandi        $script  = preg_replace('/\/\/+/','/',$script);
647d71d4b7SAndreas Gohr        $request = preg_replace('/\/\/+/','/',$request);
6552339126Sandi
666c7843b5Sandi        //remove script URL and Querystring to gain the id
6752339126Sandi        if(preg_match('/^'.preg_quote($script,'/').'(.*)/',$request, $match)){
686c7843b5Sandi            $id = preg_replace ('/\?.*/','',$match[1]);
696c7843b5Sandi        }
706de3759aSAndreas Gohr        $id = urldecode($id);
7142905504SAndreas Gohr        //strip leading slashes
7242905504SAndreas Gohr        $id = preg_replace('!^/+!','',$id);
736c7843b5Sandi    }
74671a58a6SGuy Brand
75671a58a6SGuy Brand    // Namespace autolinking from URL
76b6084253SAndreas Gohr    if(substr($id,-1) == ':' || ($conf['useslash'] && substr($id,-1) == '/')){
77103c256aSChris Smith        if(page_exists($id.$conf['start'])){
78671a58a6SGuy Brand            // start page inside namespace
79671a58a6SGuy Brand            $id = $id.$conf['start'];
80103c256aSChris Smith        }elseif(page_exists($id.noNS(cleanID($id)))){
81671a58a6SGuy Brand            // page named like the NS inside the NS
82671a58a6SGuy Brand            $id = $id.noNS(cleanID($id));
83103c256aSChris Smith        }elseif(page_exists($id)){
84671a58a6SGuy Brand            // page like namespace exists
857a42ac9eSBen Coburn            $id = substr($id,0,-1);
86671a58a6SGuy Brand        }else{
87671a58a6SGuy Brand            // fall back to default
88671a58a6SGuy Brand            $id = $id.$conf['start'];
89671a58a6SGuy Brand        }
909dc53973SMichael Grosse        if (isset($ACT) && $ACT === 'show') {
919dc53973SMichael Grosse            $urlParameters = $_GET;
92e380abb2SMichael Grosse            if (isset($urlParameters['id'])) {
93e380abb2SMichael Grosse                unset($urlParameters['id']);
94e380abb2SMichael Grosse            }
95e9fede20SPhy            send_redirect(wl($id, $urlParameters, true, '&'));
969dc53973SMichael Grosse        }
97671a58a6SGuy Brand    }
9842905504SAndreas Gohr    if($clean) $id = cleanID($id);
9940b5fb5bSPhy    if($id === '' && $param=='id') $id = $conf['start'];
1006c7843b5Sandi
1016c7843b5Sandi    return $id;
1026c7843b5Sandi}
103b625487dSandi
104b625487dSandi/**
105b625487dSandi * Remove unwanted chars from ID
106b625487dSandi *
107b625487dSandi * Cleans a given ID to only use allowed characters. Accented characters are
108b625487dSandi * converted to unaccented ones
109b625487dSandi *
110b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
11142ea7f44SGerrit Uitslag *
1126e0cc83aSchris * @param  string  $raw_id    The pageid to clean
1138a831f2bSAndreas Gohr * @param  boolean $ascii     Force ASCII
114dbf714f7SGerrit Uitslag * @return string cleaned id
115b625487dSandi */
116c8bbb094SAnika Henkefunction cleanID($raw_id,$ascii=false){
117b625487dSandi    global $conf;
1184b5db43bSjoe.lapp    static $sepcharpat = null;
1194b5db43bSjoe.lapp
120dc2c0e04Schris    global $cache_cleanid;
121dc2c0e04Schris    $cache = & $cache_cleanid;
1226e0cc83aSchris
1236e0cc83aSchris    // check if it's already in the memory cache
12430f3bd15SMichael Grosse    if (!$ascii && isset($cache[(string)$raw_id])) {
1253a50618cSgweissbach        return $cache[(string)$raw_id];
1266e0cc83aSchris    }
1276e0cc83aSchris
1284b5db43bSjoe.lapp    $sepchar = $conf['sepchar'];
1294b5db43bSjoe.lapp    if($sepcharpat == null) // build string only once to save clock cycles
1304b5db43bSjoe.lapp        $sepcharpat = '#\\'.$sepchar.'+#';
1314b5db43bSjoe.lapp
1323a50618cSgweissbach    $id = trim((string)$raw_id);
1338cbc5ee8SAndreas Gohr    $id = \dokuwiki\Utf8\PhpString::strtolower($id);
134b625487dSandi
135b625487dSandi    //alternative namespace seperator
136b625487dSandi    if($conf['useslash']){
1373755fc25STom N Harris        $id = strtr($id,';/','::');
138b625487dSandi    }else{
1393755fc25STom N Harris        $id = strtr($id,';/',':'.$sepchar);
140b625487dSandi    }
141b625487dSandi
1428cbc5ee8SAndreas Gohr    if($conf['deaccent'] == 2 || $ascii) $id = \dokuwiki\Utf8\Clean::romanize($id);
1438cbc5ee8SAndreas Gohr    if($conf['deaccent'] || $ascii) $id = \dokuwiki\Utf8\Clean::deaccent($id,-1);
144b625487dSandi
145b625487dSandi    //remove specials
1468cbc5ee8SAndreas Gohr    $id = \dokuwiki\Utf8\Clean::stripspecials($id,$sepchar,'\*');
147b625487dSandi
1488cbc5ee8SAndreas Gohr    if($ascii) $id = \dokuwiki\Utf8\Clean::strip($id);
1498a831f2bSAndreas Gohr
150b625487dSandi    //clean up
1514b5db43bSjoe.lapp    $id = preg_replace($sepcharpat,$sepchar,$id);
152b625487dSandi    $id = preg_replace('#:+#',':',$id);
1533543c6deSAndreas Gohr    $id = trim($id,':._-');
154b625487dSandi    $id = preg_replace('#:[:\._\-]+#',':',$id);
155b680ea06SAndreas Gohr    $id = preg_replace('#[:\._\-]+:#',':',$id);
156b625487dSandi
15730f3bd15SMichael Grosse    if (!$ascii) $cache[(string)$raw_id] = $id;
158b625487dSandi    return($id);
159b625487dSandi}
160b625487dSandi
161b625487dSandi/**
162b625487dSandi * Return namespacepart of a wiki ID
163b625487dSandi *
164b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
16515851b98SGerrit Uitslag *
16615851b98SGerrit Uitslag * @param string $id
16742ea7f44SGerrit Uitslag * @return string|false the namespace part or false if the given ID has no namespace (root)
168b625487dSandi */
169b625487dSandifunction getNS($id){
1703a50618cSgweissbach    $pos = strrpos((string)$id,':');
171c4e0e4a1SAndreas Gohr    if($pos!==false){
1723a50618cSgweissbach        return substr((string)$id,0,$pos);
173b625487dSandi    }
174ef11fcfcSAndreas Gohr    return false;
175b625487dSandi}
176b625487dSandi
177b625487dSandi/**
178b625487dSandi * Returns the ID without the namespace
179b625487dSandi *
180b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
18115851b98SGerrit Uitslag *
18215851b98SGerrit Uitslag * @param string $id
18315851b98SGerrit Uitslag * @return string
184b625487dSandi */
185b625487dSandifunction noNS($id) {
1862844584fSBen Coburn    $pos = strrpos($id, ':');
1872844584fSBen Coburn    if ($pos!==false) {
1882844584fSBen Coburn        return substr($id, $pos+1);
1892844584fSBen Coburn    } else {
1902844584fSBen Coburn        return $id;
1912844584fSBen Coburn    }
1921a84a0f3SAnika Henke}
1931a84a0f3SAnika Henke
1941a84a0f3SAnika Henke/**
1951a84a0f3SAnika Henke * Returns the current namespace
1961a84a0f3SAnika Henke *
1971a84a0f3SAnika Henke * @author Nathan Fritz <fritzn@crown.edu>
19884657ea2SGerrit Uitslag *
19984657ea2SGerrit Uitslag * @param string $id
20084657ea2SGerrit Uitslag * @return string
2011a84a0f3SAnika Henke */
2021a84a0f3SAnika Henkefunction curNS($id) {
2031a84a0f3SAnika Henke    return noNS(getNS($id));
2041a84a0f3SAnika Henke}
2051a84a0f3SAnika Henke
2061a84a0f3SAnika Henke/**
2071a84a0f3SAnika Henke * Returns the ID without the namespace or current namespace for 'start' pages
2081a84a0f3SAnika Henke *
2091a84a0f3SAnika Henke * @author Nathan Fritz <fritzn@crown.edu>
21084657ea2SGerrit Uitslag *
21184657ea2SGerrit Uitslag * @param string $id
21284657ea2SGerrit Uitslag * @return string
2131a84a0f3SAnika Henke */
2141a84a0f3SAnika Henkefunction noNSorNS($id) {
2151a84a0f3SAnika Henke    global $conf;
2161a84a0f3SAnika Henke
2171a84a0f3SAnika Henke    $p = noNS($id);
218c077d4dcSAndreas Gohr    if ($p === $conf['start'] || $p === false || $p === '') {
2191a84a0f3SAnika Henke        $p = curNS($id);
220c077d4dcSAndreas Gohr        if ($p === false || $p === '') {
2219708106bSAdrian Lang            return $conf['start'];
2221a84a0f3SAnika Henke        }
2231a84a0f3SAnika Henke    }
2241a84a0f3SAnika Henke    return $p;
225b625487dSandi}
2264ceab83fSAndreas Gohr
2274ceab83fSAndreas Gohr/**
2284ceab83fSAndreas Gohr * Creates a XHTML valid linkid from a given headline title
2294ceab83fSAndreas Gohr *
2304ceab83fSAndreas Gohr * @param string  $title   The headline title
2314f582736SGuillaume Turri * @param array|bool   $check   Existing IDs
232c857afe0SMichael Hamann * @return string the title
23384657ea2SGerrit Uitslag *
2344ceab83fSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
2354ceab83fSAndreas Gohr */
236443d207bSAndreas Gohrfunction sectionID($title,&$check) {
237de9114eaSAnika Henke    $title = str_replace(array(':','.'),'',cleanID($title));
238de9114eaSAnika Henke    $new = ltrim($title,'0123456789_-');
2394ceab83fSAndreas Gohr    if(empty($new)){
2404ceab83fSAndreas Gohr        $title = 'section'.preg_replace('/[^0-9]+/','',$title); //keep numbers from headline
2414ceab83fSAndreas Gohr    }else{
2424ceab83fSAndreas Gohr        $title = $new;
2434ceab83fSAndreas Gohr    }
2444ceab83fSAndreas Gohr
245443d207bSAndreas Gohr    if(is_array($check)){
2464f582736SGuillaume Turri        $suffix=0;
2474f582736SGuillaume Turri        $candidateTitle = $title;
2484f582736SGuillaume Turri        while(in_array($candidateTitle, $check)){
2494f582736SGuillaume Turri          $candidateTitle = $title . ++$suffix;
2504f582736SGuillaume Turri        }
2514f582736SGuillaume Turri        $check []= $candidateTitle;
2524f582736SGuillaume Turri        return $candidateTitle;
25301e3159cSChris Tapp    } else {
2544ceab83fSAndreas Gohr      return $title;
2554ceab83fSAndreas Gohr    }
2564f582736SGuillaume Turri}
2574ceab83fSAndreas Gohr
258b625487dSandi/**
259103c256aSChris Smith * Wiki page existence check
260103c256aSChris Smith *
261103c256aSChris Smith * parameters as for wikiFN
262103c256aSChris Smith *
263103c256aSChris Smith * @author Chris Smith <chris@jalakai.co.uk>
26484657ea2SGerrit Uitslag *
26584657ea2SGerrit Uitslag * @param string $id page id
26684657ea2SGerrit Uitslag * @param string|int $rev empty or revision timestamp
26784657ea2SGerrit Uitslag * @param bool $clean flag indicating that $id should be cleaned (see wikiFN as well)
2687de86af9SGerrit Uitslag * @param bool $date_at
26984657ea2SGerrit Uitslag * @return bool exists?
270103c256aSChris Smith */
2711d053a56Slispsfunction page_exists($id,$rev='',$clean=true, $date_at=false) {
27290bee600Slisps    if($rev !== '' && $date_at) {
2731d053a56Slisps        $pagelog = new PageChangeLog($id);
27490bee600Slisps        $pagelog_rev = $pagelog->getLastRevisionAt($rev);
27590bee600Slisps        if($pagelog_rev !== false)
27690bee600Slisps            $rev = $pagelog_rev;
27790bee600Slisps    }
27879e79377SAndreas Gohr    return file_exists(wikiFN($id,$rev,$clean));
279103c256aSChris Smith}
280103c256aSChris Smith
281103c256aSChris Smith/**
2825c844bb3SAndreas Gohr * Media existence check
2835c844bb3SAndreas Gohr *
2845c844bb3SAndreas Gohr * @param string $id page id
2855c844bb3SAndreas Gohr * @param string|int $rev empty or revision timestamp
2865c844bb3SAndreas Gohr * @param bool $clean flag indicating that $id should be cleaned (see mediaFN as well)
2875c844bb3SAndreas Gohr * @param bool $date_at
2885c844bb3SAndreas Gohr * @return bool exists?
2895c844bb3SAndreas Gohr */
2905c844bb3SAndreas Gohrfunction media_exists($id, $rev = '', $clean = true, $date_at = false)
2915c844bb3SAndreas Gohr{
2925c844bb3SAndreas Gohr    if ($rev !== '' && $date_at) {
2935c844bb3SAndreas Gohr        $changeLog = new MediaChangeLog($id);
2945c844bb3SAndreas Gohr        $changelog_rev = $changeLog->getLastRevisionAt($rev);
2955c844bb3SAndreas Gohr        if ($changelog_rev !== false) {
2965c844bb3SAndreas Gohr            $rev = $changelog_rev;
2975c844bb3SAndreas Gohr        }
2985c844bb3SAndreas Gohr    }
2995c844bb3SAndreas Gohr    return file_exists(mediaFN($id, $rev, $clean));
3005c844bb3SAndreas Gohr}
3015c844bb3SAndreas Gohr
3025c844bb3SAndreas Gohr/**
303103c256aSChris Smith * returns the full path to the datafile specified by ID and optional revision
304b625487dSandi *
305b625487dSandi * The filename is URL encoded to protect Unicode chars
306b625487dSandi *
307103c256aSChris Smith * @param  $raw_id  string   id of wikipage
308e0c26282SGerrit Uitslag * @param  $rev     int|string   page revision, empty string for current
309103c256aSChris Smith * @param  $clean   bool     flag indicating that $raw_id should be cleaned.  Only set to false
310103c256aSChris Smith *                           when $id is guaranteed to have been cleaned already.
311dbf714f7SGerrit Uitslag * @return string full path
312103c256aSChris Smith *
313b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
314b625487dSandi */
3156e0cc83aSchrisfunction wikiFN($raw_id,$rev='',$clean=true){
316b625487dSandi    global $conf;
3176e0cc83aSchris
318dc2c0e04Schris    global $cache_wikifn;
319dc2c0e04Schris    $cache = & $cache_wikifn;
320dc2c0e04Schris
3216e0cc83aSchris    $id = $raw_id;
3226e0cc83aSchris
3230d8ea614Schris    if ($clean) $id = cleanID($id);
324b625487dSandi    $id = str_replace(':','/',$id);
325b018ecbeSMichael Grosse
326b018ecbeSMichael Grosse    if (isset($cache[$id]) && isset($cache[$id][$rev])) {
327b018ecbeSMichael Grosse        return $cache[$id][$rev];
328b018ecbeSMichael Grosse    }
329b018ecbeSMichael Grosse
330b625487dSandi    if(empty($rev)){
331b625487dSandi        $fn = $conf['datadir'].'/'.utf8_encodeFN($id).'.txt';
332b625487dSandi    }else{
333b625487dSandi        $fn = $conf['olddir'].'/'.utf8_encodeFN($id).'.'.$rev.'.txt';
334ff3ed99fSmarcel        if($conf['compression']){
335ff3ed99fSmarcel            //test for extensions here, we want to read both compressions
33679e79377SAndreas Gohr            if (file_exists($fn . '.gz')){
337b625487dSandi                $fn .= '.gz';
33879e79377SAndreas Gohr            }else if(file_exists($fn . '.bz2')){
339ff3ed99fSmarcel                $fn .= '.bz2';
340ff3ed99fSmarcel            }else{
341ff3ed99fSmarcel                //file doesnt exist yet, so we take the configured extension
342ff3ed99fSmarcel                $fn .= '.' . $conf['compression'];
343ff3ed99fSmarcel            }
344b625487dSandi        }
345b625487dSandi    }
3466e0cc83aSchris
347b018ecbeSMichael Grosse    if (!isset($cache[$id])) { $cache[$id] = array(); }
348b018ecbeSMichael Grosse    $cache[$id][$rev] = $fn;
349b625487dSandi    return $fn;
350b625487dSandi}
351b625487dSandi
352b625487dSandi/**
353c9b4bd1eSBen Coburn * Returns the full path to the file for locking the page while editing.
354c9b4bd1eSBen Coburn *
355c9b4bd1eSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
35684657ea2SGerrit Uitslag *
35784657ea2SGerrit Uitslag * @param string $id page id
35884657ea2SGerrit Uitslag * @return string full path
359c9b4bd1eSBen Coburn */
360c9b4bd1eSBen Coburnfunction wikiLockFN($id) {
361c9b4bd1eSBen Coburn    global $conf;
362662ff478SAndreas Gohr    return $conf['lockdir'].'/'.md5(cleanID($id)).'.lock';
363c9b4bd1eSBen Coburn}
364c9b4bd1eSBen Coburn
365c9b4bd1eSBen Coburn
366c9b4bd1eSBen Coburn/**
3671380fc45SAndreas Gohr * returns the full path to the meta file specified by ID and extension
368b158d625SSteven Danz *
369b158d625SSteven Danz * @author Steven Danz <steven-danz@kc.rr.com>
37084657ea2SGerrit Uitslag *
37184657ea2SGerrit Uitslag * @param string $id   page id
37284657ea2SGerrit Uitslag * @param string $ext  file extension
37384657ea2SGerrit Uitslag * @return string full path
374b158d625SSteven Danz */
3751380fc45SAndreas Gohrfunction metaFN($id,$ext){
376b158d625SSteven Danz    global $conf;
377b158d625SSteven Danz    $id = cleanID($id);
378b158d625SSteven Danz    $id = str_replace(':','/',$id);
3791380fc45SAndreas Gohr    $fn = $conf['metadir'].'/'.utf8_encodeFN($id).$ext;
380b158d625SSteven Danz    return $fn;
381b158d625SSteven Danz}
382b158d625SSteven Danz
383b158d625SSteven Danz/**
384e4f389efSKate Arzamastseva * returns the full path to the media's meta file specified by ID and extension
385e4f389efSKate Arzamastseva *
386cbe26ad6SKate Arzamastseva * @author Kate Arzamastseva <pshns@ukr.net>
38784657ea2SGerrit Uitslag *
38884657ea2SGerrit Uitslag * @param string $id   media id
38984657ea2SGerrit Uitslag * @param string $ext  extension of media
39084657ea2SGerrit Uitslag * @return string
391e4f389efSKate Arzamastseva */
392e4f389efSKate Arzamastsevafunction mediaMetaFN($id,$ext){
393e4f389efSKate Arzamastseva    global $conf;
394e4f389efSKate Arzamastseva    $id = cleanID($id);
395e4f389efSKate Arzamastseva    $id = str_replace(':','/',$id);
396e4f389efSKate Arzamastseva    $fn = $conf['mediametadir'].'/'.utf8_encodeFN($id).$ext;
397e4f389efSKate Arzamastseva    return $fn;
398e4f389efSKate Arzamastseva}
399e4f389efSKate Arzamastseva
400e4f389efSKate Arzamastseva/**
401e1f3d9e1SEsther Brunner * returns an array of full paths to all metafiles of a given ID
402e1f3d9e1SEsther Brunner *
403e1f3d9e1SEsther Brunner * @author Esther Brunner <esther@kaffeehaus.ch>
404ba0267b3SMichael Hamann * @author Michael Hamann <michael@content-space.de>
40584657ea2SGerrit Uitslag *
40684657ea2SGerrit Uitslag * @param string $id page id
40784657ea2SGerrit Uitslag * @return array
408e1f3d9e1SEsther Brunner */
409e1f3d9e1SEsther Brunnerfunction metaFiles($id){
410ba0267b3SMichael Hamann    $basename = metaFN($id, '');
411ba0267b3SMichael Hamann    $files    = glob($basename.'.*', GLOB_MARK);
412ba0267b3SMichael Hamann    // filter files like foo.bar.meta when $id == 'foo'
413ba0267b3SMichael Hamann    return    $files ? preg_grep('/^'.preg_quote($basename, '/').'\.[^.\/]*$/u', $files) : array();
414e1f3d9e1SEsther Brunner}
415e1f3d9e1SEsther Brunner
416e1f3d9e1SEsther Brunner/**
417b625487dSandi * returns the full path to the mediafile specified by ID
418b625487dSandi *
419b625487dSandi * The filename is URL encoded to protect Unicode chars
420b625487dSandi *
421b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
422cbe26ad6SKate Arzamastseva * @author Kate Arzamastseva <pshns@ukr.net>
42384657ea2SGerrit Uitslag *
42484657ea2SGerrit Uitslag * @param string     $id  media id
42584657ea2SGerrit Uitslag * @param string|int $rev empty string or revision timestamp
426f50a239bSTakamura * @param bool $clean
427f50a239bSTakamura *
42884657ea2SGerrit Uitslag * @return string full path
429b625487dSandi */
430d0e997c6SMichael Großefunction mediaFN($id, $rev='', $clean=true){
431b625487dSandi    global $conf;
432d0e997c6SMichael Große    if ($clean) $id = cleanID($id);
433b625487dSandi    $id = str_replace(':','/',$id);
434e4f389efSKate Arzamastseva    if(empty($rev)){
435b625487dSandi        $fn = $conf['mediadir'].'/'.utf8_encodeFN($id);
436e4f389efSKate Arzamastseva    }else{
437cbe26ad6SKate Arzamastseva        $ext = mimetype($id);
4388e69fd30SKate Arzamastseva        $name = substr($id,0, -1*strlen($ext[0])-1);
43961f1aad8SKate Arzamastseva        $fn = $conf['mediaolddir'].'/'.utf8_encodeFN($name .'.'.( (int) $rev ).'.'.$ext[0]);
440e4f389efSKate Arzamastseva    }
441b625487dSandi    return $fn;
442b625487dSandi}
443b625487dSandi
444b625487dSandi/**
4452adaf2b8SAndreas Gohr * Returns the full filepath to a localized file if local
446b625487dSandi * version isn't found the english one is returned
447b625487dSandi *
4482adaf2b8SAndreas Gohr * @param  string $id  The id of the local file
4492adaf2b8SAndreas Gohr * @param  string $ext The file extension (usually txt)
450dbf714f7SGerrit Uitslag * @return string full filepath to localized file
45184657ea2SGerrit Uitslag *
452b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
453b625487dSandi */
4542adaf2b8SAndreas Gohrfunction localeFN($id,$ext='txt'){
455b625487dSandi    global $conf;
4568819fbf5ShArpanet    $file = DOKU_CONF.'lang/'.$conf['lang'].'/'.$id.'.'.$ext;
45779e79377SAndreas Gohr    if(!file_exists($file)){
4582adaf2b8SAndreas Gohr        $file = DOKU_INC.'inc/lang/'.$conf['lang'].'/'.$id.'.'.$ext;
45979e79377SAndreas Gohr        if(!file_exists($file)){
460b625487dSandi            //fall back to english
4612adaf2b8SAndreas Gohr            $file = DOKU_INC.'inc/lang/en/'.$id.'.'.$ext;
462b625487dSandi        }
463e6cecb08SMichael Hamann    }
464b625487dSandi    return $file;
465b625487dSandi}
466b625487dSandi
467b625487dSandi/**
468c4e0e4a1SAndreas Gohr * Resolve relative paths in IDs
469c4e0e4a1SAndreas Gohr *
470c4e0e4a1SAndreas Gohr * Do not call directly use resolve_mediaid or resolve_pageid
471c4e0e4a1SAndreas Gohr * instead
472c4e0e4a1SAndreas Gohr *
473c4e0e4a1SAndreas Gohr * Partyly based on a cleanPath function found at
47459752844SAnders Sandblad * http://php.net/manual/en/function.realpath.php#57016
475c4e0e4a1SAndreas Gohr *
476bfcf8009SAndreas Gohr * @deprecated 2020-09-30
47784657ea2SGerrit Uitslag * @param string $ns     namespace which is context of id
47884657ea2SGerrit Uitslag * @param string $id     relative id
47984657ea2SGerrit Uitslag * @param bool   $clean  flag indicating that id should be cleaned
48042ea7f44SGerrit Uitslag * @return string
481c4e0e4a1SAndreas Gohr */
482a6ef4796SAndreas Gohrfunction resolve_id($ns,$id,$clean=true){
483c662a49aSAndreas Gohr    global $conf;
484bfcf8009SAndreas Gohr    dbg_deprecated(\dokuwiki\Utils\Resolver::class.' and its children');
485c662a49aSAndreas Gohr
486c662a49aSAndreas Gohr    // some pre cleaning for useslash:
487c662a49aSAndreas Gohr    if($conf['useslash']) $id = str_replace('/',':',$id);
488c662a49aSAndreas Gohr
489c4e0e4a1SAndreas Gohr    // if the id starts with a dot we need to handle the
490c4e0e4a1SAndreas Gohr    // relative stuff
4912401f18dSSyntaxseed    if($id && $id[0] == '.'){
492c4e0e4a1SAndreas Gohr        // normalize initial dots without a colon
4934986a584SPhy        $id = preg_replace('/^((\.+:)*)(\.+)(?=[^:\.])/','\1\3:',$id);
494c4e0e4a1SAndreas Gohr        // prepend the current namespace
495c4e0e4a1SAndreas Gohr        $id = $ns.':'.$id;
496c4e0e4a1SAndreas Gohr
497c4e0e4a1SAndreas Gohr        // cleanup relatives
498c4e0e4a1SAndreas Gohr        $result = array();
499c4e0e4a1SAndreas Gohr        $pathA  = explode(':', $id);
500c4e0e4a1SAndreas Gohr        if (!$pathA[0]) $result[] = '';
501c4e0e4a1SAndreas Gohr        foreach ($pathA AS $key => $dir) {
502c4e0e4a1SAndreas Gohr            if ($dir == '..') {
503c4e0e4a1SAndreas Gohr                if (end($result) == '..') {
504c4e0e4a1SAndreas Gohr                    $result[] = '..';
505c4e0e4a1SAndreas Gohr                } elseif (!array_pop($result)) {
506c4e0e4a1SAndreas Gohr                    $result[] = '..';
507c4e0e4a1SAndreas Gohr                }
508c4e0e4a1SAndreas Gohr            } elseif ($dir && $dir != '.') {
509c4e0e4a1SAndreas Gohr                $result[] = $dir;
510c4e0e4a1SAndreas Gohr            }
511c4e0e4a1SAndreas Gohr        }
512c4e0e4a1SAndreas Gohr        if (!end($pathA)) $result[] = '';
513c4e0e4a1SAndreas Gohr        $id = implode(':', $result);
514c4e0e4a1SAndreas Gohr    }elseif($ns !== false && strpos($id,':') === false){
515c4e0e4a1SAndreas Gohr        //if link contains no namespace. add current namespace (if any)
516c4e0e4a1SAndreas Gohr        $id = $ns.':'.$id;
517c4e0e4a1SAndreas Gohr    }
518c4e0e4a1SAndreas Gohr
519a6ef4796SAndreas Gohr    if($clean) $id = cleanID($id);
520a6ef4796SAndreas Gohr    return $id;
521c4e0e4a1SAndreas Gohr}
522c4e0e4a1SAndreas Gohr
523c4e0e4a1SAndreas Gohr/**
524b625487dSandi * Returns a full media id
525b625487dSandi *
52684657ea2SGerrit Uitslag * @param string $ns namespace which is context of id
5275c844bb3SAndreas Gohr * @param string &$media (reference) relative media id, updated to resolved id
52884657ea2SGerrit Uitslag * @param bool &$exists (reference) updated with existance of media
5297de86af9SGerrit Uitslag * @param int|string $rev
5307de86af9SGerrit Uitslag * @param bool $date_at
5315c844bb3SAndreas Gohr * @deprecated 2020-09-30
532b625487dSandi */
5335c844bb3SAndreas Gohrfunction resolve_mediaid($ns,&$media,&$exists,$rev='',$date_at=false){
5345c844bb3SAndreas Gohr    dbg_deprecated(MediaResolver::class);
5355c844bb3SAndreas Gohr    $resolver = new MediaResolver("$ns:deprecated");
5365c844bb3SAndreas Gohr    $media = $resolver->resolveId($media, $rev, $date_at);
5375c844bb3SAndreas Gohr    $exists = media_exists($media, $rev, false, $date_at);
538b625487dSandi}
539b625487dSandi
540b625487dSandi/**
541b625487dSandi * Returns a full page id
542b625487dSandi *
543bfcf8009SAndreas Gohr * @deprecated 2020-09-30
54484657ea2SGerrit Uitslag * @param string $ns namespace which is context of id
54584657ea2SGerrit Uitslag * @param string &$page (reference) relative page id, updated to resolved id
54684657ea2SGerrit Uitslag * @param bool &$exists (reference) updated with existance of media
5477de86af9SGerrit Uitslag * @param string $rev
5487de86af9SGerrit Uitslag * @param bool $date_at
549b625487dSandi */
550bfcf8009SAndreas Gohrfunction resolve_pageid($ns,&$page,&$exists,$rev='',$date_at=false )
551bfcf8009SAndreas Gohr{
5528c6be208SAndreas Gohr    dbg_deprecated(PageResolver::class);
553*54611a7aSAndreas Gohr
554*54611a7aSAndreas Gohr    global $ID;
555*54611a7aSAndreas Gohr    if(getNS($ID) == $ns) {
556*54611a7aSAndreas Gohr        $context = $ID; // this is usually the case
557*54611a7aSAndreas Gohr    } else {
558*54611a7aSAndreas Gohr        $context = "$ns:deprecated"; // only used when a different context namespace was given
559*54611a7aSAndreas Gohr    }
560*54611a7aSAndreas Gohr
561*54611a7aSAndreas Gohr    $resolver = new PageResolver($context);
562bfcf8009SAndreas Gohr    $page = $resolver->resolveId($page, $rev, $date_at);
563bfcf8009SAndreas Gohr    $exists = page_exists($page, $rev, false, $date_at);
564b625487dSandi}
565b625487dSandi
56698407a7aSandi/**
56798407a7aSandi * Returns the name of a cachefile from given data
56898407a7aSandi *
56998407a7aSandi * The needed directory is created by this function!
57098407a7aSandi *
57198407a7aSandi * @author Andreas Gohr <andi@splitbrain.org>
57298407a7aSandi *
57398407a7aSandi * @param string $data  This data is used to create a unique md5 name
57498407a7aSandi * @param string $ext   This is appended to the filename if given
57598407a7aSandi * @return string       The filename of the cachefile
57698407a7aSandi */
57798407a7aSandifunction getCacheName($data,$ext=''){
57898407a7aSandi    global $conf;
57998407a7aSandi    $md5  = md5($data);
5802401f18dSSyntaxseed    $file = $conf['cachedir'].'/'.$md5[0].'/'.$md5.$ext;
58198407a7aSandi    io_makeFileDir($file);
58298407a7aSandi    return $file;
58398407a7aSandi}
58498407a7aSandi
5850dc92c6fSAndreas Gohr/**
5860dc92c6fSAndreas Gohr * Checks a pageid against $conf['hidepages']
5870dc92c6fSAndreas Gohr *
5880dc92c6fSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
58984657ea2SGerrit Uitslag *
59084657ea2SGerrit Uitslag * @param string $id page id
59184657ea2SGerrit Uitslag * @return bool
5920dc92c6fSAndreas Gohr */
5930dc92c6fSAndreas Gohrfunction isHiddenPage($id){
5948449cc9dSDominik Eckelmann    $data = array(
5958449cc9dSDominik Eckelmann        'id' => $id,
5968449cc9dSDominik Eckelmann        'hidden' => false
5978449cc9dSDominik Eckelmann    );
598cbb44eabSAndreas Gohr    \dokuwiki\Extension\Event::createAndTrigger('PAGEUTILS_ID_HIDEPAGE', $data, '_isHiddenPage');
599fb55b51eSDominik Eckelmann    return $data['hidden'];
6000dc92c6fSAndreas Gohr}
601fb55b51eSDominik Eckelmann
602dbf714f7SGerrit Uitslag/**
603dbf714f7SGerrit Uitslag * callback checks if page is hidden
604dbf714f7SGerrit Uitslag *
60584657ea2SGerrit Uitslag * @param array $data event data    - see isHiddenPage()
606dbf714f7SGerrit Uitslag */
607fb55b51eSDominik Eckelmannfunction _isHiddenPage(&$data) {
608fb55b51eSDominik Eckelmann    global $conf;
609fb55b51eSDominik Eckelmann    global $ACT;
610fb55b51eSDominik Eckelmann
611fb55b51eSDominik Eckelmann    if ($data['hidden']) return;
612fb55b51eSDominik Eckelmann    if(empty($conf['hidepages'])) return;
613fb55b51eSDominik Eckelmann    if($ACT == 'admin') return;
614fb55b51eSDominik Eckelmann
615fb55b51eSDominik Eckelmann    if(preg_match('/'.$conf['hidepages'].'/ui',':'.$data['id'])){
616fb55b51eSDominik Eckelmann        $data['hidden'] = true;
617fb55b51eSDominik Eckelmann    }
6180dc92c6fSAndreas Gohr}
6190dc92c6fSAndreas Gohr
6200dc92c6fSAndreas Gohr/**
6210dc92c6fSAndreas Gohr * Reverse of isHiddenPage
6220dc92c6fSAndreas Gohr *
6230dc92c6fSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
62484657ea2SGerrit Uitslag *
62584657ea2SGerrit Uitslag * @param string $id page id
62684657ea2SGerrit Uitslag * @return bool
6270dc92c6fSAndreas Gohr */
6280dc92c6fSAndreas Gohrfunction isVisiblePage($id){
6290dc92c6fSAndreas Gohr    return !isHiddenPage($id);
6300dc92c6fSAndreas Gohr}
6310dc92c6fSAndreas Gohr
6325b75cd1fSAdrian Lang/**
6335b75cd1fSAdrian Lang * Format an id for output to a user
6345b75cd1fSAdrian Lang *
6355b75cd1fSAdrian Lang * Namespaces are denoted by a trailing “:*”. The root namespace is
6365b75cd1fSAdrian Lang * “*”. Output is escaped.
6375b75cd1fSAdrian Lang *
6385b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
63984657ea2SGerrit Uitslag *
64084657ea2SGerrit Uitslag * @param string $id page id
64184657ea2SGerrit Uitslag * @return string
6425b75cd1fSAdrian Lang */
6435b75cd1fSAdrian Langfunction prettyprint_id($id) {
6445b75cd1fSAdrian Lang    if (!$id || $id === ':') {
6455b75cd1fSAdrian Lang        return '*';
6465b75cd1fSAdrian Lang    }
6475b75cd1fSAdrian Lang    if ((substr($id, -1, 1) === ':')) {
6485b75cd1fSAdrian Lang        $id .= '*';
6495b75cd1fSAdrian Lang    }
6505b75cd1fSAdrian Lang    return hsc($id);
6515b75cd1fSAdrian Lang}
652f03fd957SAndreas Gohr
653f03fd957SAndreas Gohr/**
654f03fd957SAndreas Gohr * Encode a UTF-8 filename to use on any filesystem
655f03fd957SAndreas Gohr *
656f03fd957SAndreas Gohr * Uses the 'fnencode' option to determine encoding
657f03fd957SAndreas Gohr *
658f03fd957SAndreas Gohr * When the second parameter is true the string will
659f03fd957SAndreas Gohr * be encoded only if non ASCII characters are detected -
660f03fd957SAndreas Gohr * This makes it safe to run it multiple times on the
661f03fd957SAndreas Gohr * same string (default is true)
662f03fd957SAndreas Gohr *
663f03fd957SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
664f03fd957SAndreas Gohr * @see    urlencode
66584657ea2SGerrit Uitslag *
66684657ea2SGerrit Uitslag * @param string $file file name
66784657ea2SGerrit Uitslag * @param bool   $safe if true, only encoded when non ASCII characters detected
66884657ea2SGerrit Uitslag * @return string
669f03fd957SAndreas Gohr */
670f03fd957SAndreas Gohrfunction utf8_encodeFN($file,$safe=true){
671f03fd957SAndreas Gohr    global $conf;
672f03fd957SAndreas Gohr    if($conf['fnencode'] == 'utf-8') return $file;
673f03fd957SAndreas Gohr
674f03fd957SAndreas Gohr    if($safe && preg_match('#^[a-zA-Z0-9/_\-\.%]+$#',$file)){
675f03fd957SAndreas Gohr        return $file;
676f03fd957SAndreas Gohr    }
677f03fd957SAndreas Gohr
678f03fd957SAndreas Gohr    if($conf['fnencode'] == 'safe'){
679f03fd957SAndreas Gohr        return SafeFN::encode($file);
680f03fd957SAndreas Gohr    }
681f03fd957SAndreas Gohr
682f03fd957SAndreas Gohr    $file = urlencode($file);
683f03fd957SAndreas Gohr    $file = str_replace('%2F','/',$file);
684f03fd957SAndreas Gohr    return $file;
685f03fd957SAndreas Gohr}
686f03fd957SAndreas Gohr
687f03fd957SAndreas Gohr/**
688f03fd957SAndreas Gohr * Decode a filename back to UTF-8
689f03fd957SAndreas Gohr *
690f03fd957SAndreas Gohr * Uses the 'fnencode' option to determine encoding
691f03fd957SAndreas Gohr *
692f03fd957SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
693f03fd957SAndreas Gohr * @see    urldecode
69484657ea2SGerrit Uitslag *
69584657ea2SGerrit Uitslag * @param string $file file name
69684657ea2SGerrit Uitslag * @return string
697f03fd957SAndreas Gohr */
698f03fd957SAndreas Gohrfunction utf8_decodeFN($file){
699f03fd957SAndreas Gohr    global $conf;
700f03fd957SAndreas Gohr    if($conf['fnencode'] == 'utf-8') return $file;
701f03fd957SAndreas Gohr
702f03fd957SAndreas Gohr    if($conf['fnencode'] == 'safe'){
703f03fd957SAndreas Gohr        return SafeFN::decode($file);
704f03fd957SAndreas Gohr    }
705f03fd957SAndreas Gohr
706f03fd957SAndreas Gohr    return urldecode($file);
707f03fd957SAndreas Gohr}
708f03fd957SAndreas Gohr
709e66d3e6dSAndreas Gohr/**
710e66d3e6dSAndreas Gohr * Find a page in the current namespace (determined from $ID) or any
711cc529468SMichael Hamann * higher namespace that can be accessed by the current user,
712cc529468SMichael Hamann * this condition can be overriden by an optional parameter.
713e66d3e6dSAndreas Gohr *
714e66d3e6dSAndreas Gohr * Used for sidebars, but can be used other stuff as well
715e66d3e6dSAndreas Gohr *
716e66d3e6dSAndreas Gohr * @todo   add event hook
71742ea7f44SGerrit Uitslag *
718e66d3e6dSAndreas Gohr * @param  string $page the pagename you're looking for
7197c3e4a67SAndreas Gohr * @param bool $useacl only return pages readable by the current user, false to ignore ACLs
720cc529468SMichael Hamann * @return false|string the full page id of the found page, false if any
721e66d3e6dSAndreas Gohr */
7227c3e4a67SAndreas Gohrfunction page_findnearest($page, $useacl = true){
72306a70133SPhy    if ((string) $page === '') return false;
724e66d3e6dSAndreas Gohr    global $ID;
725e66d3e6dSAndreas Gohr
726e66d3e6dSAndreas Gohr    $ns = $ID;
727e66d3e6dSAndreas Gohr    do {
728e66d3e6dSAndreas Gohr        $ns = getNS($ns);
729cc529468SMichael Hamann        $pageid = cleanID("$ns:$page");
7307c3e4a67SAndreas Gohr        if(page_exists($pageid) && (!$useacl || auth_quickaclcheck($pageid) >= AUTH_READ)){
731e66d3e6dSAndreas Gohr            return $pageid;
732e66d3e6dSAndreas Gohr        }
73306a70133SPhy    } while($ns !== false);
734e66d3e6dSAndreas Gohr
735e66d3e6dSAndreas Gohr    return false;
736e66d3e6dSAndreas Gohr}
737