xref: /dokuwiki/inc/pageutils.php (revision cc5294682913a4fdb87184d3b5bfdd8e28678ed2)
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
2342ea7f44SGerrit Uitslag * @return 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>
10042ea7f44SGerrit Uitslag *
1016e0cc83aSchris * @param  string  $raw_id    The pageid to clean
1028a831f2bSAndreas Gohr * @param  boolean $ascii     Force ASCII
103dbf714f7SGerrit Uitslag * @return string cleaned id
104b625487dSandi */
105c8bbb094SAnika Henkefunction cleanID($raw_id,$ascii=false){
106b625487dSandi    global $conf;
1074b5db43bSjoe.lapp    static $sepcharpat = null;
1084b5db43bSjoe.lapp
109dc2c0e04Schris    global $cache_cleanid;
110dc2c0e04Schris    $cache = & $cache_cleanid;
1116e0cc83aSchris
1126e0cc83aSchris    // check if it's already in the memory cache
1133a50618cSgweissbach    if (isset($cache[(string)$raw_id])) {
1143a50618cSgweissbach        return $cache[(string)$raw_id];
1156e0cc83aSchris    }
1166e0cc83aSchris
1174b5db43bSjoe.lapp    $sepchar = $conf['sepchar'];
1184b5db43bSjoe.lapp    if($sepcharpat == null) // build string only once to save clock cycles
1194b5db43bSjoe.lapp        $sepcharpat = '#\\'.$sepchar.'+#';
1204b5db43bSjoe.lapp
1213a50618cSgweissbach    $id = trim((string)$raw_id);
122b625487dSandi    $id = utf8_strtolower($id);
123b625487dSandi
124b625487dSandi    //alternative namespace seperator
125b625487dSandi    if($conf['useslash']){
1263755fc25STom N Harris        $id = strtr($id,';/','::');
127b625487dSandi    }else{
1283755fc25STom N Harris        $id = strtr($id,';/',':'.$sepchar);
129b625487dSandi    }
130b625487dSandi
1318a831f2bSAndreas Gohr    if($conf['deaccent'] == 2 || $ascii) $id = utf8_romanize($id);
1328a831f2bSAndreas Gohr    if($conf['deaccent'] || $ascii) $id = utf8_deaccent($id,-1);
133b625487dSandi
134b625487dSandi    //remove specials
135ad81d431SAndreas Gohr    $id = utf8_stripspecials($id,$sepchar,'\*');
136b625487dSandi
1378a831f2bSAndreas Gohr    if($ascii) $id = utf8_strip($id);
1388a831f2bSAndreas Gohr
139b625487dSandi    //clean up
1404b5db43bSjoe.lapp    $id = preg_replace($sepcharpat,$sepchar,$id);
141b625487dSandi    $id = preg_replace('#:+#',':',$id);
1423543c6deSAndreas Gohr    $id = trim($id,':._-');
143b625487dSandi    $id = preg_replace('#:[:\._\-]+#',':',$id);
144b680ea06SAndreas Gohr    $id = preg_replace('#[:\._\-]+:#',':',$id);
145b625487dSandi
1463a50618cSgweissbach    $cache[(string)$raw_id] = $id;
147b625487dSandi    return($id);
148b625487dSandi}
149b625487dSandi
150b625487dSandi/**
151b625487dSandi * Return namespacepart of a wiki ID
152b625487dSandi *
153b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
15415851b98SGerrit Uitslag *
15515851b98SGerrit Uitslag * @param string $id
15642ea7f44SGerrit Uitslag * @return string|false the namespace part or false if the given ID has no namespace (root)
157b625487dSandi */
158b625487dSandifunction getNS($id){
1593a50618cSgweissbach    $pos = strrpos((string)$id,':');
160c4e0e4a1SAndreas Gohr    if($pos!==false){
1613a50618cSgweissbach        return substr((string)$id,0,$pos);
162b625487dSandi    }
163ef11fcfcSAndreas Gohr    return false;
164b625487dSandi}
165b625487dSandi
166b625487dSandi/**
167b625487dSandi * Returns the ID without the namespace
168b625487dSandi *
169b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
17015851b98SGerrit Uitslag *
17115851b98SGerrit Uitslag * @param string $id
17215851b98SGerrit Uitslag * @return string
173b625487dSandi */
174b625487dSandifunction noNS($id) {
1752844584fSBen Coburn    $pos = strrpos($id, ':');
1762844584fSBen Coburn    if ($pos!==false) {
1772844584fSBen Coburn        return substr($id, $pos+1);
1782844584fSBen Coburn    } else {
1792844584fSBen Coburn        return $id;
1802844584fSBen Coburn    }
1811a84a0f3SAnika Henke}
1821a84a0f3SAnika Henke
1831a84a0f3SAnika Henke/**
1841a84a0f3SAnika Henke * Returns the current namespace
1851a84a0f3SAnika Henke *
1861a84a0f3SAnika Henke * @author Nathan Fritz <fritzn@crown.edu>
18784657ea2SGerrit Uitslag *
18884657ea2SGerrit Uitslag * @param string $id
18984657ea2SGerrit Uitslag * @return string
1901a84a0f3SAnika Henke */
1911a84a0f3SAnika Henkefunction curNS($id) {
1921a84a0f3SAnika Henke    return noNS(getNS($id));
1931a84a0f3SAnika Henke}
1941a84a0f3SAnika Henke
1951a84a0f3SAnika Henke/**
1961a84a0f3SAnika Henke * Returns the ID without the namespace or current namespace for 'start' pages
1971a84a0f3SAnika Henke *
1981a84a0f3SAnika Henke * @author Nathan Fritz <fritzn@crown.edu>
19984657ea2SGerrit Uitslag *
20084657ea2SGerrit Uitslag * @param string $id
20184657ea2SGerrit Uitslag * @return string
2021a84a0f3SAnika Henke */
2031a84a0f3SAnika Henkefunction noNSorNS($id) {
2041a84a0f3SAnika Henke    global $conf;
2051a84a0f3SAnika Henke
2061a84a0f3SAnika Henke    $p = noNS($id);
2079708106bSAdrian Lang    if ($p == $conf['start'] || $p == false) {
2081a84a0f3SAnika Henke        $p = curNS($id);
2091a84a0f3SAnika Henke        if ($p == false) {
2109708106bSAdrian Lang            return $conf['start'];
2111a84a0f3SAnika Henke        }
2121a84a0f3SAnika Henke    }
2131a84a0f3SAnika Henke    return $p;
214b625487dSandi}
2154ceab83fSAndreas Gohr
2164ceab83fSAndreas Gohr/**
2174ceab83fSAndreas Gohr * Creates a XHTML valid linkid from a given headline title
2184ceab83fSAndreas Gohr *
2194ceab83fSAndreas Gohr * @param string  $title   The headline title
220c857afe0SMichael Hamann * @param array|bool   $check   Existing IDs (title => number)
221c857afe0SMichael Hamann * @return string the title
22284657ea2SGerrit Uitslag *
2234ceab83fSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
2244ceab83fSAndreas Gohr */
225443d207bSAndreas Gohrfunction sectionID($title,&$check) {
226de9114eaSAnika Henke    $title = str_replace(array(':','.'),'',cleanID($title));
227de9114eaSAnika Henke    $new = ltrim($title,'0123456789_-');
2284ceab83fSAndreas Gohr    if(empty($new)){
2294ceab83fSAndreas Gohr        $title = 'section'.preg_replace('/[^0-9]+/','',$title); //keep numbers from headline
2304ceab83fSAndreas Gohr    }else{
2314ceab83fSAndreas Gohr        $title = $new;
2324ceab83fSAndreas Gohr    }
2334ceab83fSAndreas Gohr
234443d207bSAndreas Gohr    if(is_array($check)){
2354ceab83fSAndreas Gohr        // make sure tiles are unique
23601e3159cSChris Tapp        if (!array_key_exists ($title,$check)) {
23701e3159cSChris Tapp            $check[$title] = 0;
23801e3159cSChris Tapp        } else {
23901e3159cSChris Tapp            $title .= ++ $check[$title];
2404ceab83fSAndreas Gohr        }
2414ceab83fSAndreas Gohr    }
2424ceab83fSAndreas Gohr
2434ceab83fSAndreas Gohr    return $title;
2444ceab83fSAndreas Gohr}
2454ceab83fSAndreas Gohr
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)
2567de86af9SGerrit Uitslag * @param bool $date_at
25784657ea2SGerrit Uitslag * @return bool exists?
258103c256aSChris Smith */
2591d053a56Slispsfunction page_exists($id,$rev='',$clean=true, $date_at=false) {
26090bee600Slisps    if($rev !== '' && $date_at) {
2611d053a56Slisps        $pagelog = new PageChangeLog($id);
26290bee600Slisps        $pagelog_rev = $pagelog->getLastRevisionAt($rev);
26390bee600Slisps        if($pagelog_rev !== false)
26490bee600Slisps            $rev = $pagelog_rev;
26590bee600Slisps    }
26679e79377SAndreas Gohr    return file_exists(wikiFN($id,$rev,$clean));
267103c256aSChris Smith}
268103c256aSChris Smith
269103c256aSChris Smith/**
270103c256aSChris Smith * returns the full path to the datafile specified by ID and optional revision
271b625487dSandi *
272b625487dSandi * The filename is URL encoded to protect Unicode chars
273b625487dSandi *
274103c256aSChris Smith * @param  $raw_id  string   id of wikipage
275e0c26282SGerrit Uitslag * @param  $rev     int|string   page revision, empty string for current
276103c256aSChris Smith * @param  $clean   bool     flag indicating that $raw_id should be cleaned.  Only set to false
277103c256aSChris Smith *                           when $id is guaranteed to have been cleaned already.
278dbf714f7SGerrit Uitslag * @return string full path
279103c256aSChris Smith *
280b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
281b625487dSandi */
2826e0cc83aSchrisfunction wikiFN($raw_id,$rev='',$clean=true){
283b625487dSandi    global $conf;
2846e0cc83aSchris
285dc2c0e04Schris    global $cache_wikifn;
286dc2c0e04Schris    $cache = & $cache_wikifn;
287dc2c0e04Schris
2886e0cc83aSchris    if (isset($cache[$raw_id]) && isset($cache[$raw_id][$rev])) {
2896e0cc83aSchris        return $cache[$raw_id][$rev];
2906e0cc83aSchris    }
2916e0cc83aSchris
2926e0cc83aSchris    $id = $raw_id;
2936e0cc83aSchris
2940d8ea614Schris    if ($clean) $id = cleanID($id);
295b625487dSandi    $id = str_replace(':','/',$id);
296b625487dSandi    if(empty($rev)){
297b625487dSandi        $fn = $conf['datadir'].'/'.utf8_encodeFN($id).'.txt';
298b625487dSandi    }else{
299b625487dSandi        $fn = $conf['olddir'].'/'.utf8_encodeFN($id).'.'.$rev.'.txt';
300ff3ed99fSmarcel        if($conf['compression']){
301ff3ed99fSmarcel            //test for extensions here, we want to read both compressions
30279e79377SAndreas Gohr            if (file_exists($fn . '.gz')){
303b625487dSandi                $fn .= '.gz';
30479e79377SAndreas Gohr            }else if(file_exists($fn . '.bz2')){
305ff3ed99fSmarcel                $fn .= '.bz2';
306ff3ed99fSmarcel            }else{
307ff3ed99fSmarcel                //file doesnt exist yet, so we take the configured extension
308ff3ed99fSmarcel                $fn .= '.' . $conf['compression'];
309ff3ed99fSmarcel            }
310b625487dSandi        }
311b625487dSandi    }
3126e0cc83aSchris
31350602150SBen Coburn    if (!isset($cache[$raw_id])) { $cache[$raw_id] = array(); }
3146e0cc83aSchris    $cache[$raw_id][$rev] = $fn;
315b625487dSandi    return $fn;
316b625487dSandi}
317b625487dSandi
318b625487dSandi/**
319c9b4bd1eSBen Coburn * Returns the full path to the file for locking the page while editing.
320c9b4bd1eSBen Coburn *
321c9b4bd1eSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
32284657ea2SGerrit Uitslag *
32384657ea2SGerrit Uitslag * @param string $id page id
32484657ea2SGerrit Uitslag * @return string full path
325c9b4bd1eSBen Coburn */
326c9b4bd1eSBen Coburnfunction wikiLockFN($id) {
327c9b4bd1eSBen Coburn    global $conf;
328662ff478SAndreas Gohr    return $conf['lockdir'].'/'.md5(cleanID($id)).'.lock';
329c9b4bd1eSBen Coburn}
330c9b4bd1eSBen Coburn
331c9b4bd1eSBen Coburn
332c9b4bd1eSBen Coburn/**
3331380fc45SAndreas Gohr * returns the full path to the meta file specified by ID and extension
334b158d625SSteven Danz *
335b158d625SSteven Danz * @author Steven Danz <steven-danz@kc.rr.com>
33684657ea2SGerrit Uitslag *
33784657ea2SGerrit Uitslag * @param string $id   page id
33884657ea2SGerrit Uitslag * @param string $ext  file extension
33984657ea2SGerrit Uitslag * @return string full path
340b158d625SSteven Danz */
3411380fc45SAndreas Gohrfunction metaFN($id,$ext){
342b158d625SSteven Danz    global $conf;
343b158d625SSteven Danz    $id = cleanID($id);
344b158d625SSteven Danz    $id = str_replace(':','/',$id);
3451380fc45SAndreas Gohr    $fn = $conf['metadir'].'/'.utf8_encodeFN($id).$ext;
346b158d625SSteven Danz    return $fn;
347b158d625SSteven Danz}
348b158d625SSteven Danz
349b158d625SSteven Danz/**
350e4f389efSKate Arzamastseva * returns the full path to the media's meta file specified by ID and extension
351e4f389efSKate Arzamastseva *
352cbe26ad6SKate Arzamastseva * @author Kate Arzamastseva <pshns@ukr.net>
35384657ea2SGerrit Uitslag *
35484657ea2SGerrit Uitslag * @param string $id   media id
35584657ea2SGerrit Uitslag * @param string $ext  extension of media
35684657ea2SGerrit Uitslag * @return string
357e4f389efSKate Arzamastseva */
358e4f389efSKate Arzamastsevafunction mediaMetaFN($id,$ext){
359e4f389efSKate Arzamastseva    global $conf;
360e4f389efSKate Arzamastseva    $id = cleanID($id);
361e4f389efSKate Arzamastseva    $id = str_replace(':','/',$id);
362e4f389efSKate Arzamastseva    $fn = $conf['mediametadir'].'/'.utf8_encodeFN($id).$ext;
363e4f389efSKate Arzamastseva    return $fn;
364e4f389efSKate Arzamastseva}
365e4f389efSKate Arzamastseva
366e4f389efSKate Arzamastseva/**
367e1f3d9e1SEsther Brunner * returns an array of full paths to all metafiles of a given ID
368e1f3d9e1SEsther Brunner *
369e1f3d9e1SEsther Brunner * @author Esther Brunner <esther@kaffeehaus.ch>
370ba0267b3SMichael Hamann * @author Michael Hamann <michael@content-space.de>
37184657ea2SGerrit Uitslag *
37284657ea2SGerrit Uitslag * @param string $id page id
37384657ea2SGerrit Uitslag * @return array
374e1f3d9e1SEsther Brunner */
375e1f3d9e1SEsther Brunnerfunction metaFiles($id){
376ba0267b3SMichael Hamann    $basename = metaFN($id, '');
377ba0267b3SMichael Hamann    $files    = glob($basename.'.*', GLOB_MARK);
378ba0267b3SMichael Hamann    // filter files like foo.bar.meta when $id == 'foo'
379ba0267b3SMichael Hamann    return    $files ? preg_grep('/^'.preg_quote($basename, '/').'\.[^.\/]*$/u', $files) : array();
380e1f3d9e1SEsther Brunner}
381e1f3d9e1SEsther Brunner
382e1f3d9e1SEsther Brunner/**
383b625487dSandi * returns the full path to the mediafile specified by ID
384b625487dSandi *
385b625487dSandi * The filename is URL encoded to protect Unicode chars
386b625487dSandi *
387b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
388cbe26ad6SKate Arzamastseva * @author Kate Arzamastseva <pshns@ukr.net>
38984657ea2SGerrit Uitslag *
39084657ea2SGerrit Uitslag * @param string     $id  media id
39184657ea2SGerrit Uitslag * @param string|int $rev empty string or revision timestamp
39284657ea2SGerrit Uitslag * @return string full path
393b625487dSandi */
394e4f389efSKate Arzamastsevafunction mediaFN($id, $rev=''){
395b625487dSandi    global $conf;
396b625487dSandi    $id = cleanID($id);
397b625487dSandi    $id = str_replace(':','/',$id);
398e4f389efSKate Arzamastseva    if(empty($rev)){
399b625487dSandi        $fn = $conf['mediadir'].'/'.utf8_encodeFN($id);
400e4f389efSKate Arzamastseva    }else{
401cbe26ad6SKate Arzamastseva        $ext = mimetype($id);
4028e69fd30SKate Arzamastseva        $name = substr($id,0, -1*strlen($ext[0])-1);
40361f1aad8SKate Arzamastseva        $fn = $conf['mediaolddir'].'/'.utf8_encodeFN($name .'.'.( (int) $rev ).'.'.$ext[0]);
404e4f389efSKate Arzamastseva    }
405b625487dSandi    return $fn;
406b625487dSandi}
407b625487dSandi
408b625487dSandi/**
4092adaf2b8SAndreas Gohr * Returns the full filepath to a localized file if local
410b625487dSandi * version isn't found the english one is returned
411b625487dSandi *
4122adaf2b8SAndreas Gohr * @param  string $id  The id of the local file
4132adaf2b8SAndreas Gohr * @param  string $ext The file extension (usually txt)
414dbf714f7SGerrit Uitslag * @return string full filepath to localized file
41584657ea2SGerrit Uitslag *
416b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
417b625487dSandi */
4182adaf2b8SAndreas Gohrfunction localeFN($id,$ext='txt'){
419b625487dSandi    global $conf;
4208819fbf5ShArpanet    $file = DOKU_CONF.'lang/'.$conf['lang'].'/'.$id.'.'.$ext;
42179e79377SAndreas Gohr    if(!file_exists($file)){
4222adaf2b8SAndreas Gohr        $file = DOKU_INC.'inc/lang/'.$conf['lang'].'/'.$id.'.'.$ext;
42379e79377SAndreas Gohr        if(!file_exists($file)){
424b625487dSandi            //fall back to english
4252adaf2b8SAndreas Gohr            $file = DOKU_INC.'inc/lang/en/'.$id.'.'.$ext;
426b625487dSandi        }
427e6cecb08SMichael Hamann    }
428b625487dSandi    return $file;
429b625487dSandi}
430b625487dSandi
431b625487dSandi/**
432c4e0e4a1SAndreas Gohr * Resolve relative paths in IDs
433c4e0e4a1SAndreas Gohr *
434c4e0e4a1SAndreas Gohr * Do not call directly use resolve_mediaid or resolve_pageid
435c4e0e4a1SAndreas Gohr * instead
436c4e0e4a1SAndreas Gohr *
437c4e0e4a1SAndreas Gohr * Partyly based on a cleanPath function found at
438c4e0e4a1SAndreas Gohr * http://www.php.net/manual/en/function.realpath.php#57016
439c4e0e4a1SAndreas Gohr *
440c4e0e4a1SAndreas Gohr * @author <bart at mediawave dot nl>
44184657ea2SGerrit Uitslag *
44284657ea2SGerrit Uitslag * @param string $ns     namespace which is context of id
44384657ea2SGerrit Uitslag * @param string $id     relative id
44484657ea2SGerrit Uitslag * @param bool   $clean  flag indicating that id should be cleaned
44542ea7f44SGerrit Uitslag * @return string
446c4e0e4a1SAndreas Gohr */
447a6ef4796SAndreas Gohrfunction resolve_id($ns,$id,$clean=true){
448c662a49aSAndreas Gohr    global $conf;
449c662a49aSAndreas Gohr
450c662a49aSAndreas Gohr    // some pre cleaning for useslash:
451c662a49aSAndreas Gohr    if($conf['useslash']) $id = str_replace('/',':',$id);
452c662a49aSAndreas Gohr
453c4e0e4a1SAndreas Gohr    // if the id starts with a dot we need to handle the
454c4e0e4a1SAndreas Gohr    // relative stuff
455443e135dSChristopher Smith    if($id && $id{0} == '.'){
456c4e0e4a1SAndreas Gohr        // normalize initial dots without a colon
457c4e0e4a1SAndreas Gohr        $id = preg_replace('/^(\.+)(?=[^:\.])/','\1:',$id);
458c4e0e4a1SAndreas Gohr        // prepend the current namespace
459c4e0e4a1SAndreas Gohr        $id = $ns.':'.$id;
460c4e0e4a1SAndreas Gohr
461c4e0e4a1SAndreas Gohr        // cleanup relatives
462c4e0e4a1SAndreas Gohr        $result = array();
463c4e0e4a1SAndreas Gohr        $pathA  = explode(':', $id);
464c4e0e4a1SAndreas Gohr        if (!$pathA[0]) $result[] = '';
465c4e0e4a1SAndreas Gohr        foreach ($pathA AS $key => $dir) {
466c4e0e4a1SAndreas Gohr            if ($dir == '..') {
467c4e0e4a1SAndreas Gohr                if (end($result) == '..') {
468c4e0e4a1SAndreas Gohr                    $result[] = '..';
469c4e0e4a1SAndreas Gohr                } elseif (!array_pop($result)) {
470c4e0e4a1SAndreas Gohr                    $result[] = '..';
471c4e0e4a1SAndreas Gohr                }
472c4e0e4a1SAndreas Gohr            } elseif ($dir && $dir != '.') {
473c4e0e4a1SAndreas Gohr                $result[] = $dir;
474c4e0e4a1SAndreas Gohr            }
475c4e0e4a1SAndreas Gohr        }
476c4e0e4a1SAndreas Gohr        if (!end($pathA)) $result[] = '';
477c4e0e4a1SAndreas Gohr        $id = implode(':', $result);
478c4e0e4a1SAndreas Gohr    }elseif($ns !== false && strpos($id,':') === false){
479c4e0e4a1SAndreas Gohr        //if link contains no namespace. add current namespace (if any)
480c4e0e4a1SAndreas Gohr        $id = $ns.':'.$id;
481c4e0e4a1SAndreas Gohr    }
482c4e0e4a1SAndreas Gohr
483a6ef4796SAndreas Gohr    if($clean) $id = cleanID($id);
484a6ef4796SAndreas Gohr    return $id;
485c4e0e4a1SAndreas Gohr}
486c4e0e4a1SAndreas Gohr
487c4e0e4a1SAndreas Gohr/**
488b625487dSandi * Returns a full media id
489b625487dSandi *
490b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
49184657ea2SGerrit Uitslag *
49284657ea2SGerrit Uitslag * @param string $ns namespace which is context of id
49384657ea2SGerrit Uitslag * @param string &$page (reference) relative media id, updated to resolved id
49484657ea2SGerrit Uitslag * @param bool &$exists (reference) updated with existance of media
4957de86af9SGerrit Uitslag * @param int|string $rev
4967de86af9SGerrit Uitslag * @param bool $date_at
497b625487dSandi */
49890bee600Slispsfunction resolve_mediaid($ns,&$page,&$exists,$rev='',$date_at=false){
499c4e0e4a1SAndreas Gohr    $page   = resolve_id($ns,$page);
50090bee600Slisps    if($rev !== '' &&  $date_at){
5011d053a56Slisps        $medialog = new MediaChangeLog($page);
50290bee600Slisps        $medialog_rev = $medialog->getLastRevisionAt($rev);
50390bee600Slisps        if($medialog_rev !== false) {
50490bee600Slisps            $rev = $medialog_rev;
50590bee600Slisps        }
50690bee600Slisps    }
5071d053a56Slisps
5084cd9f791Slisps    $file   = mediaFN($page,$rev);
50979e79377SAndreas Gohr    $exists = file_exists($file);
510b625487dSandi}
511b625487dSandi
512b625487dSandi/**
513b625487dSandi * Returns a full page id
514b625487dSandi *
515b625487dSandi * @author Andreas Gohr <andi@splitbrain.org>
51684657ea2SGerrit Uitslag *
51784657ea2SGerrit Uitslag * @param string $ns namespace which is context of id
51884657ea2SGerrit Uitslag * @param string &$page (reference) relative page id, updated to resolved id
51984657ea2SGerrit Uitslag * @param bool &$exists (reference) updated with existance of media
5207de86af9SGerrit Uitslag * @param string $rev
5217de86af9SGerrit Uitslag * @param bool $date_at
522b625487dSandi */
52390bee600Slispsfunction resolve_pageid($ns,&$page,&$exists,$rev='',$date_at=false ){
524b625487dSandi    global $conf;
525c006739eSIzidor Matušov    global $ID;
5260b7c14c2Sandi    $exists = false;
527b625487dSandi
528c006739eSIzidor Matušov    //empty address should point to current page
529c006739eSIzidor Matušov    if ($page === "") {
530c006739eSIzidor Matušov        $page = $ID;
531c006739eSIzidor Matušov    }
532c006739eSIzidor Matušov
533b625487dSandi    //keep hashlink if exists then clean both parts
53403c4aec3Schris    if (strpos($page,'#')) {
5354b7f9e70STom N Harris        list($page,$hash) = explode('#',$page,2);
53603c4aec3Schris    } else {
53703c4aec3Schris        $hash = '';
53803c4aec3Schris    }
539b625487dSandi    $hash = cleanID($hash);
540a6ef4796SAndreas Gohr    $page = resolve_id($ns,$page,false); // resolve but don't clean, yet
541b625487dSandi
542a6ef4796SAndreas Gohr    // get filename (calls clean itself)
54390bee600Slisps    if($rev !== '' && $date_at) {
54490bee600Slisps        $pagelog = new PageChangeLog($page);
54590bee600Slisps        $pagelog_rev = $pagelog->getLastRevisionAt($rev);
54690bee600Slisps        if($pagelog_rev !== false)//something found
54790bee600Slisps           $rev  = $pagelog_rev;
54890bee600Slisps    }
5494cd9f791Slisps    $file = wikiFN($page,$rev);
550b625487dSandi
5511179df0eSGuy Brand    // if ends with colon or slash we have a namespace link
552b26cdbbeSAdrian Lang    if(in_array(substr($page,-1), array(':', ';')) ||
553b26cdbbeSAdrian Lang       ($conf['useslash'] && substr($page,-1) == '/')){
55490bee600Slisps        if(page_exists($page.$conf['start'],$rev,true,$date_at)){
555a6ef4796SAndreas Gohr            // start page inside namespace
556a6ef4796SAndreas Gohr            $page = $page.$conf['start'];
557a6ef4796SAndreas Gohr            $exists = true;
55890bee600Slisps        }elseif(page_exists($page.noNS(cleanID($page)),$rev,true,$date_at)){
559a6ef4796SAndreas Gohr            // page named like the NS inside the NS
560a6ef4796SAndreas Gohr            $page = $page.noNS(cleanID($page));
561a6ef4796SAndreas Gohr            $exists = true;
56290bee600Slisps        }elseif(page_exists($page,$rev,true,$date_at)){
563a6ef4796SAndreas Gohr            // page like namespace exists
564a6ef4796SAndreas Gohr            $page = $page;
565a6ef4796SAndreas Gohr            $exists = true;
566a6ef4796SAndreas Gohr        }else{
567a6ef4796SAndreas Gohr            // fall back to default
568a6ef4796SAndreas Gohr            $page = $page.$conf['start'];
569a6ef4796SAndreas Gohr        }
570a6ef4796SAndreas Gohr    }else{
571b625487dSandi        //check alternative plural/nonplural form
57279e79377SAndreas Gohr        if(!file_exists($file)){
573b625487dSandi            if( $conf['autoplural'] ){
574b625487dSandi                if(substr($page,-1) == 's'){
575b625487dSandi                    $try = substr($page,0,-1);
576b625487dSandi                }else{
577b625487dSandi                    $try = $page.'s';
578b625487dSandi                }
57990bee600Slisps                if(page_exists($try,$rev,true,$date_at)){
580b625487dSandi                    $page   = $try;
581b625487dSandi                    $exists = true;
582b625487dSandi                }
583b625487dSandi            }
584b625487dSandi        }else{
585b625487dSandi            $exists = true;
586b625487dSandi        }
587a6ef4796SAndreas Gohr    }
588a6ef4796SAndreas Gohr
589a6ef4796SAndreas Gohr    // now make sure we have a clean page
590a6ef4796SAndreas Gohr    $page = cleanID($page);
591b625487dSandi
592b625487dSandi    //add hash if any
593b2d7d3f2Sandi    if(!empty($hash)) $page .= '#'.$hash;
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 */
60798407a7aSandifunction getCacheName($data,$ext=''){
60898407a7aSandi    global $conf;
60998407a7aSandi    $md5  = md5($data);
61098407a7aSandi    $file = $conf['cachedir'].'/'.$md5{0}.'/'.$md5.$ext;
61198407a7aSandi    io_makeFileDir($file);
61298407a7aSandi    return $file;
61398407a7aSandi}
61498407a7aSandi
6150dc92c6fSAndreas Gohr/**
6160dc92c6fSAndreas Gohr * Checks a pageid against $conf['hidepages']
6170dc92c6fSAndreas Gohr *
6180dc92c6fSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
61984657ea2SGerrit Uitslag *
62084657ea2SGerrit Uitslag * @param string $id page id
62184657ea2SGerrit Uitslag * @return bool
6220dc92c6fSAndreas Gohr */
6230dc92c6fSAndreas Gohrfunction isHiddenPage($id){
6248449cc9dSDominik Eckelmann    $data = array(
6258449cc9dSDominik Eckelmann        'id' => $id,
6268449cc9dSDominik Eckelmann        'hidden' => false
6278449cc9dSDominik Eckelmann    );
628fb55b51eSDominik Eckelmann    trigger_event('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 */
637fb55b51eSDominik Eckelmannfunction _isHiddenPage(&$data) {
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 */
6580dc92c6fSAndreas Gohrfunction isVisiblePage($id){
6590dc92c6fSAndreas Gohr    return !isHiddenPage($id);
6600dc92c6fSAndreas Gohr}
6610dc92c6fSAndreas Gohr
6625b75cd1fSAdrian Lang/**
6635b75cd1fSAdrian Lang * Format an id for output to a user
6645b75cd1fSAdrian Lang *
6655b75cd1fSAdrian Lang * Namespaces are denoted by a trailing “:*”. The root namespace is
6665b75cd1fSAdrian Lang * “*”. Output is escaped.
6675b75cd1fSAdrian Lang *
6685b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
66984657ea2SGerrit Uitslag *
67084657ea2SGerrit Uitslag * @param string $id page id
67184657ea2SGerrit Uitslag * @return string
6725b75cd1fSAdrian Lang */
6735b75cd1fSAdrian Langfunction prettyprint_id($id) {
6745b75cd1fSAdrian Lang    if (!$id || $id === ':') {
6755b75cd1fSAdrian Lang        return '*';
6765b75cd1fSAdrian Lang    }
6775b75cd1fSAdrian Lang    if ((substr($id, -1, 1) === ':')) {
6785b75cd1fSAdrian Lang        $id .= '*';
6795b75cd1fSAdrian Lang    }
6805b75cd1fSAdrian Lang    return hsc($id);
6815b75cd1fSAdrian Lang}
682f03fd957SAndreas Gohr
683f03fd957SAndreas Gohr/**
684f03fd957SAndreas Gohr * Encode a UTF-8 filename to use on any filesystem
685f03fd957SAndreas Gohr *
686f03fd957SAndreas Gohr * Uses the 'fnencode' option to determine encoding
687f03fd957SAndreas Gohr *
688f03fd957SAndreas Gohr * When the second parameter is true the string will
689f03fd957SAndreas Gohr * be encoded only if non ASCII characters are detected -
690f03fd957SAndreas Gohr * This makes it safe to run it multiple times on the
691f03fd957SAndreas Gohr * same string (default is true)
692f03fd957SAndreas Gohr *
693f03fd957SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
694f03fd957SAndreas Gohr * @see    urlencode
69584657ea2SGerrit Uitslag *
69684657ea2SGerrit Uitslag * @param string $file file name
69784657ea2SGerrit Uitslag * @param bool   $safe if true, only encoded when non ASCII characters detected
69884657ea2SGerrit Uitslag * @return string
699f03fd957SAndreas Gohr */
700f03fd957SAndreas Gohrfunction utf8_encodeFN($file,$safe=true){
701f03fd957SAndreas Gohr    global $conf;
702f03fd957SAndreas Gohr    if($conf['fnencode'] == 'utf-8') return $file;
703f03fd957SAndreas Gohr
704f03fd957SAndreas Gohr    if($safe && preg_match('#^[a-zA-Z0-9/_\-\.%]+$#',$file)){
705f03fd957SAndreas Gohr        return $file;
706f03fd957SAndreas Gohr    }
707f03fd957SAndreas Gohr
708f03fd957SAndreas Gohr    if($conf['fnencode'] == 'safe'){
709f03fd957SAndreas Gohr        return SafeFN::encode($file);
710f03fd957SAndreas Gohr    }
711f03fd957SAndreas Gohr
712f03fd957SAndreas Gohr    $file = urlencode($file);
713f03fd957SAndreas Gohr    $file = str_replace('%2F','/',$file);
714f03fd957SAndreas Gohr    return $file;
715f03fd957SAndreas Gohr}
716f03fd957SAndreas Gohr
717f03fd957SAndreas Gohr/**
718f03fd957SAndreas Gohr * Decode a filename back to UTF-8
719f03fd957SAndreas Gohr *
720f03fd957SAndreas Gohr * Uses the 'fnencode' option to determine encoding
721f03fd957SAndreas Gohr *
722f03fd957SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
723f03fd957SAndreas Gohr * @see    urldecode
72484657ea2SGerrit Uitslag *
72584657ea2SGerrit Uitslag * @param string $file file name
72684657ea2SGerrit Uitslag * @return string
727f03fd957SAndreas Gohr */
728f03fd957SAndreas Gohrfunction utf8_decodeFN($file){
729f03fd957SAndreas Gohr    global $conf;
730f03fd957SAndreas Gohr    if($conf['fnencode'] == 'utf-8') return $file;
731f03fd957SAndreas Gohr
732f03fd957SAndreas Gohr    if($conf['fnencode'] == 'safe'){
733f03fd957SAndreas Gohr        return SafeFN::decode($file);
734f03fd957SAndreas Gohr    }
735f03fd957SAndreas Gohr
736f03fd957SAndreas Gohr    return urldecode($file);
737f03fd957SAndreas Gohr}
738f03fd957SAndreas Gohr
739e66d3e6dSAndreas Gohr/**
740e66d3e6dSAndreas Gohr * Find a page in the current namespace (determined from $ID) or any
741*cc529468SMichael Hamann * higher namespace that can be accessed by the current user,
742*cc529468SMichael Hamann * this condition can be overriden by an optional parameter.
743e66d3e6dSAndreas Gohr *
744e66d3e6dSAndreas Gohr * Used for sidebars, but can be used other stuff as well
745e66d3e6dSAndreas Gohr *
746e66d3e6dSAndreas Gohr * @todo   add event hook
74742ea7f44SGerrit Uitslag *
748e66d3e6dSAndreas Gohr * @param  string $page the pagename you're looking for
749*cc529468SMichael Hamann * @param bool $ignoreacl If pages that can't be accessed by the current user shall be returend
750*cc529468SMichael Hamann * @return false|string the full page id of the found page, false if any
751e66d3e6dSAndreas Gohr */
752*cc529468SMichael Hamannfunction page_findnearest($page, $ignoreacl = false){
753c786a1b6SAnika Henke    if (!$page) return false;
754e66d3e6dSAndreas Gohr    global $ID;
755e66d3e6dSAndreas Gohr
756e66d3e6dSAndreas Gohr    $ns = $ID;
757e66d3e6dSAndreas Gohr    do {
758e66d3e6dSAndreas Gohr        $ns = getNS($ns);
759*cc529468SMichael Hamann        $pageid = cleanID("$ns:$page");
760*cc529468SMichael Hamann        if(page_exists($pageid) && ($ignoreacl || auth_quickaclcheck($pageid) > 0)){
761e66d3e6dSAndreas Gohr            return $pageid;
762e66d3e6dSAndreas Gohr        }
763e66d3e6dSAndreas Gohr    } while($ns);
764e66d3e6dSAndreas Gohr
765e66d3e6dSAndreas Gohr    return false;
766e66d3e6dSAndreas Gohr}
767