xref: /dokuwiki/inc/pageutils.php (revision 1d053a561daf3b6539283811cc44d39b315e1dbf)
1b625487dSandi<?php
2b625487dSandi/**
3b625487dSandi * Utilities for handling pagenames
4b625487dSandi *
5b625487dSandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6b625487dSandi * @author     Andreas Gohr <andi@splitbrain.org>
71380fc45SAndreas Gohr * @todo       Combine similar functions like {wiki,media,meta}FN()
8b625487dSandi */
9b625487dSandi
106c7843b5Sandi/**
116de3759aSAndreas Gohr * Fetch the an ID from request
126c7843b5Sandi *
136c7843b5Sandi * Uses either standard $_REQUEST variable or extracts it from
146c7843b5Sandi * the full request URI when userewrite is set to 2
156c7843b5Sandi *
1642905504SAndreas Gohr * For $param='id' $conf['start'] is returned if no id was found.
1742905504SAndreas Gohr * If the second parameter is true (default) the ID is cleaned.
186c7843b5Sandi *
196c7843b5Sandi * @author Andreas Gohr <andi@splitbrain.org>
2084657ea2SGerrit Uitslag *
2184657ea2SGerrit Uitslag * @param string $param  the $_REQUEST variable name, default 'id'
2284657ea2SGerrit Uitslag * @param bool   $clean  if true, ID is cleaned
2384657ea2SGerrit Uitslag * @return mixed|string
246c7843b5Sandi */
2542905504SAndreas Gohrfunction getID($param='id',$clean=true){
26585bf44eSChristopher Smith    /** @var Input $INPUT */
277d01a0eaSTom N Harris    global $INPUT;
286c7843b5Sandi    global $conf;
294e90caaaSMichael Hamann    global $ACT;
306c7843b5Sandi
317d01a0eaSTom N Harris    $id = $INPUT->str($param);
3248665d38SAndreas Gohr
336c7843b5Sandi    //construct page id from request URI
346c7843b5Sandi    if(empty($id) && $conf['userewrite'] == 2){
35585bf44eSChristopher Smith        $request = $INPUT->server->str('REQUEST_URI');
3606368e4dSMichael Hamann        $script = '';
3706368e4dSMichael Hamann
386c7843b5Sandi        //get the script URL
396c7843b5Sandi        if($conf['basedir']){
4081124000Sjan            $relpath = '';
4181124000Sjan            if($param != 'id') {
4281124000Sjan                $relpath = 'lib/exe/';
4381124000Sjan            }
44585bf44eSChristopher Smith            $script = $conf['basedir'].$relpath.utf8_basename($INPUT->server->str('SCRIPT_FILENAME'));
457d71d4b7SAndreas Gohr
46585bf44eSChristopher Smith        }elseif($INPUT->server->str('PATH_INFO')){
47585bf44eSChristopher Smith            $request = $INPUT->server->str('PATH_INFO');
48585bf44eSChristopher Smith        }elseif($INPUT->server->str('SCRIPT_NAME')){
49585bf44eSChristopher Smith            $script = $INPUT->server->str('SCRIPT_NAME');
50585bf44eSChristopher Smith        }elseif($INPUT->server->str('DOCUMENT_ROOT') && $INPUT->server->str('SCRIPT_FILENAME')){
51585bf44eSChristopher Smith            $script = preg_replace ('/^'.preg_quote($INPUT->server->str('DOCUMENT_ROOT'),'/').'/','',
52585bf44eSChristopher Smith                    $INPUT->server->str('SCRIPT_FILENAME'));
536c7843b5Sandi            $script = '/'.$script;
546c7843b5Sandi        }
556c7843b5Sandi
5652339126Sandi        //clean script and request (fixes a windows problem)
5752339126Sandi        $script  = preg_replace('/\/\/+/','/',$script);
587d71d4b7SAndreas Gohr        $request = preg_replace('/\/\/+/','/',$request);
5952339126Sandi
606c7843b5Sandi        //remove script URL and Querystring to gain the id
6152339126Sandi        if(preg_match('/^'.preg_quote($script,'/').'(.*)/',$request, $match)){
626c7843b5Sandi            $id = preg_replace ('/\?.*/','',$match[1]);
636c7843b5Sandi        }
646de3759aSAndreas Gohr        $id = urldecode($id);
6542905504SAndreas Gohr        //strip leading slashes
6642905504SAndreas Gohr        $id = preg_replace('!^/+!','',$id);
676c7843b5Sandi    }
68671a58a6SGuy Brand
69671a58a6SGuy Brand    // Namespace autolinking from URL
70b6084253SAndreas Gohr    if(substr($id,-1) == ':' || ($conf['useslash'] && substr($id,-1) == '/')){
71103c256aSChris Smith        if(page_exists($id.$conf['start'])){
72671a58a6SGuy Brand            // start page inside namespace
73671a58a6SGuy Brand            $id = $id.$conf['start'];
74103c256aSChris Smith        }elseif(page_exists($id.noNS(cleanID($id)))){
75671a58a6SGuy Brand            // page named like the NS inside the NS
76671a58a6SGuy Brand            $id = $id.noNS(cleanID($id));
77103c256aSChris Smith        }elseif(page_exists($id)){
78671a58a6SGuy Brand            // page like namespace exists
797a42ac9eSBen Coburn            $id = substr($id,0,-1);
80671a58a6SGuy Brand        }else{
81671a58a6SGuy Brand            // fall back to default
82671a58a6SGuy Brand            $id = $id.$conf['start'];
83671a58a6SGuy Brand        }
844e90caaaSMichael Hamann        if (isset($ACT) && $ACT === 'show') send_redirect(wl($id,'',true));
85671a58a6SGuy Brand    }
86671a58a6SGuy Brand
8742905504SAndreas Gohr    if($clean) $id = cleanID($id);
880868021bSAndreas Gohr    if(empty($id) && $param=='id') $id = $conf['start'];
896c7843b5Sandi
906c7843b5Sandi    return $id;
916c7843b5Sandi}
92b625487dSandi
93b625487dSandi/**
94b625487dSandi * Remove unwanted chars from ID
95b625487dSandi *
96b625487dSandi * Cleans a given ID to only use allowed characters. Accented characters are
97b625487dSandi * converted to unaccented ones
98b625487dSandi *
99b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
1006e0cc83aSchris * @param  string  $raw_id    The pageid to clean
1018a831f2bSAndreas Gohr * @param  boolean $ascii     Force ASCII
102dbf714f7SGerrit Uitslag * @return string cleaned id
103b625487dSandi */
104c8bbb094SAnika Henkefunction cleanID($raw_id,$ascii=false){
105b625487dSandi    global $conf;
1064b5db43bSjoe.lapp    static $sepcharpat = null;
1074b5db43bSjoe.lapp
108dc2c0e04Schris    global $cache_cleanid;
109dc2c0e04Schris    $cache = & $cache_cleanid;
1106e0cc83aSchris
1116e0cc83aSchris    // check if it's already in the memory cache
1123a50618cSgweissbach    if (isset($cache[(string)$raw_id])) {
1133a50618cSgweissbach        return $cache[(string)$raw_id];
1146e0cc83aSchris    }
1156e0cc83aSchris
1164b5db43bSjoe.lapp    $sepchar = $conf['sepchar'];
1174b5db43bSjoe.lapp    if($sepcharpat == null) // build string only once to save clock cycles
1184b5db43bSjoe.lapp        $sepcharpat = '#\\'.$sepchar.'+#';
1194b5db43bSjoe.lapp
1203a50618cSgweissbach    $id = trim((string)$raw_id);
121b625487dSandi    $id = utf8_strtolower($id);
122b625487dSandi
123b625487dSandi    //alternative namespace seperator
124b625487dSandi    if($conf['useslash']){
1253755fc25STom N Harris        $id = strtr($id,';/','::');
126b625487dSandi    }else{
1273755fc25STom N Harris        $id = strtr($id,';/',':'.$sepchar);
128b625487dSandi    }
129b625487dSandi
1308a831f2bSAndreas Gohr    if($conf['deaccent'] == 2 || $ascii) $id = utf8_romanize($id);
1318a831f2bSAndreas Gohr    if($conf['deaccent'] || $ascii) $id = utf8_deaccent($id,-1);
132b625487dSandi
133b625487dSandi    //remove specials
134ad81d431SAndreas Gohr    $id = utf8_stripspecials($id,$sepchar,'\*');
135b625487dSandi
1368a831f2bSAndreas Gohr    if($ascii) $id = utf8_strip($id);
1378a831f2bSAndreas Gohr
138b625487dSandi    //clean up
1394b5db43bSjoe.lapp    $id = preg_replace($sepcharpat,$sepchar,$id);
140b625487dSandi    $id = preg_replace('#:+#',':',$id);
1413543c6deSAndreas Gohr    $id = trim($id,':._-');
142b625487dSandi    $id = preg_replace('#:[:\._\-]+#',':',$id);
143b680ea06SAndreas Gohr    $id = preg_replace('#[:\._\-]+:#',':',$id);
144b625487dSandi
1453a50618cSgweissbach    $cache[(string)$raw_id] = $id;
146b625487dSandi    return($id);
147b625487dSandi}
148b625487dSandi
149b625487dSandi/**
150b625487dSandi * Return namespacepart of a wiki ID
151b625487dSandi *
152b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
15315851b98SGerrit Uitslag *
15415851b98SGerrit Uitslag * @param string $id
155ef11fcfcSAndreas Gohr * @return string|bool the namespace part or false if the given ID has no namespace (root)
156b625487dSandi */
157b625487dSandifunction getNS($id){
1583a50618cSgweissbach    $pos = strrpos((string)$id,':');
159c4e0e4a1SAndreas Gohr    if($pos!==false){
1603a50618cSgweissbach        return substr((string)$id,0,$pos);
161b625487dSandi    }
162b625487dSandi    return false;
163b625487dSandi}
164b625487dSandi
165b625487dSandi/**
166b625487dSandi * Returns the ID without the namespace
167b625487dSandi *
168b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
16915851b98SGerrit Uitslag *
17015851b98SGerrit Uitslag * @param string $id
17115851b98SGerrit Uitslag * @return string
172b625487dSandi */
173b625487dSandifunction noNS($id) {
1742844584fSBen Coburn    $pos = strrpos($id, ':');
1752844584fSBen Coburn    if ($pos!==false) {
1762844584fSBen Coburn        return substr($id, $pos+1);
1772844584fSBen Coburn    } else {
1782844584fSBen Coburn        return $id;
1792844584fSBen Coburn    }
1801a84a0f3SAnika Henke}
1811a84a0f3SAnika Henke
1821a84a0f3SAnika Henke/**
1831a84a0f3SAnika Henke * Returns the current namespace
1841a84a0f3SAnika Henke *
1851a84a0f3SAnika Henke * @author Nathan Fritz <fritzn@crown.edu>
18684657ea2SGerrit Uitslag *
18784657ea2SGerrit Uitslag * @param string $id
18884657ea2SGerrit Uitslag * @return string
1891a84a0f3SAnika Henke */
1901a84a0f3SAnika Henkefunction curNS($id) {
1911a84a0f3SAnika Henke    return noNS(getNS($id));
1921a84a0f3SAnika Henke}
1931a84a0f3SAnika Henke
1941a84a0f3SAnika Henke/**
1951a84a0f3SAnika Henke * Returns the ID without the namespace or current namespace for 'start' pages
1961a84a0f3SAnika Henke *
1971a84a0f3SAnika Henke * @author Nathan Fritz <fritzn@crown.edu>
19884657ea2SGerrit Uitslag *
19984657ea2SGerrit Uitslag * @param string $id
20084657ea2SGerrit Uitslag * @return string
2011a84a0f3SAnika Henke */
2021a84a0f3SAnika Henkefunction noNSorNS($id) {
2031a84a0f3SAnika Henke    global $conf;
2041a84a0f3SAnika Henke
2051a84a0f3SAnika Henke    $p = noNS($id);
2069708106bSAdrian Lang    if ($p == $conf['start'] || $p == false) {
2071a84a0f3SAnika Henke        $p = curNS($id);
2081a84a0f3SAnika Henke        if ($p == false) {
2099708106bSAdrian Lang            return $conf['start'];
2101a84a0f3SAnika Henke        }
2111a84a0f3SAnika Henke    }
2121a84a0f3SAnika Henke    return $p;
213b625487dSandi}
2144ceab83fSAndreas Gohr
2154ceab83fSAndreas Gohr/**
2164ceab83fSAndreas Gohr * Creates a XHTML valid linkid from a given headline title
2174ceab83fSAndreas Gohr *
2184ceab83fSAndreas Gohr * @param string  $title   The headline title
219c857afe0SMichael Hamann * @param array|bool   $check   Existing IDs (title => number)
220c857afe0SMichael Hamann * @return string the title
22184657ea2SGerrit Uitslag *
2224ceab83fSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
2234ceab83fSAndreas Gohr */
224443d207bSAndreas Gohrfunction sectionID($title,&$check) {
225de9114eaSAnika Henke    $title = str_replace(array(':','.'),'',cleanID($title));
226de9114eaSAnika Henke    $new = ltrim($title,'0123456789_-');
2274ceab83fSAndreas Gohr    if(empty($new)){
2284ceab83fSAndreas Gohr        $title = 'section'.preg_replace('/[^0-9]+/','',$title); //keep numbers from headline
2294ceab83fSAndreas Gohr    }else{
2304ceab83fSAndreas Gohr        $title = $new;
2314ceab83fSAndreas Gohr    }
2324ceab83fSAndreas Gohr
233443d207bSAndreas Gohr    if(is_array($check)){
2344ceab83fSAndreas Gohr        // make sure tiles are unique
23501e3159cSChris Tapp        if (!array_key_exists ($title,$check)) {
23601e3159cSChris Tapp            $check[$title] = 0;
23701e3159cSChris Tapp        } else {
23801e3159cSChris Tapp            $title .= ++ $check[$title];
2394ceab83fSAndreas Gohr        }
2404ceab83fSAndreas Gohr    }
2414ceab83fSAndreas Gohr
2424ceab83fSAndreas Gohr    return $title;
2434ceab83fSAndreas Gohr}
2444ceab83fSAndreas Gohr
245b625487dSandi
246b625487dSandi/**
247103c256aSChris Smith * Wiki page existence check
248103c256aSChris Smith *
249103c256aSChris Smith * parameters as for wikiFN
250103c256aSChris Smith *
251103c256aSChris Smith * @author Chris Smith <chris@jalakai.co.uk>
25284657ea2SGerrit Uitslag *
25384657ea2SGerrit Uitslag * @param string     $id     page id
25484657ea2SGerrit Uitslag * @param string|int $rev    empty or revision timestamp
25584657ea2SGerrit Uitslag * @param bool       $clean  flag indicating that $id should be cleaned (see wikiFN as well)
25684657ea2SGerrit Uitslag * @return bool exists?
257103c256aSChris Smith */
258*1d053a56Slispsfunction page_exists($id,$rev='',$clean=true, $date_at=false) {
25990bee600Slisps    if($rev !== '' && $date_at) {
260*1d053a56Slisps        $pagelog = new PageChangeLog($id);
26190bee600Slisps        $pagelog_rev = $pagelog->getLastRevisionAt($rev);
26290bee600Slisps        if($pagelog_rev !== false)
26390bee600Slisps            $rev = $pagelog_rev;
26490bee600Slisps    }
265103c256aSChris Smith    return @file_exists(wikiFN($id,$rev,$clean));
266103c256aSChris Smith}
267103c256aSChris Smith
268103c256aSChris Smith/**
269103c256aSChris Smith * returns the full path to the datafile specified by ID and optional revision
270b625487dSandi *
271b625487dSandi * The filename is URL encoded to protect Unicode chars
272b625487dSandi *
273103c256aSChris Smith * @param  $raw_id  string   id of wikipage
274103c256aSChris Smith * @param  $rev     string   page revision, empty string for current
275103c256aSChris Smith * @param  $clean   bool     flag indicating that $raw_id should be cleaned.  Only set to false
276103c256aSChris Smith *                           when $id is guaranteed to have been cleaned already.
277dbf714f7SGerrit Uitslag * @return string full path
278103c256aSChris Smith *
279b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
280b625487dSandi */
2816e0cc83aSchrisfunction wikiFN($raw_id,$rev='',$clean=true){
282b625487dSandi    global $conf;
2836e0cc83aSchris
284dc2c0e04Schris    global $cache_wikifn;
285dc2c0e04Schris    $cache = & $cache_wikifn;
286dc2c0e04Schris
2876e0cc83aSchris    if (isset($cache[$raw_id]) && isset($cache[$raw_id][$rev])) {
2886e0cc83aSchris        return $cache[$raw_id][$rev];
2896e0cc83aSchris    }
2906e0cc83aSchris
2916e0cc83aSchris    $id = $raw_id;
2926e0cc83aSchris
2930d8ea614Schris    if ($clean) $id = cleanID($id);
294b625487dSandi    $id = str_replace(':','/',$id);
295b625487dSandi    if(empty($rev)){
296b625487dSandi        $fn = $conf['datadir'].'/'.utf8_encodeFN($id).'.txt';
297b625487dSandi    }else{
298b625487dSandi        $fn = $conf['olddir'].'/'.utf8_encodeFN($id).'.'.$rev.'.txt';
299ff3ed99fSmarcel        if($conf['compression']){
300ff3ed99fSmarcel            //test for extensions here, we want to read both compressions
301d8186216SBen Coburn            if (@file_exists($fn . '.gz')){
302b625487dSandi                $fn .= '.gz';
303d8186216SBen Coburn            }else if(@file_exists($fn . '.bz2')){
304ff3ed99fSmarcel                $fn .= '.bz2';
305ff3ed99fSmarcel            }else{
306ff3ed99fSmarcel                //file doesnt exist yet, so we take the configured extension
307ff3ed99fSmarcel                $fn .= '.' . $conf['compression'];
308ff3ed99fSmarcel            }
309b625487dSandi        }
310b625487dSandi    }
3116e0cc83aSchris
31250602150SBen Coburn    if (!isset($cache[$raw_id])) { $cache[$raw_id] = array(); }
3136e0cc83aSchris    $cache[$raw_id][$rev] = $fn;
314b625487dSandi    return $fn;
315b625487dSandi}
316b625487dSandi
317b625487dSandi/**
318c9b4bd1eSBen Coburn * Returns the full path to the file for locking the page while editing.
319c9b4bd1eSBen Coburn *
320c9b4bd1eSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
32184657ea2SGerrit Uitslag *
32284657ea2SGerrit Uitslag * @param string $id page id
32384657ea2SGerrit Uitslag * @return string full path
324c9b4bd1eSBen Coburn */
325c9b4bd1eSBen Coburnfunction wikiLockFN($id) {
326c9b4bd1eSBen Coburn    global $conf;
327662ff478SAndreas Gohr    return $conf['lockdir'].'/'.md5(cleanID($id)).'.lock';
328c9b4bd1eSBen Coburn}
329c9b4bd1eSBen Coburn
330c9b4bd1eSBen Coburn
331c9b4bd1eSBen Coburn/**
3321380fc45SAndreas Gohr * returns the full path to the meta file specified by ID and extension
333b158d625SSteven Danz *
334b158d625SSteven Danz * @author Steven Danz <steven-danz@kc.rr.com>
33584657ea2SGerrit Uitslag *
33684657ea2SGerrit Uitslag * @param string $id   page id
33784657ea2SGerrit Uitslag * @param string $ext  file extension
33884657ea2SGerrit Uitslag * @return string full path
339b158d625SSteven Danz */
3401380fc45SAndreas Gohrfunction metaFN($id,$ext){
341b158d625SSteven Danz    global $conf;
342b158d625SSteven Danz    $id = cleanID($id);
343b158d625SSteven Danz    $id = str_replace(':','/',$id);
3441380fc45SAndreas Gohr    $fn = $conf['metadir'].'/'.utf8_encodeFN($id).$ext;
345b158d625SSteven Danz    return $fn;
346b158d625SSteven Danz}
347b158d625SSteven Danz
348b158d625SSteven Danz/**
349e4f389efSKate Arzamastseva * returns the full path to the media's meta file specified by ID and extension
350e4f389efSKate Arzamastseva *
351cbe26ad6SKate Arzamastseva * @author Kate Arzamastseva <pshns@ukr.net>
35284657ea2SGerrit Uitslag *
35384657ea2SGerrit Uitslag * @param string $id   media id
35484657ea2SGerrit Uitslag * @param string $ext  extension of media
35584657ea2SGerrit Uitslag * @return string
356e4f389efSKate Arzamastseva */
357e4f389efSKate Arzamastsevafunction mediaMetaFN($id,$ext){
358e4f389efSKate Arzamastseva    global $conf;
359e4f389efSKate Arzamastseva    $id = cleanID($id);
360e4f389efSKate Arzamastseva    $id = str_replace(':','/',$id);
361e4f389efSKate Arzamastseva    $fn = $conf['mediametadir'].'/'.utf8_encodeFN($id).$ext;
362e4f389efSKate Arzamastseva    return $fn;
363e4f389efSKate Arzamastseva}
364e4f389efSKate Arzamastseva
365e4f389efSKate Arzamastseva/**
366e1f3d9e1SEsther Brunner * returns an array of full paths to all metafiles of a given ID
367e1f3d9e1SEsther Brunner *
368e1f3d9e1SEsther Brunner * @author Esther Brunner <esther@kaffeehaus.ch>
369ba0267b3SMichael Hamann * @author Michael Hamann <michael@content-space.de>
37084657ea2SGerrit Uitslag *
37184657ea2SGerrit Uitslag * @param string $id page id
37284657ea2SGerrit Uitslag * @return array
373e1f3d9e1SEsther Brunner */
374e1f3d9e1SEsther Brunnerfunction metaFiles($id){
375ba0267b3SMichael Hamann    $basename = metaFN($id, '');
376ba0267b3SMichael Hamann    $files    = glob($basename.'.*', GLOB_MARK);
377ba0267b3SMichael Hamann    // filter files like foo.bar.meta when $id == 'foo'
378ba0267b3SMichael Hamann    return    $files ? preg_grep('/^'.preg_quote($basename, '/').'\.[^.\/]*$/u', $files) : array();
379e1f3d9e1SEsther Brunner}
380e1f3d9e1SEsther Brunner
381e1f3d9e1SEsther Brunner/**
382b625487dSandi * returns the full path to the mediafile specified by ID
383b625487dSandi *
384b625487dSandi * The filename is URL encoded to protect Unicode chars
385b625487dSandi *
386b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
387cbe26ad6SKate Arzamastseva * @author Kate Arzamastseva <pshns@ukr.net>
38884657ea2SGerrit Uitslag *
38984657ea2SGerrit Uitslag * @param string     $id  media id
39084657ea2SGerrit Uitslag * @param string|int $rev empty string or revision timestamp
39184657ea2SGerrit Uitslag * @return string full path
392b625487dSandi */
393e4f389efSKate Arzamastsevafunction mediaFN($id, $rev=''){
394b625487dSandi    global $conf;
395b625487dSandi    $id = cleanID($id);
396b625487dSandi    $id = str_replace(':','/',$id);
397e4f389efSKate Arzamastseva    if(empty($rev)){
398b625487dSandi        $fn = $conf['mediadir'].'/'.utf8_encodeFN($id);
399e4f389efSKate Arzamastseva    }else{
400cbe26ad6SKate Arzamastseva        $ext = mimetype($id);
4018e69fd30SKate Arzamastseva        $name = substr($id,0, -1*strlen($ext[0])-1);
40261f1aad8SKate Arzamastseva        $fn = $conf['mediaolddir'].'/'.utf8_encodeFN($name .'.'.( (int) $rev ).'.'.$ext[0]);
403e4f389efSKate Arzamastseva    }
404b625487dSandi    return $fn;
405b625487dSandi}
406b625487dSandi
407b625487dSandi/**
4082adaf2b8SAndreas Gohr * Returns the full filepath to a localized file if local
409b625487dSandi * version isn't found the english one is returned
410b625487dSandi *
4112adaf2b8SAndreas Gohr * @param  string $id  The id of the local file
4122adaf2b8SAndreas Gohr * @param  string $ext The file extension (usually txt)
413dbf714f7SGerrit Uitslag * @return string full filepath to localized file
41484657ea2SGerrit Uitslag *
415b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
416b625487dSandi */
4172adaf2b8SAndreas Gohrfunction localeFN($id,$ext='txt'){
418b625487dSandi    global $conf;
4198819fbf5ShArpanet    $file = DOKU_CONF.'lang/'.$conf['lang'].'/'.$id.'.'.$ext;
420e6cecb08SMichael Hamann    if(!@file_exists($file)){
4212adaf2b8SAndreas Gohr        $file = DOKU_INC.'inc/lang/'.$conf['lang'].'/'.$id.'.'.$ext;
422b625487dSandi        if(!@file_exists($file)){
423b625487dSandi            //fall back to english
4242adaf2b8SAndreas Gohr            $file = DOKU_INC.'inc/lang/en/'.$id.'.'.$ext;
425b625487dSandi        }
426e6cecb08SMichael Hamann    }
427b625487dSandi    return $file;
428b625487dSandi}
429b625487dSandi
430b625487dSandi/**
431c4e0e4a1SAndreas Gohr * Resolve relative paths in IDs
432c4e0e4a1SAndreas Gohr *
433c4e0e4a1SAndreas Gohr * Do not call directly use resolve_mediaid or resolve_pageid
434c4e0e4a1SAndreas Gohr * instead
435c4e0e4a1SAndreas Gohr *
436c4e0e4a1SAndreas Gohr * Partyly based on a cleanPath function found at
437c4e0e4a1SAndreas Gohr * http://www.php.net/manual/en/function.realpath.php#57016
438c4e0e4a1SAndreas Gohr *
439c4e0e4a1SAndreas Gohr * @author <bart at mediawave dot nl>
44084657ea2SGerrit Uitslag *
44184657ea2SGerrit Uitslag * @param string $ns     namespace which is context of id
44284657ea2SGerrit Uitslag * @param string $id     relative id
44384657ea2SGerrit Uitslag * @param bool   $clean  flag indicating that id should be cleaned
44484657ea2SGerrit Uitslag * @return mixed|string
445c4e0e4a1SAndreas Gohr */
446a6ef4796SAndreas Gohrfunction resolve_id($ns,$id,$clean=true){
447c662a49aSAndreas Gohr    global $conf;
448c662a49aSAndreas Gohr
449c662a49aSAndreas Gohr    // some pre cleaning for useslash:
450c662a49aSAndreas Gohr    if($conf['useslash']) $id = str_replace('/',':',$id);
451c662a49aSAndreas Gohr
452c4e0e4a1SAndreas Gohr    // if the id starts with a dot we need to handle the
453c4e0e4a1SAndreas Gohr    // relative stuff
454443e135dSChristopher Smith    if($id && $id{0} == '.'){
455c4e0e4a1SAndreas Gohr        // normalize initial dots without a colon
456c4e0e4a1SAndreas Gohr        $id = preg_replace('/^(\.+)(?=[^:\.])/','\1:',$id);
457c4e0e4a1SAndreas Gohr        // prepend the current namespace
458c4e0e4a1SAndreas Gohr        $id = $ns.':'.$id;
459c4e0e4a1SAndreas Gohr
460c4e0e4a1SAndreas Gohr        // cleanup relatives
461c4e0e4a1SAndreas Gohr        $result = array();
462c4e0e4a1SAndreas Gohr        $pathA  = explode(':', $id);
463c4e0e4a1SAndreas Gohr        if (!$pathA[0]) $result[] = '';
464c4e0e4a1SAndreas Gohr        foreach ($pathA AS $key => $dir) {
465c4e0e4a1SAndreas Gohr            if ($dir == '..') {
466c4e0e4a1SAndreas Gohr                if (end($result) == '..') {
467c4e0e4a1SAndreas Gohr                    $result[] = '..';
468c4e0e4a1SAndreas Gohr                } elseif (!array_pop($result)) {
469c4e0e4a1SAndreas Gohr                    $result[] = '..';
470c4e0e4a1SAndreas Gohr                }
471c4e0e4a1SAndreas Gohr            } elseif ($dir && $dir != '.') {
472c4e0e4a1SAndreas Gohr                $result[] = $dir;
473c4e0e4a1SAndreas Gohr            }
474c4e0e4a1SAndreas Gohr        }
475c4e0e4a1SAndreas Gohr        if (!end($pathA)) $result[] = '';
476c4e0e4a1SAndreas Gohr        $id = implode(':', $result);
477c4e0e4a1SAndreas Gohr    }elseif($ns !== false && strpos($id,':') === false){
478c4e0e4a1SAndreas Gohr        //if link contains no namespace. add current namespace (if any)
479c4e0e4a1SAndreas Gohr        $id = $ns.':'.$id;
480c4e0e4a1SAndreas Gohr    }
481c4e0e4a1SAndreas Gohr
482a6ef4796SAndreas Gohr    if($clean) $id = cleanID($id);
483a6ef4796SAndreas Gohr    return $id;
484c4e0e4a1SAndreas Gohr}
485c4e0e4a1SAndreas Gohr
486c4e0e4a1SAndreas Gohr/**
487b625487dSandi * Returns a full media id
488b625487dSandi *
489b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
49084657ea2SGerrit Uitslag *
49184657ea2SGerrit Uitslag * @param string  $ns     namespace which is context of id
49284657ea2SGerrit Uitslag * @param string &$page   (reference) relative media id, updated to resolved id
49384657ea2SGerrit Uitslag * @param bool   &$exists (reference) updated with existance of media
494b625487dSandi */
49590bee600Slispsfunction resolve_mediaid($ns,&$page,&$exists,$rev='',$date_at=false){
496*1d053a56Slisps    $page   = resolve_id($ns,$page);
49790bee600Slisps    if($rev !== '' &&  $date_at){
498*1d053a56Slisps        $medialog = new MediaChangeLog($page);
49990bee600Slisps        $medialog_rev = $medialog->getLastRevisionAt($rev);
50090bee600Slisps        if($medialog_rev !== false) {
50190bee600Slisps            $rev = $medialog_rev;
50290bee600Slisps        }
50390bee600Slisps    }
504*1d053a56Slisps
5054cd9f791Slisps    $file   = mediaFN($page,$rev);
506b625487dSandi    $exists = @file_exists($file);
507b625487dSandi}
508b625487dSandi
509b625487dSandi/**
510b625487dSandi * Returns a full page id
511b625487dSandi *
512b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
51384657ea2SGerrit Uitslag *
51484657ea2SGerrit Uitslag * @param string  $ns     namespace which is context of id
51584657ea2SGerrit Uitslag * @param string &$page   (reference) relative page id, updated to resolved id
51684657ea2SGerrit Uitslag * @param bool   &$exists (reference) updated with existance of media
517b625487dSandi */
51890bee600Slispsfunction resolve_pageid($ns,&$page,&$exists,$rev='',$date_at=false ){
519b625487dSandi    global $conf;
520c006739eSIzidor Matušov    global $ID;
5210b7c14c2Sandi    $exists = false;
522b625487dSandi
523c006739eSIzidor Matušov    //empty address should point to current page
524c006739eSIzidor Matušov    if ($page === "") {
525c006739eSIzidor Matušov        $page = $ID;
526c006739eSIzidor Matušov    }
527c006739eSIzidor Matušov
528b625487dSandi    //keep hashlink if exists then clean both parts
52903c4aec3Schris    if (strpos($page,'#')) {
5304b7f9e70STom N Harris        list($page,$hash) = explode('#',$page,2);
53103c4aec3Schris    } else {
53203c4aec3Schris        $hash = '';
53303c4aec3Schris    }
534b625487dSandi    $hash = cleanID($hash);
535a6ef4796SAndreas Gohr    $page = resolve_id($ns,$page,false); // resolve but don't clean, yet
536b625487dSandi
537a6ef4796SAndreas Gohr    // get filename (calls clean itself)
53890bee600Slisps    if($rev !== '' && $date_at) {
53990bee600Slisps        $pagelog = new PageChangeLog($page);
54090bee600Slisps        $pagelog_rev = $pagelog->getLastRevisionAt($rev);
54190bee600Slisps        if($pagelog_rev !== false)//something found
54290bee600Slisps           $rev  = $pagelog_rev;
54390bee600Slisps    }
5444cd9f791Slisps    $file = wikiFN($page,$rev);
545b625487dSandi
5461179df0eSGuy Brand    // if ends with colon or slash we have a namespace link
547b26cdbbeSAdrian Lang    if(in_array(substr($page,-1), array(':', ';')) ||
548b26cdbbeSAdrian Lang       ($conf['useslash'] && substr($page,-1) == '/')){
54990bee600Slisps        if(page_exists($page.$conf['start'],$rev,true,$date_at)){
550a6ef4796SAndreas Gohr            // start page inside namespace
551a6ef4796SAndreas Gohr            $page = $page.$conf['start'];
552a6ef4796SAndreas Gohr            $exists = true;
55390bee600Slisps        }elseif(page_exists($page.noNS(cleanID($page)),$rev,true,$date_at)){
554a6ef4796SAndreas Gohr            // page named like the NS inside the NS
555a6ef4796SAndreas Gohr            $page = $page.noNS(cleanID($page));
556a6ef4796SAndreas Gohr            $exists = true;
55790bee600Slisps        }elseif(page_exists($page,$rev,true,$date_at)){
558a6ef4796SAndreas Gohr            // page like namespace exists
559a6ef4796SAndreas Gohr            $page = $page;
560a6ef4796SAndreas Gohr            $exists = true;
561a6ef4796SAndreas Gohr        }else{
562a6ef4796SAndreas Gohr            // fall back to default
563a6ef4796SAndreas Gohr            $page = $page.$conf['start'];
564a6ef4796SAndreas Gohr        }
565a6ef4796SAndreas Gohr    }else{
566b625487dSandi        //check alternative plural/nonplural form
567b625487dSandi        if(!@file_exists($file)){
568b625487dSandi            if( $conf['autoplural'] ){
569b625487dSandi                if(substr($page,-1) == 's'){
570b625487dSandi                    $try = substr($page,0,-1);
571b625487dSandi                }else{
572b625487dSandi                    $try = $page.'s';
573b625487dSandi                }
57490bee600Slisps                if(page_exists($try,$rev,true,$date_at)){
575b625487dSandi                    $page   = $try;
576b625487dSandi                    $exists = true;
577b625487dSandi                }
578b625487dSandi            }
579b625487dSandi        }else{
580b625487dSandi            $exists = true;
581b625487dSandi        }
582a6ef4796SAndreas Gohr    }
583a6ef4796SAndreas Gohr
584a6ef4796SAndreas Gohr    // now make sure we have a clean page
585a6ef4796SAndreas Gohr    $page = cleanID($page);
586b625487dSandi
587b625487dSandi    //add hash if any
588b2d7d3f2Sandi    if(!empty($hash)) $page .= '#'.$hash;
589b625487dSandi}
590b625487dSandi
59198407a7aSandi/**
59298407a7aSandi * Returns the name of a cachefile from given data
59398407a7aSandi *
59498407a7aSandi * The needed directory is created by this function!
59598407a7aSandi *
59698407a7aSandi * @author Andreas Gohr <andi@splitbrain.org>
59798407a7aSandi *
59898407a7aSandi * @param string $data  This data is used to create a unique md5 name
59998407a7aSandi * @param string $ext   This is appended to the filename if given
60098407a7aSandi * @return string       The filename of the cachefile
60198407a7aSandi */
60298407a7aSandifunction getCacheName($data,$ext=''){
60398407a7aSandi    global $conf;
60498407a7aSandi    $md5  = md5($data);
60598407a7aSandi    $file = $conf['cachedir'].'/'.$md5{0}.'/'.$md5.$ext;
60698407a7aSandi    io_makeFileDir($file);
60798407a7aSandi    return $file;
60898407a7aSandi}
60998407a7aSandi
6100dc92c6fSAndreas Gohr/**
6110dc92c6fSAndreas Gohr * Checks a pageid against $conf['hidepages']
6120dc92c6fSAndreas Gohr *
6130dc92c6fSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
61484657ea2SGerrit Uitslag *
61584657ea2SGerrit Uitslag * @param string $id page id
61684657ea2SGerrit Uitslag * @return bool
6170dc92c6fSAndreas Gohr */
6180dc92c6fSAndreas Gohrfunction isHiddenPage($id){
6198449cc9dSDominik Eckelmann    $data = array(
6208449cc9dSDominik Eckelmann        'id' => $id,
6218449cc9dSDominik Eckelmann        'hidden' => false
6228449cc9dSDominik Eckelmann    );
623fb55b51eSDominik Eckelmann    trigger_event('PAGEUTILS_ID_HIDEPAGE', $data, '_isHiddenPage');
624fb55b51eSDominik Eckelmann    return $data['hidden'];
6250dc92c6fSAndreas Gohr}
626fb55b51eSDominik Eckelmann
627dbf714f7SGerrit Uitslag/**
628dbf714f7SGerrit Uitslag * callback checks if page is hidden
629dbf714f7SGerrit Uitslag *
63084657ea2SGerrit Uitslag * @param array $data event data    - see isHiddenPage()
631dbf714f7SGerrit Uitslag */
632fb55b51eSDominik Eckelmannfunction _isHiddenPage(&$data) {
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 */
6530dc92c6fSAndreas Gohrfunction isVisiblePage($id){
6540dc92c6fSAndreas Gohr    return !isHiddenPage($id);
6550dc92c6fSAndreas Gohr}
6560dc92c6fSAndreas Gohr
6575b75cd1fSAdrian Lang/**
6585b75cd1fSAdrian Lang * Format an id for output to a user
6595b75cd1fSAdrian Lang *
6605b75cd1fSAdrian Lang * Namespaces are denoted by a trailing “:*”. The root namespace is
6615b75cd1fSAdrian Lang * “*”. Output is escaped.
6625b75cd1fSAdrian Lang *
6635b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
66484657ea2SGerrit Uitslag *
66584657ea2SGerrit Uitslag * @param string $id page id
66684657ea2SGerrit Uitslag * @return string
6675b75cd1fSAdrian Lang */
6685b75cd1fSAdrian Langfunction prettyprint_id($id) {
6695b75cd1fSAdrian Lang    if (!$id || $id === ':') {
6705b75cd1fSAdrian Lang        return '*';
6715b75cd1fSAdrian Lang    }
6725b75cd1fSAdrian Lang    if ((substr($id, -1, 1) === ':')) {
6735b75cd1fSAdrian Lang        $id .= '*';
6745b75cd1fSAdrian Lang    }
6755b75cd1fSAdrian Lang    return hsc($id);
6765b75cd1fSAdrian Lang}
677f03fd957SAndreas Gohr
678f03fd957SAndreas Gohr/**
679f03fd957SAndreas Gohr * Encode a UTF-8 filename to use on any filesystem
680f03fd957SAndreas Gohr *
681f03fd957SAndreas Gohr * Uses the 'fnencode' option to determine encoding
682f03fd957SAndreas Gohr *
683f03fd957SAndreas Gohr * When the second parameter is true the string will
684f03fd957SAndreas Gohr * be encoded only if non ASCII characters are detected -
685f03fd957SAndreas Gohr * This makes it safe to run it multiple times on the
686f03fd957SAndreas Gohr * same string (default is true)
687f03fd957SAndreas Gohr *
688f03fd957SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
689f03fd957SAndreas Gohr * @see    urlencode
69084657ea2SGerrit Uitslag *
69184657ea2SGerrit Uitslag * @param string $file file name
69284657ea2SGerrit Uitslag * @param bool   $safe if true, only encoded when non ASCII characters detected
69384657ea2SGerrit Uitslag * @return string
694f03fd957SAndreas Gohr */
695f03fd957SAndreas Gohrfunction utf8_encodeFN($file,$safe=true){
696f03fd957SAndreas Gohr    global $conf;
697f03fd957SAndreas Gohr    if($conf['fnencode'] == 'utf-8') return $file;
698f03fd957SAndreas Gohr
699f03fd957SAndreas Gohr    if($safe && preg_match('#^[a-zA-Z0-9/_\-\.%]+$#',$file)){
700f03fd957SAndreas Gohr        return $file;
701f03fd957SAndreas Gohr    }
702f03fd957SAndreas Gohr
703f03fd957SAndreas Gohr    if($conf['fnencode'] == 'safe'){
704f03fd957SAndreas Gohr        return SafeFN::encode($file);
705f03fd957SAndreas Gohr    }
706f03fd957SAndreas Gohr
707f03fd957SAndreas Gohr    $file = urlencode($file);
708f03fd957SAndreas Gohr    $file = str_replace('%2F','/',$file);
709f03fd957SAndreas Gohr    return $file;
710f03fd957SAndreas Gohr}
711f03fd957SAndreas Gohr
712f03fd957SAndreas Gohr/**
713f03fd957SAndreas Gohr * Decode a filename back to UTF-8
714f03fd957SAndreas Gohr *
715f03fd957SAndreas Gohr * Uses the 'fnencode' option to determine encoding
716f03fd957SAndreas Gohr *
717f03fd957SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
718f03fd957SAndreas Gohr * @see    urldecode
71984657ea2SGerrit Uitslag *
72084657ea2SGerrit Uitslag * @param string $file file name
72184657ea2SGerrit Uitslag * @return string
722f03fd957SAndreas Gohr */
723f03fd957SAndreas Gohrfunction utf8_decodeFN($file){
724f03fd957SAndreas Gohr    global $conf;
725f03fd957SAndreas Gohr    if($conf['fnencode'] == 'utf-8') return $file;
726f03fd957SAndreas Gohr
727f03fd957SAndreas Gohr    if($conf['fnencode'] == 'safe'){
728f03fd957SAndreas Gohr        return SafeFN::decode($file);
729f03fd957SAndreas Gohr    }
730f03fd957SAndreas Gohr
731f03fd957SAndreas Gohr    return urldecode($file);
732f03fd957SAndreas Gohr}
733f03fd957SAndreas Gohr
734e66d3e6dSAndreas Gohr/**
735e66d3e6dSAndreas Gohr * Find a page in the current namespace (determined from $ID) or any
736e66d3e6dSAndreas Gohr * higher namespace
737e66d3e6dSAndreas Gohr *
738e66d3e6dSAndreas Gohr * Used for sidebars, but can be used other stuff as well
739e66d3e6dSAndreas Gohr *
740e66d3e6dSAndreas Gohr * @todo   add event hook
741e66d3e6dSAndreas Gohr * @param  string $page the pagename you're looking for
742e66d3e6dSAndreas Gohr * @return string|false the full page id of the found page, false if any
743e66d3e6dSAndreas Gohr */
744e66d3e6dSAndreas Gohrfunction page_findnearest($page){
745c786a1b6SAnika Henke    if (!$page) return false;
746e66d3e6dSAndreas Gohr    global $ID;
747e66d3e6dSAndreas Gohr
748e66d3e6dSAndreas Gohr    $ns = $ID;
749e66d3e6dSAndreas Gohr    do {
750e66d3e6dSAndreas Gohr        $ns = getNS($ns);
751e66d3e6dSAndreas Gohr        $pageid = ltrim("$ns:$page",':');
752e66d3e6dSAndreas Gohr        if(page_exists($pageid)){
753e66d3e6dSAndreas Gohr            return $pageid;
754e66d3e6dSAndreas Gohr        }
755e66d3e6dSAndreas Gohr    } while($ns);
756e66d3e6dSAndreas Gohr
757e66d3e6dSAndreas Gohr    return false;
758e66d3e6dSAndreas Gohr}
759