xref: /dokuwiki/inc/pageutils.php (revision 92085f137340e36abbdd84941ad32174392e7038)
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;
122cd6cc0aSAndreas Gohruse dokuwiki\File\MediaResolver;
132cd6cc0aSAndreas Gohruse dokuwiki\File\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) {
272*92085f13SAndreas Gohr    $id = (explode('#', $id, 2))[0]; // #3608
273*92085f13SAndreas Gohr
27490bee600Slisps    if ($rev !== '' && $date_at) {
2751d053a56Slisps        $pagelog = new PageChangeLog($id);
27690bee600Slisps        $pagelog_rev = $pagelog->getLastRevisionAt($rev);
27790bee600Slisps        if ($pagelog_rev !== false)
27890bee600Slisps            $rev = $pagelog_rev;
27990bee600Slisps    }
28079e79377SAndreas Gohr    return file_exists(wikiFN($id, $rev, $clean));
281103c256aSChris Smith}
282103c256aSChris Smith
283103c256aSChris Smith/**
2845c844bb3SAndreas Gohr * Media existence check
2855c844bb3SAndreas Gohr *
2865c844bb3SAndreas Gohr * @param string $id page id
2875c844bb3SAndreas Gohr * @param string|int $rev empty or revision timestamp
2885c844bb3SAndreas Gohr * @param bool $clean flag indicating that $id should be cleaned (see mediaFN as well)
2895c844bb3SAndreas Gohr * @param bool $date_at
2905c844bb3SAndreas Gohr * @return bool exists?
2915c844bb3SAndreas Gohr */
2925c844bb3SAndreas Gohrfunction media_exists($id, $rev = '', $clean = true, $date_at = false)
2935c844bb3SAndreas Gohr{
2945c844bb3SAndreas Gohr    if ($rev !== '' && $date_at) {
2955c844bb3SAndreas Gohr        $changeLog = new MediaChangeLog($id);
2965c844bb3SAndreas Gohr        $changelog_rev = $changeLog->getLastRevisionAt($rev);
2975c844bb3SAndreas Gohr        if ($changelog_rev !== false) {
2985c844bb3SAndreas Gohr            $rev = $changelog_rev;
2995c844bb3SAndreas Gohr        }
3005c844bb3SAndreas Gohr    }
3015c844bb3SAndreas Gohr    return file_exists(mediaFN($id, $rev, $clean));
3025c844bb3SAndreas Gohr}
3035c844bb3SAndreas Gohr
3045c844bb3SAndreas Gohr/**
305103c256aSChris Smith * returns the full path to the datafile specified by ID and optional revision
306b625487dSandi *
307b625487dSandi * The filename is URL encoded to protect Unicode chars
308b625487dSandi *
309103c256aSChris Smith * @param  $raw_id  string   id of wikipage
310e0c26282SGerrit Uitslag * @param  $rev     int|string   page revision, empty string for current
311103c256aSChris Smith * @param  $clean   bool     flag indicating that $raw_id should be cleaned.  Only set to false
312103c256aSChris Smith *                           when $id is guaranteed to have been cleaned already.
313dbf714f7SGerrit Uitslag * @return string full path
314103c256aSChris Smith *
315b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
316b625487dSandi */
3176e0cc83aSchrisfunction wikiFN($raw_id,$rev='',$clean=true){
318b625487dSandi    global $conf;
3196e0cc83aSchris
320dc2c0e04Schris    global $cache_wikifn;
321dc2c0e04Schris    $cache = & $cache_wikifn;
322dc2c0e04Schris
3236e0cc83aSchris    $id = $raw_id;
3246e0cc83aSchris
3250d8ea614Schris    if ($clean) $id = cleanID($id);
326b625487dSandi    $id = str_replace(':','/',$id);
327b018ecbeSMichael Grosse
328b018ecbeSMichael Grosse    if (isset($cache[$id]) && isset($cache[$id][$rev])) {
329b018ecbeSMichael Grosse        return $cache[$id][$rev];
330b018ecbeSMichael Grosse    }
331b018ecbeSMichael Grosse
332b625487dSandi    if(empty($rev)){
333b625487dSandi        $fn = $conf['datadir'].'/'.utf8_encodeFN($id).'.txt';
334b625487dSandi    }else{
335b625487dSandi        $fn = $conf['olddir'].'/'.utf8_encodeFN($id).'.'.$rev.'.txt';
336ff3ed99fSmarcel        if($conf['compression']){
337ff3ed99fSmarcel            //test for extensions here, we want to read both compressions
33879e79377SAndreas Gohr            if (file_exists($fn . '.gz')){
339b625487dSandi                $fn .= '.gz';
34079e79377SAndreas Gohr            }else if(file_exists($fn . '.bz2')){
341ff3ed99fSmarcel                $fn .= '.bz2';
342ff3ed99fSmarcel            }else{
343ff3ed99fSmarcel                //file doesnt exist yet, so we take the configured extension
344ff3ed99fSmarcel                $fn .= '.' . $conf['compression'];
345ff3ed99fSmarcel            }
346b625487dSandi        }
347b625487dSandi    }
3486e0cc83aSchris
349b018ecbeSMichael Grosse    if (!isset($cache[$id])) { $cache[$id] = array(); }
350b018ecbeSMichael Grosse    $cache[$id][$rev] = $fn;
351b625487dSandi    return $fn;
352b625487dSandi}
353b625487dSandi
354b625487dSandi/**
355c9b4bd1eSBen Coburn * Returns the full path to the file for locking the page while editing.
356c9b4bd1eSBen Coburn *
357c9b4bd1eSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
35884657ea2SGerrit Uitslag *
35984657ea2SGerrit Uitslag * @param string $id page id
36084657ea2SGerrit Uitslag * @return string full path
361c9b4bd1eSBen Coburn */
362c9b4bd1eSBen Coburnfunction wikiLockFN($id) {
363c9b4bd1eSBen Coburn    global $conf;
364662ff478SAndreas Gohr    return $conf['lockdir'].'/'.md5(cleanID($id)).'.lock';
365c9b4bd1eSBen Coburn}
366c9b4bd1eSBen Coburn
367c9b4bd1eSBen Coburn
368c9b4bd1eSBen Coburn/**
3691380fc45SAndreas Gohr * returns the full path to the meta file specified by ID and extension
370b158d625SSteven Danz *
371b158d625SSteven Danz * @author Steven Danz <steven-danz@kc.rr.com>
37284657ea2SGerrit Uitslag *
37384657ea2SGerrit Uitslag * @param string $id   page id
37484657ea2SGerrit Uitslag * @param string $ext  file extension
37584657ea2SGerrit Uitslag * @return string full path
376b158d625SSteven Danz */
3771380fc45SAndreas Gohrfunction metaFN($id,$ext){
378b158d625SSteven Danz    global $conf;
379b158d625SSteven Danz    $id = cleanID($id);
380b158d625SSteven Danz    $id = str_replace(':','/',$id);
3811380fc45SAndreas Gohr    $fn = $conf['metadir'].'/'.utf8_encodeFN($id).$ext;
382b158d625SSteven Danz    return $fn;
383b158d625SSteven Danz}
384b158d625SSteven Danz
385b158d625SSteven Danz/**
386e4f389efSKate Arzamastseva * returns the full path to the media's meta file specified by ID and extension
387e4f389efSKate Arzamastseva *
388cbe26ad6SKate Arzamastseva * @author Kate Arzamastseva <pshns@ukr.net>
38984657ea2SGerrit Uitslag *
39084657ea2SGerrit Uitslag * @param string $id   media id
39184657ea2SGerrit Uitslag * @param string $ext  extension of media
39284657ea2SGerrit Uitslag * @return string
393e4f389efSKate Arzamastseva */
394e4f389efSKate Arzamastsevafunction mediaMetaFN($id,$ext){
395e4f389efSKate Arzamastseva    global $conf;
396e4f389efSKate Arzamastseva    $id = cleanID($id);
397e4f389efSKate Arzamastseva    $id = str_replace(':','/',$id);
398e4f389efSKate Arzamastseva    $fn = $conf['mediametadir'].'/'.utf8_encodeFN($id).$ext;
399e4f389efSKate Arzamastseva    return $fn;
400e4f389efSKate Arzamastseva}
401e4f389efSKate Arzamastseva
402e4f389efSKate Arzamastseva/**
403e1f3d9e1SEsther Brunner * returns an array of full paths to all metafiles of a given ID
404e1f3d9e1SEsther Brunner *
405e1f3d9e1SEsther Brunner * @author Esther Brunner <esther@kaffeehaus.ch>
406ba0267b3SMichael Hamann * @author Michael Hamann <michael@content-space.de>
40784657ea2SGerrit Uitslag *
40884657ea2SGerrit Uitslag * @param string $id page id
40984657ea2SGerrit Uitslag * @return array
410e1f3d9e1SEsther Brunner */
411e1f3d9e1SEsther Brunnerfunction metaFiles($id){
412ba0267b3SMichael Hamann    $basename = metaFN($id, '');
413ba0267b3SMichael Hamann    $files    = glob($basename.'.*', GLOB_MARK);
414ba0267b3SMichael Hamann    // filter files like foo.bar.meta when $id == 'foo'
415ba0267b3SMichael Hamann    return    $files ? preg_grep('/^'.preg_quote($basename, '/').'\.[^.\/]*$/u', $files) : array();
416e1f3d9e1SEsther Brunner}
417e1f3d9e1SEsther Brunner
418e1f3d9e1SEsther Brunner/**
419b625487dSandi * returns the full path to the mediafile specified by ID
420b625487dSandi *
421b625487dSandi * The filename is URL encoded to protect Unicode chars
422b625487dSandi *
423b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
424cbe26ad6SKate Arzamastseva * @author Kate Arzamastseva <pshns@ukr.net>
42584657ea2SGerrit Uitslag *
42684657ea2SGerrit Uitslag * @param string     $id  media id
42784657ea2SGerrit Uitslag * @param string|int $rev empty string or revision timestamp
428f50a239bSTakamura * @param bool $clean
429f50a239bSTakamura *
43084657ea2SGerrit Uitslag * @return string full path
431b625487dSandi */
432d0e997c6SMichael Großefunction mediaFN($id, $rev='', $clean=true){
433b625487dSandi    global $conf;
434d0e997c6SMichael Große    if ($clean) $id = cleanID($id);
435b625487dSandi    $id = str_replace(':','/',$id);
436e4f389efSKate Arzamastseva    if(empty($rev)){
437b625487dSandi        $fn = $conf['mediadir'].'/'.utf8_encodeFN($id);
438e4f389efSKate Arzamastseva    }else{
439cbe26ad6SKate Arzamastseva        $ext = mimetype($id);
4408e69fd30SKate Arzamastseva        $name = substr($id,0, -1*strlen($ext[0])-1);
44161f1aad8SKate Arzamastseva        $fn = $conf['mediaolddir'].'/'.utf8_encodeFN($name .'.'.( (int) $rev ).'.'.$ext[0]);
442e4f389efSKate Arzamastseva    }
443b625487dSandi    return $fn;
444b625487dSandi}
445b625487dSandi
446b625487dSandi/**
4472adaf2b8SAndreas Gohr * Returns the full filepath to a localized file if local
448b625487dSandi * version isn't found the english one is returned
449b625487dSandi *
4502adaf2b8SAndreas Gohr * @param  string $id  The id of the local file
4512adaf2b8SAndreas Gohr * @param  string $ext The file extension (usually txt)
452dbf714f7SGerrit Uitslag * @return string full filepath to localized file
45384657ea2SGerrit Uitslag *
454b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
455b625487dSandi */
4562adaf2b8SAndreas Gohrfunction localeFN($id,$ext='txt'){
457b625487dSandi    global $conf;
4588819fbf5ShArpanet    $file = DOKU_CONF.'lang/'.$conf['lang'].'/'.$id.'.'.$ext;
45979e79377SAndreas Gohr    if(!file_exists($file)){
4602adaf2b8SAndreas Gohr        $file = DOKU_INC.'inc/lang/'.$conf['lang'].'/'.$id.'.'.$ext;
46179e79377SAndreas Gohr        if(!file_exists($file)){
462b625487dSandi            //fall back to english
4632adaf2b8SAndreas Gohr            $file = DOKU_INC.'inc/lang/en/'.$id.'.'.$ext;
464b625487dSandi        }
465e6cecb08SMichael Hamann    }
466b625487dSandi    return $file;
467b625487dSandi}
468b625487dSandi
469b625487dSandi/**
470c4e0e4a1SAndreas Gohr * Resolve relative paths in IDs
471c4e0e4a1SAndreas Gohr *
472c4e0e4a1SAndreas Gohr * Do not call directly use resolve_mediaid or resolve_pageid
473c4e0e4a1SAndreas Gohr * instead
474c4e0e4a1SAndreas Gohr *
475c4e0e4a1SAndreas Gohr * Partyly based on a cleanPath function found at
47659752844SAnders Sandblad * http://php.net/manual/en/function.realpath.php#57016
477c4e0e4a1SAndreas Gohr *
478bfcf8009SAndreas Gohr * @deprecated 2020-09-30
47984657ea2SGerrit Uitslag * @param string $ns     namespace which is context of id
48084657ea2SGerrit Uitslag * @param string $id     relative id
48184657ea2SGerrit Uitslag * @param bool   $clean  flag indicating that id should be cleaned
48242ea7f44SGerrit Uitslag * @return string
483c4e0e4a1SAndreas Gohr */
484a6ef4796SAndreas Gohrfunction resolve_id($ns,$id,$clean=true){
485c662a49aSAndreas Gohr    global $conf;
4862cd6cc0aSAndreas Gohr    dbg_deprecated(\dokuwiki\File\Resolver::class.' and its children');
487c662a49aSAndreas Gohr
488c662a49aSAndreas Gohr    // some pre cleaning for useslash:
489c662a49aSAndreas Gohr    if($conf['useslash']) $id = str_replace('/',':',$id);
490c662a49aSAndreas Gohr
491c4e0e4a1SAndreas Gohr    // if the id starts with a dot we need to handle the
492c4e0e4a1SAndreas Gohr    // relative stuff
4932401f18dSSyntaxseed    if($id && $id[0] == '.'){
494c4e0e4a1SAndreas Gohr        // normalize initial dots without a colon
4954986a584SPhy        $id = preg_replace('/^((\.+:)*)(\.+)(?=[^:\.])/','\1\3:',$id);
496c4e0e4a1SAndreas Gohr        // prepend the current namespace
497c4e0e4a1SAndreas Gohr        $id = $ns.':'.$id;
498c4e0e4a1SAndreas Gohr
499c4e0e4a1SAndreas Gohr        // cleanup relatives
500c4e0e4a1SAndreas Gohr        $result = array();
501c4e0e4a1SAndreas Gohr        $pathA  = explode(':', $id);
502c4e0e4a1SAndreas Gohr        if (!$pathA[0]) $result[] = '';
503c4e0e4a1SAndreas Gohr        foreach ($pathA AS $key => $dir) {
504c4e0e4a1SAndreas Gohr            if ($dir == '..') {
505c4e0e4a1SAndreas Gohr                if (end($result) == '..') {
506c4e0e4a1SAndreas Gohr                    $result[] = '..';
507c4e0e4a1SAndreas Gohr                } elseif (!array_pop($result)) {
508c4e0e4a1SAndreas Gohr                    $result[] = '..';
509c4e0e4a1SAndreas Gohr                }
510c4e0e4a1SAndreas Gohr            } elseif ($dir && $dir != '.') {
511c4e0e4a1SAndreas Gohr                $result[] = $dir;
512c4e0e4a1SAndreas Gohr            }
513c4e0e4a1SAndreas Gohr        }
514c4e0e4a1SAndreas Gohr        if (!end($pathA)) $result[] = '';
515c4e0e4a1SAndreas Gohr        $id = implode(':', $result);
516c4e0e4a1SAndreas Gohr    }elseif($ns !== false && strpos($id,':') === false){
517c4e0e4a1SAndreas Gohr        //if link contains no namespace. add current namespace (if any)
518c4e0e4a1SAndreas Gohr        $id = $ns.':'.$id;
519c4e0e4a1SAndreas Gohr    }
520c4e0e4a1SAndreas Gohr
521a6ef4796SAndreas Gohr    if($clean) $id = cleanID($id);
522a6ef4796SAndreas Gohr    return $id;
523c4e0e4a1SAndreas Gohr}
524c4e0e4a1SAndreas Gohr
525c4e0e4a1SAndreas Gohr/**
526b625487dSandi * Returns a full media id
527b625487dSandi *
52884657ea2SGerrit Uitslag * @param string $ns namespace which is context of id
5295c844bb3SAndreas Gohr * @param string &$media (reference) relative media id, updated to resolved id
53084657ea2SGerrit Uitslag * @param bool &$exists (reference) updated with existance of media
5317de86af9SGerrit Uitslag * @param int|string $rev
5327de86af9SGerrit Uitslag * @param bool $date_at
5335c844bb3SAndreas Gohr * @deprecated 2020-09-30
534b625487dSandi */
5355c844bb3SAndreas Gohrfunction resolve_mediaid($ns,&$media,&$exists,$rev='',$date_at=false){
5365c844bb3SAndreas Gohr    dbg_deprecated(MediaResolver::class);
5375c844bb3SAndreas Gohr    $resolver = new MediaResolver("$ns:deprecated");
5385c844bb3SAndreas Gohr    $media = $resolver->resolveId($media, $rev, $date_at);
5395c844bb3SAndreas Gohr    $exists = media_exists($media, $rev, false, $date_at);
540b625487dSandi}
541b625487dSandi
542b625487dSandi/**
543b625487dSandi * Returns a full page id
544b625487dSandi *
545bfcf8009SAndreas Gohr * @deprecated 2020-09-30
54684657ea2SGerrit Uitslag * @param string $ns namespace which is context of id
54784657ea2SGerrit Uitslag * @param string &$page (reference) relative page id, updated to resolved id
54884657ea2SGerrit Uitslag * @param bool &$exists (reference) updated with existance of media
5497de86af9SGerrit Uitslag * @param string $rev
5507de86af9SGerrit Uitslag * @param bool $date_at
551b625487dSandi */
552bfcf8009SAndreas Gohrfunction resolve_pageid($ns,&$page,&$exists,$rev='',$date_at=false )
553bfcf8009SAndreas Gohr{
5548c6be208SAndreas Gohr    dbg_deprecated(PageResolver::class);
55554611a7aSAndreas Gohr
55654611a7aSAndreas Gohr    global $ID;
55754611a7aSAndreas Gohr    if(getNS($ID) == $ns) {
55854611a7aSAndreas Gohr        $context = $ID; // this is usually the case
55954611a7aSAndreas Gohr    } else {
56054611a7aSAndreas Gohr        $context = "$ns:deprecated"; // only used when a different context namespace was given
56154611a7aSAndreas Gohr    }
56254611a7aSAndreas Gohr
56354611a7aSAndreas Gohr    $resolver = new PageResolver($context);
564bfcf8009SAndreas Gohr    $page = $resolver->resolveId($page, $rev, $date_at);
565bfcf8009SAndreas Gohr    $exists = page_exists($page, $rev, false, $date_at);
566b625487dSandi}
567b625487dSandi
56898407a7aSandi/**
56998407a7aSandi * Returns the name of a cachefile from given data
57098407a7aSandi *
57198407a7aSandi * The needed directory is created by this function!
57298407a7aSandi *
57398407a7aSandi * @author Andreas Gohr <andi@splitbrain.org>
57498407a7aSandi *
57598407a7aSandi * @param string $data  This data is used to create a unique md5 name
57698407a7aSandi * @param string $ext   This is appended to the filename if given
57798407a7aSandi * @return string       The filename of the cachefile
57898407a7aSandi */
57998407a7aSandifunction getCacheName($data,$ext=''){
58098407a7aSandi    global $conf;
58198407a7aSandi    $md5  = md5($data);
5822401f18dSSyntaxseed    $file = $conf['cachedir'].'/'.$md5[0].'/'.$md5.$ext;
58398407a7aSandi    io_makeFileDir($file);
58498407a7aSandi    return $file;
58598407a7aSandi}
58698407a7aSandi
5870dc92c6fSAndreas Gohr/**
5880dc92c6fSAndreas Gohr * Checks a pageid against $conf['hidepages']
5890dc92c6fSAndreas Gohr *
5900dc92c6fSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
59184657ea2SGerrit Uitslag *
59284657ea2SGerrit Uitslag * @param string $id page id
59384657ea2SGerrit Uitslag * @return bool
5940dc92c6fSAndreas Gohr */
5950dc92c6fSAndreas Gohrfunction isHiddenPage($id){
5968449cc9dSDominik Eckelmann    $data = array(
5978449cc9dSDominik Eckelmann        'id' => $id,
5988449cc9dSDominik Eckelmann        'hidden' => false
5998449cc9dSDominik Eckelmann    );
600cbb44eabSAndreas Gohr    \dokuwiki\Extension\Event::createAndTrigger('PAGEUTILS_ID_HIDEPAGE', $data, '_isHiddenPage');
601fb55b51eSDominik Eckelmann    return $data['hidden'];
6020dc92c6fSAndreas Gohr}
603fb55b51eSDominik Eckelmann
604dbf714f7SGerrit Uitslag/**
605dbf714f7SGerrit Uitslag * callback checks if page is hidden
606dbf714f7SGerrit Uitslag *
60784657ea2SGerrit Uitslag * @param array $data event data    - see isHiddenPage()
608dbf714f7SGerrit Uitslag */
609fb55b51eSDominik Eckelmannfunction _isHiddenPage(&$data) {
610fb55b51eSDominik Eckelmann    global $conf;
611fb55b51eSDominik Eckelmann    global $ACT;
612fb55b51eSDominik Eckelmann
613fb55b51eSDominik Eckelmann    if ($data['hidden']) return;
614fb55b51eSDominik Eckelmann    if(empty($conf['hidepages'])) return;
615fb55b51eSDominik Eckelmann    if($ACT == 'admin') return;
616fb55b51eSDominik Eckelmann
617fb55b51eSDominik Eckelmann    if(preg_match('/'.$conf['hidepages'].'/ui',':'.$data['id'])){
618fb55b51eSDominik Eckelmann        $data['hidden'] = true;
619fb55b51eSDominik Eckelmann    }
6200dc92c6fSAndreas Gohr}
6210dc92c6fSAndreas Gohr
6220dc92c6fSAndreas Gohr/**
6230dc92c6fSAndreas Gohr * Reverse of isHiddenPage
6240dc92c6fSAndreas Gohr *
6250dc92c6fSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
62684657ea2SGerrit Uitslag *
62784657ea2SGerrit Uitslag * @param string $id page id
62884657ea2SGerrit Uitslag * @return bool
6290dc92c6fSAndreas Gohr */
6300dc92c6fSAndreas Gohrfunction isVisiblePage($id){
6310dc92c6fSAndreas Gohr    return !isHiddenPage($id);
6320dc92c6fSAndreas Gohr}
6330dc92c6fSAndreas Gohr
6345b75cd1fSAdrian Lang/**
6355b75cd1fSAdrian Lang * Format an id for output to a user
6365b75cd1fSAdrian Lang *
6375b75cd1fSAdrian Lang * Namespaces are denoted by a trailing “:*”. The root namespace is
6385b75cd1fSAdrian Lang * “*”. Output is escaped.
6395b75cd1fSAdrian Lang *
6405b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
64184657ea2SGerrit Uitslag *
64284657ea2SGerrit Uitslag * @param string $id page id
64384657ea2SGerrit Uitslag * @return string
6445b75cd1fSAdrian Lang */
6455b75cd1fSAdrian Langfunction prettyprint_id($id) {
6465b75cd1fSAdrian Lang    if (!$id || $id === ':') {
6475b75cd1fSAdrian Lang        return '*';
6485b75cd1fSAdrian Lang    }
6495b75cd1fSAdrian Lang    if ((substr($id, -1, 1) === ':')) {
6505b75cd1fSAdrian Lang        $id .= '*';
6515b75cd1fSAdrian Lang    }
6525b75cd1fSAdrian Lang    return hsc($id);
6535b75cd1fSAdrian Lang}
654f03fd957SAndreas Gohr
655f03fd957SAndreas Gohr/**
656f03fd957SAndreas Gohr * Encode a UTF-8 filename to use on any filesystem
657f03fd957SAndreas Gohr *
658f03fd957SAndreas Gohr * Uses the 'fnencode' option to determine encoding
659f03fd957SAndreas Gohr *
660f03fd957SAndreas Gohr * When the second parameter is true the string will
661f03fd957SAndreas Gohr * be encoded only if non ASCII characters are detected -
662f03fd957SAndreas Gohr * This makes it safe to run it multiple times on the
663f03fd957SAndreas Gohr * same string (default is true)
664f03fd957SAndreas Gohr *
665f03fd957SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
666f03fd957SAndreas Gohr * @see    urlencode
66784657ea2SGerrit Uitslag *
66884657ea2SGerrit Uitslag * @param string $file file name
66984657ea2SGerrit Uitslag * @param bool   $safe if true, only encoded when non ASCII characters detected
67084657ea2SGerrit Uitslag * @return string
671f03fd957SAndreas Gohr */
672f03fd957SAndreas Gohrfunction utf8_encodeFN($file,$safe=true){
673f03fd957SAndreas Gohr    global $conf;
674f03fd957SAndreas Gohr    if($conf['fnencode'] == 'utf-8') return $file;
675f03fd957SAndreas Gohr
676f03fd957SAndreas Gohr    if($safe && preg_match('#^[a-zA-Z0-9/_\-\.%]+$#',$file)){
677f03fd957SAndreas Gohr        return $file;
678f03fd957SAndreas Gohr    }
679f03fd957SAndreas Gohr
680f03fd957SAndreas Gohr    if($conf['fnencode'] == 'safe'){
681f03fd957SAndreas Gohr        return SafeFN::encode($file);
682f03fd957SAndreas Gohr    }
683f03fd957SAndreas Gohr
684f03fd957SAndreas Gohr    $file = urlencode($file);
685f03fd957SAndreas Gohr    $file = str_replace('%2F','/',$file);
686f03fd957SAndreas Gohr    return $file;
687f03fd957SAndreas Gohr}
688f03fd957SAndreas Gohr
689f03fd957SAndreas Gohr/**
690f03fd957SAndreas Gohr * Decode a filename back to UTF-8
691f03fd957SAndreas Gohr *
692f03fd957SAndreas Gohr * Uses the 'fnencode' option to determine encoding
693f03fd957SAndreas Gohr *
694f03fd957SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
695f03fd957SAndreas Gohr * @see    urldecode
69684657ea2SGerrit Uitslag *
69784657ea2SGerrit Uitslag * @param string $file file name
69884657ea2SGerrit Uitslag * @return string
699f03fd957SAndreas Gohr */
700f03fd957SAndreas Gohrfunction utf8_decodeFN($file){
701f03fd957SAndreas Gohr    global $conf;
702f03fd957SAndreas Gohr    if($conf['fnencode'] == 'utf-8') return $file;
703f03fd957SAndreas Gohr
704f03fd957SAndreas Gohr    if($conf['fnencode'] == 'safe'){
705f03fd957SAndreas Gohr        return SafeFN::decode($file);
706f03fd957SAndreas Gohr    }
707f03fd957SAndreas Gohr
708f03fd957SAndreas Gohr    return urldecode($file);
709f03fd957SAndreas Gohr}
710f03fd957SAndreas Gohr
711e66d3e6dSAndreas Gohr/**
712e66d3e6dSAndreas Gohr * Find a page in the current namespace (determined from $ID) or any
713cc529468SMichael Hamann * higher namespace that can be accessed by the current user,
714cc529468SMichael Hamann * this condition can be overriden by an optional parameter.
715e66d3e6dSAndreas Gohr *
716e66d3e6dSAndreas Gohr * Used for sidebars, but can be used other stuff as well
717e66d3e6dSAndreas Gohr *
718e66d3e6dSAndreas Gohr * @todo   add event hook
71942ea7f44SGerrit Uitslag *
720e66d3e6dSAndreas Gohr * @param  string $page the pagename you're looking for
7217c3e4a67SAndreas Gohr * @param bool $useacl only return pages readable by the current user, false to ignore ACLs
722cc529468SMichael Hamann * @return false|string the full page id of the found page, false if any
723e66d3e6dSAndreas Gohr */
7247c3e4a67SAndreas Gohrfunction page_findnearest($page, $useacl = true){
72506a70133SPhy    if ((string) $page === '') return false;
726e66d3e6dSAndreas Gohr    global $ID;
727e66d3e6dSAndreas Gohr
728e66d3e6dSAndreas Gohr    $ns = $ID;
729e66d3e6dSAndreas Gohr    do {
730e66d3e6dSAndreas Gohr        $ns = getNS($ns);
731cc529468SMichael Hamann        $pageid = cleanID("$ns:$page");
7327c3e4a67SAndreas Gohr        if(page_exists($pageid) && (!$useacl || auth_quickaclcheck($pageid) >= AUTH_READ)){
733e66d3e6dSAndreas Gohr            return $pageid;
734e66d3e6dSAndreas Gohr        }
73506a70133SPhy    } while($ns !== false);
736e66d3e6dSAndreas Gohr
737e66d3e6dSAndreas Gohr    return false;
738e66d3e6dSAndreas Gohr}
739