xref: /dokuwiki/inc/pageutils.php (revision d4f83172d9533c4d84f450fe22ef630816b21d75)
1b625487dSandi<?php
2a5752066Sjpedryc
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 */
10*d4f83172SAndreas Gohr
1124870174SAndreas Gohruse dokuwiki\Utf8\PhpString;
1224870174SAndreas Gohruse dokuwiki\Utf8\Clean;
1324870174SAndreas Gohruse dokuwiki\File\Resolver;
1424870174SAndreas Gohruse dokuwiki\Extension\Event;
150c3a5702SAndreas Gohruse dokuwiki\ChangeLog\MediaChangeLog;
160c3a5702SAndreas Gohruse dokuwiki\ChangeLog\PageChangeLog;
172cd6cc0aSAndreas Gohruse dokuwiki\File\MediaResolver;
182cd6cc0aSAndreas Gohruse dokuwiki\File\PageResolver;
190c3a5702SAndreas Gohr
206c7843b5Sandi/**
216de3759aSAndreas Gohr * Fetch the an ID from request
226c7843b5Sandi *
236c7843b5Sandi * Uses either standard $_REQUEST variable or extracts it from
246c7843b5Sandi * the full request URI when userewrite is set to 2
256c7843b5Sandi *
2642905504SAndreas Gohr * For $param='id' $conf['start'] is returned if no id was found.
2742905504SAndreas Gohr * If the second parameter is true (default) the ID is cleaned.
286c7843b5Sandi *
296c7843b5Sandi * @author Andreas Gohr <andi@splitbrain.org>
3084657ea2SGerrit Uitslag *
3184657ea2SGerrit Uitslag * @param string $param  the $_REQUEST variable name, default 'id'
3284657ea2SGerrit Uitslag * @param bool   $clean  if true, ID is cleaned
3342ea7f44SGerrit Uitslag * @return string
346c7843b5Sandi */
35a5752066Sjpedrycfunction getID($param = 'id', $clean = true)
36a5752066Sjpedryc{
37585bf44eSChristopher Smith    /** @var Input $INPUT */
387d01a0eaSTom N Harris    global $INPUT;
396c7843b5Sandi    global $conf;
404e90caaaSMichael Hamann    global $ACT;
416c7843b5Sandi
427d01a0eaSTom N Harris    $id = $INPUT->str($param);
4348665d38SAndreas Gohr
446c7843b5Sandi    //construct page id from request URI
456c7843b5Sandi    if (empty($id) && $conf['userewrite'] == 2) {
46585bf44eSChristopher Smith        $request = $INPUT->server->str('REQUEST_URI');
4706368e4dSMichael Hamann        $script = '';
4806368e4dSMichael Hamann
496c7843b5Sandi        //get the script URL
506c7843b5Sandi        if ($conf['basedir']) {
5181124000Sjan            $relpath = '';
5281124000Sjan            if ($param != 'id') {
5381124000Sjan                $relpath = 'lib/exe/';
5481124000Sjan            }
556ce3e5f8SAndreas Gohr            $script = $conf['basedir'] . $relpath .
5624870174SAndreas Gohr                PhpString::basename($INPUT->server->str('SCRIPT_FILENAME'));
57585bf44eSChristopher Smith        } elseif ($INPUT->server->str('PATH_INFO')) {
58585bf44eSChristopher Smith            $request = $INPUT->server->str('PATH_INFO');
59585bf44eSChristopher Smith        } elseif ($INPUT->server->str('SCRIPT_NAME')) {
60585bf44eSChristopher Smith            $script = $INPUT->server->str('SCRIPT_NAME');
61585bf44eSChristopher Smith        } elseif ($INPUT->server->str('DOCUMENT_ROOT') && $INPUT->server->str('SCRIPT_FILENAME')) {
62a5752066Sjpedryc            $script = preg_replace(
63a5752066Sjpedryc                '/^' . preg_quote($INPUT->server->str('DOCUMENT_ROOT'), '/') . '/',
64a5752066Sjpedryc                '',
65a5752066Sjpedryc                $INPUT->server->str('SCRIPT_FILENAME')
66a5752066Sjpedryc            );
676c7843b5Sandi            $script = '/' . $script;
686c7843b5Sandi        }
696c7843b5Sandi
7052339126Sandi        //clean script and request (fixes a windows problem)
7152339126Sandi        $script  = preg_replace('/\/\/+/', '/', $script);
727d71d4b7SAndreas Gohr        $request = preg_replace('/\/\/+/', '/', $request);
7352339126Sandi
746c7843b5Sandi        //remove script URL and Querystring to gain the id
7552339126Sandi        if (preg_match('/^' . preg_quote($script, '/') . '(.*)/', $request, $match)) {
766c7843b5Sandi            $id = preg_replace('/\?.*/', '', $match[1]);
776c7843b5Sandi        }
786de3759aSAndreas Gohr        $id = urldecode($id);
7942905504SAndreas Gohr        //strip leading slashes
8042905504SAndreas Gohr        $id = preg_replace('!^/+!', '', $id);
816c7843b5Sandi    }
82671a58a6SGuy Brand
83671a58a6SGuy Brand    // Namespace autolinking from URL
84b6084253SAndreas Gohr    if (substr($id, -1) == ':' || ($conf['useslash'] && substr($id, -1) == '/')) {
85103c256aSChris Smith        if (page_exists($id . $conf['start'])) {
86671a58a6SGuy Brand            // start page inside namespace
8724870174SAndreas Gohr            $id .= $conf['start'];
88103c256aSChris Smith        } elseif (page_exists($id . noNS(cleanID($id)))) {
89671a58a6SGuy Brand            // page named like the NS inside the NS
9024870174SAndreas Gohr            $id .= noNS(cleanID($id));
91103c256aSChris Smith        } elseif (page_exists($id)) {
92671a58a6SGuy Brand            // page like namespace exists
937a42ac9eSBen Coburn            $id = substr($id, 0, -1);
94671a58a6SGuy Brand        } else {
95671a58a6SGuy Brand            // fall back to default
9624870174SAndreas Gohr            $id .= $conf['start'];
97671a58a6SGuy Brand        }
989dc53973SMichael Grosse        if (isset($ACT) && $ACT === 'show') {
999dc53973SMichael Grosse            $urlParameters = $_GET;
100e380abb2SMichael Grosse            if (isset($urlParameters['id'])) {
101e380abb2SMichael Grosse                unset($urlParameters['id']);
102e380abb2SMichael Grosse            }
103e9fede20SPhy            send_redirect(wl($id, $urlParameters, true, '&'));
1049dc53973SMichael Grosse        }
105671a58a6SGuy Brand    }
10642905504SAndreas Gohr    if ($clean) $id = cleanID($id);
10740b5fb5bSPhy    if ($id === '' && $param == 'id') $id = $conf['start'];
1086c7843b5Sandi
1096c7843b5Sandi    return $id;
1106c7843b5Sandi}
111b625487dSandi
112b625487dSandi/**
113b625487dSandi * Remove unwanted chars from ID
114b625487dSandi *
115b625487dSandi * Cleans a given ID to only use allowed characters. Accented characters are
116b625487dSandi * converted to unaccented ones
117b625487dSandi *
118b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
11942ea7f44SGerrit Uitslag *
1206e0cc83aSchris * @param  string  $raw_id    The pageid to clean
1218a831f2bSAndreas Gohr * @param  boolean $ascii     Force ASCII
122dbf714f7SGerrit Uitslag * @return string cleaned id
123b625487dSandi */
124a5752066Sjpedrycfunction cleanID($raw_id, $ascii = false)
125a5752066Sjpedryc{
126b625487dSandi    global $conf;
1274b5db43bSjoe.lapp    static $sepcharpat = null;
1284b5db43bSjoe.lapp
129dc2c0e04Schris    global $cache_cleanid;
130dc2c0e04Schris    $cache = & $cache_cleanid;
1316e0cc83aSchris
1326e0cc83aSchris    // check if it's already in the memory cache
13330f3bd15SMichael Grosse    if (!$ascii && isset($cache[(string)$raw_id])) {
1343a50618cSgweissbach        return $cache[(string)$raw_id];
1356e0cc83aSchris    }
1366e0cc83aSchris
1374b5db43bSjoe.lapp    $sepchar = $conf['sepchar'];
1384b5db43bSjoe.lapp    if ($sepcharpat == null) // build string only once to save clock cycles
1394b5db43bSjoe.lapp        $sepcharpat = '#\\' . $sepchar . '+#';
1404b5db43bSjoe.lapp
1413a50618cSgweissbach    $id = trim((string)$raw_id);
14224870174SAndreas Gohr    $id = PhpString::strtolower($id);
143b625487dSandi
144b625487dSandi    //alternative namespace seperator
145b625487dSandi    if ($conf['useslash']) {
1463755fc25STom N Harris        $id = strtr($id, ';/', '::');
147b625487dSandi    } else {
1483755fc25STom N Harris        $id = strtr($id, ';/', ':' . $sepchar);
149b625487dSandi    }
150b625487dSandi
15124870174SAndreas Gohr    if ($conf['deaccent'] == 2 || $ascii) $id = Clean::romanize($id);
15224870174SAndreas Gohr    if ($conf['deaccent'] || $ascii) $id = Clean::deaccent($id, -1);
153b625487dSandi
154b625487dSandi    //remove specials
15524870174SAndreas Gohr    $id = Clean::stripspecials($id, $sepchar, '\*');
156b625487dSandi
15724870174SAndreas Gohr    if ($ascii) $id = Clean::strip($id);
1588a831f2bSAndreas Gohr
159b625487dSandi    //clean up
1604b5db43bSjoe.lapp    $id = preg_replace($sepcharpat, $sepchar, $id);
161b625487dSandi    $id = preg_replace('#:+#', ':', $id);
1623543c6deSAndreas Gohr    $id = trim($id, ':._-');
163b625487dSandi    $id = preg_replace('#:[:\._\-]+#', ':', $id);
164b680ea06SAndreas Gohr    $id = preg_replace('#[:\._\-]+:#', ':', $id);
165b625487dSandi
16630f3bd15SMichael Grosse    if (!$ascii) $cache[(string)$raw_id] = $id;
167b625487dSandi    return($id);
168b625487dSandi}
169b625487dSandi
170b625487dSandi/**
171b625487dSandi * Return namespacepart of a wiki ID
172b625487dSandi *
173b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
17415851b98SGerrit Uitslag *
17515851b98SGerrit Uitslag * @param string $id
17642ea7f44SGerrit Uitslag * @return string|false the namespace part or false if the given ID has no namespace (root)
177b625487dSandi */
178a5752066Sjpedrycfunction getNS($id)
179a5752066Sjpedryc{
1803a50618cSgweissbach    $pos = strrpos((string)$id, ':');
181c4e0e4a1SAndreas Gohr    if ($pos !== false) {
1823a50618cSgweissbach        return substr((string)$id, 0, $pos);
183b625487dSandi    }
184ef11fcfcSAndreas Gohr    return false;
185b625487dSandi}
186b625487dSandi
187b625487dSandi/**
188b625487dSandi * Returns the ID without the namespace
189b625487dSandi *
190b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
19115851b98SGerrit Uitslag *
19215851b98SGerrit Uitslag * @param string $id
19315851b98SGerrit Uitslag * @return string
194b625487dSandi */
195a5752066Sjpedrycfunction noNS($id)
196a5752066Sjpedryc{
1972844584fSBen Coburn    $pos = strrpos($id, ':');
1982844584fSBen Coburn    if ($pos !== false) {
1992844584fSBen Coburn        return substr($id, $pos + 1);
2002844584fSBen Coburn    } else {
2012844584fSBen Coburn        return $id;
2022844584fSBen Coburn    }
2031a84a0f3SAnika Henke}
2041a84a0f3SAnika Henke
2051a84a0f3SAnika Henke/**
2061a84a0f3SAnika Henke * Returns the current namespace
2071a84a0f3SAnika Henke *
2081a84a0f3SAnika Henke * @author Nathan Fritz <fritzn@crown.edu>
20984657ea2SGerrit Uitslag *
21084657ea2SGerrit Uitslag * @param string $id
21184657ea2SGerrit Uitslag * @return string
2121a84a0f3SAnika Henke */
213a5752066Sjpedrycfunction curNS($id)
214a5752066Sjpedryc{
2151a84a0f3SAnika Henke    return noNS(getNS($id));
2161a84a0f3SAnika Henke}
2171a84a0f3SAnika Henke
2181a84a0f3SAnika Henke/**
2191a84a0f3SAnika Henke * Returns the ID without the namespace or current namespace for 'start' pages
2201a84a0f3SAnika Henke *
2211a84a0f3SAnika Henke * @author Nathan Fritz <fritzn@crown.edu>
22284657ea2SGerrit Uitslag *
22384657ea2SGerrit Uitslag * @param string $id
22484657ea2SGerrit Uitslag * @return string
2251a84a0f3SAnika Henke */
226a5752066Sjpedrycfunction noNSorNS($id)
227a5752066Sjpedryc{
2281a84a0f3SAnika Henke    global $conf;
2291a84a0f3SAnika Henke
2301a84a0f3SAnika Henke    $p = noNS($id);
231c077d4dcSAndreas Gohr    if ($p === $conf['start'] || $p === false || $p === '') {
2321a84a0f3SAnika Henke        $p = curNS($id);
233c077d4dcSAndreas Gohr        if ($p === false || $p === '') {
2349708106bSAdrian Lang            return $conf['start'];
2351a84a0f3SAnika Henke        }
2361a84a0f3SAnika Henke    }
2371a84a0f3SAnika Henke    return $p;
238b625487dSandi}
2394ceab83fSAndreas Gohr
2404ceab83fSAndreas Gohr/**
2414ceab83fSAndreas Gohr * Creates a XHTML valid linkid from a given headline title
2424ceab83fSAndreas Gohr *
2434ceab83fSAndreas Gohr * @param string  $title   The headline title
2444f582736SGuillaume Turri * @param array|bool   $check   Existing IDs
245c857afe0SMichael Hamann * @return string the title
24684657ea2SGerrit Uitslag *
2474ceab83fSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
2484ceab83fSAndreas Gohr */
249a5752066Sjpedrycfunction sectionID($title, &$check)
250a5752066Sjpedryc{
25124870174SAndreas Gohr    $title = str_replace([':', '.'], '', cleanID($title));
252de9114eaSAnika Henke    $new = ltrim($title, '0123456789_-');
2534ceab83fSAndreas Gohr    if (empty($new)) {
2544ceab83fSAndreas Gohr        $title = 'section' . preg_replace('/[^0-9]+/', '', $title); //keep numbers from headline
2554ceab83fSAndreas Gohr    } else {
2564ceab83fSAndreas Gohr        $title = $new;
2574ceab83fSAndreas Gohr    }
2584ceab83fSAndreas Gohr
259443d207bSAndreas Gohr    if (is_array($check)) {
2604f582736SGuillaume Turri        $suffix = 0;
2614f582736SGuillaume Turri        $candidateTitle = $title;
2624f582736SGuillaume Turri        while (in_array($candidateTitle, $check)) {
2634f582736SGuillaume Turri            $candidateTitle = $title . ++$suffix;
2644f582736SGuillaume Turri        }
2654f582736SGuillaume Turri        $check [] = $candidateTitle;
2664f582736SGuillaume Turri        return $candidateTitle;
26701e3159cSChris Tapp    } else {
2684ceab83fSAndreas Gohr        return $title;
2694ceab83fSAndreas Gohr    }
2704f582736SGuillaume Turri}
2714ceab83fSAndreas Gohr
272b625487dSandi/**
273103c256aSChris Smith * Wiki page existence check
274103c256aSChris Smith *
275103c256aSChris Smith * parameters as for wikiFN
276103c256aSChris Smith *
277103c256aSChris Smith * @author Chris Smith <chris@jalakai.co.uk>
27884657ea2SGerrit Uitslag *
27984657ea2SGerrit Uitslag * @param string $id page id
28084657ea2SGerrit Uitslag * @param string|int $rev empty or revision timestamp
28184657ea2SGerrit Uitslag * @param bool $clean flag indicating that $id should be cleaned (see wikiFN as well)
2827de86af9SGerrit Uitslag * @param bool $date_at
28384657ea2SGerrit Uitslag * @return bool exists?
284103c256aSChris Smith */
285a5752066Sjpedrycfunction page_exists($id, $rev = '', $clean = true, $date_at = false)
286a5752066Sjpedryc{
28792085f13SAndreas Gohr    $id = (explode('#', $id, 2))[0]; // #3608
28892085f13SAndreas Gohr
28990bee600Slisps    if ($rev !== '' && $date_at) {
2901d053a56Slisps        $pagelog = new PageChangeLog($id);
29190bee600Slisps        $pagelog_rev = $pagelog->getLastRevisionAt($rev);
29290bee600Slisps        if ($pagelog_rev !== false)
29390bee600Slisps            $rev = $pagelog_rev;
29490bee600Slisps    }
29579e79377SAndreas Gohr    return file_exists(wikiFN($id, $rev, $clean));
296103c256aSChris Smith}
297103c256aSChris Smith
298103c256aSChris Smith/**
2995c844bb3SAndreas Gohr * Media existence check
3005c844bb3SAndreas Gohr *
3015c844bb3SAndreas Gohr * @param string $id page id
3025c844bb3SAndreas Gohr * @param string|int $rev empty or revision timestamp
3035c844bb3SAndreas Gohr * @param bool $clean flag indicating that $id should be cleaned (see mediaFN as well)
3045c844bb3SAndreas Gohr * @param bool $date_at
3055c844bb3SAndreas Gohr * @return bool exists?
3065c844bb3SAndreas Gohr */
3075c844bb3SAndreas Gohrfunction media_exists($id, $rev = '', $clean = true, $date_at = false)
3085c844bb3SAndreas Gohr{
3095c844bb3SAndreas Gohr    if ($rev !== '' && $date_at) {
3105c844bb3SAndreas Gohr        $changeLog = new MediaChangeLog($id);
3115c844bb3SAndreas Gohr        $changelog_rev = $changeLog->getLastRevisionAt($rev);
3125c844bb3SAndreas Gohr        if ($changelog_rev !== false) {
3135c844bb3SAndreas Gohr            $rev = $changelog_rev;
3145c844bb3SAndreas Gohr        }
3155c844bb3SAndreas Gohr    }
3165c844bb3SAndreas Gohr    return file_exists(mediaFN($id, $rev, $clean));
3175c844bb3SAndreas Gohr}
3185c844bb3SAndreas Gohr
3195c844bb3SAndreas Gohr/**
320103c256aSChris Smith * returns the full path to the datafile specified by ID and optional revision
321b625487dSandi *
322b625487dSandi * The filename is URL encoded to protect Unicode chars
323b625487dSandi *
324103c256aSChris Smith * @param  $raw_id  string   id of wikipage
325e0c26282SGerrit Uitslag * @param  $rev     int|string   page revision, empty string for current
326103c256aSChris Smith * @param  $clean   bool     flag indicating that $raw_id should be cleaned.  Only set to false
327103c256aSChris Smith *                           when $id is guaranteed to have been cleaned already.
328dbf714f7SGerrit Uitslag * @return string full path
329103c256aSChris Smith *
330b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
331b625487dSandi */
332a5752066Sjpedrycfunction wikiFN($raw_id, $rev = '', $clean = true)
333a5752066Sjpedryc{
334b625487dSandi    global $conf;
3356e0cc83aSchris
336dc2c0e04Schris    global $cache_wikifn;
337dc2c0e04Schris    $cache = & $cache_wikifn;
338dc2c0e04Schris
3396e0cc83aSchris    $id = $raw_id;
3406e0cc83aSchris
3410d8ea614Schris    if ($clean) $id = cleanID($id);
342b625487dSandi    $id = str_replace(':', '/', $id);
343b018ecbeSMichael Grosse
344b018ecbeSMichael Grosse    if (isset($cache[$id]) && isset($cache[$id][$rev])) {
345b018ecbeSMichael Grosse        return $cache[$id][$rev];
346b018ecbeSMichael Grosse    }
347b018ecbeSMichael Grosse
348b625487dSandi    if (empty($rev)) {
349b625487dSandi        $fn = $conf['datadir'] . '/' . utf8_encodeFN($id) . '.txt';
350b625487dSandi    } else {
351b625487dSandi        $fn = $conf['olddir'] . '/' . utf8_encodeFN($id) . '.' . $rev . '.txt';
352ff3ed99fSmarcel        if ($conf['compression']) {
353ff3ed99fSmarcel            //test for extensions here, we want to read both compressions
35479e79377SAndreas Gohr            if (file_exists($fn . '.gz')) {
355b625487dSandi                $fn .= '.gz';
35679e79377SAndreas Gohr            } elseif (file_exists($fn . '.bz2')) {
357ff3ed99fSmarcel                $fn .= '.bz2';
358ff3ed99fSmarcel            } else {
359ff3ed99fSmarcel                //file doesnt exist yet, so we take the configured extension
360ff3ed99fSmarcel                $fn .= '.' . $conf['compression'];
361ff3ed99fSmarcel            }
362b625487dSandi        }
363b625487dSandi    }
3646e0cc83aSchris
365a5752066Sjpedryc    if (!isset($cache[$id])) {
36624870174SAndreas Gohr        $cache[$id] = [];
367a5752066Sjpedryc    }
368b018ecbeSMichael Grosse    $cache[$id][$rev] = $fn;
369b625487dSandi    return $fn;
370b625487dSandi}
371b625487dSandi
372b625487dSandi/**
373c9b4bd1eSBen Coburn * Returns the full path to the file for locking the page while editing.
374c9b4bd1eSBen Coburn *
375c9b4bd1eSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
37684657ea2SGerrit Uitslag *
37784657ea2SGerrit Uitslag * @param string $id page id
37884657ea2SGerrit Uitslag * @return string full path
379c9b4bd1eSBen Coburn */
380a5752066Sjpedrycfunction wikiLockFN($id)
381a5752066Sjpedryc{
382c9b4bd1eSBen Coburn    global $conf;
383662ff478SAndreas Gohr    return $conf['lockdir'] . '/' . md5(cleanID($id)) . '.lock';
384c9b4bd1eSBen Coburn}
385c9b4bd1eSBen Coburn
386c9b4bd1eSBen Coburn
387c9b4bd1eSBen Coburn/**
3881380fc45SAndreas Gohr * returns the full path to the meta file specified by ID and extension
389b158d625SSteven Danz *
390b158d625SSteven Danz * @author Steven Danz <steven-danz@kc.rr.com>
39184657ea2SGerrit Uitslag *
39284657ea2SGerrit Uitslag * @param string $id   page id
39384657ea2SGerrit Uitslag * @param string $ext  file extension
39484657ea2SGerrit Uitslag * @return string full path
395b158d625SSteven Danz */
396a5752066Sjpedrycfunction metaFN($id, $ext)
397a5752066Sjpedryc{
398b158d625SSteven Danz    global $conf;
399b158d625SSteven Danz    $id = cleanID($id);
400b158d625SSteven Danz    $id = str_replace(':', '/', $id);
40124870174SAndreas Gohr
4021380fc45SAndreas Gohr    $fn = $conf['metadir'] . '/' . utf8_encodeFN($id) . $ext;
403b158d625SSteven Danz    return $fn;
404b158d625SSteven Danz}
405b158d625SSteven Danz
406b158d625SSteven Danz/**
407e4f389efSKate Arzamastseva * returns the full path to the media's meta file specified by ID and extension
408e4f389efSKate Arzamastseva *
409cbe26ad6SKate Arzamastseva * @author Kate Arzamastseva <pshns@ukr.net>
41084657ea2SGerrit Uitslag *
41184657ea2SGerrit Uitslag * @param string $id   media id
41284657ea2SGerrit Uitslag * @param string $ext  extension of media
41384657ea2SGerrit Uitslag * @return string
414e4f389efSKate Arzamastseva */
415a5752066Sjpedrycfunction mediaMetaFN($id, $ext)
416a5752066Sjpedryc{
417e4f389efSKate Arzamastseva    global $conf;
418e4f389efSKate Arzamastseva    $id = cleanID($id);
419e4f389efSKate Arzamastseva    $id = str_replace(':', '/', $id);
42024870174SAndreas Gohr
421e4f389efSKate Arzamastseva    $fn = $conf['mediametadir'] . '/' . utf8_encodeFN($id) . $ext;
422e4f389efSKate Arzamastseva    return $fn;
423e4f389efSKate Arzamastseva}
424e4f389efSKate Arzamastseva
425e4f389efSKate Arzamastseva/**
426e1f3d9e1SEsther Brunner * returns an array of full paths to all metafiles of a given ID
427e1f3d9e1SEsther Brunner *
428e1f3d9e1SEsther Brunner * @author Esther Brunner <esther@kaffeehaus.ch>
429ba0267b3SMichael Hamann * @author Michael Hamann <michael@content-space.de>
43084657ea2SGerrit Uitslag *
43184657ea2SGerrit Uitslag * @param string $id page id
43284657ea2SGerrit Uitslag * @return array
433e1f3d9e1SEsther Brunner */
434a5752066Sjpedrycfunction metaFiles($id)
435a5752066Sjpedryc{
436ba0267b3SMichael Hamann    $basename = metaFN($id, '');
437ba0267b3SMichael Hamann    $files    = glob($basename . '.*', GLOB_MARK);
438ba0267b3SMichael Hamann    // filter files like foo.bar.meta when $id == 'foo'
43924870174SAndreas Gohr    return    $files ? preg_grep('/^' . preg_quote($basename, '/') . '\.[^.\/]*$/u', $files) : [];
440e1f3d9e1SEsther Brunner}
441e1f3d9e1SEsther Brunner
442e1f3d9e1SEsther Brunner/**
443b625487dSandi * returns the full path to the mediafile specified by ID
444b625487dSandi *
445b625487dSandi * The filename is URL encoded to protect Unicode chars
446b625487dSandi *
447b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
448cbe26ad6SKate Arzamastseva * @author Kate Arzamastseva <pshns@ukr.net>
44984657ea2SGerrit Uitslag *
45084657ea2SGerrit Uitslag * @param string     $id  media id
45184657ea2SGerrit Uitslag * @param string|int $rev empty string or revision timestamp
452f50a239bSTakamura * @param bool $clean
453f50a239bSTakamura *
45484657ea2SGerrit Uitslag * @return string full path
455b625487dSandi */
456a5752066Sjpedrycfunction mediaFN($id, $rev = '', $clean = true)
457a5752066Sjpedryc{
458b625487dSandi    global $conf;
459d0e997c6SMichael Große    if ($clean) $id = cleanID($id);
460b625487dSandi    $id = str_replace(':', '/', $id);
461e4f389efSKate Arzamastseva    if (empty($rev)) {
462b625487dSandi        $fn = $conf['mediadir'] . '/' . utf8_encodeFN($id);
463e4f389efSKate Arzamastseva    } else {
464cbe26ad6SKate Arzamastseva        $ext = mimetype($id);
4658e69fd30SKate Arzamastseva        $name = substr($id, 0, -1 * strlen($ext[0]) - 1);
46661f1aad8SKate Arzamastseva        $fn = $conf['mediaolddir'] . '/' . utf8_encodeFN($name . '.' . ( (int) $rev ) . '.' . $ext[0]);
467e4f389efSKate Arzamastseva    }
468b625487dSandi    return $fn;
469b625487dSandi}
470b625487dSandi
471b625487dSandi/**
4722adaf2b8SAndreas Gohr * Returns the full filepath to a localized file if local
473b625487dSandi * version isn't found the english one is returned
474b625487dSandi *
4752adaf2b8SAndreas Gohr * @param  string $id  The id of the local file
4762adaf2b8SAndreas Gohr * @param  string $ext The file extension (usually txt)
477dbf714f7SGerrit Uitslag * @return string full filepath to localized file
47884657ea2SGerrit Uitslag *
479b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
480b625487dSandi */
481a5752066Sjpedrycfunction localeFN($id, $ext = 'txt')
482a5752066Sjpedryc{
483b625487dSandi    global $conf;
4848819fbf5ShArpanet    $file = DOKU_CONF . 'lang/' . $conf['lang'] . '/' . $id . '.' . $ext;
48579e79377SAndreas Gohr    if (!file_exists($file)) {
4862adaf2b8SAndreas Gohr        $file = DOKU_INC . 'inc/lang/' . $conf['lang'] . '/' . $id . '.' . $ext;
48779e79377SAndreas Gohr        if (!file_exists($file)) {
488b625487dSandi            //fall back to english
4892adaf2b8SAndreas Gohr            $file = DOKU_INC . 'inc/lang/en/' . $id . '.' . $ext;
490b625487dSandi        }
491e6cecb08SMichael Hamann    }
492b625487dSandi    return $file;
493b625487dSandi}
494b625487dSandi
495b625487dSandi/**
496c4e0e4a1SAndreas Gohr * Resolve relative paths in IDs
497c4e0e4a1SAndreas Gohr *
498c4e0e4a1SAndreas Gohr * Do not call directly use resolve_mediaid or resolve_pageid
499c4e0e4a1SAndreas Gohr * instead
500c4e0e4a1SAndreas Gohr *
501c4e0e4a1SAndreas Gohr * Partyly based on a cleanPath function found at
50259752844SAnders Sandblad * http://php.net/manual/en/function.realpath.php#57016
503c4e0e4a1SAndreas Gohr *
504bfcf8009SAndreas Gohr * @deprecated 2020-09-30
50584657ea2SGerrit Uitslag * @param string $ns     namespace which is context of id
50684657ea2SGerrit Uitslag * @param string $id     relative id
50784657ea2SGerrit Uitslag * @param bool   $clean  flag indicating that id should be cleaned
50842ea7f44SGerrit Uitslag * @return string
509c4e0e4a1SAndreas Gohr */
510a5752066Sjpedrycfunction resolve_id($ns, $id, $clean = true)
511a5752066Sjpedryc{
512c662a49aSAndreas Gohr    global $conf;
51324870174SAndreas Gohr    dbg_deprecated(Resolver::class . ' and its children');
514c662a49aSAndreas Gohr
515c662a49aSAndreas Gohr    // some pre cleaning for useslash:
516c662a49aSAndreas Gohr    if ($conf['useslash']) $id = str_replace('/', ':', $id);
517c662a49aSAndreas Gohr
518c4e0e4a1SAndreas Gohr    // if the id starts with a dot we need to handle the
519c4e0e4a1SAndreas Gohr    // relative stuff
5202401f18dSSyntaxseed    if ($id && $id[0] == '.') {
521c4e0e4a1SAndreas Gohr        // normalize initial dots without a colon
5224986a584SPhy        $id = preg_replace('/^((\.+:)*)(\.+)(?=[^:\.])/', '\1\3:', $id);
523c4e0e4a1SAndreas Gohr        // prepend the current namespace
524c4e0e4a1SAndreas Gohr        $id = $ns . ':' . $id;
525c4e0e4a1SAndreas Gohr
526c4e0e4a1SAndreas Gohr        // cleanup relatives
52724870174SAndreas Gohr        $result = [];
528c4e0e4a1SAndreas Gohr        $pathA  = explode(':', $id);
529c4e0e4a1SAndreas Gohr        if (!$pathA[0]) $result[] = '';
53024870174SAndreas Gohr        foreach ($pathA as $dir) {
531c4e0e4a1SAndreas Gohr            if ($dir == '..') {
532c4e0e4a1SAndreas Gohr                if (end($result) == '..') {
533c4e0e4a1SAndreas Gohr                    $result[] = '..';
534c4e0e4a1SAndreas Gohr                } elseif (!array_pop($result)) {
535c4e0e4a1SAndreas Gohr                    $result[] = '..';
536c4e0e4a1SAndreas Gohr                }
537c4e0e4a1SAndreas Gohr            } elseif ($dir && $dir != '.') {
538c4e0e4a1SAndreas Gohr                $result[] = $dir;
539c4e0e4a1SAndreas Gohr            }
540c4e0e4a1SAndreas Gohr        }
541c4e0e4a1SAndreas Gohr        if (!end($pathA)) $result[] = '';
542c4e0e4a1SAndreas Gohr        $id = implode(':', $result);
543c4e0e4a1SAndreas Gohr    } elseif ($ns !== false && strpos($id, ':') === false) {
544c4e0e4a1SAndreas Gohr        //if link contains no namespace. add current namespace (if any)
545c4e0e4a1SAndreas Gohr        $id = $ns . ':' . $id;
546c4e0e4a1SAndreas Gohr    }
547c4e0e4a1SAndreas Gohr
548a6ef4796SAndreas Gohr    if ($clean) $id = cleanID($id);
549a6ef4796SAndreas Gohr    return $id;
550c4e0e4a1SAndreas Gohr}
551c4e0e4a1SAndreas Gohr
552c4e0e4a1SAndreas Gohr/**
553b625487dSandi * Returns a full media id
554b625487dSandi *
55584657ea2SGerrit Uitslag * @param string $ns namespace which is context of id
5565c844bb3SAndreas Gohr * @param string &$media (reference) relative media id, updated to resolved id
55784657ea2SGerrit Uitslag * @param bool &$exists (reference) updated with existance of media
5587de86af9SGerrit Uitslag * @param int|string $rev
5597de86af9SGerrit Uitslag * @param bool $date_at
5605c844bb3SAndreas Gohr * @deprecated 2020-09-30
561b625487dSandi */
562a5752066Sjpedrycfunction resolve_mediaid($ns, &$media, &$exists, $rev = '', $date_at = false)
563a5752066Sjpedryc{
5645c844bb3SAndreas Gohr    dbg_deprecated(MediaResolver::class);
5655c844bb3SAndreas Gohr    $resolver = new MediaResolver("$ns:deprecated");
5665c844bb3SAndreas Gohr    $media = $resolver->resolveId($media, $rev, $date_at);
5675c844bb3SAndreas Gohr    $exists = media_exists($media, $rev, false, $date_at);
568b625487dSandi}
569b625487dSandi
570b625487dSandi/**
571b625487dSandi * Returns a full page id
572b625487dSandi *
573bfcf8009SAndreas Gohr * @deprecated 2020-09-30
57484657ea2SGerrit Uitslag * @param string $ns namespace which is context of id
57584657ea2SGerrit Uitslag * @param string &$page (reference) relative page id, updated to resolved id
57684657ea2SGerrit Uitslag * @param bool &$exists (reference) updated with existance of media
5777de86af9SGerrit Uitslag * @param string $rev
5787de86af9SGerrit Uitslag * @param bool $date_at
579b625487dSandi */
580bfcf8009SAndreas Gohrfunction resolve_pageid($ns, &$page, &$exists, $rev = '', $date_at = false)
581bfcf8009SAndreas Gohr{
5828c6be208SAndreas Gohr    dbg_deprecated(PageResolver::class);
58354611a7aSAndreas Gohr
58454611a7aSAndreas Gohr    global $ID;
58554611a7aSAndreas Gohr    if (getNS($ID) == $ns) {
58654611a7aSAndreas Gohr        $context = $ID; // this is usually the case
58754611a7aSAndreas Gohr    } else {
58854611a7aSAndreas Gohr        $context = "$ns:deprecated"; // only used when a different context namespace was given
58954611a7aSAndreas Gohr    }
59054611a7aSAndreas Gohr
59154611a7aSAndreas Gohr    $resolver = new PageResolver($context);
592bfcf8009SAndreas Gohr    $page = $resolver->resolveId($page, $rev, $date_at);
593bfcf8009SAndreas Gohr    $exists = page_exists($page, $rev, false, $date_at);
594b625487dSandi}
595b625487dSandi
59698407a7aSandi/**
59798407a7aSandi * Returns the name of a cachefile from given data
59898407a7aSandi *
59998407a7aSandi * The needed directory is created by this function!
60098407a7aSandi *
60198407a7aSandi * @author Andreas Gohr <andi@splitbrain.org>
60298407a7aSandi *
60398407a7aSandi * @param string $data  This data is used to create a unique md5 name
60498407a7aSandi * @param string $ext   This is appended to the filename if given
60598407a7aSandi * @return string       The filename of the cachefile
60698407a7aSandi */
607a5752066Sjpedrycfunction getCacheName($data, $ext = '')
608a5752066Sjpedryc{
60998407a7aSandi    global $conf;
61098407a7aSandi    $md5  = md5($data);
6112401f18dSSyntaxseed    $file = $conf['cachedir'] . '/' . $md5[0] . '/' . $md5 . $ext;
61298407a7aSandi    io_makeFileDir($file);
61398407a7aSandi    return $file;
61498407a7aSandi}
61598407a7aSandi
6160dc92c6fSAndreas Gohr/**
6170dc92c6fSAndreas Gohr * Checks a pageid against $conf['hidepages']
6180dc92c6fSAndreas Gohr *
6190dc92c6fSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
62084657ea2SGerrit Uitslag *
62184657ea2SGerrit Uitslag * @param string $id page id
62284657ea2SGerrit Uitslag * @return bool
6230dc92c6fSAndreas Gohr */
624a5752066Sjpedrycfunction isHiddenPage($id)
625a5752066Sjpedryc{
62624870174SAndreas Gohr    $data = ['id' => $id, 'hidden' => false];
62724870174SAndreas Gohr    Event::createAndTrigger('PAGEUTILS_ID_HIDEPAGE', $data, '_isHiddenPage');
628fb55b51eSDominik Eckelmann    return $data['hidden'];
6290dc92c6fSAndreas Gohr}
630fb55b51eSDominik Eckelmann
631dbf714f7SGerrit Uitslag/**
632dbf714f7SGerrit Uitslag * callback checks if page is hidden
633dbf714f7SGerrit Uitslag *
63484657ea2SGerrit Uitslag * @param array $data event data    - see isHiddenPage()
635dbf714f7SGerrit Uitslag */
636a5752066Sjpedrycfunction _isHiddenPage(&$data)
637a5752066Sjpedryc{
638fb55b51eSDominik Eckelmann    global $conf;
639fb55b51eSDominik Eckelmann    global $ACT;
640fb55b51eSDominik Eckelmann
641fb55b51eSDominik Eckelmann    if ($data['hidden']) return;
642fb55b51eSDominik Eckelmann    if (empty($conf['hidepages'])) return;
643fb55b51eSDominik Eckelmann    if ($ACT == 'admin') return;
644fb55b51eSDominik Eckelmann
645fb55b51eSDominik Eckelmann    if (preg_match('/' . $conf['hidepages'] . '/ui', ':' . $data['id'])) {
646fb55b51eSDominik Eckelmann        $data['hidden'] = true;
647fb55b51eSDominik Eckelmann    }
6480dc92c6fSAndreas Gohr}
6490dc92c6fSAndreas Gohr
6500dc92c6fSAndreas Gohr/**
6510dc92c6fSAndreas Gohr * Reverse of isHiddenPage
6520dc92c6fSAndreas Gohr *
6530dc92c6fSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
65484657ea2SGerrit Uitslag *
65584657ea2SGerrit Uitslag * @param string $id page id
65684657ea2SGerrit Uitslag * @return bool
6570dc92c6fSAndreas Gohr */
658a5752066Sjpedrycfunction isVisiblePage($id)
659a5752066Sjpedryc{
6600dc92c6fSAndreas Gohr    return !isHiddenPage($id);
6610dc92c6fSAndreas Gohr}
6620dc92c6fSAndreas Gohr
6635b75cd1fSAdrian Lang/**
6645b75cd1fSAdrian Lang * Format an id for output to a user
6655b75cd1fSAdrian Lang *
6665b75cd1fSAdrian Lang * Namespaces are denoted by a trailing “:*”. The root namespace is
6675b75cd1fSAdrian Lang * “*”. Output is escaped.
6685b75cd1fSAdrian Lang *
6695b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
67084657ea2SGerrit Uitslag *
67184657ea2SGerrit Uitslag * @param string $id page id
67284657ea2SGerrit Uitslag * @return string
6735b75cd1fSAdrian Lang */
674a5752066Sjpedrycfunction prettyprint_id($id)
675a5752066Sjpedryc{
6765b75cd1fSAdrian Lang    if (!$id || $id === ':') {
6775b75cd1fSAdrian Lang        return '*';
6785b75cd1fSAdrian Lang    }
6795b75cd1fSAdrian Lang    if ((substr($id, -1, 1) === ':')) {
6805b75cd1fSAdrian Lang        $id .= '*';
6815b75cd1fSAdrian Lang    }
6825b75cd1fSAdrian Lang    return hsc($id);
6835b75cd1fSAdrian Lang}
684f03fd957SAndreas Gohr
685f03fd957SAndreas Gohr/**
686f03fd957SAndreas Gohr * Encode a UTF-8 filename to use on any filesystem
687f03fd957SAndreas Gohr *
688f03fd957SAndreas Gohr * Uses the 'fnencode' option to determine encoding
689f03fd957SAndreas Gohr *
690f03fd957SAndreas Gohr * When the second parameter is true the string will
691f03fd957SAndreas Gohr * be encoded only if non ASCII characters are detected -
692f03fd957SAndreas Gohr * This makes it safe to run it multiple times on the
693f03fd957SAndreas Gohr * same string (default is true)
694f03fd957SAndreas Gohr *
695f03fd957SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
696f03fd957SAndreas Gohr * @see    urlencode
69784657ea2SGerrit Uitslag *
69884657ea2SGerrit Uitslag * @param string $file file name
69984657ea2SGerrit Uitslag * @param bool   $safe if true, only encoded when non ASCII characters detected
70084657ea2SGerrit Uitslag * @return string
701f03fd957SAndreas Gohr */
702a5752066Sjpedrycfunction utf8_encodeFN($file, $safe = true)
703a5752066Sjpedryc{
704f03fd957SAndreas Gohr    global $conf;
705f03fd957SAndreas Gohr    if ($conf['fnencode'] == 'utf-8') return $file;
706f03fd957SAndreas Gohr
707f03fd957SAndreas Gohr    if ($safe && preg_match('#^[a-zA-Z0-9/_\-\.%]+$#', $file)) {
708f03fd957SAndreas Gohr        return $file;
709f03fd957SAndreas Gohr    }
710f03fd957SAndreas Gohr
711f03fd957SAndreas Gohr    if ($conf['fnencode'] == 'safe') {
712f03fd957SAndreas Gohr        return SafeFN::encode($file);
713f03fd957SAndreas Gohr    }
714f03fd957SAndreas Gohr
715f03fd957SAndreas Gohr    $file = urlencode($file);
716f03fd957SAndreas Gohr    $file = str_replace('%2F', '/', $file);
717f03fd957SAndreas Gohr    return $file;
718f03fd957SAndreas Gohr}
719f03fd957SAndreas Gohr
720f03fd957SAndreas Gohr/**
721f03fd957SAndreas Gohr * Decode a filename back to UTF-8
722f03fd957SAndreas Gohr *
723f03fd957SAndreas Gohr * Uses the 'fnencode' option to determine encoding
724f03fd957SAndreas Gohr *
725f03fd957SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
726f03fd957SAndreas Gohr * @see    urldecode
72784657ea2SGerrit Uitslag *
72884657ea2SGerrit Uitslag * @param string $file file name
72984657ea2SGerrit Uitslag * @return string
730f03fd957SAndreas Gohr */
731a5752066Sjpedrycfunction utf8_decodeFN($file)
732a5752066Sjpedryc{
733f03fd957SAndreas Gohr    global $conf;
734f03fd957SAndreas Gohr    if ($conf['fnencode'] == 'utf-8') return $file;
735f03fd957SAndreas Gohr
736f03fd957SAndreas Gohr    if ($conf['fnencode'] == 'safe') {
737f03fd957SAndreas Gohr        return SafeFN::decode($file);
738f03fd957SAndreas Gohr    }
739f03fd957SAndreas Gohr
740f03fd957SAndreas Gohr    return urldecode($file);
741f03fd957SAndreas Gohr}
742f03fd957SAndreas Gohr
743e66d3e6dSAndreas Gohr/**
744e66d3e6dSAndreas Gohr * Find a page in the current namespace (determined from $ID) or any
745cc529468SMichael Hamann * higher namespace that can be accessed by the current user,
746cc529468SMichael Hamann * this condition can be overriden by an optional parameter.
747e66d3e6dSAndreas Gohr *
748e66d3e6dSAndreas Gohr * Used for sidebars, but can be used other stuff as well
749e66d3e6dSAndreas Gohr *
750e66d3e6dSAndreas Gohr * @todo   add event hook
75142ea7f44SGerrit Uitslag *
752e66d3e6dSAndreas Gohr * @param  string $page the pagename you're looking for
7537c3e4a67SAndreas Gohr * @param bool $useacl only return pages readable by the current user, false to ignore ACLs
754cc529468SMichael Hamann * @return false|string the full page id of the found page, false if any
755e66d3e6dSAndreas Gohr */
756a5752066Sjpedrycfunction page_findnearest($page, $useacl = true)
757a5752066Sjpedryc{
75806a70133SPhy    if ((string) $page === '') return false;
759e66d3e6dSAndreas Gohr    global $ID;
760e66d3e6dSAndreas Gohr
761e66d3e6dSAndreas Gohr    $ns = $ID;
762e66d3e6dSAndreas Gohr    do {
763e66d3e6dSAndreas Gohr        $ns = getNS($ns);
764cc529468SMichael Hamann        $pageid = cleanID("$ns:$page");
7657c3e4a67SAndreas Gohr        if (page_exists($pageid) && (!$useacl || auth_quickaclcheck($pageid) >= AUTH_READ)) {
766e66d3e6dSAndreas Gohr            return $pageid;
767e66d3e6dSAndreas Gohr        }
76806a70133SPhy    } while ($ns !== false);
769e66d3e6dSAndreas Gohr
770e66d3e6dSAndreas Gohr    return false;
771e66d3e6dSAndreas Gohr}
772