xref: /dokuwiki/inc/pageutils.php (revision bfcf8009182fabb89cbae83d9b5117faf0035ede)
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;
120c3a5702SAndreas Gohr
136c7843b5Sandi/**
146de3759aSAndreas Gohr * Fetch the an ID from request
156c7843b5Sandi *
166c7843b5Sandi * Uses either standard $_REQUEST variable or extracts it from
176c7843b5Sandi * the full request URI when userewrite is set to 2
186c7843b5Sandi *
1942905504SAndreas Gohr * For $param='id' $conf['start'] is returned if no id was found.
2042905504SAndreas Gohr * If the second parameter is true (default) the ID is cleaned.
216c7843b5Sandi *
226c7843b5Sandi * @author Andreas Gohr <andi@splitbrain.org>
2384657ea2SGerrit Uitslag *
2484657ea2SGerrit Uitslag * @param string $param  the $_REQUEST variable name, default 'id'
2584657ea2SGerrit Uitslag * @param bool   $clean  if true, ID is cleaned
2642ea7f44SGerrit Uitslag * @return string
276c7843b5Sandi */
2842905504SAndreas Gohrfunction getID($param='id',$clean=true){
29585bf44eSChristopher Smith    /** @var Input $INPUT */
307d01a0eaSTom N Harris    global $INPUT;
316c7843b5Sandi    global $conf;
324e90caaaSMichael Hamann    global $ACT;
336c7843b5Sandi
347d01a0eaSTom N Harris    $id = $INPUT->str($param);
3548665d38SAndreas Gohr
366c7843b5Sandi    //construct page id from request URI
376c7843b5Sandi    if(empty($id) && $conf['userewrite'] == 2){
38585bf44eSChristopher Smith        $request = $INPUT->server->str('REQUEST_URI');
3906368e4dSMichael Hamann        $script = '';
4006368e4dSMichael Hamann
416c7843b5Sandi        //get the script URL
426c7843b5Sandi        if($conf['basedir']){
4381124000Sjan            $relpath = '';
4481124000Sjan            if($param != 'id') {
4581124000Sjan                $relpath = 'lib/exe/';
4681124000Sjan            }
476ce3e5f8SAndreas Gohr            $script = $conf['basedir'] . $relpath .
486ce3e5f8SAndreas Gohr                \dokuwiki\Utf8\PhpString::basename($INPUT->server->str('SCRIPT_FILENAME'));
497d71d4b7SAndreas Gohr
50585bf44eSChristopher Smith        }elseif($INPUT->server->str('PATH_INFO')){
51585bf44eSChristopher Smith            $request = $INPUT->server->str('PATH_INFO');
52585bf44eSChristopher Smith        }elseif($INPUT->server->str('SCRIPT_NAME')){
53585bf44eSChristopher Smith            $script = $INPUT->server->str('SCRIPT_NAME');
54585bf44eSChristopher Smith        }elseif($INPUT->server->str('DOCUMENT_ROOT') && $INPUT->server->str('SCRIPT_FILENAME')){
55585bf44eSChristopher Smith            $script = preg_replace ('/^'.preg_quote($INPUT->server->str('DOCUMENT_ROOT'),'/').'/','',
56585bf44eSChristopher Smith                    $INPUT->server->str('SCRIPT_FILENAME'));
576c7843b5Sandi            $script = '/'.$script;
586c7843b5Sandi        }
596c7843b5Sandi
6052339126Sandi        //clean script and request (fixes a windows problem)
6152339126Sandi        $script  = preg_replace('/\/\/+/','/',$script);
627d71d4b7SAndreas Gohr        $request = preg_replace('/\/\/+/','/',$request);
6352339126Sandi
646c7843b5Sandi        //remove script URL and Querystring to gain the id
6552339126Sandi        if(preg_match('/^'.preg_quote($script,'/').'(.*)/',$request, $match)){
666c7843b5Sandi            $id = preg_replace ('/\?.*/','',$match[1]);
676c7843b5Sandi        }
686de3759aSAndreas Gohr        $id = urldecode($id);
6942905504SAndreas Gohr        //strip leading slashes
7042905504SAndreas Gohr        $id = preg_replace('!^/+!','',$id);
716c7843b5Sandi    }
72671a58a6SGuy Brand
73671a58a6SGuy Brand    // Namespace autolinking from URL
74b6084253SAndreas Gohr    if(substr($id,-1) == ':' || ($conf['useslash'] && substr($id,-1) == '/')){
75103c256aSChris Smith        if(page_exists($id.$conf['start'])){
76671a58a6SGuy Brand            // start page inside namespace
77671a58a6SGuy Brand            $id = $id.$conf['start'];
78103c256aSChris Smith        }elseif(page_exists($id.noNS(cleanID($id)))){
79671a58a6SGuy Brand            // page named like the NS inside the NS
80671a58a6SGuy Brand            $id = $id.noNS(cleanID($id));
81103c256aSChris Smith        }elseif(page_exists($id)){
82671a58a6SGuy Brand            // page like namespace exists
837a42ac9eSBen Coburn            $id = substr($id,0,-1);
84671a58a6SGuy Brand        }else{
85671a58a6SGuy Brand            // fall back to default
86671a58a6SGuy Brand            $id = $id.$conf['start'];
87671a58a6SGuy Brand        }
889dc53973SMichael Grosse        if (isset($ACT) && $ACT === 'show') {
899dc53973SMichael Grosse            $urlParameters = $_GET;
90e380abb2SMichael Grosse            if (isset($urlParameters['id'])) {
91e380abb2SMichael Grosse                unset($urlParameters['id']);
92e380abb2SMichael Grosse            }
93e9fede20SPhy            send_redirect(wl($id, $urlParameters, true, '&'));
949dc53973SMichael Grosse        }
95671a58a6SGuy Brand    }
9642905504SAndreas Gohr    if($clean) $id = cleanID($id);
9740b5fb5bSPhy    if($id === '' && $param=='id') $id = $conf['start'];
986c7843b5Sandi
996c7843b5Sandi    return $id;
1006c7843b5Sandi}
101b625487dSandi
102b625487dSandi/**
103b625487dSandi * Remove unwanted chars from ID
104b625487dSandi *
105b625487dSandi * Cleans a given ID to only use allowed characters. Accented characters are
106b625487dSandi * converted to unaccented ones
107b625487dSandi *
108b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
10942ea7f44SGerrit Uitslag *
1106e0cc83aSchris * @param  string  $raw_id    The pageid to clean
1118a831f2bSAndreas Gohr * @param  boolean $ascii     Force ASCII
112dbf714f7SGerrit Uitslag * @return string cleaned id
113b625487dSandi */
114c8bbb094SAnika Henkefunction cleanID($raw_id,$ascii=false){
115b625487dSandi    global $conf;
1164b5db43bSjoe.lapp    static $sepcharpat = null;
1174b5db43bSjoe.lapp
118dc2c0e04Schris    global $cache_cleanid;
119dc2c0e04Schris    $cache = & $cache_cleanid;
1206e0cc83aSchris
1216e0cc83aSchris    // check if it's already in the memory cache
12230f3bd15SMichael Grosse    if (!$ascii && isset($cache[(string)$raw_id])) {
1233a50618cSgweissbach        return $cache[(string)$raw_id];
1246e0cc83aSchris    }
1256e0cc83aSchris
1264b5db43bSjoe.lapp    $sepchar = $conf['sepchar'];
1274b5db43bSjoe.lapp    if($sepcharpat == null) // build string only once to save clock cycles
1284b5db43bSjoe.lapp        $sepcharpat = '#\\'.$sepchar.'+#';
1294b5db43bSjoe.lapp
1303a50618cSgweissbach    $id = trim((string)$raw_id);
1318cbc5ee8SAndreas Gohr    $id = \dokuwiki\Utf8\PhpString::strtolower($id);
132b625487dSandi
133b625487dSandi    //alternative namespace seperator
134b625487dSandi    if($conf['useslash']){
1353755fc25STom N Harris        $id = strtr($id,';/','::');
136b625487dSandi    }else{
1373755fc25STom N Harris        $id = strtr($id,';/',':'.$sepchar);
138b625487dSandi    }
139b625487dSandi
1408cbc5ee8SAndreas Gohr    if($conf['deaccent'] == 2 || $ascii) $id = \dokuwiki\Utf8\Clean::romanize($id);
1418cbc5ee8SAndreas Gohr    if($conf['deaccent'] || $ascii) $id = \dokuwiki\Utf8\Clean::deaccent($id,-1);
142b625487dSandi
143b625487dSandi    //remove specials
1448cbc5ee8SAndreas Gohr    $id = \dokuwiki\Utf8\Clean::stripspecials($id,$sepchar,'\*');
145b625487dSandi
1468cbc5ee8SAndreas Gohr    if($ascii) $id = \dokuwiki\Utf8\Clean::strip($id);
1478a831f2bSAndreas Gohr
148b625487dSandi    //clean up
1494b5db43bSjoe.lapp    $id = preg_replace($sepcharpat,$sepchar,$id);
150b625487dSandi    $id = preg_replace('#:+#',':',$id);
1513543c6deSAndreas Gohr    $id = trim($id,':._-');
152b625487dSandi    $id = preg_replace('#:[:\._\-]+#',':',$id);
153b680ea06SAndreas Gohr    $id = preg_replace('#[:\._\-]+:#',':',$id);
154b625487dSandi
15530f3bd15SMichael Grosse    if (!$ascii) $cache[(string)$raw_id] = $id;
156b625487dSandi    return($id);
157b625487dSandi}
158b625487dSandi
159b625487dSandi/**
160b625487dSandi * Return namespacepart of a wiki ID
161b625487dSandi *
162b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
16315851b98SGerrit Uitslag *
16415851b98SGerrit Uitslag * @param string $id
16542ea7f44SGerrit Uitslag * @return string|false the namespace part or false if the given ID has no namespace (root)
166b625487dSandi */
167b625487dSandifunction getNS($id){
1683a50618cSgweissbach    $pos = strrpos((string)$id,':');
169c4e0e4a1SAndreas Gohr    if($pos!==false){
1703a50618cSgweissbach        return substr((string)$id,0,$pos);
171b625487dSandi    }
172ef11fcfcSAndreas Gohr    return false;
173b625487dSandi}
174b625487dSandi
175b625487dSandi/**
176b625487dSandi * Returns the ID without the namespace
177b625487dSandi *
178b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
17915851b98SGerrit Uitslag *
18015851b98SGerrit Uitslag * @param string $id
18115851b98SGerrit Uitslag * @return string
182b625487dSandi */
183b625487dSandifunction noNS($id) {
1842844584fSBen Coburn    $pos = strrpos($id, ':');
1852844584fSBen Coburn    if ($pos!==false) {
1862844584fSBen Coburn        return substr($id, $pos+1);
1872844584fSBen Coburn    } else {
1882844584fSBen Coburn        return $id;
1892844584fSBen Coburn    }
1901a84a0f3SAnika Henke}
1911a84a0f3SAnika Henke
1921a84a0f3SAnika Henke/**
1931a84a0f3SAnika Henke * Returns the current namespace
1941a84a0f3SAnika Henke *
1951a84a0f3SAnika Henke * @author Nathan Fritz <fritzn@crown.edu>
19684657ea2SGerrit Uitslag *
19784657ea2SGerrit Uitslag * @param string $id
19884657ea2SGerrit Uitslag * @return string
1991a84a0f3SAnika Henke */
2001a84a0f3SAnika Henkefunction curNS($id) {
2011a84a0f3SAnika Henke    return noNS(getNS($id));
2021a84a0f3SAnika Henke}
2031a84a0f3SAnika Henke
2041a84a0f3SAnika Henke/**
2051a84a0f3SAnika Henke * Returns the ID without the namespace or current namespace for 'start' pages
2061a84a0f3SAnika Henke *
2071a84a0f3SAnika Henke * @author Nathan Fritz <fritzn@crown.edu>
20884657ea2SGerrit Uitslag *
20984657ea2SGerrit Uitslag * @param string $id
21084657ea2SGerrit Uitslag * @return string
2111a84a0f3SAnika Henke */
2121a84a0f3SAnika Henkefunction noNSorNS($id) {
2131a84a0f3SAnika Henke    global $conf;
2141a84a0f3SAnika Henke
2151a84a0f3SAnika Henke    $p = noNS($id);
216c077d4dcSAndreas Gohr    if ($p === $conf['start'] || $p === false || $p === '') {
2171a84a0f3SAnika Henke        $p = curNS($id);
218c077d4dcSAndreas Gohr        if ($p === false || $p === '') {
2199708106bSAdrian Lang            return $conf['start'];
2201a84a0f3SAnika Henke        }
2211a84a0f3SAnika Henke    }
2221a84a0f3SAnika Henke    return $p;
223b625487dSandi}
2244ceab83fSAndreas Gohr
2254ceab83fSAndreas Gohr/**
2264ceab83fSAndreas Gohr * Creates a XHTML valid linkid from a given headline title
2274ceab83fSAndreas Gohr *
2284ceab83fSAndreas Gohr * @param string  $title   The headline title
229c857afe0SMichael Hamann * @param array|bool   $check   Existing IDs (title => number)
230c857afe0SMichael Hamann * @return string the title
23184657ea2SGerrit Uitslag *
2324ceab83fSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
2334ceab83fSAndreas Gohr */
234443d207bSAndreas Gohrfunction sectionID($title,&$check) {
235de9114eaSAnika Henke    $title = str_replace(array(':','.'),'',cleanID($title));
236de9114eaSAnika Henke    $new = ltrim($title,'0123456789_-');
2374ceab83fSAndreas Gohr    if(empty($new)){
2384ceab83fSAndreas Gohr        $title = 'section'.preg_replace('/[^0-9]+/','',$title); //keep numbers from headline
2394ceab83fSAndreas Gohr    }else{
2404ceab83fSAndreas Gohr        $title = $new;
2414ceab83fSAndreas Gohr    }
2424ceab83fSAndreas Gohr
243443d207bSAndreas Gohr    if(is_array($check)){
2444ceab83fSAndreas Gohr        // make sure tiles are unique
24501e3159cSChris Tapp        if (!array_key_exists ($title,$check)) {
24601e3159cSChris Tapp            $check[$title] = 0;
24701e3159cSChris Tapp        } else {
24801e3159cSChris Tapp            $title .= ++ $check[$title];
2494ceab83fSAndreas Gohr        }
2504ceab83fSAndreas Gohr    }
2514ceab83fSAndreas Gohr
2524ceab83fSAndreas Gohr    return $title;
2534ceab83fSAndreas Gohr}
2544ceab83fSAndreas Gohr
255b625487dSandi/**
256103c256aSChris Smith * Wiki page existence check
257103c256aSChris Smith *
258103c256aSChris Smith * parameters as for wikiFN
259103c256aSChris Smith *
260103c256aSChris Smith * @author Chris Smith <chris@jalakai.co.uk>
26184657ea2SGerrit Uitslag *
26284657ea2SGerrit Uitslag * @param string $id page id
26384657ea2SGerrit Uitslag * @param string|int $rev empty or revision timestamp
26484657ea2SGerrit Uitslag * @param bool $clean flag indicating that $id should be cleaned (see wikiFN as well)
2657de86af9SGerrit Uitslag * @param bool $date_at
26684657ea2SGerrit Uitslag * @return bool exists?
267103c256aSChris Smith */
2681d053a56Slispsfunction page_exists($id,$rev='',$clean=true, $date_at=false) {
26990bee600Slisps    if($rev !== '' && $date_at) {
2701d053a56Slisps        $pagelog = new PageChangeLog($id);
27190bee600Slisps        $pagelog_rev = $pagelog->getLastRevisionAt($rev);
27290bee600Slisps        if($pagelog_rev !== false)
27390bee600Slisps            $rev = $pagelog_rev;
27490bee600Slisps    }
27579e79377SAndreas Gohr    return file_exists(wikiFN($id,$rev,$clean));
276103c256aSChris Smith}
277103c256aSChris Smith
278103c256aSChris Smith/**
279103c256aSChris Smith * returns the full path to the datafile specified by ID and optional revision
280b625487dSandi *
281b625487dSandi * The filename is URL encoded to protect Unicode chars
282b625487dSandi *
283103c256aSChris Smith * @param  $raw_id  string   id of wikipage
284e0c26282SGerrit Uitslag * @param  $rev     int|string   page revision, empty string for current
285103c256aSChris Smith * @param  $clean   bool     flag indicating that $raw_id should be cleaned.  Only set to false
286103c256aSChris Smith *                           when $id is guaranteed to have been cleaned already.
287dbf714f7SGerrit Uitslag * @return string full path
288103c256aSChris Smith *
289b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
290b625487dSandi */
2916e0cc83aSchrisfunction wikiFN($raw_id,$rev='',$clean=true){
292b625487dSandi    global $conf;
2936e0cc83aSchris
294dc2c0e04Schris    global $cache_wikifn;
295dc2c0e04Schris    $cache = & $cache_wikifn;
296dc2c0e04Schris
2976e0cc83aSchris    $id = $raw_id;
2986e0cc83aSchris
2990d8ea614Schris    if ($clean) $id = cleanID($id);
300b625487dSandi    $id = str_replace(':','/',$id);
301b018ecbeSMichael Grosse
302b018ecbeSMichael Grosse    if (isset($cache[$id]) && isset($cache[$id][$rev])) {
303b018ecbeSMichael Grosse        return $cache[$id][$rev];
304b018ecbeSMichael Grosse    }
305b018ecbeSMichael Grosse
306b625487dSandi    if(empty($rev)){
307b625487dSandi        $fn = $conf['datadir'].'/'.utf8_encodeFN($id).'.txt';
308b625487dSandi    }else{
309b625487dSandi        $fn = $conf['olddir'].'/'.utf8_encodeFN($id).'.'.$rev.'.txt';
310ff3ed99fSmarcel        if($conf['compression']){
311ff3ed99fSmarcel            //test for extensions here, we want to read both compressions
31279e79377SAndreas Gohr            if (file_exists($fn . '.gz')){
313b625487dSandi                $fn .= '.gz';
31479e79377SAndreas Gohr            }else if(file_exists($fn . '.bz2')){
315ff3ed99fSmarcel                $fn .= '.bz2';
316ff3ed99fSmarcel            }else{
317ff3ed99fSmarcel                //file doesnt exist yet, so we take the configured extension
318ff3ed99fSmarcel                $fn .= '.' . $conf['compression'];
319ff3ed99fSmarcel            }
320b625487dSandi        }
321b625487dSandi    }
3226e0cc83aSchris
323b018ecbeSMichael Grosse    if (!isset($cache[$id])) { $cache[$id] = array(); }
324b018ecbeSMichael Grosse    $cache[$id][$rev] = $fn;
325b625487dSandi    return $fn;
326b625487dSandi}
327b625487dSandi
328b625487dSandi/**
329c9b4bd1eSBen Coburn * Returns the full path to the file for locking the page while editing.
330c9b4bd1eSBen Coburn *
331c9b4bd1eSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
33284657ea2SGerrit Uitslag *
33384657ea2SGerrit Uitslag * @param string $id page id
33484657ea2SGerrit Uitslag * @return string full path
335c9b4bd1eSBen Coburn */
336c9b4bd1eSBen Coburnfunction wikiLockFN($id) {
337c9b4bd1eSBen Coburn    global $conf;
338662ff478SAndreas Gohr    return $conf['lockdir'].'/'.md5(cleanID($id)).'.lock';
339c9b4bd1eSBen Coburn}
340c9b4bd1eSBen Coburn
341c9b4bd1eSBen Coburn
342c9b4bd1eSBen Coburn/**
3431380fc45SAndreas Gohr * returns the full path to the meta file specified by ID and extension
344b158d625SSteven Danz *
345b158d625SSteven Danz * @author Steven Danz <steven-danz@kc.rr.com>
34684657ea2SGerrit Uitslag *
34784657ea2SGerrit Uitslag * @param string $id   page id
34884657ea2SGerrit Uitslag * @param string $ext  file extension
34984657ea2SGerrit Uitslag * @return string full path
350b158d625SSteven Danz */
3511380fc45SAndreas Gohrfunction metaFN($id,$ext){
352b158d625SSteven Danz    global $conf;
353b158d625SSteven Danz    $id = cleanID($id);
354b158d625SSteven Danz    $id = str_replace(':','/',$id);
3551380fc45SAndreas Gohr    $fn = $conf['metadir'].'/'.utf8_encodeFN($id).$ext;
356b158d625SSteven Danz    return $fn;
357b158d625SSteven Danz}
358b158d625SSteven Danz
359b158d625SSteven Danz/**
360e4f389efSKate Arzamastseva * returns the full path to the media's meta file specified by ID and extension
361e4f389efSKate Arzamastseva *
362cbe26ad6SKate Arzamastseva * @author Kate Arzamastseva <pshns@ukr.net>
36384657ea2SGerrit Uitslag *
36484657ea2SGerrit Uitslag * @param string $id   media id
36584657ea2SGerrit Uitslag * @param string $ext  extension of media
36684657ea2SGerrit Uitslag * @return string
367e4f389efSKate Arzamastseva */
368e4f389efSKate Arzamastsevafunction mediaMetaFN($id,$ext){
369e4f389efSKate Arzamastseva    global $conf;
370e4f389efSKate Arzamastseva    $id = cleanID($id);
371e4f389efSKate Arzamastseva    $id = str_replace(':','/',$id);
372e4f389efSKate Arzamastseva    $fn = $conf['mediametadir'].'/'.utf8_encodeFN($id).$ext;
373e4f389efSKate Arzamastseva    return $fn;
374e4f389efSKate Arzamastseva}
375e4f389efSKate Arzamastseva
376e4f389efSKate Arzamastseva/**
377e1f3d9e1SEsther Brunner * returns an array of full paths to all metafiles of a given ID
378e1f3d9e1SEsther Brunner *
379e1f3d9e1SEsther Brunner * @author Esther Brunner <esther@kaffeehaus.ch>
380ba0267b3SMichael Hamann * @author Michael Hamann <michael@content-space.de>
38184657ea2SGerrit Uitslag *
38284657ea2SGerrit Uitslag * @param string $id page id
38384657ea2SGerrit Uitslag * @return array
384e1f3d9e1SEsther Brunner */
385e1f3d9e1SEsther Brunnerfunction metaFiles($id){
386ba0267b3SMichael Hamann    $basename = metaFN($id, '');
387ba0267b3SMichael Hamann    $files    = glob($basename.'.*', GLOB_MARK);
388ba0267b3SMichael Hamann    // filter files like foo.bar.meta when $id == 'foo'
389ba0267b3SMichael Hamann    return    $files ? preg_grep('/^'.preg_quote($basename, '/').'\.[^.\/]*$/u', $files) : array();
390e1f3d9e1SEsther Brunner}
391e1f3d9e1SEsther Brunner
392e1f3d9e1SEsther Brunner/**
393b625487dSandi * returns the full path to the mediafile specified by ID
394b625487dSandi *
395b625487dSandi * The filename is URL encoded to protect Unicode chars
396b625487dSandi *
397b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
398cbe26ad6SKate Arzamastseva * @author Kate Arzamastseva <pshns@ukr.net>
39984657ea2SGerrit Uitslag *
40084657ea2SGerrit Uitslag * @param string     $id  media id
40184657ea2SGerrit Uitslag * @param string|int $rev empty string or revision timestamp
402f50a239bSTakamura * @param bool $clean
403f50a239bSTakamura *
40484657ea2SGerrit Uitslag * @return string full path
405b625487dSandi */
406d0e997c6SMichael Großefunction mediaFN($id, $rev='', $clean=true){
407b625487dSandi    global $conf;
408d0e997c6SMichael Große    if ($clean) $id = cleanID($id);
409b625487dSandi    $id = str_replace(':','/',$id);
410e4f389efSKate Arzamastseva    if(empty($rev)){
411b625487dSandi        $fn = $conf['mediadir'].'/'.utf8_encodeFN($id);
412e4f389efSKate Arzamastseva    }else{
413cbe26ad6SKate Arzamastseva        $ext = mimetype($id);
4148e69fd30SKate Arzamastseva        $name = substr($id,0, -1*strlen($ext[0])-1);
41561f1aad8SKate Arzamastseva        $fn = $conf['mediaolddir'].'/'.utf8_encodeFN($name .'.'.( (int) $rev ).'.'.$ext[0]);
416e4f389efSKate Arzamastseva    }
417b625487dSandi    return $fn;
418b625487dSandi}
419b625487dSandi
420b625487dSandi/**
4212adaf2b8SAndreas Gohr * Returns the full filepath to a localized file if local
422b625487dSandi * version isn't found the english one is returned
423b625487dSandi *
4242adaf2b8SAndreas Gohr * @param  string $id  The id of the local file
4252adaf2b8SAndreas Gohr * @param  string $ext The file extension (usually txt)
426dbf714f7SGerrit Uitslag * @return string full filepath to localized file
42784657ea2SGerrit Uitslag *
428b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
429b625487dSandi */
4302adaf2b8SAndreas Gohrfunction localeFN($id,$ext='txt'){
431b625487dSandi    global $conf;
4328819fbf5ShArpanet    $file = DOKU_CONF.'lang/'.$conf['lang'].'/'.$id.'.'.$ext;
43379e79377SAndreas Gohr    if(!file_exists($file)){
4342adaf2b8SAndreas Gohr        $file = DOKU_INC.'inc/lang/'.$conf['lang'].'/'.$id.'.'.$ext;
43579e79377SAndreas Gohr        if(!file_exists($file)){
436b625487dSandi            //fall back to english
4372adaf2b8SAndreas Gohr            $file = DOKU_INC.'inc/lang/en/'.$id.'.'.$ext;
438b625487dSandi        }
439e6cecb08SMichael Hamann    }
440b625487dSandi    return $file;
441b625487dSandi}
442b625487dSandi
443b625487dSandi/**
444c4e0e4a1SAndreas Gohr * Resolve relative paths in IDs
445c4e0e4a1SAndreas Gohr *
446c4e0e4a1SAndreas Gohr * Do not call directly use resolve_mediaid or resolve_pageid
447c4e0e4a1SAndreas Gohr * instead
448c4e0e4a1SAndreas Gohr *
449c4e0e4a1SAndreas Gohr * Partyly based on a cleanPath function found at
45059752844SAnders Sandblad * http://php.net/manual/en/function.realpath.php#57016
451c4e0e4a1SAndreas Gohr *
452*bfcf8009SAndreas Gohr * @deprecated 2020-09-30
45384657ea2SGerrit Uitslag * @param string $ns     namespace which is context of id
45484657ea2SGerrit Uitslag * @param string $id     relative id
45584657ea2SGerrit Uitslag * @param bool   $clean  flag indicating that id should be cleaned
45642ea7f44SGerrit Uitslag * @return string
457c4e0e4a1SAndreas Gohr */
458a6ef4796SAndreas Gohrfunction resolve_id($ns,$id,$clean=true){
459c662a49aSAndreas Gohr    global $conf;
460*bfcf8009SAndreas Gohr    dbg_deprecated(\dokuwiki\Utils\Resolver::class.' and its children');
461c662a49aSAndreas Gohr
462c662a49aSAndreas Gohr    // some pre cleaning for useslash:
463c662a49aSAndreas Gohr    if($conf['useslash']) $id = str_replace('/',':',$id);
464c662a49aSAndreas Gohr
465c4e0e4a1SAndreas Gohr    // if the id starts with a dot we need to handle the
466c4e0e4a1SAndreas Gohr    // relative stuff
4672401f18dSSyntaxseed    if($id && $id[0] == '.'){
468c4e0e4a1SAndreas Gohr        // normalize initial dots without a colon
4694986a584SPhy        $id = preg_replace('/^((\.+:)*)(\.+)(?=[^:\.])/','\1\3:',$id);
470c4e0e4a1SAndreas Gohr        // prepend the current namespace
471c4e0e4a1SAndreas Gohr        $id = $ns.':'.$id;
472c4e0e4a1SAndreas Gohr
473c4e0e4a1SAndreas Gohr        // cleanup relatives
474c4e0e4a1SAndreas Gohr        $result = array();
475c4e0e4a1SAndreas Gohr        $pathA  = explode(':', $id);
476c4e0e4a1SAndreas Gohr        if (!$pathA[0]) $result[] = '';
477c4e0e4a1SAndreas Gohr        foreach ($pathA AS $key => $dir) {
478c4e0e4a1SAndreas Gohr            if ($dir == '..') {
479c4e0e4a1SAndreas Gohr                if (end($result) == '..') {
480c4e0e4a1SAndreas Gohr                    $result[] = '..';
481c4e0e4a1SAndreas Gohr                } elseif (!array_pop($result)) {
482c4e0e4a1SAndreas Gohr                    $result[] = '..';
483c4e0e4a1SAndreas Gohr                }
484c4e0e4a1SAndreas Gohr            } elseif ($dir && $dir != '.') {
485c4e0e4a1SAndreas Gohr                $result[] = $dir;
486c4e0e4a1SAndreas Gohr            }
487c4e0e4a1SAndreas Gohr        }
488c4e0e4a1SAndreas Gohr        if (!end($pathA)) $result[] = '';
489c4e0e4a1SAndreas Gohr        $id = implode(':', $result);
490c4e0e4a1SAndreas Gohr    }elseif($ns !== false && strpos($id,':') === false){
491c4e0e4a1SAndreas Gohr        //if link contains no namespace. add current namespace (if any)
492c4e0e4a1SAndreas Gohr        $id = $ns.':'.$id;
493c4e0e4a1SAndreas Gohr    }
494c4e0e4a1SAndreas Gohr
495a6ef4796SAndreas Gohr    if($clean) $id = cleanID($id);
496a6ef4796SAndreas Gohr    return $id;
497c4e0e4a1SAndreas Gohr}
498c4e0e4a1SAndreas Gohr
499c4e0e4a1SAndreas Gohr/**
500b625487dSandi * Returns a full media id
501b625487dSandi *
502*bfcf8009SAndreas Gohr * @deprecated 2020-09-30
50384657ea2SGerrit Uitslag * @param string $ns namespace which is context of id
50484657ea2SGerrit Uitslag * @param string &$page (reference) relative media id, updated to resolved id
50584657ea2SGerrit Uitslag * @param bool &$exists (reference) updated with existance of media
5067de86af9SGerrit Uitslag * @param int|string $rev
5077de86af9SGerrit Uitslag * @param bool $date_at
508b625487dSandi */
50990bee600Slispsfunction resolve_mediaid($ns,&$page,&$exists,$rev='',$date_at=false){
510*bfcf8009SAndreas Gohr    dbg_deprecated(\dokuwiki\Utils\MediaResolver::class);
511*bfcf8009SAndreas Gohr    $resolver = new \dokuwiki\Utils\MediaResolver("$ns:deprecated");
512*bfcf8009SAndreas Gohr    $page = $resolver->resolveId($page, $rev, $date_at);
513*bfcf8009SAndreas Gohr    $exists = page_exists($page, $rev, false, $date_at);
514b625487dSandi}
515b625487dSandi
516b625487dSandi/**
517b625487dSandi * Returns a full page id
518b625487dSandi *
519*bfcf8009SAndreas Gohr * @deprecated 2020-09-30
52084657ea2SGerrit Uitslag * @param string $ns namespace which is context of id
52184657ea2SGerrit Uitslag * @param string &$page (reference) relative page id, updated to resolved id
52284657ea2SGerrit Uitslag * @param bool &$exists (reference) updated with existance of media
5237de86af9SGerrit Uitslag * @param string $rev
5247de86af9SGerrit Uitslag * @param bool $date_at
525b625487dSandi */
526*bfcf8009SAndreas Gohrfunction resolve_pageid($ns,&$page,&$exists,$rev='',$date_at=false )
527*bfcf8009SAndreas Gohr{
528*bfcf8009SAndreas Gohr    dbg_deprecated(\dokuwiki\Utils\PageResolver::class);
529*bfcf8009SAndreas Gohr    $resolver = new \dokuwiki\Utils\PageResolver("$ns:deprecated");
530*bfcf8009SAndreas Gohr    $page = $resolver->resolveId($page, $rev, $date_at);
531*bfcf8009SAndreas Gohr    $exists = page_exists($page, $rev, false, $date_at);
532b625487dSandi}
533b625487dSandi
53498407a7aSandi/**
53598407a7aSandi * Returns the name of a cachefile from given data
53698407a7aSandi *
53798407a7aSandi * The needed directory is created by this function!
53898407a7aSandi *
53998407a7aSandi * @author Andreas Gohr <andi@splitbrain.org>
54098407a7aSandi *
54198407a7aSandi * @param string $data  This data is used to create a unique md5 name
54298407a7aSandi * @param string $ext   This is appended to the filename if given
54398407a7aSandi * @return string       The filename of the cachefile
54498407a7aSandi */
54598407a7aSandifunction getCacheName($data,$ext=''){
54698407a7aSandi    global $conf;
54798407a7aSandi    $md5  = md5($data);
5482401f18dSSyntaxseed    $file = $conf['cachedir'].'/'.$md5[0].'/'.$md5.$ext;
54998407a7aSandi    io_makeFileDir($file);
55098407a7aSandi    return $file;
55198407a7aSandi}
55298407a7aSandi
5530dc92c6fSAndreas Gohr/**
5540dc92c6fSAndreas Gohr * Checks a pageid against $conf['hidepages']
5550dc92c6fSAndreas Gohr *
5560dc92c6fSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
55784657ea2SGerrit Uitslag *
55884657ea2SGerrit Uitslag * @param string $id page id
55984657ea2SGerrit Uitslag * @return bool
5600dc92c6fSAndreas Gohr */
5610dc92c6fSAndreas Gohrfunction isHiddenPage($id){
5628449cc9dSDominik Eckelmann    $data = array(
5638449cc9dSDominik Eckelmann        'id' => $id,
5648449cc9dSDominik Eckelmann        'hidden' => false
5658449cc9dSDominik Eckelmann    );
566cbb44eabSAndreas Gohr    \dokuwiki\Extension\Event::createAndTrigger('PAGEUTILS_ID_HIDEPAGE', $data, '_isHiddenPage');
567fb55b51eSDominik Eckelmann    return $data['hidden'];
5680dc92c6fSAndreas Gohr}
569fb55b51eSDominik Eckelmann
570dbf714f7SGerrit Uitslag/**
571dbf714f7SGerrit Uitslag * callback checks if page is hidden
572dbf714f7SGerrit Uitslag *
57384657ea2SGerrit Uitslag * @param array $data event data    - see isHiddenPage()
574dbf714f7SGerrit Uitslag */
575fb55b51eSDominik Eckelmannfunction _isHiddenPage(&$data) {
576fb55b51eSDominik Eckelmann    global $conf;
577fb55b51eSDominik Eckelmann    global $ACT;
578fb55b51eSDominik Eckelmann
579fb55b51eSDominik Eckelmann    if ($data['hidden']) return;
580fb55b51eSDominik Eckelmann    if(empty($conf['hidepages'])) return;
581fb55b51eSDominik Eckelmann    if($ACT == 'admin') return;
582fb55b51eSDominik Eckelmann
583fb55b51eSDominik Eckelmann    if(preg_match('/'.$conf['hidepages'].'/ui',':'.$data['id'])){
584fb55b51eSDominik Eckelmann        $data['hidden'] = true;
585fb55b51eSDominik Eckelmann    }
5860dc92c6fSAndreas Gohr}
5870dc92c6fSAndreas Gohr
5880dc92c6fSAndreas Gohr/**
5890dc92c6fSAndreas Gohr * Reverse of isHiddenPage
5900dc92c6fSAndreas Gohr *
5910dc92c6fSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
59284657ea2SGerrit Uitslag *
59384657ea2SGerrit Uitslag * @param string $id page id
59484657ea2SGerrit Uitslag * @return bool
5950dc92c6fSAndreas Gohr */
5960dc92c6fSAndreas Gohrfunction isVisiblePage($id){
5970dc92c6fSAndreas Gohr    return !isHiddenPage($id);
5980dc92c6fSAndreas Gohr}
5990dc92c6fSAndreas Gohr
6005b75cd1fSAdrian Lang/**
6015b75cd1fSAdrian Lang * Format an id for output to a user
6025b75cd1fSAdrian Lang *
6035b75cd1fSAdrian Lang * Namespaces are denoted by a trailing “:*”. The root namespace is
6045b75cd1fSAdrian Lang * “*”. Output is escaped.
6055b75cd1fSAdrian Lang *
6065b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
60784657ea2SGerrit Uitslag *
60884657ea2SGerrit Uitslag * @param string $id page id
60984657ea2SGerrit Uitslag * @return string
6105b75cd1fSAdrian Lang */
6115b75cd1fSAdrian Langfunction prettyprint_id($id) {
6125b75cd1fSAdrian Lang    if (!$id || $id === ':') {
6135b75cd1fSAdrian Lang        return '*';
6145b75cd1fSAdrian Lang    }
6155b75cd1fSAdrian Lang    if ((substr($id, -1, 1) === ':')) {
6165b75cd1fSAdrian Lang        $id .= '*';
6175b75cd1fSAdrian Lang    }
6185b75cd1fSAdrian Lang    return hsc($id);
6195b75cd1fSAdrian Lang}
620f03fd957SAndreas Gohr
621f03fd957SAndreas Gohr/**
622f03fd957SAndreas Gohr * Encode a UTF-8 filename to use on any filesystem
623f03fd957SAndreas Gohr *
624f03fd957SAndreas Gohr * Uses the 'fnencode' option to determine encoding
625f03fd957SAndreas Gohr *
626f03fd957SAndreas Gohr * When the second parameter is true the string will
627f03fd957SAndreas Gohr * be encoded only if non ASCII characters are detected -
628f03fd957SAndreas Gohr * This makes it safe to run it multiple times on the
629f03fd957SAndreas Gohr * same string (default is true)
630f03fd957SAndreas Gohr *
631f03fd957SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
632f03fd957SAndreas Gohr * @see    urlencode
63384657ea2SGerrit Uitslag *
63484657ea2SGerrit Uitslag * @param string $file file name
63584657ea2SGerrit Uitslag * @param bool   $safe if true, only encoded when non ASCII characters detected
63684657ea2SGerrit Uitslag * @return string
637f03fd957SAndreas Gohr */
638f03fd957SAndreas Gohrfunction utf8_encodeFN($file,$safe=true){
639f03fd957SAndreas Gohr    global $conf;
640f03fd957SAndreas Gohr    if($conf['fnencode'] == 'utf-8') return $file;
641f03fd957SAndreas Gohr
642f03fd957SAndreas Gohr    if($safe && preg_match('#^[a-zA-Z0-9/_\-\.%]+$#',$file)){
643f03fd957SAndreas Gohr        return $file;
644f03fd957SAndreas Gohr    }
645f03fd957SAndreas Gohr
646f03fd957SAndreas Gohr    if($conf['fnencode'] == 'safe'){
647f03fd957SAndreas Gohr        return SafeFN::encode($file);
648f03fd957SAndreas Gohr    }
649f03fd957SAndreas Gohr
650f03fd957SAndreas Gohr    $file = urlencode($file);
651f03fd957SAndreas Gohr    $file = str_replace('%2F','/',$file);
652f03fd957SAndreas Gohr    return $file;
653f03fd957SAndreas Gohr}
654f03fd957SAndreas Gohr
655f03fd957SAndreas Gohr/**
656f03fd957SAndreas Gohr * Decode a filename back to UTF-8
657f03fd957SAndreas Gohr *
658f03fd957SAndreas Gohr * Uses the 'fnencode' option to determine encoding
659f03fd957SAndreas Gohr *
660f03fd957SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
661f03fd957SAndreas Gohr * @see    urldecode
66284657ea2SGerrit Uitslag *
66384657ea2SGerrit Uitslag * @param string $file file name
66484657ea2SGerrit Uitslag * @return string
665f03fd957SAndreas Gohr */
666f03fd957SAndreas Gohrfunction utf8_decodeFN($file){
667f03fd957SAndreas Gohr    global $conf;
668f03fd957SAndreas Gohr    if($conf['fnencode'] == 'utf-8') return $file;
669f03fd957SAndreas Gohr
670f03fd957SAndreas Gohr    if($conf['fnencode'] == 'safe'){
671f03fd957SAndreas Gohr        return SafeFN::decode($file);
672f03fd957SAndreas Gohr    }
673f03fd957SAndreas Gohr
674f03fd957SAndreas Gohr    return urldecode($file);
675f03fd957SAndreas Gohr}
676f03fd957SAndreas Gohr
677e66d3e6dSAndreas Gohr/**
678e66d3e6dSAndreas Gohr * Find a page in the current namespace (determined from $ID) or any
679cc529468SMichael Hamann * higher namespace that can be accessed by the current user,
680cc529468SMichael Hamann * this condition can be overriden by an optional parameter.
681e66d3e6dSAndreas Gohr *
682e66d3e6dSAndreas Gohr * Used for sidebars, but can be used other stuff as well
683e66d3e6dSAndreas Gohr *
684e66d3e6dSAndreas Gohr * @todo   add event hook
68542ea7f44SGerrit Uitslag *
686e66d3e6dSAndreas Gohr * @param  string $page the pagename you're looking for
6877c3e4a67SAndreas Gohr * @param bool $useacl only return pages readable by the current user, false to ignore ACLs
688cc529468SMichael Hamann * @return false|string the full page id of the found page, false if any
689e66d3e6dSAndreas Gohr */
6907c3e4a67SAndreas Gohrfunction page_findnearest($page, $useacl = true){
69106a70133SPhy    if ((string) $page === '') return false;
692e66d3e6dSAndreas Gohr    global $ID;
693e66d3e6dSAndreas Gohr
694e66d3e6dSAndreas Gohr    $ns = $ID;
695e66d3e6dSAndreas Gohr    do {
696e66d3e6dSAndreas Gohr        $ns = getNS($ns);
697cc529468SMichael Hamann        $pageid = cleanID("$ns:$page");
6987c3e4a67SAndreas Gohr        if(page_exists($pageid) && (!$useacl || auth_quickaclcheck($pageid) >= AUTH_READ)){
699e66d3e6dSAndreas Gohr            return $pageid;
700e66d3e6dSAndreas Gohr        }
70106a70133SPhy    } while($ns !== false);
702e66d3e6dSAndreas Gohr
703e66d3e6dSAndreas Gohr    return false;
704e66d3e6dSAndreas Gohr}
705