xref: /dokuwiki/inc/pageutils.php (revision a5752066bd5ea83ac9b5dbb512f5768819a3437b)
1b625487dSandi<?php
2*a5752066Sjpedryc
3b625487dSandi/**
4b625487dSandi * Utilities for handling pagenames
5b625487dSandi *
6b625487dSandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
7b625487dSandi * @author     Andreas Gohr <andi@splitbrain.org>
81380fc45SAndreas Gohr * @todo       Combine similar functions like {wiki,media,meta}FN()
9b625487dSandi */
10b625487dSandi
110c3a5702SAndreas Gohruse dokuwiki\ChangeLog\MediaChangeLog;
120c3a5702SAndreas Gohruse dokuwiki\ChangeLog\PageChangeLog;
132cd6cc0aSAndreas Gohruse dokuwiki\File\MediaResolver;
142cd6cc0aSAndreas Gohruse dokuwiki\File\PageResolver;
150c3a5702SAndreas Gohr
166c7843b5Sandi/**
176de3759aSAndreas Gohr * Fetch the an ID from request
186c7843b5Sandi *
196c7843b5Sandi * Uses either standard $_REQUEST variable or extracts it from
206c7843b5Sandi * the full request URI when userewrite is set to 2
216c7843b5Sandi *
2242905504SAndreas Gohr * For $param='id' $conf['start'] is returned if no id was found.
2342905504SAndreas Gohr * If the second parameter is true (default) the ID is cleaned.
246c7843b5Sandi *
256c7843b5Sandi * @author Andreas Gohr <andi@splitbrain.org>
2684657ea2SGerrit Uitslag *
2784657ea2SGerrit Uitslag * @param string $param  the $_REQUEST variable name, default 'id'
2884657ea2SGerrit Uitslag * @param bool   $clean  if true, ID is cleaned
2942ea7f44SGerrit Uitslag * @return string
306c7843b5Sandi */
31*a5752066Sjpedrycfunction getID($param = 'id', $clean = true)
32*a5752066Sjpedryc{
33585bf44eSChristopher Smith    /** @var Input $INPUT */
347d01a0eaSTom N Harris    global $INPUT;
356c7843b5Sandi    global $conf;
364e90caaaSMichael Hamann    global $ACT;
376c7843b5Sandi
387d01a0eaSTom N Harris    $id = $INPUT->str($param);
3948665d38SAndreas Gohr
406c7843b5Sandi    //construct page id from request URI
416c7843b5Sandi    if (empty($id) && $conf['userewrite'] == 2) {
42585bf44eSChristopher Smith        $request = $INPUT->server->str('REQUEST_URI');
4306368e4dSMichael Hamann        $script = '';
4406368e4dSMichael Hamann
456c7843b5Sandi        //get the script URL
466c7843b5Sandi        if ($conf['basedir']) {
4781124000Sjan            $relpath = '';
4881124000Sjan            if ($param != 'id') {
4981124000Sjan                $relpath = 'lib/exe/';
5081124000Sjan            }
516ce3e5f8SAndreas Gohr            $script = $conf['basedir'] . $relpath .
526ce3e5f8SAndreas Gohr                \dokuwiki\Utf8\PhpString::basename($INPUT->server->str('SCRIPT_FILENAME'));
53585bf44eSChristopher Smith        } elseif ($INPUT->server->str('PATH_INFO')) {
54585bf44eSChristopher Smith            $request = $INPUT->server->str('PATH_INFO');
55585bf44eSChristopher Smith        } elseif ($INPUT->server->str('SCRIPT_NAME')) {
56585bf44eSChristopher Smith            $script = $INPUT->server->str('SCRIPT_NAME');
57585bf44eSChristopher Smith        } elseif ($INPUT->server->str('DOCUMENT_ROOT') && $INPUT->server->str('SCRIPT_FILENAME')) {
58*a5752066Sjpedryc            $script = preg_replace(
59*a5752066Sjpedryc                '/^' . preg_quote($INPUT->server->str('DOCUMENT_ROOT'), '/') . '/',
60*a5752066Sjpedryc                '',
61*a5752066Sjpedryc                $INPUT->server->str('SCRIPT_FILENAME')
62*a5752066Sjpedryc            );
636c7843b5Sandi            $script = '/' . $script;
646c7843b5Sandi        }
656c7843b5Sandi
6652339126Sandi        //clean script and request (fixes a windows problem)
6752339126Sandi        $script  = preg_replace('/\/\/+/', '/', $script);
687d71d4b7SAndreas Gohr        $request = preg_replace('/\/\/+/', '/', $request);
6952339126Sandi
706c7843b5Sandi        //remove script URL and Querystring to gain the id
7152339126Sandi        if (preg_match('/^' . preg_quote($script, '/') . '(.*)/', $request, $match)) {
726c7843b5Sandi            $id = preg_replace('/\?.*/', '', $match[1]);
736c7843b5Sandi        }
746de3759aSAndreas Gohr        $id = urldecode($id);
7542905504SAndreas Gohr        //strip leading slashes
7642905504SAndreas Gohr        $id = preg_replace('!^/+!', '', $id);
776c7843b5Sandi    }
78671a58a6SGuy Brand
79671a58a6SGuy Brand    // Namespace autolinking from URL
80b6084253SAndreas Gohr    if (substr($id, -1) == ':' || ($conf['useslash'] && substr($id, -1) == '/')) {
81103c256aSChris Smith        if (page_exists($id . $conf['start'])) {
82671a58a6SGuy Brand            // start page inside namespace
83671a58a6SGuy Brand            $id = $id . $conf['start'];
84103c256aSChris Smith        } elseif (page_exists($id . noNS(cleanID($id)))) {
85671a58a6SGuy Brand            // page named like the NS inside the NS
86671a58a6SGuy Brand            $id = $id . noNS(cleanID($id));
87103c256aSChris Smith        } elseif (page_exists($id)) {
88671a58a6SGuy Brand            // page like namespace exists
897a42ac9eSBen Coburn            $id = substr($id, 0, -1);
90671a58a6SGuy Brand        } else {
91671a58a6SGuy Brand            // fall back to default
92671a58a6SGuy Brand            $id = $id . $conf['start'];
93671a58a6SGuy Brand        }
949dc53973SMichael Grosse        if (isset($ACT) && $ACT === 'show') {
959dc53973SMichael Grosse            $urlParameters = $_GET;
96e380abb2SMichael Grosse            if (isset($urlParameters['id'])) {
97e380abb2SMichael Grosse                unset($urlParameters['id']);
98e380abb2SMichael Grosse            }
99e9fede20SPhy            send_redirect(wl($id, $urlParameters, true, '&'));
1009dc53973SMichael Grosse        }
101671a58a6SGuy Brand    }
10242905504SAndreas Gohr    if ($clean) $id = cleanID($id);
10340b5fb5bSPhy    if ($id === '' && $param == 'id') $id = $conf['start'];
1046c7843b5Sandi
1056c7843b5Sandi    return $id;
1066c7843b5Sandi}
107b625487dSandi
108b625487dSandi/**
109b625487dSandi * Remove unwanted chars from ID
110b625487dSandi *
111b625487dSandi * Cleans a given ID to only use allowed characters. Accented characters are
112b625487dSandi * converted to unaccented ones
113b625487dSandi *
114b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
11542ea7f44SGerrit Uitslag *
1166e0cc83aSchris * @param  string  $raw_id    The pageid to clean
1178a831f2bSAndreas Gohr * @param  boolean $ascii     Force ASCII
118dbf714f7SGerrit Uitslag * @return string cleaned id
119b625487dSandi */
120*a5752066Sjpedrycfunction cleanID($raw_id, $ascii = false)
121*a5752066Sjpedryc{
122b625487dSandi    global $conf;
1234b5db43bSjoe.lapp    static $sepcharpat = null;
1244b5db43bSjoe.lapp
125dc2c0e04Schris    global $cache_cleanid;
126dc2c0e04Schris    $cache = & $cache_cleanid;
1276e0cc83aSchris
1286e0cc83aSchris    // check if it's already in the memory cache
12930f3bd15SMichael Grosse    if (!$ascii && isset($cache[(string)$raw_id])) {
1303a50618cSgweissbach        return $cache[(string)$raw_id];
1316e0cc83aSchris    }
1326e0cc83aSchris
1334b5db43bSjoe.lapp    $sepchar = $conf['sepchar'];
1344b5db43bSjoe.lapp    if ($sepcharpat == null) // build string only once to save clock cycles
1354b5db43bSjoe.lapp        $sepcharpat = '#\\' . $sepchar . '+#';
1364b5db43bSjoe.lapp
1373a50618cSgweissbach    $id = trim((string)$raw_id);
1388cbc5ee8SAndreas Gohr    $id = \dokuwiki\Utf8\PhpString::strtolower($id);
139b625487dSandi
140b625487dSandi    //alternative namespace seperator
141b625487dSandi    if ($conf['useslash']) {
1423755fc25STom N Harris        $id = strtr($id, ';/', '::');
143b625487dSandi    } else {
1443755fc25STom N Harris        $id = strtr($id, ';/', ':' . $sepchar);
145b625487dSandi    }
146b625487dSandi
1478cbc5ee8SAndreas Gohr    if ($conf['deaccent'] == 2 || $ascii) $id = \dokuwiki\Utf8\Clean::romanize($id);
1488cbc5ee8SAndreas Gohr    if ($conf['deaccent'] || $ascii) $id = \dokuwiki\Utf8\Clean::deaccent($id, -1);
149b625487dSandi
150b625487dSandi    //remove specials
1518cbc5ee8SAndreas Gohr    $id = \dokuwiki\Utf8\Clean::stripspecials($id, $sepchar, '\*');
152b625487dSandi
1538cbc5ee8SAndreas Gohr    if ($ascii) $id = \dokuwiki\Utf8\Clean::strip($id);
1548a831f2bSAndreas Gohr
155b625487dSandi    //clean up
1564b5db43bSjoe.lapp    $id = preg_replace($sepcharpat, $sepchar, $id);
157b625487dSandi    $id = preg_replace('#:+#', ':', $id);
1583543c6deSAndreas Gohr    $id = trim($id, ':._-');
159b625487dSandi    $id = preg_replace('#:[:\._\-]+#', ':', $id);
160b680ea06SAndreas Gohr    $id = preg_replace('#[:\._\-]+:#', ':', $id);
161b625487dSandi
16230f3bd15SMichael Grosse    if (!$ascii) $cache[(string)$raw_id] = $id;
163b625487dSandi    return($id);
164b625487dSandi}
165b625487dSandi
166b625487dSandi/**
167b625487dSandi * Return namespacepart of a wiki ID
168b625487dSandi *
169b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
17015851b98SGerrit Uitslag *
17115851b98SGerrit Uitslag * @param string $id
17242ea7f44SGerrit Uitslag * @return string|false the namespace part or false if the given ID has no namespace (root)
173b625487dSandi */
174*a5752066Sjpedrycfunction getNS($id)
175*a5752066Sjpedryc{
1763a50618cSgweissbach    $pos = strrpos((string)$id, ':');
177c4e0e4a1SAndreas Gohr    if ($pos !== false) {
1783a50618cSgweissbach        return substr((string)$id, 0, $pos);
179b625487dSandi    }
180ef11fcfcSAndreas Gohr    return false;
181b625487dSandi}
182b625487dSandi
183b625487dSandi/**
184b625487dSandi * Returns the ID without the namespace
185b625487dSandi *
186b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
18715851b98SGerrit Uitslag *
18815851b98SGerrit Uitslag * @param string $id
18915851b98SGerrit Uitslag * @return string
190b625487dSandi */
191*a5752066Sjpedrycfunction noNS($id)
192*a5752066Sjpedryc{
1932844584fSBen Coburn    $pos = strrpos($id, ':');
1942844584fSBen Coburn    if ($pos !== false) {
1952844584fSBen Coburn        return substr($id, $pos + 1);
1962844584fSBen Coburn    } else {
1972844584fSBen Coburn        return $id;
1982844584fSBen Coburn    }
1991a84a0f3SAnika Henke}
2001a84a0f3SAnika Henke
2011a84a0f3SAnika Henke/**
2021a84a0f3SAnika Henke * Returns the current namespace
2031a84a0f3SAnika Henke *
2041a84a0f3SAnika Henke * @author Nathan Fritz <fritzn@crown.edu>
20584657ea2SGerrit Uitslag *
20684657ea2SGerrit Uitslag * @param string $id
20784657ea2SGerrit Uitslag * @return string
2081a84a0f3SAnika Henke */
209*a5752066Sjpedrycfunction curNS($id)
210*a5752066Sjpedryc{
2111a84a0f3SAnika Henke    return noNS(getNS($id));
2121a84a0f3SAnika Henke}
2131a84a0f3SAnika Henke
2141a84a0f3SAnika Henke/**
2151a84a0f3SAnika Henke * Returns the ID without the namespace or current namespace for 'start' pages
2161a84a0f3SAnika Henke *
2171a84a0f3SAnika Henke * @author Nathan Fritz <fritzn@crown.edu>
21884657ea2SGerrit Uitslag *
21984657ea2SGerrit Uitslag * @param string $id
22084657ea2SGerrit Uitslag * @return string
2211a84a0f3SAnika Henke */
222*a5752066Sjpedrycfunction noNSorNS($id)
223*a5752066Sjpedryc{
2241a84a0f3SAnika Henke    global $conf;
2251a84a0f3SAnika Henke
2261a84a0f3SAnika Henke    $p = noNS($id);
227c077d4dcSAndreas Gohr    if ($p === $conf['start'] || $p === false || $p === '') {
2281a84a0f3SAnika Henke        $p = curNS($id);
229c077d4dcSAndreas Gohr        if ($p === false || $p === '') {
2309708106bSAdrian Lang            return $conf['start'];
2311a84a0f3SAnika Henke        }
2321a84a0f3SAnika Henke    }
2331a84a0f3SAnika Henke    return $p;
234b625487dSandi}
2354ceab83fSAndreas Gohr
2364ceab83fSAndreas Gohr/**
2374ceab83fSAndreas Gohr * Creates a XHTML valid linkid from a given headline title
2384ceab83fSAndreas Gohr *
2394ceab83fSAndreas Gohr * @param string  $title   The headline title
2404f582736SGuillaume Turri * @param array|bool   $check   Existing IDs
241c857afe0SMichael Hamann * @return string the title
24284657ea2SGerrit Uitslag *
2434ceab83fSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
2444ceab83fSAndreas Gohr */
245*a5752066Sjpedrycfunction sectionID($title, &$check)
246*a5752066Sjpedryc{
247de9114eaSAnika Henke    $title = str_replace(array(':','.'), '', cleanID($title));
248de9114eaSAnika Henke    $new = ltrim($title, '0123456789_-');
2494ceab83fSAndreas Gohr    if (empty($new)) {
2504ceab83fSAndreas Gohr        $title = 'section' . preg_replace('/[^0-9]+/', '', $title); //keep numbers from headline
2514ceab83fSAndreas Gohr    } else {
2524ceab83fSAndreas Gohr        $title = $new;
2534ceab83fSAndreas Gohr    }
2544ceab83fSAndreas Gohr
255443d207bSAndreas Gohr    if (is_array($check)) {
2564f582736SGuillaume Turri        $suffix = 0;
2574f582736SGuillaume Turri        $candidateTitle = $title;
2584f582736SGuillaume Turri        while (in_array($candidateTitle, $check)) {
2594f582736SGuillaume Turri            $candidateTitle = $title . ++$suffix;
2604f582736SGuillaume Turri        }
2614f582736SGuillaume Turri        $check [] = $candidateTitle;
2624f582736SGuillaume Turri        return $candidateTitle;
26301e3159cSChris Tapp    } else {
2644ceab83fSAndreas Gohr        return $title;
2654ceab83fSAndreas Gohr    }
2664f582736SGuillaume Turri}
2674ceab83fSAndreas Gohr
268b625487dSandi/**
269103c256aSChris Smith * Wiki page existence check
270103c256aSChris Smith *
271103c256aSChris Smith * parameters as for wikiFN
272103c256aSChris Smith *
273103c256aSChris Smith * @author Chris Smith <chris@jalakai.co.uk>
27484657ea2SGerrit Uitslag *
27584657ea2SGerrit Uitslag * @param string $id page id
27684657ea2SGerrit Uitslag * @param string|int $rev empty or revision timestamp
27784657ea2SGerrit Uitslag * @param bool $clean flag indicating that $id should be cleaned (see wikiFN as well)
2787de86af9SGerrit Uitslag * @param bool $date_at
27984657ea2SGerrit Uitslag * @return bool exists?
280103c256aSChris Smith */
281*a5752066Sjpedrycfunction page_exists($id, $rev = '', $clean = true, $date_at = false)
282*a5752066Sjpedryc{
28390bee600Slisps    if ($rev !== '' && $date_at) {
2841d053a56Slisps        $pagelog = new PageChangeLog($id);
28590bee600Slisps        $pagelog_rev = $pagelog->getLastRevisionAt($rev);
28690bee600Slisps        if ($pagelog_rev !== false)
28790bee600Slisps            $rev = $pagelog_rev;
28890bee600Slisps    }
28979e79377SAndreas Gohr    return file_exists(wikiFN($id, $rev, $clean));
290103c256aSChris Smith}
291103c256aSChris Smith
292103c256aSChris Smith/**
2935c844bb3SAndreas Gohr * Media existence check
2945c844bb3SAndreas Gohr *
2955c844bb3SAndreas Gohr * @param string $id page id
2965c844bb3SAndreas Gohr * @param string|int $rev empty or revision timestamp
2975c844bb3SAndreas Gohr * @param bool $clean flag indicating that $id should be cleaned (see mediaFN as well)
2985c844bb3SAndreas Gohr * @param bool $date_at
2995c844bb3SAndreas Gohr * @return bool exists?
3005c844bb3SAndreas Gohr */
3015c844bb3SAndreas Gohrfunction media_exists($id, $rev = '', $clean = true, $date_at = false)
3025c844bb3SAndreas Gohr{
3035c844bb3SAndreas Gohr    if ($rev !== '' && $date_at) {
3045c844bb3SAndreas Gohr        $changeLog = new MediaChangeLog($id);
3055c844bb3SAndreas Gohr        $changelog_rev = $changeLog->getLastRevisionAt($rev);
3065c844bb3SAndreas Gohr        if ($changelog_rev !== false) {
3075c844bb3SAndreas Gohr            $rev = $changelog_rev;
3085c844bb3SAndreas Gohr        }
3095c844bb3SAndreas Gohr    }
3105c844bb3SAndreas Gohr    return file_exists(mediaFN($id, $rev, $clean));
3115c844bb3SAndreas Gohr}
3125c844bb3SAndreas Gohr
3135c844bb3SAndreas Gohr/**
314103c256aSChris Smith * returns the full path to the datafile specified by ID and optional revision
315b625487dSandi *
316b625487dSandi * The filename is URL encoded to protect Unicode chars
317b625487dSandi *
318103c256aSChris Smith * @param  $raw_id  string   id of wikipage
319e0c26282SGerrit Uitslag * @param  $rev     int|string   page revision, empty string for current
320103c256aSChris Smith * @param  $clean   bool     flag indicating that $raw_id should be cleaned.  Only set to false
321103c256aSChris Smith *                           when $id is guaranteed to have been cleaned already.
322dbf714f7SGerrit Uitslag * @return string full path
323103c256aSChris Smith *
324b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
325b625487dSandi */
326*a5752066Sjpedrycfunction wikiFN($raw_id, $rev = '', $clean = true)
327*a5752066Sjpedryc{
328b625487dSandi    global $conf;
3296e0cc83aSchris
330dc2c0e04Schris    global $cache_wikifn;
331dc2c0e04Schris    $cache = & $cache_wikifn;
332dc2c0e04Schris
3336e0cc83aSchris    $id = $raw_id;
3346e0cc83aSchris
3350d8ea614Schris    if ($clean) $id = cleanID($id);
336b625487dSandi    $id = str_replace(':', '/', $id);
337b018ecbeSMichael Grosse
338b018ecbeSMichael Grosse    if (isset($cache[$id]) && isset($cache[$id][$rev])) {
339b018ecbeSMichael Grosse        return $cache[$id][$rev];
340b018ecbeSMichael Grosse    }
341b018ecbeSMichael Grosse
342b625487dSandi    if (empty($rev)) {
343b625487dSandi        $fn = $conf['datadir'] . '/' . utf8_encodeFN($id) . '.txt';
344b625487dSandi    } else {
345b625487dSandi        $fn = $conf['olddir'] . '/' . utf8_encodeFN($id) . '.' . $rev . '.txt';
346ff3ed99fSmarcel        if ($conf['compression']) {
347ff3ed99fSmarcel            //test for extensions here, we want to read both compressions
34879e79377SAndreas Gohr            if (file_exists($fn . '.gz')) {
349b625487dSandi                $fn .= '.gz';
35079e79377SAndreas Gohr            } elseif (file_exists($fn . '.bz2')) {
351ff3ed99fSmarcel                $fn .= '.bz2';
352ff3ed99fSmarcel            } else {
353ff3ed99fSmarcel                //file doesnt exist yet, so we take the configured extension
354ff3ed99fSmarcel                $fn .= '.' . $conf['compression'];
355ff3ed99fSmarcel            }
356b625487dSandi        }
357b625487dSandi    }
3586e0cc83aSchris
359*a5752066Sjpedryc    if (!isset($cache[$id])) {
360*a5752066Sjpedryc        $cache[$id] = array();
361*a5752066Sjpedryc    }
362b018ecbeSMichael Grosse    $cache[$id][$rev] = $fn;
363b625487dSandi    return $fn;
364b625487dSandi}
365b625487dSandi
366b625487dSandi/**
367c9b4bd1eSBen Coburn * Returns the full path to the file for locking the page while editing.
368c9b4bd1eSBen Coburn *
369c9b4bd1eSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
37084657ea2SGerrit Uitslag *
37184657ea2SGerrit Uitslag * @param string $id page id
37284657ea2SGerrit Uitslag * @return string full path
373c9b4bd1eSBen Coburn */
374*a5752066Sjpedrycfunction wikiLockFN($id)
375*a5752066Sjpedryc{
376c9b4bd1eSBen Coburn    global $conf;
377662ff478SAndreas Gohr    return $conf['lockdir'] . '/' . md5(cleanID($id)) . '.lock';
378c9b4bd1eSBen Coburn}
379c9b4bd1eSBen Coburn
380c9b4bd1eSBen Coburn
381c9b4bd1eSBen Coburn/**
3821380fc45SAndreas Gohr * returns the full path to the meta file specified by ID and extension
383b158d625SSteven Danz *
384b158d625SSteven Danz * @author Steven Danz <steven-danz@kc.rr.com>
38584657ea2SGerrit Uitslag *
38684657ea2SGerrit Uitslag * @param string $id   page id
38784657ea2SGerrit Uitslag * @param string $ext  file extension
38884657ea2SGerrit Uitslag * @return string full path
389b158d625SSteven Danz */
390*a5752066Sjpedrycfunction metaFN($id, $ext)
391*a5752066Sjpedryc{
392b158d625SSteven Danz    global $conf;
393b158d625SSteven Danz    $id = cleanID($id);
394b158d625SSteven Danz    $id = str_replace(':', '/', $id);
3951380fc45SAndreas Gohr    $fn = $conf['metadir'] . '/' . utf8_encodeFN($id) . $ext;
396b158d625SSteven Danz    return $fn;
397b158d625SSteven Danz}
398b158d625SSteven Danz
399b158d625SSteven Danz/**
400e4f389efSKate Arzamastseva * returns the full path to the media's meta file specified by ID and extension
401e4f389efSKate Arzamastseva *
402cbe26ad6SKate Arzamastseva * @author Kate Arzamastseva <pshns@ukr.net>
40384657ea2SGerrit Uitslag *
40484657ea2SGerrit Uitslag * @param string $id   media id
40584657ea2SGerrit Uitslag * @param string $ext  extension of media
40684657ea2SGerrit Uitslag * @return string
407e4f389efSKate Arzamastseva */
408*a5752066Sjpedrycfunction mediaMetaFN($id, $ext)
409*a5752066Sjpedryc{
410e4f389efSKate Arzamastseva    global $conf;
411e4f389efSKate Arzamastseva    $id = cleanID($id);
412e4f389efSKate Arzamastseva    $id = str_replace(':', '/', $id);
413e4f389efSKate Arzamastseva    $fn = $conf['mediametadir'] . '/' . utf8_encodeFN($id) . $ext;
414e4f389efSKate Arzamastseva    return $fn;
415e4f389efSKate Arzamastseva}
416e4f389efSKate Arzamastseva
417e4f389efSKate Arzamastseva/**
418e1f3d9e1SEsther Brunner * returns an array of full paths to all metafiles of a given ID
419e1f3d9e1SEsther Brunner *
420e1f3d9e1SEsther Brunner * @author Esther Brunner <esther@kaffeehaus.ch>
421ba0267b3SMichael Hamann * @author Michael Hamann <michael@content-space.de>
42284657ea2SGerrit Uitslag *
42384657ea2SGerrit Uitslag * @param string $id page id
42484657ea2SGerrit Uitslag * @return array
425e1f3d9e1SEsther Brunner */
426*a5752066Sjpedrycfunction metaFiles($id)
427*a5752066Sjpedryc{
428ba0267b3SMichael Hamann    $basename = metaFN($id, '');
429ba0267b3SMichael Hamann    $files    = glob($basename . '.*', GLOB_MARK);
430ba0267b3SMichael Hamann    // filter files like foo.bar.meta when $id == 'foo'
431ba0267b3SMichael Hamann    return    $files ? preg_grep('/^' . preg_quote($basename, '/') . '\.[^.\/]*$/u', $files) : array();
432e1f3d9e1SEsther Brunner}
433e1f3d9e1SEsther Brunner
434e1f3d9e1SEsther Brunner/**
435b625487dSandi * returns the full path to the mediafile specified by ID
436b625487dSandi *
437b625487dSandi * The filename is URL encoded to protect Unicode chars
438b625487dSandi *
439b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
440cbe26ad6SKate Arzamastseva * @author Kate Arzamastseva <pshns@ukr.net>
44184657ea2SGerrit Uitslag *
44284657ea2SGerrit Uitslag * @param string     $id  media id
44384657ea2SGerrit Uitslag * @param string|int $rev empty string or revision timestamp
444f50a239bSTakamura * @param bool $clean
445f50a239bSTakamura *
44684657ea2SGerrit Uitslag * @return string full path
447b625487dSandi */
448*a5752066Sjpedrycfunction mediaFN($id, $rev = '', $clean = true)
449*a5752066Sjpedryc{
450b625487dSandi    global $conf;
451d0e997c6SMichael Große    if ($clean) $id = cleanID($id);
452b625487dSandi    $id = str_replace(':', '/', $id);
453e4f389efSKate Arzamastseva    if (empty($rev)) {
454b625487dSandi        $fn = $conf['mediadir'] . '/' . utf8_encodeFN($id);
455e4f389efSKate Arzamastseva    } else {
456cbe26ad6SKate Arzamastseva        $ext = mimetype($id);
4578e69fd30SKate Arzamastseva        $name = substr($id, 0, -1 * strlen($ext[0]) - 1);
45861f1aad8SKate Arzamastseva        $fn = $conf['mediaolddir'] . '/' . utf8_encodeFN($name . '.' . ( (int) $rev ) . '.' . $ext[0]);
459e4f389efSKate Arzamastseva    }
460b625487dSandi    return $fn;
461b625487dSandi}
462b625487dSandi
463b625487dSandi/**
4642adaf2b8SAndreas Gohr * Returns the full filepath to a localized file if local
465b625487dSandi * version isn't found the english one is returned
466b625487dSandi *
4672adaf2b8SAndreas Gohr * @param  string $id  The id of the local file
4682adaf2b8SAndreas Gohr * @param  string $ext The file extension (usually txt)
469dbf714f7SGerrit Uitslag * @return string full filepath to localized file
47084657ea2SGerrit Uitslag *
471b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
472b625487dSandi */
473*a5752066Sjpedrycfunction localeFN($id, $ext = 'txt')
474*a5752066Sjpedryc{
475b625487dSandi    global $conf;
4768819fbf5ShArpanet    $file = DOKU_CONF . 'lang/' . $conf['lang'] . '/' . $id . '.' . $ext;
47779e79377SAndreas Gohr    if (!file_exists($file)) {
4782adaf2b8SAndreas Gohr        $file = DOKU_INC . 'inc/lang/' . $conf['lang'] . '/' . $id . '.' . $ext;
47979e79377SAndreas Gohr        if (!file_exists($file)) {
480b625487dSandi            //fall back to english
4812adaf2b8SAndreas Gohr            $file = DOKU_INC . 'inc/lang/en/' . $id . '.' . $ext;
482b625487dSandi        }
483e6cecb08SMichael Hamann    }
484b625487dSandi    return $file;
485b625487dSandi}
486b625487dSandi
487b625487dSandi/**
488c4e0e4a1SAndreas Gohr * Resolve relative paths in IDs
489c4e0e4a1SAndreas Gohr *
490c4e0e4a1SAndreas Gohr * Do not call directly use resolve_mediaid or resolve_pageid
491c4e0e4a1SAndreas Gohr * instead
492c4e0e4a1SAndreas Gohr *
493c4e0e4a1SAndreas Gohr * Partyly based on a cleanPath function found at
49459752844SAnders Sandblad * http://php.net/manual/en/function.realpath.php#57016
495c4e0e4a1SAndreas Gohr *
496bfcf8009SAndreas Gohr * @deprecated 2020-09-30
49784657ea2SGerrit Uitslag * @param string $ns     namespace which is context of id
49884657ea2SGerrit Uitslag * @param string $id     relative id
49984657ea2SGerrit Uitslag * @param bool   $clean  flag indicating that id should be cleaned
50042ea7f44SGerrit Uitslag * @return string
501c4e0e4a1SAndreas Gohr */
502*a5752066Sjpedrycfunction resolve_id($ns, $id, $clean = true)
503*a5752066Sjpedryc{
504c662a49aSAndreas Gohr    global $conf;
5052cd6cc0aSAndreas Gohr    dbg_deprecated(\dokuwiki\File\Resolver::class . ' and its children');
506c662a49aSAndreas Gohr
507c662a49aSAndreas Gohr    // some pre cleaning for useslash:
508c662a49aSAndreas Gohr    if ($conf['useslash']) $id = str_replace('/', ':', $id);
509c662a49aSAndreas Gohr
510c4e0e4a1SAndreas Gohr    // if the id starts with a dot we need to handle the
511c4e0e4a1SAndreas Gohr    // relative stuff
5122401f18dSSyntaxseed    if ($id && $id[0] == '.') {
513c4e0e4a1SAndreas Gohr        // normalize initial dots without a colon
5144986a584SPhy        $id = preg_replace('/^((\.+:)*)(\.+)(?=[^:\.])/', '\1\3:', $id);
515c4e0e4a1SAndreas Gohr        // prepend the current namespace
516c4e0e4a1SAndreas Gohr        $id = $ns . ':' . $id;
517c4e0e4a1SAndreas Gohr
518c4e0e4a1SAndreas Gohr        // cleanup relatives
519c4e0e4a1SAndreas Gohr        $result = array();
520c4e0e4a1SAndreas Gohr        $pathA  = explode(':', $id);
521c4e0e4a1SAndreas Gohr        if (!$pathA[0]) $result[] = '';
522*a5752066Sjpedryc        foreach ($pathA as $key => $dir) {
523c4e0e4a1SAndreas Gohr            if ($dir == '..') {
524c4e0e4a1SAndreas Gohr                if (end($result) == '..') {
525c4e0e4a1SAndreas Gohr                    $result[] = '..';
526c4e0e4a1SAndreas Gohr                } elseif (!array_pop($result)) {
527c4e0e4a1SAndreas Gohr                    $result[] = '..';
528c4e0e4a1SAndreas Gohr                }
529c4e0e4a1SAndreas Gohr            } elseif ($dir && $dir != '.') {
530c4e0e4a1SAndreas Gohr                $result[] = $dir;
531c4e0e4a1SAndreas Gohr            }
532c4e0e4a1SAndreas Gohr        }
533c4e0e4a1SAndreas Gohr        if (!end($pathA)) $result[] = '';
534c4e0e4a1SAndreas Gohr        $id = implode(':', $result);
535c4e0e4a1SAndreas Gohr    } elseif ($ns !== false && strpos($id, ':') === false) {
536c4e0e4a1SAndreas Gohr        //if link contains no namespace. add current namespace (if any)
537c4e0e4a1SAndreas Gohr        $id = $ns . ':' . $id;
538c4e0e4a1SAndreas Gohr    }
539c4e0e4a1SAndreas Gohr
540a6ef4796SAndreas Gohr    if ($clean) $id = cleanID($id);
541a6ef4796SAndreas Gohr    return $id;
542c4e0e4a1SAndreas Gohr}
543c4e0e4a1SAndreas Gohr
544c4e0e4a1SAndreas Gohr/**
545b625487dSandi * Returns a full media id
546b625487dSandi *
54784657ea2SGerrit Uitslag * @param string $ns namespace which is context of id
5485c844bb3SAndreas Gohr * @param string &$media (reference) relative media id, updated to resolved id
54984657ea2SGerrit Uitslag * @param bool &$exists (reference) updated with existance of media
5507de86af9SGerrit Uitslag * @param int|string $rev
5517de86af9SGerrit Uitslag * @param bool $date_at
5525c844bb3SAndreas Gohr * @deprecated 2020-09-30
553b625487dSandi */
554*a5752066Sjpedrycfunction resolve_mediaid($ns, &$media, &$exists, $rev = '', $date_at = false)
555*a5752066Sjpedryc{
5565c844bb3SAndreas Gohr    dbg_deprecated(MediaResolver::class);
5575c844bb3SAndreas Gohr    $resolver = new MediaResolver("$ns:deprecated");
5585c844bb3SAndreas Gohr    $media = $resolver->resolveId($media, $rev, $date_at);
5595c844bb3SAndreas Gohr    $exists = media_exists($media, $rev, false, $date_at);
560b625487dSandi}
561b625487dSandi
562b625487dSandi/**
563b625487dSandi * Returns a full page id
564b625487dSandi *
565bfcf8009SAndreas Gohr * @deprecated 2020-09-30
56684657ea2SGerrit Uitslag * @param string $ns namespace which is context of id
56784657ea2SGerrit Uitslag * @param string &$page (reference) relative page id, updated to resolved id
56884657ea2SGerrit Uitslag * @param bool &$exists (reference) updated with existance of media
5697de86af9SGerrit Uitslag * @param string $rev
5707de86af9SGerrit Uitslag * @param bool $date_at
571b625487dSandi */
572bfcf8009SAndreas Gohrfunction resolve_pageid($ns, &$page, &$exists, $rev = '', $date_at = false)
573bfcf8009SAndreas Gohr{
5748c6be208SAndreas Gohr    dbg_deprecated(PageResolver::class);
57554611a7aSAndreas Gohr
57654611a7aSAndreas Gohr    global $ID;
57754611a7aSAndreas Gohr    if (getNS($ID) == $ns) {
57854611a7aSAndreas Gohr        $context = $ID; // this is usually the case
57954611a7aSAndreas Gohr    } else {
58054611a7aSAndreas Gohr        $context = "$ns:deprecated"; // only used when a different context namespace was given
58154611a7aSAndreas Gohr    }
58254611a7aSAndreas Gohr
58354611a7aSAndreas Gohr    $resolver = new PageResolver($context);
584bfcf8009SAndreas Gohr    $page = $resolver->resolveId($page, $rev, $date_at);
585bfcf8009SAndreas Gohr    $exists = page_exists($page, $rev, false, $date_at);
586b625487dSandi}
587b625487dSandi
58898407a7aSandi/**
58998407a7aSandi * Returns the name of a cachefile from given data
59098407a7aSandi *
59198407a7aSandi * The needed directory is created by this function!
59298407a7aSandi *
59398407a7aSandi * @author Andreas Gohr <andi@splitbrain.org>
59498407a7aSandi *
59598407a7aSandi * @param string $data  This data is used to create a unique md5 name
59698407a7aSandi * @param string $ext   This is appended to the filename if given
59798407a7aSandi * @return string       The filename of the cachefile
59898407a7aSandi */
599*a5752066Sjpedrycfunction getCacheName($data, $ext = '')
600*a5752066Sjpedryc{
60198407a7aSandi    global $conf;
60298407a7aSandi    $md5  = md5($data);
6032401f18dSSyntaxseed    $file = $conf['cachedir'] . '/' . $md5[0] . '/' . $md5 . $ext;
60498407a7aSandi    io_makeFileDir($file);
60598407a7aSandi    return $file;
60698407a7aSandi}
60798407a7aSandi
6080dc92c6fSAndreas Gohr/**
6090dc92c6fSAndreas Gohr * Checks a pageid against $conf['hidepages']
6100dc92c6fSAndreas Gohr *
6110dc92c6fSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
61284657ea2SGerrit Uitslag *
61384657ea2SGerrit Uitslag * @param string $id page id
61484657ea2SGerrit Uitslag * @return bool
6150dc92c6fSAndreas Gohr */
616*a5752066Sjpedrycfunction isHiddenPage($id)
617*a5752066Sjpedryc{
6188449cc9dSDominik Eckelmann    $data = array(
6198449cc9dSDominik Eckelmann        'id' => $id,
6208449cc9dSDominik Eckelmann        'hidden' => false
6218449cc9dSDominik Eckelmann    );
622cbb44eabSAndreas Gohr    \dokuwiki\Extension\Event::createAndTrigger('PAGEUTILS_ID_HIDEPAGE', $data, '_isHiddenPage');
623fb55b51eSDominik Eckelmann    return $data['hidden'];
6240dc92c6fSAndreas Gohr}
625fb55b51eSDominik Eckelmann
626dbf714f7SGerrit Uitslag/**
627dbf714f7SGerrit Uitslag * callback checks if page is hidden
628dbf714f7SGerrit Uitslag *
62984657ea2SGerrit Uitslag * @param array $data event data    - see isHiddenPage()
630dbf714f7SGerrit Uitslag */
631*a5752066Sjpedrycfunction _isHiddenPage(&$data)
632*a5752066Sjpedryc{
633fb55b51eSDominik Eckelmann    global $conf;
634fb55b51eSDominik Eckelmann    global $ACT;
635fb55b51eSDominik Eckelmann
636fb55b51eSDominik Eckelmann    if ($data['hidden']) return;
637fb55b51eSDominik Eckelmann    if (empty($conf['hidepages'])) return;
638fb55b51eSDominik Eckelmann    if ($ACT == 'admin') return;
639fb55b51eSDominik Eckelmann
640fb55b51eSDominik Eckelmann    if (preg_match('/' . $conf['hidepages'] . '/ui', ':' . $data['id'])) {
641fb55b51eSDominik Eckelmann        $data['hidden'] = true;
642fb55b51eSDominik Eckelmann    }
6430dc92c6fSAndreas Gohr}
6440dc92c6fSAndreas Gohr
6450dc92c6fSAndreas Gohr/**
6460dc92c6fSAndreas Gohr * Reverse of isHiddenPage
6470dc92c6fSAndreas Gohr *
6480dc92c6fSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
64984657ea2SGerrit Uitslag *
65084657ea2SGerrit Uitslag * @param string $id page id
65184657ea2SGerrit Uitslag * @return bool
6520dc92c6fSAndreas Gohr */
653*a5752066Sjpedrycfunction isVisiblePage($id)
654*a5752066Sjpedryc{
6550dc92c6fSAndreas Gohr    return !isHiddenPage($id);
6560dc92c6fSAndreas Gohr}
6570dc92c6fSAndreas Gohr
6585b75cd1fSAdrian Lang/**
6595b75cd1fSAdrian Lang * Format an id for output to a user
6605b75cd1fSAdrian Lang *
6615b75cd1fSAdrian Lang * Namespaces are denoted by a trailing “:*”. The root namespace is
6625b75cd1fSAdrian Lang * “*”. Output is escaped.
6635b75cd1fSAdrian Lang *
6645b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
66584657ea2SGerrit Uitslag *
66684657ea2SGerrit Uitslag * @param string $id page id
66784657ea2SGerrit Uitslag * @return string
6685b75cd1fSAdrian Lang */
669*a5752066Sjpedrycfunction prettyprint_id($id)
670*a5752066Sjpedryc{
6715b75cd1fSAdrian Lang    if (!$id || $id === ':') {
6725b75cd1fSAdrian Lang        return '*';
6735b75cd1fSAdrian Lang    }
6745b75cd1fSAdrian Lang    if ((substr($id, -1, 1) === ':')) {
6755b75cd1fSAdrian Lang        $id .= '*';
6765b75cd1fSAdrian Lang    }
6775b75cd1fSAdrian Lang    return hsc($id);
6785b75cd1fSAdrian Lang}
679f03fd957SAndreas Gohr
680f03fd957SAndreas Gohr/**
681f03fd957SAndreas Gohr * Encode a UTF-8 filename to use on any filesystem
682f03fd957SAndreas Gohr *
683f03fd957SAndreas Gohr * Uses the 'fnencode' option to determine encoding
684f03fd957SAndreas Gohr *
685f03fd957SAndreas Gohr * When the second parameter is true the string will
686f03fd957SAndreas Gohr * be encoded only if non ASCII characters are detected -
687f03fd957SAndreas Gohr * This makes it safe to run it multiple times on the
688f03fd957SAndreas Gohr * same string (default is true)
689f03fd957SAndreas Gohr *
690f03fd957SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
691f03fd957SAndreas Gohr * @see    urlencode
69284657ea2SGerrit Uitslag *
69384657ea2SGerrit Uitslag * @param string $file file name
69484657ea2SGerrit Uitslag * @param bool   $safe if true, only encoded when non ASCII characters detected
69584657ea2SGerrit Uitslag * @return string
696f03fd957SAndreas Gohr */
697*a5752066Sjpedrycfunction utf8_encodeFN($file, $safe = true)
698*a5752066Sjpedryc{
699f03fd957SAndreas Gohr    global $conf;
700f03fd957SAndreas Gohr    if ($conf['fnencode'] == 'utf-8') return $file;
701f03fd957SAndreas Gohr
702f03fd957SAndreas Gohr    if ($safe && preg_match('#^[a-zA-Z0-9/_\-\.%]+$#', $file)) {
703f03fd957SAndreas Gohr        return $file;
704f03fd957SAndreas Gohr    }
705f03fd957SAndreas Gohr
706f03fd957SAndreas Gohr    if ($conf['fnencode'] == 'safe') {
707f03fd957SAndreas Gohr        return SafeFN::encode($file);
708f03fd957SAndreas Gohr    }
709f03fd957SAndreas Gohr
710f03fd957SAndreas Gohr    $file = urlencode($file);
711f03fd957SAndreas Gohr    $file = str_replace('%2F', '/', $file);
712f03fd957SAndreas Gohr    return $file;
713f03fd957SAndreas Gohr}
714f03fd957SAndreas Gohr
715f03fd957SAndreas Gohr/**
716f03fd957SAndreas Gohr * Decode a filename back to UTF-8
717f03fd957SAndreas Gohr *
718f03fd957SAndreas Gohr * Uses the 'fnencode' option to determine encoding
719f03fd957SAndreas Gohr *
720f03fd957SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
721f03fd957SAndreas Gohr * @see    urldecode
72284657ea2SGerrit Uitslag *
72384657ea2SGerrit Uitslag * @param string $file file name
72484657ea2SGerrit Uitslag * @return string
725f03fd957SAndreas Gohr */
726*a5752066Sjpedrycfunction utf8_decodeFN($file)
727*a5752066Sjpedryc{
728f03fd957SAndreas Gohr    global $conf;
729f03fd957SAndreas Gohr    if ($conf['fnencode'] == 'utf-8') return $file;
730f03fd957SAndreas Gohr
731f03fd957SAndreas Gohr    if ($conf['fnencode'] == 'safe') {
732f03fd957SAndreas Gohr        return SafeFN::decode($file);
733f03fd957SAndreas Gohr    }
734f03fd957SAndreas Gohr
735f03fd957SAndreas Gohr    return urldecode($file);
736f03fd957SAndreas Gohr}
737f03fd957SAndreas Gohr
738e66d3e6dSAndreas Gohr/**
739e66d3e6dSAndreas Gohr * Find a page in the current namespace (determined from $ID) or any
740cc529468SMichael Hamann * higher namespace that can be accessed by the current user,
741cc529468SMichael Hamann * this condition can be overriden by an optional parameter.
742e66d3e6dSAndreas Gohr *
743e66d3e6dSAndreas Gohr * Used for sidebars, but can be used other stuff as well
744e66d3e6dSAndreas Gohr *
745e66d3e6dSAndreas Gohr * @todo   add event hook
74642ea7f44SGerrit Uitslag *
747e66d3e6dSAndreas Gohr * @param  string $page the pagename you're looking for
7487c3e4a67SAndreas Gohr * @param bool $useacl only return pages readable by the current user, false to ignore ACLs
749cc529468SMichael Hamann * @return false|string the full page id of the found page, false if any
750e66d3e6dSAndreas Gohr */
751*a5752066Sjpedrycfunction page_findnearest($page, $useacl = true)
752*a5752066Sjpedryc{
75306a70133SPhy    if ((string) $page === '') return false;
754e66d3e6dSAndreas Gohr    global $ID;
755e66d3e6dSAndreas Gohr
756e66d3e6dSAndreas Gohr    $ns = $ID;
757e66d3e6dSAndreas Gohr    do {
758e66d3e6dSAndreas Gohr        $ns = getNS($ns);
759cc529468SMichael Hamann        $pageid = cleanID("$ns:$page");
7607c3e4a67SAndreas Gohr        if (page_exists($pageid) && (!$useacl || auth_quickaclcheck($pageid) >= AUTH_READ)) {
761e66d3e6dSAndreas Gohr            return $pageid;
762e66d3e6dSAndreas Gohr        }
76306a70133SPhy    } while ($ns !== false);
764e66d3e6dSAndreas Gohr
765e66d3e6dSAndreas Gohr    return false;
766e66d3e6dSAndreas Gohr}
767