xref: /dokuwiki/inc/pageutils.php (revision 093fe67e98c0cdb4b73fd46938e49b64971483c2)
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 */
10d4f83172SAndreas 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
846c16a3a9Sfiwswe    if (str_ends_with($id, ':') || ($conf['useslash'] && str_ends_with($id, '/'))) {
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);
231*093fe67eSAndreas Gohr    if (in_array($p, [$conf['start'], false, ''], true)) {
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;
3402082444cSAndreas Gohr    $rev = (int) $rev; // any falsy rev will be rev 0 in the cache
3416e0cc83aSchris
3420d8ea614Schris    if ($clean) $id = cleanID($id);
343b625487dSandi    $id = str_replace(':', '/', $id);
344b018ecbeSMichael Grosse
345b018ecbeSMichael Grosse    if (isset($cache[$id]) && isset($cache[$id][$rev])) {
346b018ecbeSMichael Grosse        return $cache[$id][$rev];
347b018ecbeSMichael Grosse    }
348b018ecbeSMichael Grosse
349b625487dSandi    if (empty($rev)) {
350b625487dSandi        $fn = $conf['datadir'] . '/' . utf8_encodeFN($id) . '.txt';
351b625487dSandi    } else {
352b625487dSandi        $fn = $conf['olddir'] . '/' . utf8_encodeFN($id) . '.' . $rev . '.txt';
353ff3ed99fSmarcel        if ($conf['compression']) {
354ff3ed99fSmarcel            //test for extensions here, we want to read both compressions
35579e79377SAndreas Gohr            if (file_exists($fn . '.gz')) {
356b625487dSandi                $fn .= '.gz';
35779e79377SAndreas Gohr            } elseif (file_exists($fn . '.bz2')) {
358ff3ed99fSmarcel                $fn .= '.bz2';
359ff3ed99fSmarcel            } else {
360ff3ed99fSmarcel                //file doesnt exist yet, so we take the configured extension
361ff3ed99fSmarcel                $fn .= '.' . $conf['compression'];
362ff3ed99fSmarcel            }
363b625487dSandi        }
364b625487dSandi    }
3656e0cc83aSchris
366a5752066Sjpedryc    if (!isset($cache[$id])) {
36724870174SAndreas Gohr        $cache[$id] = [];
368a5752066Sjpedryc    }
369b018ecbeSMichael Grosse    $cache[$id][$rev] = $fn;
370b625487dSandi    return $fn;
371b625487dSandi}
372b625487dSandi
373b625487dSandi/**
374c9b4bd1eSBen Coburn * Returns the full path to the file for locking the page while editing.
375c9b4bd1eSBen Coburn *
376c9b4bd1eSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
37784657ea2SGerrit Uitslag *
37884657ea2SGerrit Uitslag * @param string $id page id
37984657ea2SGerrit Uitslag * @return string full path
380c9b4bd1eSBen Coburn */
381a5752066Sjpedrycfunction wikiLockFN($id)
382a5752066Sjpedryc{
383c9b4bd1eSBen Coburn    global $conf;
384662ff478SAndreas Gohr    return $conf['lockdir'] . '/' . md5(cleanID($id)) . '.lock';
385c9b4bd1eSBen Coburn}
386c9b4bd1eSBen Coburn
387c9b4bd1eSBen Coburn
388c9b4bd1eSBen Coburn/**
3891380fc45SAndreas Gohr * returns the full path to the meta file specified by ID and extension
390b158d625SSteven Danz *
391b158d625SSteven Danz * @author Steven Danz <steven-danz@kc.rr.com>
39284657ea2SGerrit Uitslag *
39384657ea2SGerrit Uitslag * @param string $id   page id
39484657ea2SGerrit Uitslag * @param string $ext  file extension
39584657ea2SGerrit Uitslag * @return string full path
396b158d625SSteven Danz */
397a5752066Sjpedrycfunction metaFN($id, $ext)
398a5752066Sjpedryc{
399b158d625SSteven Danz    global $conf;
400b158d625SSteven Danz    $id = cleanID($id);
401b158d625SSteven Danz    $id = str_replace(':', '/', $id);
40224870174SAndreas Gohr
4031380fc45SAndreas Gohr    $fn = $conf['metadir'] . '/' . utf8_encodeFN($id) . $ext;
404b158d625SSteven Danz    return $fn;
405b158d625SSteven Danz}
406b158d625SSteven Danz
407b158d625SSteven Danz/**
408e4f389efSKate Arzamastseva * returns the full path to the media's meta file specified by ID and extension
409e4f389efSKate Arzamastseva *
410cbe26ad6SKate Arzamastseva * @author Kate Arzamastseva <pshns@ukr.net>
41184657ea2SGerrit Uitslag *
41284657ea2SGerrit Uitslag * @param string $id   media id
41384657ea2SGerrit Uitslag * @param string $ext  extension of media
41484657ea2SGerrit Uitslag * @return string
415e4f389efSKate Arzamastseva */
416a5752066Sjpedrycfunction mediaMetaFN($id, $ext)
417a5752066Sjpedryc{
418e4f389efSKate Arzamastseva    global $conf;
419e4f389efSKate Arzamastseva    $id = cleanID($id);
420e4f389efSKate Arzamastseva    $id = str_replace(':', '/', $id);
42124870174SAndreas Gohr
422e4f389efSKate Arzamastseva    $fn = $conf['mediametadir'] . '/' . utf8_encodeFN($id) . $ext;
423e4f389efSKate Arzamastseva    return $fn;
424e4f389efSKate Arzamastseva}
425e4f389efSKate Arzamastseva
426e4f389efSKate Arzamastseva/**
427e1f3d9e1SEsther Brunner * returns an array of full paths to all metafiles of a given ID
428e1f3d9e1SEsther Brunner *
429e1f3d9e1SEsther Brunner * @author Esther Brunner <esther@kaffeehaus.ch>
430ba0267b3SMichael Hamann * @author Michael Hamann <michael@content-space.de>
43184657ea2SGerrit Uitslag *
43284657ea2SGerrit Uitslag * @param string $id page id
43384657ea2SGerrit Uitslag * @return array
434e1f3d9e1SEsther Brunner */
435a5752066Sjpedrycfunction metaFiles($id)
436a5752066Sjpedryc{
437ba0267b3SMichael Hamann    $basename = metaFN($id, '');
438ba0267b3SMichael Hamann    $files    = glob($basename . '.*', GLOB_MARK);
439ba0267b3SMichael Hamann    // filter files like foo.bar.meta when $id == 'foo'
44024870174SAndreas Gohr    return    $files ? preg_grep('/^' . preg_quote($basename, '/') . '\.[^.\/]*$/u', $files) : [];
441e1f3d9e1SEsther Brunner}
442e1f3d9e1SEsther Brunner
443e1f3d9e1SEsther Brunner/**
444b625487dSandi * returns the full path to the mediafile specified by ID
445b625487dSandi *
446b625487dSandi * The filename is URL encoded to protect Unicode chars
447b625487dSandi *
448b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
449cbe26ad6SKate Arzamastseva * @author Kate Arzamastseva <pshns@ukr.net>
45084657ea2SGerrit Uitslag *
45184657ea2SGerrit Uitslag * @param string     $id  media id
45284657ea2SGerrit Uitslag * @param string|int $rev empty string or revision timestamp
453f50a239bSTakamura * @param bool $clean
454f50a239bSTakamura *
45584657ea2SGerrit Uitslag * @return string full path
456b625487dSandi */
457a5752066Sjpedrycfunction mediaFN($id, $rev = '', $clean = true)
458a5752066Sjpedryc{
459b625487dSandi    global $conf;
460d0e997c6SMichael Große    if ($clean) $id = cleanID($id);
461b625487dSandi    $id = str_replace(':', '/', $id);
462e4f389efSKate Arzamastseva    if (empty($rev)) {
463b625487dSandi        $fn = $conf['mediadir'] . '/' . utf8_encodeFN($id);
464e4f389efSKate Arzamastseva    } else {
465cbe26ad6SKate Arzamastseva        $ext = mimetype($id);
4668e69fd30SKate Arzamastseva        $name = substr($id, 0, -1 * strlen($ext[0]) - 1);
46761f1aad8SKate Arzamastseva        $fn = $conf['mediaolddir'] . '/' . utf8_encodeFN($name . '.' . ( (int) $rev ) . '.' . $ext[0]);
468e4f389efSKate Arzamastseva    }
469b625487dSandi    return $fn;
470b625487dSandi}
471b625487dSandi
472b625487dSandi/**
4732adaf2b8SAndreas Gohr * Returns the full filepath to a localized file if local
474b625487dSandi * version isn't found the english one is returned
475b625487dSandi *
4762adaf2b8SAndreas Gohr * @param  string $id  The id of the local file
4772adaf2b8SAndreas Gohr * @param  string $ext The file extension (usually txt)
478dbf714f7SGerrit Uitslag * @return string full filepath to localized file
47984657ea2SGerrit Uitslag *
480b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
481b625487dSandi */
482a5752066Sjpedrycfunction localeFN($id, $ext = 'txt')
483a5752066Sjpedryc{
484b625487dSandi    global $conf;
4858819fbf5ShArpanet    $file = DOKU_CONF . 'lang/' . $conf['lang'] . '/' . $id . '.' . $ext;
48679e79377SAndreas Gohr    if (!file_exists($file)) {
4872adaf2b8SAndreas Gohr        $file = DOKU_INC . 'inc/lang/' . $conf['lang'] . '/' . $id . '.' . $ext;
48879e79377SAndreas Gohr        if (!file_exists($file)) {
489b625487dSandi            //fall back to english
4902adaf2b8SAndreas Gohr            $file = DOKU_INC . 'inc/lang/en/' . $id . '.' . $ext;
491b625487dSandi        }
492e6cecb08SMichael Hamann    }
493b625487dSandi    return $file;
494b625487dSandi}
495b625487dSandi
496b625487dSandi/**
497c4e0e4a1SAndreas Gohr * Resolve relative paths in IDs
498c4e0e4a1SAndreas Gohr *
499c4e0e4a1SAndreas Gohr * Do not call directly use resolve_mediaid or resolve_pageid
500c4e0e4a1SAndreas Gohr * instead
501c4e0e4a1SAndreas Gohr *
502c4e0e4a1SAndreas Gohr * Partyly based on a cleanPath function found at
50359752844SAnders Sandblad * http://php.net/manual/en/function.realpath.php#57016
504c4e0e4a1SAndreas Gohr *
505bfcf8009SAndreas Gohr * @deprecated 2020-09-30
50684657ea2SGerrit Uitslag * @param string $ns     namespace which is context of id
50784657ea2SGerrit Uitslag * @param string $id     relative id
50884657ea2SGerrit Uitslag * @param bool   $clean  flag indicating that id should be cleaned
50942ea7f44SGerrit Uitslag * @return string
510c4e0e4a1SAndreas Gohr */
511a5752066Sjpedrycfunction resolve_id($ns, $id, $clean = true)
512a5752066Sjpedryc{
513c662a49aSAndreas Gohr    global $conf;
51424870174SAndreas Gohr    dbg_deprecated(Resolver::class . ' and its children');
515c662a49aSAndreas Gohr
516c662a49aSAndreas Gohr    // some pre cleaning for useslash:
517c662a49aSAndreas Gohr    if ($conf['useslash']) $id = str_replace('/', ':', $id);
518c662a49aSAndreas Gohr
519c4e0e4a1SAndreas Gohr    // if the id starts with a dot we need to handle the
520c4e0e4a1SAndreas Gohr    // relative stuff
5212401f18dSSyntaxseed    if ($id && $id[0] == '.') {
522c4e0e4a1SAndreas Gohr        // normalize initial dots without a colon
5234986a584SPhy        $id = preg_replace('/^((\.+:)*)(\.+)(?=[^:\.])/', '\1\3:', $id);
524c4e0e4a1SAndreas Gohr        // prepend the current namespace
525c4e0e4a1SAndreas Gohr        $id = $ns . ':' . $id;
526c4e0e4a1SAndreas Gohr
527c4e0e4a1SAndreas Gohr        // cleanup relatives
52824870174SAndreas Gohr        $result = [];
529c4e0e4a1SAndreas Gohr        $pathA  = explode(':', $id);
530c4e0e4a1SAndreas Gohr        if (!$pathA[0]) $result[] = '';
53124870174SAndreas Gohr        foreach ($pathA as $dir) {
532c4e0e4a1SAndreas Gohr            if ($dir == '..') {
533c4e0e4a1SAndreas Gohr                if (end($result) == '..') {
534c4e0e4a1SAndreas Gohr                    $result[] = '..';
535c4e0e4a1SAndreas Gohr                } elseif (!array_pop($result)) {
536c4e0e4a1SAndreas Gohr                    $result[] = '..';
537c4e0e4a1SAndreas Gohr                }
538c4e0e4a1SAndreas Gohr            } elseif ($dir && $dir != '.') {
539c4e0e4a1SAndreas Gohr                $result[] = $dir;
540c4e0e4a1SAndreas Gohr            }
541c4e0e4a1SAndreas Gohr        }
542c4e0e4a1SAndreas Gohr        if (!end($pathA)) $result[] = '';
543c4e0e4a1SAndreas Gohr        $id = implode(':', $result);
544*093fe67eSAndreas Gohr    } elseif ($ns !== false && !str_contains($id, ':')) {
545c4e0e4a1SAndreas Gohr        //if link contains no namespace. add current namespace (if any)
546c4e0e4a1SAndreas Gohr        $id = $ns . ':' . $id;
547c4e0e4a1SAndreas Gohr    }
548c4e0e4a1SAndreas Gohr
549a6ef4796SAndreas Gohr    if ($clean) $id = cleanID($id);
550a6ef4796SAndreas Gohr    return $id;
551c4e0e4a1SAndreas Gohr}
552c4e0e4a1SAndreas Gohr
553c4e0e4a1SAndreas Gohr/**
554b625487dSandi * Returns a full media id
555b625487dSandi *
55684657ea2SGerrit Uitslag * @param string $ns namespace which is context of id
5575c844bb3SAndreas Gohr * @param string &$media (reference) relative media id, updated to resolved id
55884657ea2SGerrit Uitslag * @param bool &$exists (reference) updated with existance of media
5597de86af9SGerrit Uitslag * @param int|string $rev
5607de86af9SGerrit Uitslag * @param bool $date_at
5615c844bb3SAndreas Gohr * @deprecated 2020-09-30
562b625487dSandi */
563a5752066Sjpedrycfunction resolve_mediaid($ns, &$media, &$exists, $rev = '', $date_at = false)
564a5752066Sjpedryc{
5655c844bb3SAndreas Gohr    dbg_deprecated(MediaResolver::class);
5665c844bb3SAndreas Gohr    $resolver = new MediaResolver("$ns:deprecated");
5675c844bb3SAndreas Gohr    $media = $resolver->resolveId($media, $rev, $date_at);
5685c844bb3SAndreas Gohr    $exists = media_exists($media, $rev, false, $date_at);
569b625487dSandi}
570b625487dSandi
571b625487dSandi/**
572b625487dSandi * Returns a full page id
573b625487dSandi *
574bfcf8009SAndreas Gohr * @deprecated 2020-09-30
57584657ea2SGerrit Uitslag * @param string $ns namespace which is context of id
57684657ea2SGerrit Uitslag * @param string &$page (reference) relative page id, updated to resolved id
57784657ea2SGerrit Uitslag * @param bool &$exists (reference) updated with existance of media
5787de86af9SGerrit Uitslag * @param string $rev
5797de86af9SGerrit Uitslag * @param bool $date_at
580b625487dSandi */
581bfcf8009SAndreas Gohrfunction resolve_pageid($ns, &$page, &$exists, $rev = '', $date_at = false)
582bfcf8009SAndreas Gohr{
5838c6be208SAndreas Gohr    dbg_deprecated(PageResolver::class);
58454611a7aSAndreas Gohr
58554611a7aSAndreas Gohr    global $ID;
58654611a7aSAndreas Gohr    if (getNS($ID) == $ns) {
58754611a7aSAndreas Gohr        $context = $ID; // this is usually the case
58854611a7aSAndreas Gohr    } else {
58954611a7aSAndreas Gohr        $context = "$ns:deprecated"; // only used when a different context namespace was given
59054611a7aSAndreas Gohr    }
59154611a7aSAndreas Gohr
59254611a7aSAndreas Gohr    $resolver = new PageResolver($context);
593bfcf8009SAndreas Gohr    $page = $resolver->resolveId($page, $rev, $date_at);
594bfcf8009SAndreas Gohr    $exists = page_exists($page, $rev, false, $date_at);
595b625487dSandi}
596b625487dSandi
59798407a7aSandi/**
59898407a7aSandi * Returns the name of a cachefile from given data
59998407a7aSandi *
60098407a7aSandi * The needed directory is created by this function!
60198407a7aSandi *
60298407a7aSandi * @author Andreas Gohr <andi@splitbrain.org>
60398407a7aSandi *
60498407a7aSandi * @param string $data  This data is used to create a unique md5 name
60598407a7aSandi * @param string $ext   This is appended to the filename if given
60698407a7aSandi * @return string       The filename of the cachefile
60798407a7aSandi */
608a5752066Sjpedrycfunction getCacheName($data, $ext = '')
609a5752066Sjpedryc{
61098407a7aSandi    global $conf;
61198407a7aSandi    $md5  = md5($data);
6122401f18dSSyntaxseed    $file = $conf['cachedir'] . '/' . $md5[0] . '/' . $md5 . $ext;
61398407a7aSandi    io_makeFileDir($file);
61498407a7aSandi    return $file;
61598407a7aSandi}
61698407a7aSandi
6170dc92c6fSAndreas Gohr/**
6180dc92c6fSAndreas Gohr * Checks a pageid against $conf['hidepages']
6190dc92c6fSAndreas Gohr *
6200dc92c6fSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
62184657ea2SGerrit Uitslag *
62284657ea2SGerrit Uitslag * @param string $id page id
62384657ea2SGerrit Uitslag * @return bool
6240dc92c6fSAndreas Gohr */
625a5752066Sjpedrycfunction isHiddenPage($id)
626a5752066Sjpedryc{
62724870174SAndreas Gohr    $data = ['id' => $id, 'hidden' => false];
62824870174SAndreas Gohr    Event::createAndTrigger('PAGEUTILS_ID_HIDEPAGE', $data, '_isHiddenPage');
629fb55b51eSDominik Eckelmann    return $data['hidden'];
6300dc92c6fSAndreas Gohr}
631fb55b51eSDominik Eckelmann
632dbf714f7SGerrit Uitslag/**
633dbf714f7SGerrit Uitslag * callback checks if page is hidden
634dbf714f7SGerrit Uitslag *
63584657ea2SGerrit Uitslag * @param array $data event data    - see isHiddenPage()
636dbf714f7SGerrit Uitslag */
637a5752066Sjpedrycfunction _isHiddenPage(&$data)
638a5752066Sjpedryc{
639fb55b51eSDominik Eckelmann    global $conf;
640fb55b51eSDominik Eckelmann    global $ACT;
641fb55b51eSDominik Eckelmann
642fb55b51eSDominik Eckelmann    if ($data['hidden']) return;
643fb55b51eSDominik Eckelmann    if (empty($conf['hidepages'])) return;
644fb55b51eSDominik Eckelmann    if ($ACT == 'admin') return;
645fb55b51eSDominik Eckelmann
646fb55b51eSDominik Eckelmann    if (preg_match('/' . $conf['hidepages'] . '/ui', ':' . $data['id'])) {
647fb55b51eSDominik Eckelmann        $data['hidden'] = true;
648fb55b51eSDominik Eckelmann    }
6490dc92c6fSAndreas Gohr}
6500dc92c6fSAndreas Gohr
6510dc92c6fSAndreas Gohr/**
6520dc92c6fSAndreas Gohr * Reverse of isHiddenPage
6530dc92c6fSAndreas Gohr *
6540dc92c6fSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
65584657ea2SGerrit Uitslag *
65684657ea2SGerrit Uitslag * @param string $id page id
65784657ea2SGerrit Uitslag * @return bool
6580dc92c6fSAndreas Gohr */
659a5752066Sjpedrycfunction isVisiblePage($id)
660a5752066Sjpedryc{
6610dc92c6fSAndreas Gohr    return !isHiddenPage($id);
6620dc92c6fSAndreas Gohr}
6630dc92c6fSAndreas Gohr
6645b75cd1fSAdrian Lang/**
6655b75cd1fSAdrian Lang * Format an id for output to a user
6665b75cd1fSAdrian Lang *
6675b75cd1fSAdrian Lang * Namespaces are denoted by a trailing “:*”. The root namespace is
6685b75cd1fSAdrian Lang * “*”. Output is escaped.
6695b75cd1fSAdrian Lang *
6705b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
67184657ea2SGerrit Uitslag *
67284657ea2SGerrit Uitslag * @param string $id page id
67384657ea2SGerrit Uitslag * @return string
6745b75cd1fSAdrian Lang */
675a5752066Sjpedrycfunction prettyprint_id($id)
676a5752066Sjpedryc{
6775b75cd1fSAdrian Lang    if (!$id || $id === ':') {
6785b75cd1fSAdrian Lang        return '*';
6795b75cd1fSAdrian Lang    }
6806c16a3a9Sfiwswe    if (str_ends_with($id, ':')) {
6815b75cd1fSAdrian Lang        $id .= '*';
6825b75cd1fSAdrian Lang    }
6835b75cd1fSAdrian Lang    return hsc($id);
6845b75cd1fSAdrian Lang}
685f03fd957SAndreas Gohr
686f03fd957SAndreas Gohr/**
687f03fd957SAndreas Gohr * Encode a UTF-8 filename to use on any filesystem
688f03fd957SAndreas Gohr *
689f03fd957SAndreas Gohr * Uses the 'fnencode' option to determine encoding
690f03fd957SAndreas Gohr *
691f03fd957SAndreas Gohr * When the second parameter is true the string will
692f03fd957SAndreas Gohr * be encoded only if non ASCII characters are detected -
693f03fd957SAndreas Gohr * This makes it safe to run it multiple times on the
694f03fd957SAndreas Gohr * same string (default is true)
695f03fd957SAndreas Gohr *
696f03fd957SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
697f03fd957SAndreas Gohr * @see    urlencode
69884657ea2SGerrit Uitslag *
69984657ea2SGerrit Uitslag * @param string $file file name
70084657ea2SGerrit Uitslag * @param bool   $safe if true, only encoded when non ASCII characters detected
70184657ea2SGerrit Uitslag * @return string
702f03fd957SAndreas Gohr */
703a5752066Sjpedrycfunction utf8_encodeFN($file, $safe = true)
704a5752066Sjpedryc{
705f03fd957SAndreas Gohr    global $conf;
706f03fd957SAndreas Gohr    if ($conf['fnencode'] == 'utf-8') return $file;
707f03fd957SAndreas Gohr
708f03fd957SAndreas Gohr    if ($safe && preg_match('#^[a-zA-Z0-9/_\-\.%]+$#', $file)) {
709f03fd957SAndreas Gohr        return $file;
710f03fd957SAndreas Gohr    }
711f03fd957SAndreas Gohr
712f03fd957SAndreas Gohr    if ($conf['fnencode'] == 'safe') {
713f03fd957SAndreas Gohr        return SafeFN::encode($file);
714f03fd957SAndreas Gohr    }
715f03fd957SAndreas Gohr
716f03fd957SAndreas Gohr    $file = urlencode($file);
717f03fd957SAndreas Gohr    $file = str_replace('%2F', '/', $file);
718f03fd957SAndreas Gohr    return $file;
719f03fd957SAndreas Gohr}
720f03fd957SAndreas Gohr
721f03fd957SAndreas Gohr/**
722f03fd957SAndreas Gohr * Decode a filename back to UTF-8
723f03fd957SAndreas Gohr *
724f03fd957SAndreas Gohr * Uses the 'fnencode' option to determine encoding
725f03fd957SAndreas Gohr *
726f03fd957SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
727f03fd957SAndreas Gohr * @see    urldecode
72884657ea2SGerrit Uitslag *
72984657ea2SGerrit Uitslag * @param string $file file name
73084657ea2SGerrit Uitslag * @return string
731f03fd957SAndreas Gohr */
732a5752066Sjpedrycfunction utf8_decodeFN($file)
733a5752066Sjpedryc{
734f03fd957SAndreas Gohr    global $conf;
735f03fd957SAndreas Gohr    if ($conf['fnencode'] == 'utf-8') return $file;
736f03fd957SAndreas Gohr
737f03fd957SAndreas Gohr    if ($conf['fnencode'] == 'safe') {
738f03fd957SAndreas Gohr        return SafeFN::decode($file);
739f03fd957SAndreas Gohr    }
740f03fd957SAndreas Gohr
741f03fd957SAndreas Gohr    return urldecode($file);
742f03fd957SAndreas Gohr}
743f03fd957SAndreas Gohr
744e66d3e6dSAndreas Gohr/**
745e66d3e6dSAndreas Gohr * Find a page in the current namespace (determined from $ID) or any
746cc529468SMichael Hamann * higher namespace that can be accessed by the current user,
747cc529468SMichael Hamann * this condition can be overriden by an optional parameter.
748e66d3e6dSAndreas Gohr *
749e66d3e6dSAndreas Gohr * Used for sidebars, but can be used other stuff as well
750e66d3e6dSAndreas Gohr *
751e66d3e6dSAndreas Gohr * @todo   add event hook
75242ea7f44SGerrit Uitslag *
753e66d3e6dSAndreas Gohr * @param  string $page the pagename you're looking for
7547c3e4a67SAndreas Gohr * @param bool $useacl only return pages readable by the current user, false to ignore ACLs
755cc529468SMichael Hamann * @return false|string the full page id of the found page, false if any
756e66d3e6dSAndreas Gohr */
757a5752066Sjpedrycfunction page_findnearest($page, $useacl = true)
758a5752066Sjpedryc{
75906a70133SPhy    if ((string) $page === '') return false;
760e66d3e6dSAndreas Gohr    global $ID;
761e66d3e6dSAndreas Gohr
762e66d3e6dSAndreas Gohr    $ns = $ID;
763e66d3e6dSAndreas Gohr    do {
764e66d3e6dSAndreas Gohr        $ns = getNS($ns);
765cc529468SMichael Hamann        $pageid = cleanID("$ns:$page");
7667c3e4a67SAndreas Gohr        if (page_exists($pageid) && (!$useacl || auth_quickaclcheck($pageid) >= AUTH_READ)) {
767e66d3e6dSAndreas Gohr            return $pageid;
768e66d3e6dSAndreas Gohr        }
76906a70133SPhy    } while ($ns !== false);
770e66d3e6dSAndreas Gohr
771e66d3e6dSAndreas Gohr    return false;
772e66d3e6dSAndreas Gohr}
773