xref: /dokuwiki/inc/pageutils.php (revision 5c844bb3459a3b146c907b624f8a4c8af16ce19d)
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;
12*5c844bb3SAndreas Gohruse dokuwiki\Utils\MediaResolver;
13*5c844bb3SAndreas 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
231c857afe0SMichael Hamann * @param array|bool   $check   Existing IDs (title => number)
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)){
2464ceab83fSAndreas Gohr        // make sure tiles are unique
24701e3159cSChris Tapp        if (!array_key_exists ($title,$check)) {
24801e3159cSChris Tapp            $check[$title] = 0;
24901e3159cSChris Tapp        } else {
25001e3159cSChris Tapp            $title .= ++ $check[$title];
2514ceab83fSAndreas Gohr        }
2524ceab83fSAndreas Gohr    }
2534ceab83fSAndreas Gohr
2544ceab83fSAndreas Gohr    return $title;
2554ceab83fSAndreas Gohr}
2564ceab83fSAndreas Gohr
257b625487dSandi/**
258103c256aSChris Smith * Wiki page existence check
259103c256aSChris Smith *
260103c256aSChris Smith * parameters as for wikiFN
261103c256aSChris Smith *
262103c256aSChris Smith * @author Chris Smith <chris@jalakai.co.uk>
26384657ea2SGerrit Uitslag *
26484657ea2SGerrit Uitslag * @param string $id page id
26584657ea2SGerrit Uitslag * @param string|int $rev empty or revision timestamp
26684657ea2SGerrit Uitslag * @param bool $clean flag indicating that $id should be cleaned (see wikiFN as well)
2677de86af9SGerrit Uitslag * @param bool $date_at
26884657ea2SGerrit Uitslag * @return bool exists?
269103c256aSChris Smith */
2701d053a56Slispsfunction page_exists($id,$rev='',$clean=true, $date_at=false) {
27190bee600Slisps    if($rev !== '' && $date_at) {
2721d053a56Slisps        $pagelog = new PageChangeLog($id);
27390bee600Slisps        $pagelog_rev = $pagelog->getLastRevisionAt($rev);
27490bee600Slisps        if($pagelog_rev !== false)
27590bee600Slisps            $rev = $pagelog_rev;
27690bee600Slisps    }
27779e79377SAndreas Gohr    return file_exists(wikiFN($id,$rev,$clean));
278103c256aSChris Smith}
279103c256aSChris Smith
280103c256aSChris Smith/**
281*5c844bb3SAndreas Gohr * Media existence check
282*5c844bb3SAndreas Gohr *
283*5c844bb3SAndreas Gohr * @param string $id page id
284*5c844bb3SAndreas Gohr * @param string|int $rev empty or revision timestamp
285*5c844bb3SAndreas Gohr * @param bool $clean flag indicating that $id should be cleaned (see mediaFN as well)
286*5c844bb3SAndreas Gohr * @param bool $date_at
287*5c844bb3SAndreas Gohr * @return bool exists?
288*5c844bb3SAndreas Gohr */
289*5c844bb3SAndreas Gohrfunction media_exists($id, $rev = '', $clean = true, $date_at = false)
290*5c844bb3SAndreas Gohr{
291*5c844bb3SAndreas Gohr    if ($rev !== '' && $date_at) {
292*5c844bb3SAndreas Gohr        $changeLog = new MediaChangeLog($id);
293*5c844bb3SAndreas Gohr        $changelog_rev = $changeLog->getLastRevisionAt($rev);
294*5c844bb3SAndreas Gohr        if ($changelog_rev !== false) {
295*5c844bb3SAndreas Gohr            $rev = $changelog_rev;
296*5c844bb3SAndreas Gohr        }
297*5c844bb3SAndreas Gohr    }
298*5c844bb3SAndreas Gohr    return file_exists(mediaFN($id, $rev, $clean));
299*5c844bb3SAndreas Gohr}
300*5c844bb3SAndreas Gohr
301*5c844bb3SAndreas Gohr/**
302103c256aSChris Smith * returns the full path to the datafile specified by ID and optional revision
303b625487dSandi *
304b625487dSandi * The filename is URL encoded to protect Unicode chars
305b625487dSandi *
306103c256aSChris Smith * @param  $raw_id  string   id of wikipage
307e0c26282SGerrit Uitslag * @param  $rev     int|string   page revision, empty string for current
308103c256aSChris Smith * @param  $clean   bool     flag indicating that $raw_id should be cleaned.  Only set to false
309103c256aSChris Smith *                           when $id is guaranteed to have been cleaned already.
310dbf714f7SGerrit Uitslag * @return string full path
311103c256aSChris Smith *
312b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
313b625487dSandi */
3146e0cc83aSchrisfunction wikiFN($raw_id,$rev='',$clean=true){
315b625487dSandi    global $conf;
3166e0cc83aSchris
317dc2c0e04Schris    global $cache_wikifn;
318dc2c0e04Schris    $cache = & $cache_wikifn;
319dc2c0e04Schris
3206e0cc83aSchris    $id = $raw_id;
3216e0cc83aSchris
3220d8ea614Schris    if ($clean) $id = cleanID($id);
323b625487dSandi    $id = str_replace(':','/',$id);
324b018ecbeSMichael Grosse
325b018ecbeSMichael Grosse    if (isset($cache[$id]) && isset($cache[$id][$rev])) {
326b018ecbeSMichael Grosse        return $cache[$id][$rev];
327b018ecbeSMichael Grosse    }
328b018ecbeSMichael Grosse
329b625487dSandi    if(empty($rev)){
330b625487dSandi        $fn = $conf['datadir'].'/'.utf8_encodeFN($id).'.txt';
331b625487dSandi    }else{
332b625487dSandi        $fn = $conf['olddir'].'/'.utf8_encodeFN($id).'.'.$rev.'.txt';
333ff3ed99fSmarcel        if($conf['compression']){
334ff3ed99fSmarcel            //test for extensions here, we want to read both compressions
33579e79377SAndreas Gohr            if (file_exists($fn . '.gz')){
336b625487dSandi                $fn .= '.gz';
33779e79377SAndreas Gohr            }else if(file_exists($fn . '.bz2')){
338ff3ed99fSmarcel                $fn .= '.bz2';
339ff3ed99fSmarcel            }else{
340ff3ed99fSmarcel                //file doesnt exist yet, so we take the configured extension
341ff3ed99fSmarcel                $fn .= '.' . $conf['compression'];
342ff3ed99fSmarcel            }
343b625487dSandi        }
344b625487dSandi    }
3456e0cc83aSchris
346b018ecbeSMichael Grosse    if (!isset($cache[$id])) { $cache[$id] = array(); }
347b018ecbeSMichael Grosse    $cache[$id][$rev] = $fn;
348b625487dSandi    return $fn;
349b625487dSandi}
350b625487dSandi
351b625487dSandi/**
352c9b4bd1eSBen Coburn * Returns the full path to the file for locking the page while editing.
353c9b4bd1eSBen Coburn *
354c9b4bd1eSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
35584657ea2SGerrit Uitslag *
35684657ea2SGerrit Uitslag * @param string $id page id
35784657ea2SGerrit Uitslag * @return string full path
358c9b4bd1eSBen Coburn */
359c9b4bd1eSBen Coburnfunction wikiLockFN($id) {
360c9b4bd1eSBen Coburn    global $conf;
361662ff478SAndreas Gohr    return $conf['lockdir'].'/'.md5(cleanID($id)).'.lock';
362c9b4bd1eSBen Coburn}
363c9b4bd1eSBen Coburn
364c9b4bd1eSBen Coburn
365c9b4bd1eSBen Coburn/**
3661380fc45SAndreas Gohr * returns the full path to the meta file specified by ID and extension
367b158d625SSteven Danz *
368b158d625SSteven Danz * @author Steven Danz <steven-danz@kc.rr.com>
36984657ea2SGerrit Uitslag *
37084657ea2SGerrit Uitslag * @param string $id   page id
37184657ea2SGerrit Uitslag * @param string $ext  file extension
37284657ea2SGerrit Uitslag * @return string full path
373b158d625SSteven Danz */
3741380fc45SAndreas Gohrfunction metaFN($id,$ext){
375b158d625SSteven Danz    global $conf;
376b158d625SSteven Danz    $id = cleanID($id);
377b158d625SSteven Danz    $id = str_replace(':','/',$id);
3781380fc45SAndreas Gohr    $fn = $conf['metadir'].'/'.utf8_encodeFN($id).$ext;
379b158d625SSteven Danz    return $fn;
380b158d625SSteven Danz}
381b158d625SSteven Danz
382b158d625SSteven Danz/**
383e4f389efSKate Arzamastseva * returns the full path to the media's meta file specified by ID and extension
384e4f389efSKate Arzamastseva *
385cbe26ad6SKate Arzamastseva * @author Kate Arzamastseva <pshns@ukr.net>
38684657ea2SGerrit Uitslag *
38784657ea2SGerrit Uitslag * @param string $id   media id
38884657ea2SGerrit Uitslag * @param string $ext  extension of media
38984657ea2SGerrit Uitslag * @return string
390e4f389efSKate Arzamastseva */
391e4f389efSKate Arzamastsevafunction mediaMetaFN($id,$ext){
392e4f389efSKate Arzamastseva    global $conf;
393e4f389efSKate Arzamastseva    $id = cleanID($id);
394e4f389efSKate Arzamastseva    $id = str_replace(':','/',$id);
395e4f389efSKate Arzamastseva    $fn = $conf['mediametadir'].'/'.utf8_encodeFN($id).$ext;
396e4f389efSKate Arzamastseva    return $fn;
397e4f389efSKate Arzamastseva}
398e4f389efSKate Arzamastseva
399e4f389efSKate Arzamastseva/**
400e1f3d9e1SEsther Brunner * returns an array of full paths to all metafiles of a given ID
401e1f3d9e1SEsther Brunner *
402e1f3d9e1SEsther Brunner * @author Esther Brunner <esther@kaffeehaus.ch>
403ba0267b3SMichael Hamann * @author Michael Hamann <michael@content-space.de>
40484657ea2SGerrit Uitslag *
40584657ea2SGerrit Uitslag * @param string $id page id
40684657ea2SGerrit Uitslag * @return array
407e1f3d9e1SEsther Brunner */
408e1f3d9e1SEsther Brunnerfunction metaFiles($id){
409ba0267b3SMichael Hamann    $basename = metaFN($id, '');
410ba0267b3SMichael Hamann    $files    = glob($basename.'.*', GLOB_MARK);
411ba0267b3SMichael Hamann    // filter files like foo.bar.meta when $id == 'foo'
412ba0267b3SMichael Hamann    return    $files ? preg_grep('/^'.preg_quote($basename, '/').'\.[^.\/]*$/u', $files) : array();
413e1f3d9e1SEsther Brunner}
414e1f3d9e1SEsther Brunner
415e1f3d9e1SEsther Brunner/**
416b625487dSandi * returns the full path to the mediafile specified by ID
417b625487dSandi *
418b625487dSandi * The filename is URL encoded to protect Unicode chars
419b625487dSandi *
420b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
421cbe26ad6SKate Arzamastseva * @author Kate Arzamastseva <pshns@ukr.net>
42284657ea2SGerrit Uitslag *
42384657ea2SGerrit Uitslag * @param string     $id  media id
42484657ea2SGerrit Uitslag * @param string|int $rev empty string or revision timestamp
425f50a239bSTakamura * @param bool $clean
426f50a239bSTakamura *
42784657ea2SGerrit Uitslag * @return string full path
428b625487dSandi */
429d0e997c6SMichael Großefunction mediaFN($id, $rev='', $clean=true){
430b625487dSandi    global $conf;
431d0e997c6SMichael Große    if ($clean) $id = cleanID($id);
432b625487dSandi    $id = str_replace(':','/',$id);
433e4f389efSKate Arzamastseva    if(empty($rev)){
434b625487dSandi        $fn = $conf['mediadir'].'/'.utf8_encodeFN($id);
435e4f389efSKate Arzamastseva    }else{
436cbe26ad6SKate Arzamastseva        $ext = mimetype($id);
4378e69fd30SKate Arzamastseva        $name = substr($id,0, -1*strlen($ext[0])-1);
43861f1aad8SKate Arzamastseva        $fn = $conf['mediaolddir'].'/'.utf8_encodeFN($name .'.'.( (int) $rev ).'.'.$ext[0]);
439e4f389efSKate Arzamastseva    }
440b625487dSandi    return $fn;
441b625487dSandi}
442b625487dSandi
443b625487dSandi/**
4442adaf2b8SAndreas Gohr * Returns the full filepath to a localized file if local
445b625487dSandi * version isn't found the english one is returned
446b625487dSandi *
4472adaf2b8SAndreas Gohr * @param  string $id  The id of the local file
4482adaf2b8SAndreas Gohr * @param  string $ext The file extension (usually txt)
449dbf714f7SGerrit Uitslag * @return string full filepath to localized file
45084657ea2SGerrit Uitslag *
451b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
452b625487dSandi */
4532adaf2b8SAndreas Gohrfunction localeFN($id,$ext='txt'){
454b625487dSandi    global $conf;
4558819fbf5ShArpanet    $file = DOKU_CONF.'lang/'.$conf['lang'].'/'.$id.'.'.$ext;
45679e79377SAndreas Gohr    if(!file_exists($file)){
4572adaf2b8SAndreas Gohr        $file = DOKU_INC.'inc/lang/'.$conf['lang'].'/'.$id.'.'.$ext;
45879e79377SAndreas Gohr        if(!file_exists($file)){
459b625487dSandi            //fall back to english
4602adaf2b8SAndreas Gohr            $file = DOKU_INC.'inc/lang/en/'.$id.'.'.$ext;
461b625487dSandi        }
462e6cecb08SMichael Hamann    }
463b625487dSandi    return $file;
464b625487dSandi}
465b625487dSandi
466b625487dSandi/**
467c4e0e4a1SAndreas Gohr * Resolve relative paths in IDs
468c4e0e4a1SAndreas Gohr *
469c4e0e4a1SAndreas Gohr * Do not call directly use resolve_mediaid or resolve_pageid
470c4e0e4a1SAndreas Gohr * instead
471c4e0e4a1SAndreas Gohr *
472c4e0e4a1SAndreas Gohr * Partyly based on a cleanPath function found at
47359752844SAnders Sandblad * http://php.net/manual/en/function.realpath.php#57016
474c4e0e4a1SAndreas Gohr *
475bfcf8009SAndreas Gohr * @deprecated 2020-09-30
47684657ea2SGerrit Uitslag * @param string $ns     namespace which is context of id
47784657ea2SGerrit Uitslag * @param string $id     relative id
47884657ea2SGerrit Uitslag * @param bool   $clean  flag indicating that id should be cleaned
47942ea7f44SGerrit Uitslag * @return string
480c4e0e4a1SAndreas Gohr */
481a6ef4796SAndreas Gohrfunction resolve_id($ns,$id,$clean=true){
482c662a49aSAndreas Gohr    global $conf;
483bfcf8009SAndreas Gohr    dbg_deprecated(\dokuwiki\Utils\Resolver::class.' and its children');
484c662a49aSAndreas Gohr
485c662a49aSAndreas Gohr    // some pre cleaning for useslash:
486c662a49aSAndreas Gohr    if($conf['useslash']) $id = str_replace('/',':',$id);
487c662a49aSAndreas Gohr
488c4e0e4a1SAndreas Gohr    // if the id starts with a dot we need to handle the
489c4e0e4a1SAndreas Gohr    // relative stuff
4902401f18dSSyntaxseed    if($id && $id[0] == '.'){
491c4e0e4a1SAndreas Gohr        // normalize initial dots without a colon
4924986a584SPhy        $id = preg_replace('/^((\.+:)*)(\.+)(?=[^:\.])/','\1\3:',$id);
493c4e0e4a1SAndreas Gohr        // prepend the current namespace
494c4e0e4a1SAndreas Gohr        $id = $ns.':'.$id;
495c4e0e4a1SAndreas Gohr
496c4e0e4a1SAndreas Gohr        // cleanup relatives
497c4e0e4a1SAndreas Gohr        $result = array();
498c4e0e4a1SAndreas Gohr        $pathA  = explode(':', $id);
499c4e0e4a1SAndreas Gohr        if (!$pathA[0]) $result[] = '';
500c4e0e4a1SAndreas Gohr        foreach ($pathA AS $key => $dir) {
501c4e0e4a1SAndreas Gohr            if ($dir == '..') {
502c4e0e4a1SAndreas Gohr                if (end($result) == '..') {
503c4e0e4a1SAndreas Gohr                    $result[] = '..';
504c4e0e4a1SAndreas Gohr                } elseif (!array_pop($result)) {
505c4e0e4a1SAndreas Gohr                    $result[] = '..';
506c4e0e4a1SAndreas Gohr                }
507c4e0e4a1SAndreas Gohr            } elseif ($dir && $dir != '.') {
508c4e0e4a1SAndreas Gohr                $result[] = $dir;
509c4e0e4a1SAndreas Gohr            }
510c4e0e4a1SAndreas Gohr        }
511c4e0e4a1SAndreas Gohr        if (!end($pathA)) $result[] = '';
512c4e0e4a1SAndreas Gohr        $id = implode(':', $result);
513c4e0e4a1SAndreas Gohr    }elseif($ns !== false && strpos($id,':') === false){
514c4e0e4a1SAndreas Gohr        //if link contains no namespace. add current namespace (if any)
515c4e0e4a1SAndreas Gohr        $id = $ns.':'.$id;
516c4e0e4a1SAndreas Gohr    }
517c4e0e4a1SAndreas Gohr
518a6ef4796SAndreas Gohr    if($clean) $id = cleanID($id);
519a6ef4796SAndreas Gohr    return $id;
520c4e0e4a1SAndreas Gohr}
521c4e0e4a1SAndreas Gohr
522c4e0e4a1SAndreas Gohr/**
523b625487dSandi * Returns a full media id
524b625487dSandi *
52584657ea2SGerrit Uitslag * @param string $ns namespace which is context of id
526*5c844bb3SAndreas Gohr * @param string &$media (reference) relative media id, updated to resolved id
52784657ea2SGerrit Uitslag * @param bool &$exists (reference) updated with existance of media
5287de86af9SGerrit Uitslag * @param int|string $rev
5297de86af9SGerrit Uitslag * @param bool $date_at
530*5c844bb3SAndreas Gohr * @deprecated 2020-09-30
531b625487dSandi */
532*5c844bb3SAndreas Gohrfunction resolve_mediaid($ns,&$media,&$exists,$rev='',$date_at=false){
533*5c844bb3SAndreas Gohr    dbg_deprecated(MediaResolver::class);
534*5c844bb3SAndreas Gohr    $resolver = new MediaResolver("$ns:deprecated");
535*5c844bb3SAndreas Gohr    $media = $resolver->resolveId($media, $rev, $date_at);
536*5c844bb3SAndreas Gohr    $exists = media_exists($media, $rev, false, $date_at);
537b625487dSandi}
538b625487dSandi
539b625487dSandi/**
540b625487dSandi * Returns a full page id
541b625487dSandi *
542bfcf8009SAndreas Gohr * @deprecated 2020-09-30
54384657ea2SGerrit Uitslag * @param string $ns namespace which is context of id
54484657ea2SGerrit Uitslag * @param string &$page (reference) relative page id, updated to resolved id
54584657ea2SGerrit Uitslag * @param bool &$exists (reference) updated with existance of media
5467de86af9SGerrit Uitslag * @param string $rev
5477de86af9SGerrit Uitslag * @param bool $date_at
548b625487dSandi */
549bfcf8009SAndreas Gohrfunction resolve_pageid($ns,&$page,&$exists,$rev='',$date_at=false )
550bfcf8009SAndreas Gohr{
551bfcf8009SAndreas Gohr    dbg_deprecated(\dokuwiki\Utils\PageResolver::class);
552bfcf8009SAndreas Gohr    $resolver = new \dokuwiki\Utils\PageResolver("$ns:deprecated");
553bfcf8009SAndreas Gohr    $page = $resolver->resolveId($page, $rev, $date_at);
554bfcf8009SAndreas Gohr    $exists = page_exists($page, $rev, false, $date_at);
555b625487dSandi}
556b625487dSandi
55798407a7aSandi/**
55898407a7aSandi * Returns the name of a cachefile from given data
55998407a7aSandi *
56098407a7aSandi * The needed directory is created by this function!
56198407a7aSandi *
56298407a7aSandi * @author Andreas Gohr <andi@splitbrain.org>
56398407a7aSandi *
56498407a7aSandi * @param string $data  This data is used to create a unique md5 name
56598407a7aSandi * @param string $ext   This is appended to the filename if given
56698407a7aSandi * @return string       The filename of the cachefile
56798407a7aSandi */
56898407a7aSandifunction getCacheName($data,$ext=''){
56998407a7aSandi    global $conf;
57098407a7aSandi    $md5  = md5($data);
5712401f18dSSyntaxseed    $file = $conf['cachedir'].'/'.$md5[0].'/'.$md5.$ext;
57298407a7aSandi    io_makeFileDir($file);
57398407a7aSandi    return $file;
57498407a7aSandi}
57598407a7aSandi
5760dc92c6fSAndreas Gohr/**
5770dc92c6fSAndreas Gohr * Checks a pageid against $conf['hidepages']
5780dc92c6fSAndreas Gohr *
5790dc92c6fSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
58084657ea2SGerrit Uitslag *
58184657ea2SGerrit Uitslag * @param string $id page id
58284657ea2SGerrit Uitslag * @return bool
5830dc92c6fSAndreas Gohr */
5840dc92c6fSAndreas Gohrfunction isHiddenPage($id){
5858449cc9dSDominik Eckelmann    $data = array(
5868449cc9dSDominik Eckelmann        'id' => $id,
5878449cc9dSDominik Eckelmann        'hidden' => false
5888449cc9dSDominik Eckelmann    );
589cbb44eabSAndreas Gohr    \dokuwiki\Extension\Event::createAndTrigger('PAGEUTILS_ID_HIDEPAGE', $data, '_isHiddenPage');
590fb55b51eSDominik Eckelmann    return $data['hidden'];
5910dc92c6fSAndreas Gohr}
592fb55b51eSDominik Eckelmann
593dbf714f7SGerrit Uitslag/**
594dbf714f7SGerrit Uitslag * callback checks if page is hidden
595dbf714f7SGerrit Uitslag *
59684657ea2SGerrit Uitslag * @param array $data event data    - see isHiddenPage()
597dbf714f7SGerrit Uitslag */
598fb55b51eSDominik Eckelmannfunction _isHiddenPage(&$data) {
599fb55b51eSDominik Eckelmann    global $conf;
600fb55b51eSDominik Eckelmann    global $ACT;
601fb55b51eSDominik Eckelmann
602fb55b51eSDominik Eckelmann    if ($data['hidden']) return;
603fb55b51eSDominik Eckelmann    if(empty($conf['hidepages'])) return;
604fb55b51eSDominik Eckelmann    if($ACT == 'admin') return;
605fb55b51eSDominik Eckelmann
606fb55b51eSDominik Eckelmann    if(preg_match('/'.$conf['hidepages'].'/ui',':'.$data['id'])){
607fb55b51eSDominik Eckelmann        $data['hidden'] = true;
608fb55b51eSDominik Eckelmann    }
6090dc92c6fSAndreas Gohr}
6100dc92c6fSAndreas Gohr
6110dc92c6fSAndreas Gohr/**
6120dc92c6fSAndreas Gohr * Reverse of isHiddenPage
6130dc92c6fSAndreas Gohr *
6140dc92c6fSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
61584657ea2SGerrit Uitslag *
61684657ea2SGerrit Uitslag * @param string $id page id
61784657ea2SGerrit Uitslag * @return bool
6180dc92c6fSAndreas Gohr */
6190dc92c6fSAndreas Gohrfunction isVisiblePage($id){
6200dc92c6fSAndreas Gohr    return !isHiddenPage($id);
6210dc92c6fSAndreas Gohr}
6220dc92c6fSAndreas Gohr
6235b75cd1fSAdrian Lang/**
6245b75cd1fSAdrian Lang * Format an id for output to a user
6255b75cd1fSAdrian Lang *
6265b75cd1fSAdrian Lang * Namespaces are denoted by a trailing “:*”. The root namespace is
6275b75cd1fSAdrian Lang * “*”. Output is escaped.
6285b75cd1fSAdrian Lang *
6295b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
63084657ea2SGerrit Uitslag *
63184657ea2SGerrit Uitslag * @param string $id page id
63284657ea2SGerrit Uitslag * @return string
6335b75cd1fSAdrian Lang */
6345b75cd1fSAdrian Langfunction prettyprint_id($id) {
6355b75cd1fSAdrian Lang    if (!$id || $id === ':') {
6365b75cd1fSAdrian Lang        return '*';
6375b75cd1fSAdrian Lang    }
6385b75cd1fSAdrian Lang    if ((substr($id, -1, 1) === ':')) {
6395b75cd1fSAdrian Lang        $id .= '*';
6405b75cd1fSAdrian Lang    }
6415b75cd1fSAdrian Lang    return hsc($id);
6425b75cd1fSAdrian Lang}
643f03fd957SAndreas Gohr
644f03fd957SAndreas Gohr/**
645f03fd957SAndreas Gohr * Encode a UTF-8 filename to use on any filesystem
646f03fd957SAndreas Gohr *
647f03fd957SAndreas Gohr * Uses the 'fnencode' option to determine encoding
648f03fd957SAndreas Gohr *
649f03fd957SAndreas Gohr * When the second parameter is true the string will
650f03fd957SAndreas Gohr * be encoded only if non ASCII characters are detected -
651f03fd957SAndreas Gohr * This makes it safe to run it multiple times on the
652f03fd957SAndreas Gohr * same string (default is true)
653f03fd957SAndreas Gohr *
654f03fd957SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
655f03fd957SAndreas Gohr * @see    urlencode
65684657ea2SGerrit Uitslag *
65784657ea2SGerrit Uitslag * @param string $file file name
65884657ea2SGerrit Uitslag * @param bool   $safe if true, only encoded when non ASCII characters detected
65984657ea2SGerrit Uitslag * @return string
660f03fd957SAndreas Gohr */
661f03fd957SAndreas Gohrfunction utf8_encodeFN($file,$safe=true){
662f03fd957SAndreas Gohr    global $conf;
663f03fd957SAndreas Gohr    if($conf['fnencode'] == 'utf-8') return $file;
664f03fd957SAndreas Gohr
665f03fd957SAndreas Gohr    if($safe && preg_match('#^[a-zA-Z0-9/_\-\.%]+$#',$file)){
666f03fd957SAndreas Gohr        return $file;
667f03fd957SAndreas Gohr    }
668f03fd957SAndreas Gohr
669f03fd957SAndreas Gohr    if($conf['fnencode'] == 'safe'){
670f03fd957SAndreas Gohr        return SafeFN::encode($file);
671f03fd957SAndreas Gohr    }
672f03fd957SAndreas Gohr
673f03fd957SAndreas Gohr    $file = urlencode($file);
674f03fd957SAndreas Gohr    $file = str_replace('%2F','/',$file);
675f03fd957SAndreas Gohr    return $file;
676f03fd957SAndreas Gohr}
677f03fd957SAndreas Gohr
678f03fd957SAndreas Gohr/**
679f03fd957SAndreas Gohr * Decode a filename back to UTF-8
680f03fd957SAndreas Gohr *
681f03fd957SAndreas Gohr * Uses the 'fnencode' option to determine encoding
682f03fd957SAndreas Gohr *
683f03fd957SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
684f03fd957SAndreas Gohr * @see    urldecode
68584657ea2SGerrit Uitslag *
68684657ea2SGerrit Uitslag * @param string $file file name
68784657ea2SGerrit Uitslag * @return string
688f03fd957SAndreas Gohr */
689f03fd957SAndreas Gohrfunction utf8_decodeFN($file){
690f03fd957SAndreas Gohr    global $conf;
691f03fd957SAndreas Gohr    if($conf['fnencode'] == 'utf-8') return $file;
692f03fd957SAndreas Gohr
693f03fd957SAndreas Gohr    if($conf['fnencode'] == 'safe'){
694f03fd957SAndreas Gohr        return SafeFN::decode($file);
695f03fd957SAndreas Gohr    }
696f03fd957SAndreas Gohr
697f03fd957SAndreas Gohr    return urldecode($file);
698f03fd957SAndreas Gohr}
699f03fd957SAndreas Gohr
700e66d3e6dSAndreas Gohr/**
701e66d3e6dSAndreas Gohr * Find a page in the current namespace (determined from $ID) or any
702cc529468SMichael Hamann * higher namespace that can be accessed by the current user,
703cc529468SMichael Hamann * this condition can be overriden by an optional parameter.
704e66d3e6dSAndreas Gohr *
705e66d3e6dSAndreas Gohr * Used for sidebars, but can be used other stuff as well
706e66d3e6dSAndreas Gohr *
707e66d3e6dSAndreas Gohr * @todo   add event hook
70842ea7f44SGerrit Uitslag *
709e66d3e6dSAndreas Gohr * @param  string $page the pagename you're looking for
7107c3e4a67SAndreas Gohr * @param bool $useacl only return pages readable by the current user, false to ignore ACLs
711cc529468SMichael Hamann * @return false|string the full page id of the found page, false if any
712e66d3e6dSAndreas Gohr */
7137c3e4a67SAndreas Gohrfunction page_findnearest($page, $useacl = true){
71406a70133SPhy    if ((string) $page === '') return false;
715e66d3e6dSAndreas Gohr    global $ID;
716e66d3e6dSAndreas Gohr
717e66d3e6dSAndreas Gohr    $ns = $ID;
718e66d3e6dSAndreas Gohr    do {
719e66d3e6dSAndreas Gohr        $ns = getNS($ns);
720cc529468SMichael Hamann        $pageid = cleanID("$ns:$page");
7217c3e4a67SAndreas Gohr        if(page_exists($pageid) && (!$useacl || auth_quickaclcheck($pageid) >= AUTH_READ)){
722e66d3e6dSAndreas Gohr            return $pageid;
723e66d3e6dSAndreas Gohr        }
72406a70133SPhy    } while($ns !== false);
725e66d3e6dSAndreas Gohr
726e66d3e6dSAndreas Gohr    return false;
727e66d3e6dSAndreas Gohr}
728