xref: /dokuwiki/inc/common.php (revision e0c26282a603881e8d2f839d94c28dbbfc57d71b)
1ed7b5f09Sandi<?php
215fae107Sandi/**
315fae107Sandi * Common DokuWiki functions
415fae107Sandi *
515fae107Sandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
615fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
715fae107Sandi */
815fae107Sandi
9fa8adffeSAndreas Gohrif(!defined('DOKU_INC')) die('meh.');
10f3f0262cSandi
11f3f0262cSandi/**
12b6912aeaSAndreas Gohr * These constants are used with the recents function
13b6912aeaSAndreas Gohr */
14b6912aeaSAndreas Gohrdefine('RECENTS_SKIP_DELETED', 2);
15b6912aeaSAndreas Gohrdefine('RECENTS_SKIP_MINORS', 4);
16b6912aeaSAndreas Gohrdefine('RECENTS_SKIP_SUBSPACES', 8);
170b926329SKate Arzamastsevadefine('RECENTS_MEDIA_CHANGES', 16);
180b926329SKate Arzamastsevadefine('RECENTS_MEDIA_PAGES_MIXED', 32);
19b6912aeaSAndreas Gohr
20b6912aeaSAndreas Gohr/**
21d5197206Schris * Wrapper around htmlspecialchars()
22d5197206Schris *
23d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
24d5197206Schris * @see    htmlspecialchars()
25140cfbcdSGerrit Uitslag *
26140cfbcdSGerrit Uitslag * @param string $string the string being converted
27140cfbcdSGerrit Uitslag * @return string converted string
28d5197206Schris */
29d5197206Schrisfunction hsc($string) {
30d5197206Schris    return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
31d5197206Schris}
32d5197206Schris
33d5197206Schris/**
34d5197206Schris * print a newline terminated string
35d5197206Schris *
36d5197206Schris * You can give an indention as optional parameter
37d5197206Schris *
38d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
39140cfbcdSGerrit Uitslag *
40140cfbcdSGerrit Uitslag * @param string $string  line of text
41140cfbcdSGerrit Uitslag * @param int    $indent  number of spaces indention
42d5197206Schris */
4325ec097bSChris Smithfunction ptln($string, $indent = 0) {
4425ec097bSChris Smith    echo str_repeat(' ', $indent)."$string\n";
4502b0b681SAndreas Gohr}
4602b0b681SAndreas Gohr
4702b0b681SAndreas Gohr/**
4802b0b681SAndreas Gohr * strips control characters (<32) from the given string
4902b0b681SAndreas Gohr *
5002b0b681SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
51140cfbcdSGerrit Uitslag *
52140cfbcdSGerrit Uitslag * @param $string string being stripped
53140cfbcdSGerrit Uitslag * @return string
5402b0b681SAndreas Gohr */
5502b0b681SAndreas Gohrfunction stripctl($string) {
5602b0b681SAndreas Gohr    return preg_replace('/[\x00-\x1F]+/s', '', $string);
57d5197206Schris}
58d5197206Schris
59d5197206Schris/**
60634d7150SAndreas Gohr * Return a secret token to be used for CSRF attack prevention
61634d7150SAndreas Gohr *
62634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
63634d7150SAndreas Gohr * @link    http://en.wikipedia.org/wiki/Cross-site_request_forgery
64634d7150SAndreas Gohr * @link    http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
65634d7150SAndreas Gohr * @return  string
66634d7150SAndreas Gohr */
67634d7150SAndreas Gohrfunction getSecurityToken() {
68585bf44eSChristopher Smith    /** @var Input $INPUT */
69585bf44eSChristopher Smith    global $INPUT;
70585bf44eSChristopher Smith    return PassHash::hmac('md5', session_id().$INPUT->server->str('REMOTE_USER'), auth_cookiesalt());
71634d7150SAndreas Gohr}
72634d7150SAndreas Gohr
73634d7150SAndreas Gohr/**
74634d7150SAndreas Gohr * Check the secret CSRF token
75140cfbcdSGerrit Uitslag *
76140cfbcdSGerrit Uitslag * @param null|string $token security token or null to read it from request variable
77140cfbcdSGerrit Uitslag * @return bool success if the token matched
78634d7150SAndreas Gohr */
79634d7150SAndreas Gohrfunction checkSecurityToken($token = null) {
80585bf44eSChristopher Smith    /** @var Input $INPUT */
817d01a0eaSTom N Harris    global $INPUT;
82585bf44eSChristopher Smith    if(!$INPUT->server->str('REMOTE_USER')) return true; // no logged in user, no need for a check
83df97eaacSAndreas Gohr
847d01a0eaSTom N Harris    if(is_null($token)) $token = $INPUT->str('sectok');
85634d7150SAndreas Gohr    if(getSecurityToken() != $token) {
86634d7150SAndreas Gohr        msg('Security Token did not match. Possible CSRF attack.', -1);
87634d7150SAndreas Gohr        return false;
88634d7150SAndreas Gohr    }
89634d7150SAndreas Gohr    return true;
90634d7150SAndreas Gohr}
91634d7150SAndreas Gohr
92634d7150SAndreas Gohr/**
93634d7150SAndreas Gohr * Print a hidden form field with a secret CSRF token
94634d7150SAndreas Gohr *
95634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
96140cfbcdSGerrit Uitslag *
97140cfbcdSGerrit Uitslag * @param bool $print  if true print the field, otherwise html of the field is returned
98140cfbcdSGerrit Uitslag * @return void|string html of hidden form field
99634d7150SAndreas Gohr */
100634d7150SAndreas Gohrfunction formSecurityToken($print = true) {
1012404d0edSAnika Henke    $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
1023272d797SAndreas Gohr    if($print) echo $ret;
103634d7150SAndreas Gohr    return $ret;
104634d7150SAndreas Gohr}
105634d7150SAndreas Gohr
106634d7150SAndreas Gohr/**
1071015a57dSChristopher Smith * Determine basic information for a request of $id
10815fae107Sandi *
10915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1107e87a794SChristopher Smith * @author Chris Smith <chris@jalakai.co.uk>
111140cfbcdSGerrit Uitslag *
112140cfbcdSGerrit Uitslag * @param string $id         pageid
113140cfbcdSGerrit Uitslag * @param bool   $htmlClient add info about whether is mobile browser
114140cfbcdSGerrit Uitslag * @return array with info for a request of $id
115140cfbcdSGerrit Uitslag *
116f3f0262cSandi */
1171015a57dSChristopher Smithfunction basicinfo($id, $htmlClient=true){
118f3f0262cSandi    global $USERINFO;
119585bf44eSChristopher Smith    /* @var Input $INPUT */
120585bf44eSChristopher Smith    global $INPUT;
1216afe8dcaSchris
122c66972f2SAdrian Lang    // set info about manager/admin status.
123c66972f2SAdrian Lang    $info['isadmin']   = false;
124c66972f2SAdrian Lang    $info['ismanager'] = false;
125585bf44eSChristopher Smith    if($INPUT->server->has('REMOTE_USER')) {
126f3f0262cSandi        $info['userinfo']   = $USERINFO;
1271015a57dSChristopher Smith        $info['perm']       = auth_quickaclcheck($id);
128585bf44eSChristopher Smith        $info['client']     = $INPUT->server->str('REMOTE_USER');
12917ee7f66SAndreas Gohr
130f8cc712eSAndreas Gohr        if($info['perm'] == AUTH_ADMIN) {
131f8cc712eSAndreas Gohr            $info['isadmin']   = true;
132f8cc712eSAndreas Gohr            $info['ismanager'] = true;
133f8cc712eSAndreas Gohr        } elseif(auth_ismanager()) {
134f8cc712eSAndreas Gohr            $info['ismanager'] = true;
135f8cc712eSAndreas Gohr        }
136f8cc712eSAndreas Gohr
13717ee7f66SAndreas Gohr        // if some outside auth were used only REMOTE_USER is set
13817ee7f66SAndreas Gohr        if(!$info['userinfo']['name']) {
139585bf44eSChristopher Smith            $info['userinfo']['name'] = $INPUT->server->str('REMOTE_USER');
14017ee7f66SAndreas Gohr        }
141ee4c4a1bSAndreas Gohr
142f3f0262cSandi    } else {
1431015a57dSChristopher Smith        $info['perm']       = auth_aclcheck($id, '', null);
144ee4c4a1bSAndreas Gohr        $info['client']     = clientIP(true);
145f3f0262cSandi    }
146f3f0262cSandi
1471015a57dSChristopher Smith    $info['namespace'] = getNS($id);
1481015a57dSChristopher Smith
1491015a57dSChristopher Smith    // mobile detection
1501015a57dSChristopher Smith    if ($htmlClient) {
1511015a57dSChristopher Smith        $info['ismobile'] = clientismobile();
1521015a57dSChristopher Smith    }
1531015a57dSChristopher Smith
1541015a57dSChristopher Smith    return $info;
1551015a57dSChristopher Smith }
1561015a57dSChristopher Smith
1571015a57dSChristopher Smith/**
1581015a57dSChristopher Smith * Return info about the current document as associative
1591015a57dSChristopher Smith * array.
1601015a57dSChristopher Smith *
1611015a57dSChristopher Smith * @author Andreas Gohr <andi@splitbrain.org>
162140cfbcdSGerrit Uitslag *
163140cfbcdSGerrit Uitslag * @return array with info about current document
1641015a57dSChristopher Smith */
1651015a57dSChristopher Smithfunction pageinfo() {
1661015a57dSChristopher Smith    global $ID;
1671015a57dSChristopher Smith    global $REV;
1681015a57dSChristopher Smith    global $RANGE;
1691015a57dSChristopher Smith    global $lang;
170585bf44eSChristopher Smith    /* @var Input $INPUT */
171585bf44eSChristopher Smith    global $INPUT;
1721015a57dSChristopher Smith
1731015a57dSChristopher Smith    $info = basicinfo($ID);
1741015a57dSChristopher Smith
1751015a57dSChristopher Smith    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
1761015a57dSChristopher Smith    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
1771015a57dSChristopher Smith    $info['id']  = $ID;
1781015a57dSChristopher Smith    $info['rev'] = $REV;
1791015a57dSChristopher Smith
180585bf44eSChristopher Smith    if($INPUT->server->has('REMOTE_USER')) {
1817e87a794SChristopher Smith        $sub = new Subscription();
1827e87a794SChristopher Smith        $info['subscribed'] = $sub->user_subscription();
1837e87a794SChristopher Smith    } else {
1847e87a794SChristopher Smith        $info['subscribed'] = false;
1857e87a794SChristopher Smith    }
1867e87a794SChristopher Smith
187f3f0262cSandi    $info['locked']     = checklock($ID);
18800976812SAndreas Gohr    $info['filepath']   = fullpath(wikiFN($ID));
1892ca9d91cSBen Coburn    $info['exists']     = @file_exists($info['filepath']);
19001c9a118SAndreas Gohr    $info['currentrev'] = @filemtime($info['filepath']);
1912ca9d91cSBen Coburn    if($REV) {
1922ca9d91cSBen Coburn        //check if current revision was meant
19301c9a118SAndreas Gohr        if($info['exists'] && ($info['currentrev'] == $REV)) {
1942ca9d91cSBen Coburn            $REV = '';
1957b3a6803SAndreas Gohr        } elseif($RANGE) {
1967b3a6803SAndreas Gohr            //section editing does not work with old revisions!
1977b3a6803SAndreas Gohr            $REV   = '';
1987b3a6803SAndreas Gohr            $RANGE = '';
1997b3a6803SAndreas Gohr            msg($lang['nosecedit'], 0);
2002ca9d91cSBen Coburn        } else {
2012ca9d91cSBen Coburn            //really use old revision
20200976812SAndreas Gohr            $info['filepath'] = fullpath(wikiFN($ID, $REV));
203f3f0262cSandi            $info['exists']   = @file_exists($info['filepath']);
204f3f0262cSandi        }
205f3f0262cSandi    }
206c112d578Sandi    $info['rev'] = $REV;
207f3f0262cSandi    if($info['exists']) {
208f3f0262cSandi        $info['writable'] = (is_writable($info['filepath']) &&
209f3f0262cSandi            ($info['perm'] >= AUTH_EDIT));
210f3f0262cSandi    } else {
211f3f0262cSandi        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
212f3f0262cSandi    }
21350e988b1SAndreas Gohr    $info['editable'] = ($info['writable'] && empty($info['locked']));
214f3f0262cSandi    $info['lastmod']  = @filemtime($info['filepath']);
215f3f0262cSandi
21671726d78SBen Coburn    //load page meta data
21771726d78SBen Coburn    $info['meta'] = p_get_metadata($ID);
21871726d78SBen Coburn
219652610a2Sandi    //who's the editor
220047bad06SGerrit Uitslag    $pagelog = new PageChangeLog($ID, 1024);
221652610a2Sandi    if($REV) {
222f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($REV);
223652610a2Sandi    } else {
2240e80bb5eSChristopher Smith        if(!empty($info['meta']['last_change']) && is_array($info['meta']['last_change'])) {
225aa27cf05SAndreas Gohr            $revinfo = $info['meta']['last_change'];
226aa27cf05SAndreas Gohr        } else {
227f523c971SGerrit Uitslag            $revinfo = $pagelog->getRevisionInfo($info['lastmod']);
228cd00a034SBen Coburn            // cache most recent changelog line in metadata if missing and still valid
229cd00a034SBen Coburn            if($revinfo !== false) {
230cd00a034SBen Coburn                $info['meta']['last_change'] = $revinfo;
231cd00a034SBen Coburn                p_set_metadata($ID, array('last_change' => $revinfo));
232cd00a034SBen Coburn            }
233cd00a034SBen Coburn        }
234cd00a034SBen Coburn    }
235cd00a034SBen Coburn    //and check for an external edit
236cd00a034SBen Coburn    if($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
237cd00a034SBen Coburn        // cached changelog line no longer valid
238cd00a034SBen Coburn        $revinfo                     = false;
239cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
240cd00a034SBen Coburn        p_set_metadata($ID, array('last_change' => $revinfo));
241652610a2Sandi    }
242bb4866bdSchris
243652610a2Sandi    $info['ip']   = $revinfo['ip'];
244652610a2Sandi    $info['user'] = $revinfo['user'];
245652610a2Sandi    $info['sum']  = $revinfo['sum'];
24671726d78SBen Coburn    // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
247ebf1501fSBen Coburn    // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
24859f257aeSchris
24988f522e9Sandi    if($revinfo['user']) {
25088f522e9Sandi        $info['editor'] = $revinfo['user'];
25188f522e9Sandi    } else {
25288f522e9Sandi        $info['editor'] = $revinfo['ip'];
25388f522e9Sandi    }
254652610a2Sandi
255ee4c4a1bSAndreas Gohr    // draft
256ee4c4a1bSAndreas Gohr    $draft = getCacheName($info['client'].$ID, '.draft');
257ee4c4a1bSAndreas Gohr    if(@file_exists($draft)) {
258ee4c4a1bSAndreas Gohr        if(@filemtime($draft) < @filemtime(wikiFN($ID))) {
259ee4c4a1bSAndreas Gohr            // remove stale draft
260ee4c4a1bSAndreas Gohr            @unlink($draft);
261ee4c4a1bSAndreas Gohr        } else {
262ee4c4a1bSAndreas Gohr            $info['draft'] = $draft;
263ee4c4a1bSAndreas Gohr        }
264ee4c4a1bSAndreas Gohr    }
265ee4c4a1bSAndreas Gohr
2661015a57dSChristopher Smith    return $info;
2671015a57dSChristopher Smith}
2681015a57dSChristopher Smith
2691015a57dSChristopher Smith/**
2701015a57dSChristopher Smith * Return information about the current media item as an associative array.
271140cfbcdSGerrit Uitslag *
272140cfbcdSGerrit Uitslag * @return array with info about current media item
2731015a57dSChristopher Smith */
2741015a57dSChristopher Smithfunction mediainfo(){
2751015a57dSChristopher Smith    global $NS;
2761015a57dSChristopher Smith    global $IMG;
2771015a57dSChristopher Smith
2781015a57dSChristopher Smith    $info = basicinfo("$NS:*");
2791015a57dSChristopher Smith    $info['image'] = $IMG;
2801c548ebeSAndreas Gohr
281f3f0262cSandi    return $info;
282f3f0262cSandi}
283f3f0262cSandi
284f3f0262cSandi/**
2852684e50aSAndreas Gohr * Build an string of URL parameters
2862684e50aSAndreas Gohr *
2872684e50aSAndreas Gohr * @author Andreas Gohr
288140cfbcdSGerrit Uitslag *
289140cfbcdSGerrit Uitslag * @param array  $params    array with key-value pairs
290140cfbcdSGerrit Uitslag * @param string $sep       series of pairs are separated by this character
291140cfbcdSGerrit Uitslag * @return string query string
2922684e50aSAndreas Gohr */
293b174aeaeSchrisfunction buildURLparams($params, $sep = '&amp;') {
2942684e50aSAndreas Gohr    $url = '';
2952684e50aSAndreas Gohr    $amp = false;
2962684e50aSAndreas Gohr    foreach($params as $key => $val) {
297b174aeaeSchris        if($amp) $url .= $sep;
2982684e50aSAndreas Gohr
29985e6871fSAdrian Lang        $url .= rawurlencode($key).'=';
3003a50618cSgweissbach        $url .= rawurlencode((string) $val);
3012684e50aSAndreas Gohr        $amp = true;
3022684e50aSAndreas Gohr    }
3032684e50aSAndreas Gohr    return $url;
3042684e50aSAndreas Gohr}
3052684e50aSAndreas Gohr
3062684e50aSAndreas Gohr/**
3072684e50aSAndreas Gohr * Build an string of html tag attributes
3082684e50aSAndreas Gohr *
3097bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
3107bff22c0SAndreas Gohr *
3112684e50aSAndreas Gohr * @author Andreas Gohr
312140cfbcdSGerrit Uitslag *
313140cfbcdSGerrit Uitslag * @param array $params    array with (attribute name-attribute value) pairs
314140cfbcdSGerrit Uitslag * @param bool  $skipempty skip empty string values?
315140cfbcdSGerrit Uitslag * @return string
3162684e50aSAndreas Gohr */
3174b030ce7SAndreas Gohrfunction buildAttributes($params, $skipempty = false) {
3182684e50aSAndreas Gohr    $url   = '';
3199063ec14SAdrian Lang    $white = false;
3202684e50aSAndreas Gohr    foreach($params as $key => $val) {
3217bff22c0SAndreas Gohr        if($key{0} == '_') continue;
322b1c94f1dSAndreas Gohr        if($val === '' && $skipempty) continue;
3239063ec14SAdrian Lang        if($white) $url .= ' ';
3247bff22c0SAndreas Gohr
3252684e50aSAndreas Gohr        $url .= $key.'="';
3262684e50aSAndreas Gohr        $url .= htmlspecialchars($val);
3272684e50aSAndreas Gohr        $url .= '"';
3289063ec14SAdrian Lang        $white = true;
3292684e50aSAndreas Gohr    }
3302684e50aSAndreas Gohr    return $url;
3312684e50aSAndreas Gohr}
3322684e50aSAndreas Gohr
3332684e50aSAndreas Gohr/**
33415fae107Sandi * This builds the breadcrumb trail and returns it as array
33515fae107Sandi *
33615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
337140cfbcdSGerrit Uitslag *
338140cfbcdSGerrit Uitslag * @return array(pageid=>name, ... )
339f3f0262cSandi */
340f3f0262cSandifunction breadcrumbs() {
3418746e727Sandi    // we prepare the breadcrumbs early for quick session closing
3428746e727Sandi    static $crumbs = null;
3438746e727Sandi    if($crumbs != null) return $crumbs;
3448746e727Sandi
345f3f0262cSandi    global $ID;
346f3f0262cSandi    global $ACT;
347f3f0262cSandi    global $conf;
348f3f0262cSandi
349f3f0262cSandi    //first visit?
350c66972f2SAdrian Lang    $crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array();
351f3f0262cSandi    //we only save on show and existing wiki documents
352a77f5846Sjan    $file = wikiFN($ID);
353a77f5846Sjan    if($ACT != 'show' || !@file_exists($file)) {
354e71ce681SAndreas Gohr        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
355f3f0262cSandi        return $crumbs;
356f3f0262cSandi    }
357a77f5846Sjan
358a77f5846Sjan    // page names
3591a84a0f3SAnika Henke    $name = noNSorNS($ID);
360fe9ec250SChris Smith    if(useHeading('navigation')) {
361a77f5846Sjan        // get page title
36267c15eceSMichael Hamann        $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
363a77f5846Sjan        if($title) {
364a77f5846Sjan            $name = $title;
365a77f5846Sjan        }
366a77f5846Sjan    }
367a77f5846Sjan
368f3f0262cSandi    //remove ID from array
369a77f5846Sjan    if(isset($crumbs[$ID])) {
370a77f5846Sjan        unset($crumbs[$ID]);
371f3f0262cSandi    }
372f3f0262cSandi
373f3f0262cSandi    //add to array
374a77f5846Sjan    $crumbs[$ID] = $name;
375f3f0262cSandi    //reduce size
376f3f0262cSandi    while(count($crumbs) > $conf['breadcrumbs']) {
377f3f0262cSandi        array_shift($crumbs);
378f3f0262cSandi    }
379f3f0262cSandi    //save to session
380e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
381f3f0262cSandi    return $crumbs;
382f3f0262cSandi}
383f3f0262cSandi
384f3f0262cSandi/**
38515fae107Sandi * Filter for page IDs
38615fae107Sandi *
387f3f0262cSandi * This is run on a ID before it is outputted somewhere
388f3f0262cSandi * currently used to replace the colon with something else
389907f24f7SAndreas Gohr * on Windows (non-IIS) systems and to have proper URL encoding
390907f24f7SAndreas Gohr *
391907f24f7SAndreas Gohr * See discussions at https://github.com/splitbrain/dokuwiki/pull/84 and
392907f24f7SAndreas Gohr * https://github.com/splitbrain/dokuwiki/pull/173 why we use a whitelist of
393907f24f7SAndreas Gohr * unaffected servers instead of blacklisting affected servers here.
39415fae107Sandi *
39549c713a3Sandi * Urlencoding is ommitted when the second parameter is false
39649c713a3Sandi *
39715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
398140cfbcdSGerrit Uitslag *
399140cfbcdSGerrit Uitslag * @param string $id pageid being filtered
400140cfbcdSGerrit Uitslag * @param bool   $ue apply urlencoding?
401140cfbcdSGerrit Uitslag * @return string
402f3f0262cSandi */
40349c713a3Sandifunction idfilter($id, $ue = true) {
404f3f0262cSandi    global $conf;
405585bf44eSChristopher Smith    /* @var Input $INPUT */
406585bf44eSChristopher Smith    global $INPUT;
407585bf44eSChristopher Smith
408f3f0262cSandi    if($conf['useslash'] && $conf['userewrite']) {
409f3f0262cSandi        $id = strtr($id, ':', '/');
410f3f0262cSandi    } elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
41158bedc8aSborekb        $conf['userewrite'] &&
412585bf44eSChristopher Smith        strpos($INPUT->server->str('SERVER_SOFTWARE'), 'Microsoft-IIS') === false
4133272d797SAndreas Gohr    ) {
414f3f0262cSandi        $id = strtr($id, ':', ';');
415f3f0262cSandi    }
41649c713a3Sandi    if($ue) {
417b6c6979fSAndreas Gohr        $id = rawurlencode($id);
418f3f0262cSandi        $id = str_replace('%3A', ':', $id); //keep as colon
419edd95259SGerrit Uitslag        $id = str_replace('%3B', ';', $id); //keep as semicolon
420f3f0262cSandi        $id = str_replace('%2F', '/', $id); //keep as slash
42149c713a3Sandi    }
422f3f0262cSandi    return $id;
423f3f0262cSandi}
424f3f0262cSandi
425f3f0262cSandi/**
426ed7b5f09Sandi * This builds a link to a wikipage
42715fae107Sandi *
4284bc480e5SAndreas Gohr * It handles URL rewriting and adds additional parameters
4296c7843b5Sandi *
43015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
4314bc480e5SAndreas Gohr *
4324bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
4334bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
4344bc480e5SAndreas Gohr * @param bool         $absolute       request an absolute URL instead of relative
4354bc480e5SAndreas Gohr * @param string       $separator      parameter separator
4364bc480e5SAndreas Gohr * @return string
437f3f0262cSandi */
43816f15a81SDominik Eckelmannfunction wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;') {
439f3f0262cSandi    global $conf;
44016f15a81SDominik Eckelmann    if(is_array($urlParameters)) {
44116f15a81SDominik Eckelmann        $urlParameters = buildURLparams($urlParameters, $separator);
4426de3759aSAndreas Gohr    } else {
44316f15a81SDominik Eckelmann        $urlParameters = str_replace(',', $separator, $urlParameters);
4446de3759aSAndreas Gohr    }
44516f15a81SDominik Eckelmann    if($id === '') {
44616f15a81SDominik Eckelmann        $id = $conf['start'];
44716f15a81SDominik Eckelmann    }
448f3f0262cSandi    $id = idfilter($id);
44916f15a81SDominik Eckelmann    if($absolute) {
450ed7b5f09Sandi        $xlink = DOKU_URL;
451ed7b5f09Sandi    } else {
452ed7b5f09Sandi        $xlink = DOKU_BASE;
453ed7b5f09Sandi    }
454f3f0262cSandi
4556c7843b5Sandi    if($conf['userewrite'] == 2) {
4566c7843b5Sandi        $xlink .= DOKU_SCRIPT.'/'.$id;
45716f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
4586c7843b5Sandi    } elseif($conf['userewrite']) {
459f3f0262cSandi        $xlink .= $id;
46016f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
461bce3726dSAndreas Gohr    } elseif($id) {
4626c7843b5Sandi        $xlink .= DOKU_SCRIPT.'?id='.$id;
46316f15a81SDominik Eckelmann        if($urlParameters) $xlink .= $separator.$urlParameters;
464bce3726dSAndreas Gohr    } else {
465bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
46616f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
467f3f0262cSandi    }
468f3f0262cSandi
469f3f0262cSandi    return $xlink;
470f3f0262cSandi}
471f3f0262cSandi
472f3f0262cSandi/**
473f5c2808fSBen Coburn * This builds a link to an alternate page format
474f5c2808fSBen Coburn *
475f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
476f5c2808fSBen Coburn *
477f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
4784bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
4794bc480e5SAndreas Gohr * @param string       $format         the export renderer to use
4804bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
4814bc480e5SAndreas Gohr * @param bool         $abs            request an absolute URL instead of relative
4824bc480e5SAndreas Gohr * @param string       $sep            parameter separator
4834bc480e5SAndreas Gohr * @return string
484f5c2808fSBen Coburn */
4854bc480e5SAndreas Gohrfunction exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;') {
486f5c2808fSBen Coburn    global $conf;
4874bc480e5SAndreas Gohr    if(is_array($urlParameters)) {
4884bc480e5SAndreas Gohr        $urlParameters = buildURLparams($urlParameters, $sep);
489f5c2808fSBen Coburn    } else {
4904bc480e5SAndreas Gohr        $urlParameters = str_replace(',', $sep, $urlParameters);
491f5c2808fSBen Coburn    }
492f5c2808fSBen Coburn
493f5c2808fSBen Coburn    $format = rawurlencode($format);
494f5c2808fSBen Coburn    $id     = idfilter($id);
495f5c2808fSBen Coburn    if($abs) {
496f5c2808fSBen Coburn        $xlink = DOKU_URL;
497f5c2808fSBen Coburn    } else {
498f5c2808fSBen Coburn        $xlink = DOKU_BASE;
499f5c2808fSBen Coburn    }
500f5c2808fSBen Coburn
501f5c2808fSBen Coburn    if($conf['userewrite'] == 2) {
502f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
5034bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
504f5c2808fSBen Coburn    } elseif($conf['userewrite'] == 1) {
505f5c2808fSBen Coburn        $xlink .= '_export/'.$format.'/'.$id;
5064bc480e5SAndreas Gohr        if($urlParameters) $xlink .= '?'.$urlParameters;
507f5c2808fSBen Coburn    } else {
508f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
5094bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
510f5c2808fSBen Coburn    }
511f5c2808fSBen Coburn
512f5c2808fSBen Coburn    return $xlink;
513f5c2808fSBen Coburn}
514f5c2808fSBen Coburn
515f5c2808fSBen Coburn/**
5166de3759aSAndreas Gohr * Build a link to a media file
5176de3759aSAndreas Gohr *
5186de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
5198c08db0aSAndreas Gohr *
5208c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
5218c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
5228c08db0aSAndreas Gohr *
5233272d797SAndreas Gohr * @param string  $id     the media file id or URL
5243272d797SAndreas Gohr * @param mixed   $more   string or array with additional parameters
5253272d797SAndreas Gohr * @param bool    $direct link to detail page if false
5263272d797SAndreas Gohr * @param string  $sep    URL parameter separator
5273272d797SAndreas Gohr * @param bool    $abs    Create an absolute URL
5283272d797SAndreas Gohr * @return string
5296de3759aSAndreas Gohr */
53055b2b31bSAndreas Gohrfunction ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false) {
5316de3759aSAndreas Gohr    global $conf;
532b9ee6a44SKlap-in    $isexternalimage = media_isexternal($id);
533826d2766SKlap-in    if(!$isexternalimage) {
534826d2766SKlap-in        $id = cleanID($id);
535826d2766SKlap-in    }
536826d2766SKlap-in
5376de3759aSAndreas Gohr    if(is_array($more)) {
5380f4e0092SChristopher Smith        // add token for resized images
539443e135dSChristopher Smith        if(!empty($more['w']) || !empty($more['h']) || $isexternalimage){
5400f4e0092SChristopher Smith            $more['tok'] = media_get_token($id,$more['w'],$more['h']);
5410f4e0092SChristopher Smith        }
5428c08db0aSAndreas Gohr        // strip defaults for shorter URLs
5438c08db0aSAndreas Gohr        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
544443e135dSChristopher Smith        if(empty($more['w'])) unset($more['w']);
545443e135dSChristopher Smith        if(empty($more['h'])) unset($more['h']);
5468c08db0aSAndreas Gohr        if(isset($more['id']) && $direct) unset($more['id']);
547b174aeaeSchris        $more = buildURLparams($more, $sep);
5486de3759aSAndreas Gohr    } else {
5495e7db1e2SChristopher Smith        $matches = array();
550cc036f74SKlap-in        if (preg_match_all('/\b(w|h)=(\d*)\b/',$more,$matches,PREG_SET_ORDER) || $isexternalimage){
5515e7db1e2SChristopher Smith            $resize = array('w'=>0, 'h'=>0);
5525e7db1e2SChristopher Smith            foreach ($matches as $match){
5535e7db1e2SChristopher Smith                $resize[$match[1]] = $match[2];
5545e7db1e2SChristopher Smith            }
555cc036f74SKlap-in            $more .= $more === '' ? '' : $sep;
556cc036f74SKlap-in            $more .= 'tok='.media_get_token($id,$resize['w'],$resize['h']);
5575e7db1e2SChristopher Smith        }
5588c08db0aSAndreas Gohr        $more = str_replace('cache=cache', '', $more); //skip default
5598c08db0aSAndreas Gohr        $more = str_replace(',,', ',', $more);
560b174aeaeSchris        $more = str_replace(',', $sep, $more);
5616de3759aSAndreas Gohr    }
5626de3759aSAndreas Gohr
56355b2b31bSAndreas Gohr    if($abs) {
56455b2b31bSAndreas Gohr        $xlink = DOKU_URL;
56555b2b31bSAndreas Gohr    } else {
5666de3759aSAndreas Gohr        $xlink = DOKU_BASE;
56755b2b31bSAndreas Gohr    }
5686de3759aSAndreas Gohr
5696de3759aSAndreas Gohr    // external URLs are always direct without rewriting
570826d2766SKlap-in    if($isexternalimage) {
5716de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
572cc036f74SKlap-in        $xlink .= '?'.$more;
573b174aeaeSchris        $xlink .= $sep.'media='.rawurlencode($id);
5746de3759aSAndreas Gohr        return $xlink;
5756de3759aSAndreas Gohr    }
5766de3759aSAndreas Gohr
5776de3759aSAndreas Gohr    $id = idfilter($id);
5786de3759aSAndreas Gohr
5796de3759aSAndreas Gohr    // decide on scriptname
5806de3759aSAndreas Gohr    if($direct) {
5816de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
5826de3759aSAndreas Gohr            $script = '_media';
5836de3759aSAndreas Gohr        } else {
5846de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
5856de3759aSAndreas Gohr        }
5866de3759aSAndreas Gohr    } else {
5876de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
5886de3759aSAndreas Gohr            $script = '_detail';
5896de3759aSAndreas Gohr        } else {
5906de3759aSAndreas Gohr            $script = 'lib/exe/detail.php';
5916de3759aSAndreas Gohr        }
5926de3759aSAndreas Gohr    }
5936de3759aSAndreas Gohr
5946de3759aSAndreas Gohr    // build URL based on rewrite mode
5956de3759aSAndreas Gohr    if($conf['userewrite']) {
5966de3759aSAndreas Gohr        $xlink .= $script.'/'.$id;
5976de3759aSAndreas Gohr        if($more) $xlink .= '?'.$more;
5986de3759aSAndreas Gohr    } else {
5996de3759aSAndreas Gohr        if($more) {
600a99d3236SEsther Brunner            $xlink .= $script.'?'.$more;
601b174aeaeSchris            $xlink .= $sep.'media='.$id;
6026de3759aSAndreas Gohr        } else {
603a99d3236SEsther Brunner            $xlink .= $script.'?media='.$id;
6046de3759aSAndreas Gohr        }
6056de3759aSAndreas Gohr    }
6066de3759aSAndreas Gohr
6076de3759aSAndreas Gohr    return $xlink;
6086de3759aSAndreas Gohr}
6096de3759aSAndreas Gohr
6106de3759aSAndreas Gohr/**
61125ca5b17SAndreas Gohr * Returns the URL to the DokuWiki base script
61215fae107Sandi *
61325ca5b17SAndreas Gohr * Consider using wl() instead, unless you absoutely need the doku.php endpoint
61425ca5b17SAndreas Gohr *
61515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
616140cfbcdSGerrit Uitslag *
617140cfbcdSGerrit Uitslag * @return string
618f3f0262cSandi */
61925ca5b17SAndreas Gohrfunction script() {
620ed7b5f09Sandi    return DOKU_BASE.DOKU_SCRIPT;
621f3f0262cSandi}
622f3f0262cSandi
623f3f0262cSandi/**
62415fae107Sandi * Spamcheck against wordlist
62515fae107Sandi *
626f3f0262cSandi * Checks the wikitext against a list of blocked expressions
627f3f0262cSandi * returns true if the text contains any bad words
62815fae107Sandi *
629e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
630e403cc58SMichael Klier *
631e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
632e403cc58SMichael Klier *  and gain information about the user who was blocked.
633e403cc58SMichael Klier *
634e403cc58SMichael Klier *  Event data:
635e403cc58SMichael Klier *    data['matches']  - array of matches
636e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
637e403cc58SMichael Klier *      [ip]           - ip address
638e403cc58SMichael Klier *      [user]         - username (if logged in)
639e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
640e403cc58SMichael Klier *      [name]         - real name (if logged in)
641e403cc58SMichael Klier *
64215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
6436dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
644140cfbcdSGerrit Uitslag *
6456dffa0e0SAndreas Gohr * @param  string $text - optional text to check, if not given the globals are used
6466dffa0e0SAndreas Gohr * @return bool         - true if a spam word was found
647f3f0262cSandi */
6486dffa0e0SAndreas Gohrfunction checkwordblock($text = '') {
649f3f0262cSandi    global $TEXT;
6506dffa0e0SAndreas Gohr    global $PRE;
6516dffa0e0SAndreas Gohr    global $SUF;
652e0086ca2SAndreas Gohr    global $SUM;
653f3f0262cSandi    global $conf;
654e403cc58SMichael Klier    global $INFO;
655585bf44eSChristopher Smith    /* @var Input $INPUT */
656585bf44eSChristopher Smith    global $INPUT;
657f3f0262cSandi
658f3f0262cSandi    if(!$conf['usewordblock']) return false;
659f3f0262cSandi
660e0086ca2SAndreas Gohr    if(!$text) $text = "$PRE $TEXT $SUF $SUM";
6616dffa0e0SAndreas Gohr
662041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
6636dffa0e0SAndreas Gohr    $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i', '\1http://\2 \2\3', $text);
664041d1964SAndreas Gohr
665b9ac8716Schris    $wordblocks = getWordblocks();
6663e2965d7Sandi    // how many lines to read at once (to work around some PCRE limits)
6673e2965d7Sandi    if(version_compare(phpversion(), '4.3.0', '<')) {
6683e2965d7Sandi        // old versions of PCRE define a maximum of parenthesises even if no
6693e2965d7Sandi        // backreferences are used - the maximum is 99
6703e2965d7Sandi        // this is very bad performancewise and may even be too high still
6713e2965d7Sandi        $chunksize = 40;
6723e2965d7Sandi    } else {
673a51d08efSAndreas Gohr        // read file in chunks of 200 - this should work around the
6743e2965d7Sandi        // MAX_PATTERN_SIZE in modern PCRE
675a51d08efSAndreas Gohr        $chunksize = 200;
6763e2965d7Sandi    }
677b9ac8716Schris    while($blocks = array_splice($wordblocks, 0, $chunksize)) {
678f3f0262cSandi        $re = array();
67949eb6e38SAndreas Gohr        // build regexp from blocks
680f3f0262cSandi        foreach($blocks as $block) {
681f3f0262cSandi            $block = preg_replace('/#.*$/', '', $block);
682f3f0262cSandi            $block = trim($block);
683f3f0262cSandi            if(empty($block)) continue;
684f3f0262cSandi            $re[] = $block;
685f3f0262cSandi        }
686e403cc58SMichael Klier        if(count($re) && preg_match('#('.join('|', $re).')#si', $text, $matches)) {
687e403cc58SMichael Klier            // prepare event data
688e403cc58SMichael Klier            $data['matches']        = $matches;
689585bf44eSChristopher Smith            $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
690585bf44eSChristopher Smith            if($INPUT->server->str('REMOTE_USER')) {
691585bf44eSChristopher Smith                $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
692e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
693e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
694e403cc58SMichael Klier            }
695e403cc58SMichael Klier            $callback = create_function('', 'return true;');
696e403cc58SMichael Klier            return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
697b9ac8716Schris        }
698703f6fdeSandi    }
699f3f0262cSandi    return false;
700f3f0262cSandi}
701f3f0262cSandi
702f3f0262cSandi/**
70315fae107Sandi * Return the IP of the client
70415fae107Sandi *
7056d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
70615fae107Sandi *
7076d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
7086d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
7096d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
7106d8affe6SAndreas Gohr * headers
7116d8affe6SAndreas Gohr *
71215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
713140cfbcdSGerrit Uitslag *
7143272d797SAndreas Gohr * @param  boolean $single If set only a single IP is returned
7153272d797SAndreas Gohr * @return string
716f3f0262cSandi */
7176d8affe6SAndreas Gohrfunction clientIP($single = false) {
718585bf44eSChristopher Smith    /* @var Input $INPUT */
719585bf44eSChristopher Smith    global $INPUT;
720585bf44eSChristopher Smith
7216d8affe6SAndreas Gohr    $ip   = array();
722585bf44eSChristopher Smith    $ip[] = $INPUT->server->str('REMOTE_ADDR');
723585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_FORWARDED_FOR')) {
724585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_FORWARDED_FOR'))));
725585bf44eSChristopher Smith    }
726585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_REAL_IP')) {
727585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_REAL_IP'))));
728585bf44eSChristopher Smith    }
7296d8affe6SAndreas Gohr
730dc14c6d1SGuy Brand    // some IPv4/v6 regexps borrowed from Feyd
731dc14c6d1SGuy Brand    // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
732dc14c6d1SGuy Brand    $dec_octet   = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
733dc14c6d1SGuy Brand    $hex_digit   = '[A-Fa-f0-9]';
734dc14c6d1SGuy Brand    $h16         = "{$hex_digit}{1,4}";
735dc14c6d1SGuy Brand    $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
736dc14c6d1SGuy Brand    $ls32        = "(?:$h16:$h16|$IPv4Address)";
737dc14c6d1SGuy Brand    $IPv6Address =
738dc14c6d1SGuy Brand        "(?:(?:{$IPv4Address})|(?:".
739dc14c6d1SGuy Brand            "(?:$h16:){6}$ls32".
740dc14c6d1SGuy Brand            "|::(?:$h16:){5}$ls32".
741dc14c6d1SGuy Brand            "|(?:$h16)?::(?:$h16:){4}$ls32".
742dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32".
743dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32".
744dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32".
745dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,4}$h16)?::$ls32".
746dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,5}$h16)?::$h16".
747dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,6}$h16)?::".
748dc14c6d1SGuy Brand            ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
749dc14c6d1SGuy Brand
7506d8affe6SAndreas Gohr    // remove any non-IP stuff
7516d8affe6SAndreas Gohr    $cnt   = count($ip);
7524ff28443Schris    $match = array();
7536d8affe6SAndreas Gohr    for($i = 0; $i < $cnt; $i++) {
754dc14c6d1SGuy Brand        if(preg_match("/^$IPv4Address$/", $ip[$i], $match) || preg_match("/^$IPv6Address$/", $ip[$i], $match)) {
7554ff28443Schris            $ip[$i] = $match[0];
7564ff28443Schris        } else {
7574ff28443Schris            $ip[$i] = '';
7584ff28443Schris        }
7596d8affe6SAndreas Gohr        if(empty($ip[$i])) unset($ip[$i]);
760f3f0262cSandi    }
7616d8affe6SAndreas Gohr    $ip = array_values(array_unique($ip));
7626d8affe6SAndreas Gohr    if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
7636d8affe6SAndreas Gohr
7646d8affe6SAndreas Gohr    if(!$single) return join(',', $ip);
7656d8affe6SAndreas Gohr
7666d8affe6SAndreas Gohr    // decide which IP to use, trying to avoid local addresses
7676d8affe6SAndreas Gohr    $ip = array_reverse($ip);
7686d8affe6SAndreas Gohr    foreach($ip as $i) {
7692343a762SAndreas Gohr        if(preg_match('/^(::1|[fF][eE]80:|127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/', $i)) {
7706d8affe6SAndreas Gohr            continue;
7716d8affe6SAndreas Gohr        } else {
7726d8affe6SAndreas Gohr            return $i;
7736d8affe6SAndreas Gohr        }
7746d8affe6SAndreas Gohr    }
7756d8affe6SAndreas Gohr    // still here? just use the first (last) address
7766d8affe6SAndreas Gohr    return $ip[0];
777f3f0262cSandi}
778f3f0262cSandi
779f3f0262cSandi/**
7801c548ebeSAndreas Gohr * Check if the browser is on a mobile device
7811c548ebeSAndreas Gohr *
7821c548ebeSAndreas Gohr * Adapted from the example code at url below
7831c548ebeSAndreas Gohr *
7841c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
785140cfbcdSGerrit Uitslag *
786140cfbcdSGerrit Uitslag * @return bool if true, client is mobile browser; otherwise false
7871c548ebeSAndreas Gohr */
7881c548ebeSAndreas Gohrfunction clientismobile() {
789585bf44eSChristopher Smith    /* @var Input $INPUT */
790585bf44eSChristopher Smith    global $INPUT;
7911c548ebeSAndreas Gohr
792585bf44eSChristopher Smith    if($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
7931c548ebeSAndreas Gohr
794585bf44eSChristopher Smith    if(preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
7951c548ebeSAndreas Gohr
796585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_USER_AGENT')) return false;
7971c548ebeSAndreas Gohr
7981c548ebeSAndreas Gohr    $uamatches = 'midp|j2me|avantg|docomo|novarra|palmos|palmsource|240x320|opwv|chtml|pda|windows ce|mmp\/|blackberry|mib\/|symbian|wireless|nokia|hand|mobi|phone|cdm|up\.b|audio|SIE\-|SEC\-|samsung|HTC|mot\-|mitsu|sagem|sony|alcatel|lg|erics|vx|NEC|philips|mmm|xx|panasonic|sharp|wap|sch|rover|pocket|benq|java|pt|pg|vox|amoi|bird|compal|kg|voda|sany|kdd|dbt|sendo|sgh|gradi|jb|\d\d\di|moto';
7991c548ebeSAndreas Gohr
800585bf44eSChristopher Smith    if(preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
8011c548ebeSAndreas Gohr
8021c548ebeSAndreas Gohr    return false;
8031c548ebeSAndreas Gohr}
8041c548ebeSAndreas Gohr
8051c548ebeSAndreas Gohr/**
80663211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
80763211f61SGlen Harris *
80822ef1e32SAndreas Gohr * If $conf['dnslookups'] is disabled it simply returns the input string
80922ef1e32SAndreas Gohr *
81063211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
811140cfbcdSGerrit Uitslag *
8123272d797SAndreas Gohr * @param  string $ips comma separated list of IP addresses
8133272d797SAndreas Gohr * @return string a comma separated list of hostnames
81463211f61SGlen Harris */
81563211f61SGlen Harrisfunction gethostsbyaddrs($ips) {
81622ef1e32SAndreas Gohr    global $conf;
81722ef1e32SAndreas Gohr    if(!$conf['dnslookups']) return $ips;
81822ef1e32SAndreas Gohr
81963211f61SGlen Harris    $hosts = array();
82063211f61SGlen Harris    $ips   = explode(',', $ips);
821551a720fSMichael Klier
822551a720fSMichael Klier    if(is_array($ips)) {
8233886270dSAndreas Gohr        foreach($ips as $ip) {
824551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
82563211f61SGlen Harris        }
826551a720fSMichael Klier        return join(',', $hosts);
827551a720fSMichael Klier    } else {
828551a720fSMichael Klier        return gethostbyaddr(trim($ips));
829551a720fSMichael Klier    }
83063211f61SGlen Harris}
83163211f61SGlen Harris
83263211f61SGlen Harris/**
83315fae107Sandi * Checks if a given page is currently locked.
83415fae107Sandi *
835f3f0262cSandi * removes stale lockfiles
83615fae107Sandi *
83715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
838140cfbcdSGerrit Uitslag *
839140cfbcdSGerrit Uitslag * @param string $id page id
840140cfbcdSGerrit Uitslag * @return bool page is locked?
841f3f0262cSandi */
842f3f0262cSandifunction checklock($id) {
843f3f0262cSandi    global $conf;
844585bf44eSChristopher Smith    /* @var Input $INPUT */
845585bf44eSChristopher Smith    global $INPUT;
846585bf44eSChristopher Smith
847c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
848f3f0262cSandi
849f3f0262cSandi    //no lockfile
850f3f0262cSandi    if(!@file_exists($lock)) return false;
851f3f0262cSandi
852f3f0262cSandi    //lockfile expired
853f3f0262cSandi    if((time() - filemtime($lock)) > $conf['locktime']) {
854d8186216SBen Coburn        @unlink($lock);
855f3f0262cSandi        return false;
856f3f0262cSandi    }
857f3f0262cSandi
858f3f0262cSandi    //my own lock
8596d2af55dSChristopher Smith    @list($ip, $session) = explode("\n", io_readFile($lock));
8600712fefaSAndreas Gohr    if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || (session_id() && $session == session_id())) {
861f3f0262cSandi        return false;
862f3f0262cSandi    }
863f3f0262cSandi
864f3f0262cSandi    return $ip;
865f3f0262cSandi}
866f3f0262cSandi
867f3f0262cSandi/**
86815fae107Sandi * Lock a page for editing
86915fae107Sandi *
87015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
871140cfbcdSGerrit Uitslag *
872140cfbcdSGerrit Uitslag * @param string $id page id to lock
873f3f0262cSandi */
874f3f0262cSandifunction lock($id) {
875544ed901SDaniel Calviño Sánchez    global $conf;
876585bf44eSChristopher Smith    /* @var Input $INPUT */
877585bf44eSChristopher Smith    global $INPUT;
878544ed901SDaniel Calviño Sánchez
879544ed901SDaniel Calviño Sánchez    if($conf['locktime'] == 0) {
880544ed901SDaniel Calviño Sánchez        return;
881544ed901SDaniel Calviño Sánchez    }
882544ed901SDaniel Calviño Sánchez
883c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
884585bf44eSChristopher Smith    if($INPUT->server->str('REMOTE_USER')) {
885585bf44eSChristopher Smith        io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
886f3f0262cSandi    } else {
88785fef7e2SAndreas Gohr        io_saveFile($lock, clientIP()."\n".session_id());
888f3f0262cSandi    }
889f3f0262cSandi}
890f3f0262cSandi
891f3f0262cSandi/**
89215fae107Sandi * Unlock a page if it was locked by the user
893f3f0262cSandi *
89415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
895140cfbcdSGerrit Uitslag *
8963272d797SAndreas Gohr * @param string $id page id to unlock
89715fae107Sandi * @return bool true if a lock was removed
898f3f0262cSandi */
899f3f0262cSandifunction unlock($id) {
900585bf44eSChristopher Smith    /* @var Input $INPUT */
901585bf44eSChristopher Smith    global $INPUT;
902585bf44eSChristopher Smith
903c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
904f3f0262cSandi    if(@file_exists($lock)) {
9056d2af55dSChristopher Smith        @list($ip, $session) = explode("\n", io_readFile($lock));
906585bf44eSChristopher Smith        if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || $session == session_id()) {
907f3f0262cSandi            @unlink($lock);
908f3f0262cSandi            return true;
909f3f0262cSandi        }
910f3f0262cSandi    }
911f3f0262cSandi    return false;
912f3f0262cSandi}
913f3f0262cSandi
914f3f0262cSandi/**
915f3f0262cSandi * convert line ending to unix format
916f3f0262cSandi *
9176db7468bSAndreas Gohr * also makes sure the given text is valid UTF-8
9186db7468bSAndreas Gohr *
91915fae107Sandi * @see    formText() for 2crlf conversion
92015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
921140cfbcdSGerrit Uitslag *
922140cfbcdSGerrit Uitslag * @param string $text
923140cfbcdSGerrit Uitslag * @return string
924f3f0262cSandi */
925f3f0262cSandifunction cleanText($text) {
926f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
9276db7468bSAndreas Gohr
9286db7468bSAndreas Gohr    // if the text is not valid UTF-8 we simply assume latin1
9296db7468bSAndreas Gohr    // this won't break any worse than it breaks with the wrong encoding
9306db7468bSAndreas Gohr    // but might actually fix the problem in many cases
9316db7468bSAndreas Gohr    if(!utf8_check($text)) $text = utf8_encode($text);
9326db7468bSAndreas Gohr
933f3f0262cSandi    return $text;
934f3f0262cSandi}
935f3f0262cSandi
936f3f0262cSandi/**
937f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
938f3f0262cSandi * It also converts line endings to Windows format which is
939f3f0262cSandi * pseudo standard for webforms.
940f3f0262cSandi *
94115fae107Sandi * @see    cleanText() for 2unix conversion
94215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
943140cfbcdSGerrit Uitslag *
944140cfbcdSGerrit Uitslag * @param string $text
945140cfbcdSGerrit Uitslag * @return string
946f3f0262cSandi */
947f3f0262cSandifunction formText($text) {
9485b7d45a5SAndreas Gohr    $text = str_replace("\012", "\015\012", $text);
949f3f0262cSandi    return htmlspecialchars($text);
950f3f0262cSandi}
951f3f0262cSandi
952f3f0262cSandi/**
95315fae107Sandi * Returns the specified local text in raw format
95415fae107Sandi *
95515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
956140cfbcdSGerrit Uitslag *
957140cfbcdSGerrit Uitslag * @param string $id   page id
958140cfbcdSGerrit Uitslag * @param string $ext  extension of file being read, default 'txt'
959140cfbcdSGerrit Uitslag * @return string
960f3f0262cSandi */
9612adaf2b8SAndreas Gohrfunction rawLocale($id, $ext = 'txt') {
9622adaf2b8SAndreas Gohr    return io_readFile(localeFN($id, $ext));
963f3f0262cSandi}
964f3f0262cSandi
965f3f0262cSandi/**
966f3f0262cSandi * Returns the raw WikiText
96715fae107Sandi *
96815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
969140cfbcdSGerrit Uitslag *
970140cfbcdSGerrit Uitslag * @param string $id   page id
971*e0c26282SGerrit Uitslag * @param string|int $rev  timestamp when a revision of wikitext is desired
972140cfbcdSGerrit Uitslag * @return string
973f3f0262cSandi */
974f3f0262cSandifunction rawWiki($id, $rev = '') {
975cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
976f3f0262cSandi}
977f3f0262cSandi
978f3f0262cSandi/**
9797146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
9807146cee2SAndreas Gohr *
9817b84afa2SAndreas Gohr * @triggers COMMON_PAGETPL_LOAD
9827146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
983140cfbcdSGerrit Uitslag *
984140cfbcdSGerrit Uitslag * @param string $id the id of the page to be created
985140cfbcdSGerrit Uitslag * @return string parsed pagetemplate content
9867146cee2SAndreas Gohr */
987fe17917eSAdrian Langfunction pageTemplate($id) {
988a15ce62dSEsther Brunner    global $conf;
989e29549feSAndreas Gohr
990fe17917eSAdrian Lang    if(is_array($id)) $id = $id[0];
991e29549feSAndreas Gohr
9927b84afa2SAndreas Gohr    // prepare initial event data
9937b84afa2SAndreas Gohr    $data = array(
9947b84afa2SAndreas Gohr        'id'        => $id, // the id of the page to be created
9957b84afa2SAndreas Gohr        'tpl'       => '', // the text used as template
9967b84afa2SAndreas Gohr        'tplfile'   => '', // the file above text was/should be loaded from
9977b84afa2SAndreas Gohr        'doreplace' => true // should wildcard replacements be done on the text?
9987b84afa2SAndreas Gohr    );
9997b84afa2SAndreas Gohr
10007b84afa2SAndreas Gohr    $evt = new Doku_Event('COMMON_PAGETPL_LOAD', $data);
10017b84afa2SAndreas Gohr    if($evt->advise_before(true)) {
10027b84afa2SAndreas Gohr        // the before event might have loaded the content already
10037b84afa2SAndreas Gohr        if(empty($data['tpl'])) {
10047b84afa2SAndreas Gohr            // if the before event did not set a template file, try to find one
10057b84afa2SAndreas Gohr            if(empty($data['tplfile'])) {
1006fe17917eSAdrian Lang                $path = dirname(wikiFN($id));
1007e29549feSAndreas Gohr                if(@file_exists($path.'/_template.txt')) {
10087b84afa2SAndreas Gohr                    $data['tplfile'] = $path.'/_template.txt';
1009e29549feSAndreas Gohr                } else {
1010e29549feSAndreas Gohr                    // search upper namespaces for templates
1011e29549feSAndreas Gohr                    $len = strlen(rtrim($conf['datadir'], '/'));
1012e29549feSAndreas Gohr                    while(strlen($path) >= $len) {
1013e29549feSAndreas Gohr                        if(@file_exists($path.'/__template.txt')) {
10147b84afa2SAndreas Gohr                            $data['tplfile'] = $path.'/__template.txt';
1015e29549feSAndreas Gohr                            break;
1016e29549feSAndreas Gohr                        }
1017e29549feSAndreas Gohr                        $path = substr($path, 0, strrpos($path, '/'));
1018e29549feSAndreas Gohr                    }
1019e29549feSAndreas Gohr                }
10207b84afa2SAndreas Gohr            }
10217b84afa2SAndreas Gohr            // load the content
10223d7ac595SMichael Hamann            $data['tpl'] = io_readFile($data['tplfile']);
10237b84afa2SAndreas Gohr        }
1024a1bbd05bSMichael Hamann        if($data['doreplace']) parsePageTemplate($data);
10257b84afa2SAndreas Gohr    }
10267b84afa2SAndreas Gohr    $evt->advise_after();
10277b84afa2SAndreas Gohr    unset($evt);
10287b84afa2SAndreas Gohr
1029fe17917eSAdrian Lang    return $data['tpl'];
10302b1223ecSAdrian Lang}
10312b1223ecSAdrian Lang
10322b1223ecSAdrian Lang/**
10332b1223ecSAdrian Lang * Performs common page template replacements
10347b84afa2SAndreas Gohr * This works on data from COMMON_PAGETPL_LOAD
10352b1223ecSAdrian Lang *
10362b1223ecSAdrian Lang * @author Andreas Gohr <andi@splitbrain.org>
1037140cfbcdSGerrit Uitslag *
1038140cfbcdSGerrit Uitslag * @param array $data array with event data
1039140cfbcdSGerrit Uitslag * @return string
10402b1223ecSAdrian Lang */
1041d535a2e9Sstretchyboyfunction parsePageTemplate(&$data) {
10423272d797SAndreas Gohr    /**
10433272d797SAndreas Gohr     * @var string $id        the id of the page to be created
10443272d797SAndreas Gohr     * @var string $tpl       the text used as template
10453272d797SAndreas Gohr     * @var string $tplfile   the file above text was/should be loaded from
10463272d797SAndreas Gohr     * @var bool   $doreplace should wildcard replacements be done on the text?
10473272d797SAndreas Gohr     */
1048fe17917eSAdrian Lang    extract($data);
1049fe17917eSAdrian Lang
1050b856f7dfSAdrian Lang    global $USERINFO;
1051bce53b1fSAdrian Lang    global $conf;
1052585bf44eSChristopher Smith    /* @var Input $INPUT */
1053585bf44eSChristopher Smith    global $INPUT;
1054e29549feSAndreas Gohr
1055e29549feSAndreas Gohr    // replace placeholders
105626ece5a7SAndreas Gohr    $file = noNS($id);
105737c1acbdSAdrian Lang    $page = strtr($file, $conf['sepchar'], ' ');
105826ece5a7SAndreas Gohr
10593272d797SAndreas Gohr    $tpl = str_replace(
10603272d797SAndreas Gohr        array(
106126ece5a7SAndreas Gohr             '@ID@',
106226ece5a7SAndreas Gohr             '@NS@',
106326ece5a7SAndreas Gohr             '@FILE@',
106426ece5a7SAndreas Gohr             '@!FILE@',
106526ece5a7SAndreas Gohr             '@!FILE!@',
106626ece5a7SAndreas Gohr             '@PAGE@',
106726ece5a7SAndreas Gohr             '@!PAGE@',
106826ece5a7SAndreas Gohr             '@!!PAGE@',
106926ece5a7SAndreas Gohr             '@!PAGE!@',
107026ece5a7SAndreas Gohr             '@USER@',
107126ece5a7SAndreas Gohr             '@NAME@',
107226ece5a7SAndreas Gohr             '@MAIL@',
107326ece5a7SAndreas Gohr             '@DATE@',
107426ece5a7SAndreas Gohr        ),
107526ece5a7SAndreas Gohr        array(
107626ece5a7SAndreas Gohr             $id,
107726ece5a7SAndreas Gohr             getNS($id),
107826ece5a7SAndreas Gohr             $file,
107926ece5a7SAndreas Gohr             utf8_ucfirst($file),
108026ece5a7SAndreas Gohr             utf8_strtoupper($file),
108126ece5a7SAndreas Gohr             $page,
108226ece5a7SAndreas Gohr             utf8_ucfirst($page),
108326ece5a7SAndreas Gohr             utf8_ucwords($page),
108426ece5a7SAndreas Gohr             utf8_strtoupper($page),
1085585bf44eSChristopher Smith             $INPUT->server->str('REMOTE_USER'),
1086b856f7dfSAdrian Lang             $USERINFO['name'],
1087b856f7dfSAdrian Lang             $USERINFO['mail'],
108826ece5a7SAndreas Gohr             $conf['dformat'],
10893272d797SAndreas Gohr        ), $tpl
10903272d797SAndreas Gohr    );
109126ece5a7SAndreas Gohr
10927d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
10937d644fc8SAndreas Gohr    $tpl         = preg_replace_callback('/%./', create_function('$m', 'return strftime($m[0]);'), $tpl);
1094d535a2e9Sstretchyboy    $data['tpl'] = $tpl;
1095a15ce62dSEsther Brunner    return $tpl;
10967146cee2SAndreas Gohr}
10977146cee2SAndreas Gohr
10987146cee2SAndreas Gohr/**
109915fae107Sandi * Returns the raw Wiki Text in three slices.
110015fae107Sandi *
110115fae107Sandi * The range parameter needs to have the form "from-to"
110215cfe303Sandi * and gives the range of the section in bytes - no
110315cfe303Sandi * UTF-8 awareness is needed.
1104f3f0262cSandi * The returned order is prefix, section and suffix.
110515fae107Sandi *
110615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1107140cfbcdSGerrit Uitslag *
1108140cfbcdSGerrit Uitslag * @param string $range in form "from-to"
1109140cfbcdSGerrit Uitslag * @param string $id    page id
1110140cfbcdSGerrit Uitslag * @param string $rev   optional, the revision timestamp
1111140cfbcdSGerrit Uitslag * @return array with three slices
1112f3f0262cSandi */
1113f3f0262cSandifunction rawWikiSlices($range, $id, $rev = '') {
1114cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1115f3f0262cSandi
111680fcb268SAdrian Lang    // Parse range
111780fcb268SAdrian Lang    list($from, $to) = explode('-', $range, 2);
111880fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
111980fcb268SAdrian Lang    $from = !$from ? 0 : ($from - 1);
112080fcb268SAdrian Lang    $to   = !$to ? strlen($text) : ($to - 1);
112180fcb268SAdrian Lang
112280fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
112380fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to - $from);
112415cfe303Sandi    $slices[2] = substr($text, $to);
1125f3f0262cSandi    return $slices;
1126f3f0262cSandi}
1127f3f0262cSandi
1128f3f0262cSandi/**
112915fae107Sandi * Joins wiki text slices
113015fae107Sandi *
113180fcb268SAdrian Lang * function to join the text slices.
1132f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
1133f3f0262cSandi * lines between sections if needed (used on saving).
113415fae107Sandi *
113515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1136140cfbcdSGerrit Uitslag *
1137140cfbcdSGerrit Uitslag * @param string $pre   prefix
1138140cfbcdSGerrit Uitslag * @param string $text  text in the middle
1139140cfbcdSGerrit Uitslag * @param string $suf   suffix
1140140cfbcdSGerrit Uitslag * @param bool $pretty add additional empty lines between sections
1141140cfbcdSGerrit Uitslag * @return string
1142f3f0262cSandi */
1143f3f0262cSandifunction con($pre, $text, $suf, $pretty = false) {
1144f3f0262cSandi    if($pretty) {
114580fcb268SAdrian Lang        if($pre !== '' && substr($pre, -1) !== "\n" &&
11463272d797SAndreas Gohr            substr($text, 0, 1) !== "\n"
11473272d797SAndreas Gohr        ) {
114880fcb268SAdrian Lang            $pre .= "\n";
114980fcb268SAdrian Lang        }
115080fcb268SAdrian Lang        if($suf !== '' && substr($text, -1) !== "\n" &&
11513272d797SAndreas Gohr            substr($suf, 0, 1) !== "\n"
11523272d797SAndreas Gohr        ) {
115380fcb268SAdrian Lang            $text .= "\n";
115480fcb268SAdrian Lang        }
1155f3f0262cSandi    }
1156f3f0262cSandi
1157f3f0262cSandi    return $pre.$text.$suf;
1158f3f0262cSandi}
1159f3f0262cSandi
1160f3f0262cSandi/**
1161a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
1162a701424fSBen Coburn * Also directs changelog and attic updates.
116315fae107Sandi *
116415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
116571726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
1166140cfbcdSGerrit Uitslag *
1167140cfbcdSGerrit Uitslag * @param string $id       page id
1168140cfbcdSGerrit Uitslag * @param string $text     wikitext being saved
1169140cfbcdSGerrit Uitslag * @param string $summary  summary of text update
1170140cfbcdSGerrit Uitslag * @param bool   $minor    mark this saved version as minor update
1171f3f0262cSandi */
1172b6912aeaSAndreas Gohrfunction saveWikiText($id, $text, $summary, $minor = false) {
1173a701424fSBen Coburn    /* Note to developers:
1174a701424fSBen Coburn       This code is subtle and delicate. Test the behavior of
1175a701424fSBen Coburn       the attic and changelog with dokuwiki and external edits
1176a701424fSBen Coburn       after any changes. External edits change the wiki page
1177a701424fSBen Coburn       directly without using php or dokuwiki.
1178a701424fSBen Coburn     */
1179f3f0262cSandi    global $conf;
1180f3f0262cSandi    global $lang;
118171726d78SBen Coburn    global $REV;
1182585bf44eSChristopher Smith    /* @var Input $INPUT */
1183585bf44eSChristopher Smith    global $INPUT;
1184585bf44eSChristopher Smith
1185f3f0262cSandi    // ignore if no changes were made
1186f3f0262cSandi    if($text == rawWiki($id, '')) {
1187f3f0262cSandi        return;
1188f3f0262cSandi    }
1189f3f0262cSandi
1190f3f0262cSandi    $file        = wikiFN($id);
1191a701424fSBen Coburn    $old         = @filemtime($file); // from page
1192407e65b9SAndreas Gohr    $wasRemoved  = (trim($text) == ''); // check for empty or whitespace only
1193d8186216SBen Coburn    $wasCreated  = !@file_exists($file);
119471726d78SBen Coburn    $wasReverted = ($REV == true);
1195047bad06SGerrit Uitslag    $pagelog     = new PageChangeLog($id, 1024);
1196e45b34cdSBen Coburn    $newRev      = false;
1197f523c971SGerrit Uitslag    $oldRev      = $pagelog->getRevisions(-1, 1); // from changelog
1198a701424fSBen Coburn    $oldRev      = (int) (empty($oldRev) ? 0 : $oldRev[0]);
1199a701424fSBen Coburn    if(!@file_exists(wikiFN($id, $old)) && @file_exists($file) && $old >= $oldRev) {
120046844156SBen Coburn        // add old revision to the attic if missing
120146844156SBen Coburn        saveOldRevision($id);
120246844156SBen Coburn        // add a changelog entry if this edit came from outside dokuwiki
1203a701424fSBen Coburn        if($old > $oldRev) {
1204ebf1501fSBen Coburn            addLogEntry($old, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=> true));
120546844156SBen Coburn            // remove soon to be stale instructions
120646844156SBen Coburn            $cache = new cache_instructions($id, $file);
120746844156SBen Coburn            $cache->removeCache();
120846844156SBen Coburn        }
120946844156SBen Coburn    }
1210f3f0262cSandi
121171726d78SBen Coburn    if($wasRemoved) {
121230725328SGabriel Birke        // Send "update" event with empty data, so plugins can react to page deletion
121330725328SGabriel Birke        $data = array(array($file, '', false), getNS($id), noNS($id), false);
121430725328SGabriel Birke        trigger_event('IO_WIKIPAGE_WRITE', $data);
1215e45b34cdSBen Coburn        // pre-save deleted revision
1216e45b34cdSBen Coburn        @touch($file);
121746844156SBen Coburn        clearstatcache();
1218e45b34cdSBen Coburn        $newRev = saveOldRevision($id);
1219e1f3d9e1SEsther Brunner        // remove empty file
1220f3f0262cSandi        @unlink($file);
1221c5f92742SMichael Hamann        // don't remove old meta info as it should be saved, plugins can use IO_WIKIPAGE_WRITE for removing their metadata...
1222c5f92742SMichael Hamann        // purge non-persistant meta data
12233d1f9ec3SMichael Klier        p_purge_metadata($id);
1224f3f0262cSandi        $del = true;
12253ce054b3Sandi        // autoset summary on deletion
12263ce054b3Sandi        if(empty($summary)) $summary = $lang['deleted'];
122753d6ccfeSandi        // remove empty namespaces
1228cc7d0c94SBen Coburn        io_sweepNS($id, 'datadir');
1229cc7d0c94SBen Coburn        io_sweepNS($id, 'mediadir');
1230f3f0262cSandi    } else {
1231cc7d0c94SBen Coburn        // save file (namespace dir is created in io_writeWikiPage)
1232cc7d0c94SBen Coburn        io_writeWikiPage($file, $text, $id);
123346844156SBen Coburn        // pre-save the revision, to keep the attic in sync
123446844156SBen Coburn        $newRev = saveOldRevision($id);
1235f3f0262cSandi        $del    = false;
1236f3f0262cSandi    }
1237f3f0262cSandi
123871726d78SBen Coburn    // select changelog line type
123971726d78SBen Coburn    $extra = '';
1240ebf1501fSBen Coburn    $type  = DOKU_CHANGE_TYPE_EDIT;
124171726d78SBen Coburn    if($wasReverted) {
1242ebf1501fSBen Coburn        $type  = DOKU_CHANGE_TYPE_REVERT;
124371726d78SBen Coburn        $extra = $REV;
12443272d797SAndreas Gohr    } else if($wasCreated) {
12453272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_CREATE;
12463272d797SAndreas Gohr    } else if($wasRemoved) {
12473272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_DELETE;
1248585bf44eSChristopher Smith    } else if($minor && $conf['useacl'] && $INPUT->server->str('REMOTE_USER')) {
12493272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_MINOR_EDIT;
12503272d797SAndreas Gohr    } //minor edits only for logged in users
125171726d78SBen Coburn
1252e45b34cdSBen Coburn    addLogEntry($newRev, $id, $type, $summary, $extra);
125326a0801fSAndreas Gohr    // send notify mails
125490033e9dSAndreas Gohr    notify($id, 'admin', $old, $summary, $minor);
125590033e9dSAndreas Gohr    notify($id, 'subscribers', $old, $summary, $minor);
1256f3f0262cSandi
1257ce6b63d9Schris    // update the purgefile (timestamp of the last time anything within the wiki was changed)
125898407a7aSandi    io_saveFile($conf['cachedir'].'/purgefile', time());
12592eccbdaaSGina Haeussge
12602eccbdaaSGina Haeussge    // if useheading is enabled, purge the cache of all linking pages
1261fe9ec250SChris Smith    if(useHeading('content')) {
126207ff0babSMichael Hamann        $pages = ft_backlinks($id, true);
12632eccbdaaSGina Haeussge        foreach($pages as $page) {
12642eccbdaaSGina Haeussge            $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
12652eccbdaaSGina Haeussge            $cache->removeCache();
12662eccbdaaSGina Haeussge        }
12672eccbdaaSGina Haeussge    }
1268f3f0262cSandi}
1269f3f0262cSandi
1270f3f0262cSandi/**
1271f3f0262cSandi * moves the current version to the attic and returns its
1272f3f0262cSandi * revision date
127315fae107Sandi *
127415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1275140cfbcdSGerrit Uitslag *
1276140cfbcdSGerrit Uitslag * @param string $id page id
1277140cfbcdSGerrit Uitslag * @return int|string revision timestamp
1278f3f0262cSandi */
1279f3f0262cSandifunction saveOldRevision($id) {
1280f3f0262cSandi    $oldf = wikiFN($id);
1281f3f0262cSandi    if(!@file_exists($oldf)) return '';
1282f3f0262cSandi    $date = filemtime($oldf);
1283f3f0262cSandi    $newf = wikiFN($id, $date);
1284cc7d0c94SBen Coburn    io_writeWikiPage($newf, rawWiki($id), $id, $date);
1285f3f0262cSandi    return $date;
1286f3f0262cSandi}
1287f3f0262cSandi
1288f3f0262cSandi/**
1289fde10de4SAdrian Lang * Sends a notify mail on page change or registration
129026a0801fSAndreas Gohr *
129126a0801fSAndreas Gohr * @param string     $id       The changed page
1292fde10de4SAdrian Lang * @param string     $who      Who to notify (admin|subscribers|register)
12933272d797SAndreas Gohr * @param int|string $rev Old page revision
129426a0801fSAndreas Gohr * @param string     $summary  What changed
129590033e9dSAndreas Gohr * @param boolean    $minor    Is this a minor edit?
129602a498e7Schris * @param array      $replace  Additional string substitutions, @KEY@ to be replaced by value
12973272d797SAndreas Gohr * @return bool
1298140cfbcdSGerrit Uitslag *
129915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1300f3f0262cSandi */
130102a498e7Schrisfunction notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array()) {
1302f3f0262cSandi    global $conf;
1303585bf44eSChristopher Smith    /* @var Input $INPUT */
1304585bf44eSChristopher Smith    global $INPUT;
1305b158d625SSteven Danz
13066df843eeSAndreas Gohr    // decide if there is something to do, eg. whom to mail
130726a0801fSAndreas Gohr    if($who == 'admin') {
13083272d797SAndreas Gohr        if(empty($conf['notify'])) return false; //notify enabled?
13092ed38036SAndreas Gohr        $tpl = 'mailtext';
131026a0801fSAndreas Gohr        $to  = $conf['notify'];
131126a0801fSAndreas Gohr    } elseif($who == 'subscribers') {
131284c1127cSAndreas Gohr        if(!actionOK('subscribe')) return false; //subscribers enabled?
1313585bf44eSChristopher Smith        if($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
13140bb37868SGerrit Uitslag        $data = array('id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace);
13153272d797SAndreas Gohr        trigger_event(
13163272d797SAndreas Gohr            'COMMON_NOTIFY_ADDRESSLIST', $data,
1317835242b0SAndreas Gohr            array(new Subscription(), 'notifyaddresses')
13183272d797SAndreas Gohr        );
13192ed38036SAndreas Gohr        $to = $data['addresslist'];
13202ed38036SAndreas Gohr        if(empty($to)) return false;
13212ed38036SAndreas Gohr        $tpl = 'subscr_single';
132226a0801fSAndreas Gohr    } else {
13233272d797SAndreas Gohr        return false; //just to be safe
132426a0801fSAndreas Gohr    }
132526a0801fSAndreas Gohr
13266df843eeSAndreas Gohr    // prepare content
13272ed38036SAndreas Gohr    $subscription = new Subscription();
13282ed38036SAndreas Gohr    return $subscription->send_diff($to, $tpl, $id, $rev, $summary);
1329f3f0262cSandi}
13302ed38036SAndreas Gohr
133115fae107Sandi/**
133271f7bde7SAndreas Gohr * extracts the query from a search engine referrer
133315fae107Sandi *
133415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
133571f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1336140cfbcdSGerrit Uitslag *
1337140cfbcdSGerrit Uitslag * @return array|string
1338f3f0262cSandi */
1339f3f0262cSandifunction getGoogleQuery() {
1340585bf44eSChristopher Smith    /* @var Input $INPUT */
1341585bf44eSChristopher Smith    global $INPUT;
1342585bf44eSChristopher Smith
1343585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_REFERER')) {
1344c66972f2SAdrian Lang        return '';
1345c66972f2SAdrian Lang    }
1346585bf44eSChristopher Smith    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1347f3f0262cSandi
1348079b3ac1SAndreas Gohr    // only handle common SEs
1349079b3ac1SAndreas Gohr    if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/',$url['host'])) return '';
1350e4d8a516SKazutaka Miyasaka
1351079b3ac1SAndreas Gohr    $query = array();
1352e4d8a516SKazutaka Miyasaka    // temporary workaround against PHP bug #49733
1353e4d8a516SKazutaka Miyasaka    // see http://bugs.php.net/bug.php?id=49733
1354e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) $enc = mb_internal_encoding();
1355f3f0262cSandi    parse_str($url['query'], $query);
1356e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) mb_internal_encoding($enc);
1357e4d8a516SKazutaka Miyasaka
1358c66972f2SAdrian Lang    $q = '';
1359079b3ac1SAndreas Gohr    if(isset($query['q'])){
1360079b3ac1SAndreas Gohr        $q = $query['q'];
1361079b3ac1SAndreas Gohr    }elseif(isset($query['p'])){
1362079b3ac1SAndreas Gohr        $q = $query['p'];
1363079b3ac1SAndreas Gohr    }elseif(isset($query['query'])){
1364079b3ac1SAndreas Gohr        $q = $query['query'];
1365079b3ac1SAndreas Gohr    }
1366079b3ac1SAndreas Gohr    $q = trim($q);
1367f3f0262cSandi
1368079b3ac1SAndreas Gohr    if(!$q) return '';
13696531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1370f93b3b50SAndreas Gohr    return $q;
1371f3f0262cSandi}
1372f3f0262cSandi
1373f3f0262cSandi/**
1374f3f0262cSandi * Return the human readable size of a file
1375f3f0262cSandi *
1376f3f0262cSandi * @param       int $size A file size
1377f3f0262cSandi * @param       int $dec A number of decimal places
137874160ca1SGerrit Uitslag * @return string human readable size
1379140cfbcdSGerrit Uitslag *
1380f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1381f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1382f3f0262cSandi * @version     1.0.0
1383f3f0262cSandi */
1384f31d5b73Sandifunction filesize_h($size, $dec = 1) {
1385f3f0262cSandi    $sizes = array('B', 'KB', 'MB', 'GB');
1386f3f0262cSandi    $count = count($sizes);
1387f3f0262cSandi    $i     = 0;
1388f3f0262cSandi
1389f3f0262cSandi    while($size >= 1024 && ($i < $count - 1)) {
1390f3f0262cSandi        $size /= 1024;
1391f3f0262cSandi        $i++;
1392f3f0262cSandi    }
1393f3f0262cSandi
1394f3f0262cSandi    return round($size, $dec).' '.$sizes[$i];
1395f3f0262cSandi}
1396f3f0262cSandi
139715fae107Sandi/**
1398c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1399c57e365eSAndreas Gohr *
1400c57e365eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1401140cfbcdSGerrit Uitslag *
1402140cfbcdSGerrit Uitslag * @param int $dt timestamp
1403140cfbcdSGerrit Uitslag * @return string
1404c57e365eSAndreas Gohr */
1405c57e365eSAndreas Gohrfunction datetime_h($dt) {
1406c57e365eSAndreas Gohr    global $lang;
1407c57e365eSAndreas Gohr
1408c57e365eSAndreas Gohr    $ago = time() - $dt;
1409c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1410c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1411c57e365eSAndreas Gohr    }
1412c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 2) {
1413c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1414c57e365eSAndreas Gohr    }
1415c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 7 * 2) {
1416c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1417c57e365eSAndreas Gohr    }
1418c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 2) {
1419c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1420c57e365eSAndreas Gohr    }
1421c57e365eSAndreas Gohr    if($ago > 60 * 60 * 2) {
1422c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago / (60 * 60)));
1423c57e365eSAndreas Gohr    }
1424c57e365eSAndreas Gohr    if($ago > 60 * 2) {
1425c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago / (60)));
1426c57e365eSAndreas Gohr    }
1427c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1428c57e365eSAndreas Gohr}
1429c57e365eSAndreas Gohr
1430c57e365eSAndreas Gohr/**
1431f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1432f2263577SAndreas Gohr *
1433f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1434f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1435f2263577SAndreas Gohr *
1436f2263577SAndreas Gohr * @see datetime_h
1437f2263577SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1438140cfbcdSGerrit Uitslag *
1439140cfbcdSGerrit Uitslag * @param int|null $dt      timestamp when given, null will take current timestamp
1440140cfbcdSGerrit Uitslag * @param string   $format  empty default to $conf['dformat'], or provide format as recognized by strftime()
1441140cfbcdSGerrit Uitslag * @return string
1442f2263577SAndreas Gohr */
1443f2263577SAndreas Gohrfunction dformat($dt = null, $format = '') {
1444f2263577SAndreas Gohr    global $conf;
1445f2263577SAndreas Gohr
1446f2263577SAndreas Gohr    if(is_null($dt)) $dt = time();
1447f2263577SAndreas Gohr    $dt = (int) $dt;
1448f2263577SAndreas Gohr    if(!$format) $format = $conf['dformat'];
1449f2263577SAndreas Gohr
1450f2263577SAndreas Gohr    $format = str_replace('%f', datetime_h($dt), $format);
1451f2263577SAndreas Gohr    return strftime($format, $dt);
1452f2263577SAndreas Gohr}
1453f2263577SAndreas Gohr
1454f2263577SAndreas Gohr/**
1455c4f79b71SMichael Hamann * Formats a timestamp as ISO 8601 date
1456c4f79b71SMichael Hamann *
1457c4f79b71SMichael Hamann * @author <ungu at terong dot com>
1458c4f79b71SMichael Hamann * @link http://www.php.net/manual/en/function.date.php#54072
1459140cfbcdSGerrit Uitslag *
146063703ba5SAndreas Gohr * @param int $int_date: current date in UNIX timestamp
14613272d797SAndreas Gohr * @return string
1462c4f79b71SMichael Hamann */
1463c4f79b71SMichael Hamannfunction date_iso8601($int_date) {
1464c4f79b71SMichael Hamann    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1465c4f79b71SMichael Hamann    $pre_timezone = date('O', $int_date);
1466c4f79b71SMichael Hamann    $time_zone    = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1467c4f79b71SMichael Hamann    $date_mod .= $time_zone;
1468c4f79b71SMichael Hamann    return $date_mod;
1469c4f79b71SMichael Hamann}
1470c4f79b71SMichael Hamann
1471c4f79b71SMichael Hamann/**
147200a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
147300a7b5adSEsther Brunner *
147400a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
147500a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
1476140cfbcdSGerrit Uitslag *
1477140cfbcdSGerrit Uitslag * @param string $email email address
1478140cfbcdSGerrit Uitslag * @return string
147900a7b5adSEsther Brunner */
148000a7b5adSEsther Brunnerfunction obfuscate($email) {
148100a7b5adSEsther Brunner    global $conf;
148200a7b5adSEsther Brunner
148300a7b5adSEsther Brunner    switch($conf['mailguard']) {
148400a7b5adSEsther Brunner        case 'visible' :
148500a7b5adSEsther Brunner            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
148600a7b5adSEsther Brunner            return strtr($email, $obfuscate);
148700a7b5adSEsther Brunner
148800a7b5adSEsther Brunner        case 'hex' :
148900a7b5adSEsther Brunner            $encode = '';
149049eb6e38SAndreas Gohr            $len    = strlen($email);
149149eb6e38SAndreas Gohr            for($x = 0; $x < $len; $x++) {
149249eb6e38SAndreas Gohr                $encode .= '&#x'.bin2hex($email{$x}).';';
149349eb6e38SAndreas Gohr            }
149400a7b5adSEsther Brunner            return $encode;
149500a7b5adSEsther Brunner
149600a7b5adSEsther Brunner        case 'none' :
149700a7b5adSEsther Brunner        default :
149800a7b5adSEsther Brunner            return $email;
149900a7b5adSEsther Brunner    }
150000a7b5adSEsther Brunner}
150100a7b5adSEsther Brunner
150200a7b5adSEsther Brunner/**
150389541d4bSAndreas Gohr * Removes quoting backslashes
150489541d4bSAndreas Gohr *
150589541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1506140cfbcdSGerrit Uitslag *
1507140cfbcdSGerrit Uitslag * @param string $string
1508140cfbcdSGerrit Uitslag * @param string $char backslashed character
1509140cfbcdSGerrit Uitslag * @return string
151089541d4bSAndreas Gohr */
151189541d4bSAndreas Gohrfunction unslash($string, $char = "'") {
151289541d4bSAndreas Gohr    return str_replace('\\'.$char, $char, $string);
151389541d4bSAndreas Gohr}
151489541d4bSAndreas Gohr
151573038c47SAndreas Gohr/**
151673038c47SAndreas Gohr * Convert php.ini shorthands to byte
151773038c47SAndreas Gohr *
151873038c47SAndreas Gohr * @author <gilthans dot NO dot SPAM at gmail dot com>
151973038c47SAndreas Gohr * @link   http://de3.php.net/manual/en/ini.core.php#79564
1520140cfbcdSGerrit Uitslag *
1521140cfbcdSGerrit Uitslag * @param string $v shorthands
1522140cfbcdSGerrit Uitslag * @return int|string
152373038c47SAndreas Gohr */
152473038c47SAndreas Gohrfunction php_to_byte($v) {
152573038c47SAndreas Gohr    $l   = substr($v, -1);
152673038c47SAndreas Gohr    $ret = substr($v, 0, -1);
152773038c47SAndreas Gohr    switch(strtoupper($l)) {
152874160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
152973038c47SAndreas Gohr        case 'P':
153073038c47SAndreas Gohr            $ret *= 1024;
153174160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
153273038c47SAndreas Gohr        case 'T':
153373038c47SAndreas Gohr            $ret *= 1024;
153474160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
153573038c47SAndreas Gohr        case 'G':
153673038c47SAndreas Gohr            $ret *= 1024;
153774160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
153873038c47SAndreas Gohr        case 'M':
153973038c47SAndreas Gohr            $ret *= 1024;
1540f168548cSGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
154173038c47SAndreas Gohr        case 'K':
154273038c47SAndreas Gohr            $ret *= 1024;
154373038c47SAndreas Gohr            break;
154449cbd23eSOtto Vainio        default;
154549cbd23eSOtto Vainio            $ret *= 10;
154649cbd23eSOtto Vainio            break;
154773038c47SAndreas Gohr    }
154873038c47SAndreas Gohr    return $ret;
154973038c47SAndreas Gohr}
155073038c47SAndreas Gohr
1551546d3a99SAndreas Gohr/**
1552546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1553140cfbcdSGerrit Uitslag *
1554140cfbcdSGerrit Uitslag * @param string $string
1555140cfbcdSGerrit Uitslag * @return string
1556546d3a99SAndreas Gohr */
1557546d3a99SAndreas Gohrfunction preg_quote_cb($string) {
1558546d3a99SAndreas Gohr    return preg_quote($string, '/');
1559546d3a99SAndreas Gohr}
156073038c47SAndreas Gohr
1561bd2f6c2fSAndreas Gohr/**
1562bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1563bd2f6c2fSAndreas Gohr *
1564c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1565bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1566bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1567bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1568bd2f6c2fSAndreas Gohr *
1569bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1570bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1571bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1572bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1573bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
15743272d797SAndreas Gohr * @return string
1575bd2f6c2fSAndreas Gohr */
1576a5d27328SAndreas Gohrfunction shorten($keep, $short, $max, $min = 9, $char = '…') {
1577bd2f6c2fSAndreas Gohr    $max = $max - utf8_strlen($keep);
1578bd2f6c2fSAndreas Gohr    if($max < $min) return $keep;
1579bd2f6c2fSAndreas Gohr    $len = utf8_strlen($short);
1580bd2f6c2fSAndreas Gohr    if($len <= $max) return $keep.$short;
1581bd2f6c2fSAndreas Gohr    $half = floor($max / 2);
1582bd2f6c2fSAndreas Gohr    return $keep.utf8_substr($short, 0, $half - 1).$char.utf8_substr($short, $len - $half);
1583bd2f6c2fSAndreas Gohr}
1584bd2f6c2fSAndreas Gohr
1585dc58b6f4SAndy Webber/**
1586dc58b6f4SAndy Webber * Return the users real name or e-mail address for use
1587dc58b6f4SAndy Webber * in page footer and recent changes pages
1588dc58b6f4SAndy Webber *
1589b4b6c9a1SGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
159015f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1591c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
159215f3bc49SGerrit Uitslag *
1593dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1594dc58b6f4SAndy Webber */
159515f3bc49SGerrit Uitslagfunction editorinfo($username, $textonly = false) {
1596cd4635eeSGerrit Uitslag    return userlink($username, $textonly);
1597dc58b6f4SAndy Webber}
1598dc58b6f4SAndy Webber
159960a396c8SGerrit Uitslag/**
160060a396c8SGerrit Uitslag * Returns users realname w/o link
160160a396c8SGerrit Uitslag *
1602f168548cSGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
160315f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1604c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
160560a396c8SGerrit Uitslag *
160660a396c8SGerrit Uitslag * @triggers COMMON_USER_LINK
160760a396c8SGerrit Uitslag */
1608cd4635eeSGerrit Uitslagfunction userlink($username = null, $textonly = false) {
160960a396c8SGerrit Uitslag    global $conf, $INFO;
161060a396c8SGerrit Uitslag    /** @var DokuWiki_Auth_Plugin $auth */
161160a396c8SGerrit Uitslag    global $auth;
161230f6ec4bSGerrit Uitslag    /** @var Input $INPUT */
161330f6ec4bSGerrit Uitslag    global $INPUT;
161460a396c8SGerrit Uitslag
161560a396c8SGerrit Uitslag    // prepare initial event data
161660a396c8SGerrit Uitslag    $data = array(
161760a396c8SGerrit Uitslag        'username' => $username, // the unique user name
161860a396c8SGerrit Uitslag        'name' => '',
161960a396c8SGerrit Uitslag        'link' => array( //setting 'link' to false disables linking
162060a396c8SGerrit Uitslag                         'target' => '',
162160a396c8SGerrit Uitslag                         'pre' => '',
162260a396c8SGerrit Uitslag                         'suf' => '',
162360a396c8SGerrit Uitslag                         'style' => '',
162460a396c8SGerrit Uitslag                         'more' => '',
162560a396c8SGerrit Uitslag                         'url' => '',
162660a396c8SGerrit Uitslag                         'title' => '',
162760a396c8SGerrit Uitslag                         'class' => ''
162860a396c8SGerrit Uitslag        ),
16294d5fc927SGerrit Uitslag        'userlink' => '', // formatted user name as will be returned
163015f3bc49SGerrit Uitslag        'textonly' => $textonly
163160a396c8SGerrit Uitslag    );
163262c8004eSGerrit Uitslag    if($username === null) {
163330f6ec4bSGerrit Uitslag        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
163415f3bc49SGerrit Uitslag        if($textonly){
163515f3bc49SGerrit Uitslag            $data['name'] = $INFO['userinfo']['name']. ' (' . $INPUT->server->str('REMOTE_USER') . ')';
163615f3bc49SGerrit Uitslag        }else {
163730f6ec4bSGerrit Uitslag            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> (<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
163860a396c8SGerrit Uitslag        }
163915f3bc49SGerrit Uitslag    }
164060a396c8SGerrit Uitslag
164160a396c8SGerrit Uitslag    $evt = new Doku_Event('COMMON_USER_LINK', $data);
164260a396c8SGerrit Uitslag    if($evt->advise_before(true)) {
164360a396c8SGerrit Uitslag        if(empty($data['name'])) {
164460a396c8SGerrit Uitslag            if($auth) $info = $auth->getUserData($username);
164565833968SGerrit Uitslag            if($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1646dc58b6f4SAndy Webber                switch($conf['showuseras']) {
1647dc58b6f4SAndy Webber                    case 'username':
16487f081821SGerrit Uitslag                    case 'username_link':
164915f3bc49SGerrit Uitslag                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
165060a396c8SGerrit Uitslag                        break;
1651dc58b6f4SAndy Webber                    case 'email':
1652dc58b6f4SAndy Webber                    case 'email_link':
165360a396c8SGerrit Uitslag                        $data['name'] = obfuscate($info['mail']);
165460a396c8SGerrit Uitslag                        break;
1655dc58b6f4SAndy Webber                }
165665833968SGerrit Uitslag            } else {
165765833968SGerrit Uitslag                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
165860a396c8SGerrit Uitslag            }
165960a396c8SGerrit Uitslag        }
16607f081821SGerrit Uitslag
16617f081821SGerrit Uitslag        /** @var Doku_Renderer_xhtml $xhtml_renderer */
16627f081821SGerrit Uitslag        static $xhtml_renderer = null;
16637f081821SGerrit Uitslag
166415f3bc49SGerrit Uitslag        if(!$data['textonly'] && empty($data['link']['url'])) {
16657f081821SGerrit Uitslag
16667f081821SGerrit Uitslag            if(in_array($conf['showuseras'], array('email_link', 'username_link'))) {
166760a396c8SGerrit Uitslag                if(!isset($info)) {
166860a396c8SGerrit Uitslag                    if($auth) $info = $auth->getUserData($username);
166960a396c8SGerrit Uitslag                }
167060a396c8SGerrit Uitslag                if(isset($info) && $info) {
16717f081821SGerrit Uitslag                    if($conf['showuseras'] == 'email_link') {
167260a396c8SGerrit Uitslag                        $data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
1673dc58b6f4SAndy Webber                    } else {
16747f081821SGerrit Uitslag                        if(is_null($xhtml_renderer)) {
16757f081821SGerrit Uitslag                            $xhtml_renderer = p_get_renderer('xhtml');
16767f081821SGerrit Uitslag                        }
16777f081821SGerrit Uitslag                        if(empty($xhtml_renderer->interwiki)) {
16787f081821SGerrit Uitslag                            $xhtml_renderer->interwiki = getInterwiki();
16797f081821SGerrit Uitslag                        }
16807f081821SGerrit Uitslag                        $shortcut = 'user';
1681533772e1SGerrit Uitslag                        $exists = null;
16826496c33fSGerrit Uitslag                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
16832a2a43c4SGerrit Uitslag                        $data['link']['class'] .= ' interwiki iw_user';
16846496c33fSGerrit Uitslag                        if($exists !== null) {
16856496c33fSGerrit Uitslag                            if($exists) {
16866496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink1';
16876496c33fSGerrit Uitslag                            } else {
16886496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink2';
16896496c33fSGerrit Uitslag                                $data['link']['rel'] = 'nofollow';
16906496c33fSGerrit Uitslag                            }
16916496c33fSGerrit Uitslag                        }
1692dc58b6f4SAndy Webber                    }
1693dc58b6f4SAndy Webber                } else {
169415f3bc49SGerrit Uitslag                    $data['textonly'] = true;
1695dc58b6f4SAndy Webber                }
169660a396c8SGerrit Uitslag
169760a396c8SGerrit Uitslag            } else {
169815f3bc49SGerrit Uitslag                $data['textonly'] = true;
169960a396c8SGerrit Uitslag            }
170060a396c8SGerrit Uitslag        }
170160a396c8SGerrit Uitslag
170215f3bc49SGerrit Uitslag        if($data['textonly']) {
17034d5fc927SGerrit Uitslag            $data['userlink'] = $data['name'];
170460a396c8SGerrit Uitslag        } else {
170560a396c8SGerrit Uitslag            $data['link']['name'] = $data['name'];
170660a396c8SGerrit Uitslag            if(is_null($xhtml_renderer)) {
170760a396c8SGerrit Uitslag                $xhtml_renderer = p_get_renderer('xhtml');
170860a396c8SGerrit Uitslag            }
17094d5fc927SGerrit Uitslag            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
171060a396c8SGerrit Uitslag        }
171160a396c8SGerrit Uitslag    }
171260a396c8SGerrit Uitslag    $evt->advise_after();
171360a396c8SGerrit Uitslag    unset($evt);
171460a396c8SGerrit Uitslag
17154d5fc927SGerrit Uitslag    return $data['userlink'];
1716066fee30SAndreas Gohr}
1717066fee30SAndreas Gohr
1718066fee30SAndreas Gohr/**
1719066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1720066fee30SAndreas Gohr * When no image exists, returns an empty string
1721066fee30SAndreas Gohr *
1722066fee30SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1723140cfbcdSGerrit Uitslag *
1724066fee30SAndreas Gohr * @param  string $type - type of image 'badge' or 'button'
17253272d797SAndreas Gohr * @return string
1726066fee30SAndreas Gohr */
1727066fee30SAndreas Gohrfunction license_img($type) {
1728066fee30SAndreas Gohr    global $license;
1729066fee30SAndreas Gohr    global $conf;
1730066fee30SAndreas Gohr    if(!$conf['license']) return '';
1731066fee30SAndreas Gohr    if(!is_array($license[$conf['license']])) return '';
1732066fee30SAndreas Gohr    $try   = array();
1733066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1734066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1735066fee30SAndreas Gohr    if(substr($conf['license'], 0, 3) == 'cc-') {
1736066fee30SAndreas Gohr        $try[] = 'lib/images/license/'.$type.'/cc.png';
1737066fee30SAndreas Gohr    }
1738066fee30SAndreas Gohr    foreach($try as $src) {
1739066fee30SAndreas Gohr        if(@file_exists(DOKU_INC.$src)) return $src;
1740066fee30SAndreas Gohr    }
1741066fee30SAndreas Gohr    return '';
1742dc58b6f4SAndy Webber}
1743dc58b6f4SAndy Webber
174413c08e2fSMichael Klier/**
174513c08e2fSMichael Klier * Checks if the given amount of memory is available
174613c08e2fSMichael Klier *
174713c08e2fSMichael Klier * If the memory_get_usage() function is not available the
174813c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
174913c08e2fSMichael Klier *
175013c08e2fSMichael Klier * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
175113c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
17523272d797SAndreas Gohr *
17533272d797SAndreas Gohr * @param int  $mem    Size of memory you want to allocate in bytes
1754140cfbcdSGerrit Uitslag * @param int  $bytes  already allocated memory (see above)
17553272d797SAndreas Gohr * @return bool
175613c08e2fSMichael Klier */
175713c08e2fSMichael Klierfunction is_mem_available($mem, $bytes = 1048576) {
175813c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
175913c08e2fSMichael Klier    if(empty($limit)) return true; // no limit set!
176013c08e2fSMichael Klier
176113c08e2fSMichael Klier    // parse limit to bytes
176213c08e2fSMichael Klier    $limit = php_to_byte($limit);
176313c08e2fSMichael Klier
176413c08e2fSMichael Klier    // get used memory if possible
176513c08e2fSMichael Klier    if(function_exists('memory_get_usage')) {
176613c08e2fSMichael Klier        $used = memory_get_usage();
176749eb6e38SAndreas Gohr    } else {
176849eb6e38SAndreas Gohr        $used = $bytes;
176913c08e2fSMichael Klier    }
177013c08e2fSMichael Klier
177113c08e2fSMichael Klier    if($used + $mem > $limit) {
177213c08e2fSMichael Klier        return false;
177313c08e2fSMichael Klier    }
177413c08e2fSMichael Klier
177513c08e2fSMichael Klier    return true;
177613c08e2fSMichael Klier}
177713c08e2fSMichael Klier
1778af2408d5SAndreas Gohr/**
1779af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1780af2408d5SAndreas Gohr *
1781af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1782af2408d5SAndreas Gohr *
1783af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1784af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1785140cfbcdSGerrit Uitslag *
1786140cfbcdSGerrit Uitslag * @param string $url url being directed to
1787af2408d5SAndreas Gohr */
1788af2408d5SAndreas Gohrfunction send_redirect($url) {
1789585bf44eSChristopher Smith    /* @var Input $INPUT */
1790585bf44eSChristopher Smith    global $INPUT;
1791585bf44eSChristopher Smith
17920181f021SAndreas Gohr    //are there any undisplayed messages? keep them in session for display
17930181f021SAndreas Gohr    global $MSG;
17940181f021SAndreas Gohr    if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
17950181f021SAndreas Gohr        //reopen session, store data and close session again
17960181f021SAndreas Gohr        @session_start();
17970181f021SAndreas Gohr        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
17980181f021SAndreas Gohr    }
17990181f021SAndreas Gohr
1800d4869846SAndreas Gohr    // always close the session
1801d4869846SAndreas Gohr    session_write_close();
1802d4869846SAndreas Gohr
1803c10dcb7dSAndreas Gohr    // work around IE bug
1804c10dcb7dSAndreas Gohr    // http://www.ianhoar.com/2008/11/16/internet-explorer-6-and-redirected-anchor-links/
18056d2af55dSChristopher Smith    @list($url, $hash) = explode('#', $url);
1806c10dcb7dSAndreas Gohr    if($hash) {
1807c10dcb7dSAndreas Gohr        if(strpos($url, '?')) {
1808c10dcb7dSAndreas Gohr            $url = $url.'&#'.$hash;
1809c10dcb7dSAndreas Gohr        } else {
1810c10dcb7dSAndreas Gohr            $url = $url.'?&#'.$hash;
1811c10dcb7dSAndreas Gohr        }
1812c10dcb7dSAndreas Gohr    }
1813c10dcb7dSAndreas Gohr
1814af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
1815585bf44eSChristopher Smith    if($INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1816585bf44eSChristopher Smith        (strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) &&
1817585bf44eSChristopher Smith        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
18183272d797SAndreas Gohr        $matches[1] < 6
18193272d797SAndreas Gohr    ) {
1820af2408d5SAndreas Gohr        header('Refresh: 0;url='.$url);
1821af2408d5SAndreas Gohr    } else {
1822af2408d5SAndreas Gohr        header('Location: '.$url);
1823af2408d5SAndreas Gohr    }
1824af2408d5SAndreas Gohr    exit;
1825af2408d5SAndreas Gohr}
1826af2408d5SAndreas Gohr
18275b75cd1fSAdrian Lang/**
18285b75cd1fSAdrian Lang * Validate a value using a set of valid values
18295b75cd1fSAdrian Lang *
18305b75cd1fSAdrian Lang * This function checks whether a specified value is set and in the array
18315b75cd1fSAdrian Lang * $valid_values. If not, the function returns a default value or, if no
18325b75cd1fSAdrian Lang * default is specified, throws an exception.
18335b75cd1fSAdrian Lang *
18345b75cd1fSAdrian Lang * @param string $param        The name of the parameter
18355b75cd1fSAdrian Lang * @param array  $valid_values A set of valid values; Optionally a default may
18365b75cd1fSAdrian Lang *                             be marked by the key “default”.
18375b75cd1fSAdrian Lang * @param array  $array        The array containing the value (typically $_POST
18385b75cd1fSAdrian Lang *                             or $_GET)
18395b75cd1fSAdrian Lang * @param string $exc          The text of the raised exception
18405b75cd1fSAdrian Lang *
18413272d797SAndreas Gohr * @throws Exception
18423272d797SAndreas Gohr * @return mixed
18435b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
18445b75cd1fSAdrian Lang */
18455b75cd1fSAdrian Langfunction valid_input_set($param, $valid_values, $array, $exc = '') {
18465b75cd1fSAdrian Lang    if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
18475b75cd1fSAdrian Lang        return $array[$param];
18485b75cd1fSAdrian Lang    } elseif(isset($valid_values['default'])) {
18495b75cd1fSAdrian Lang        return $valid_values['default'];
18505b75cd1fSAdrian Lang    } else {
18515b75cd1fSAdrian Lang        throw new Exception($exc);
18525b75cd1fSAdrian Lang    }
18535b75cd1fSAdrian Lang}
18545b75cd1fSAdrian Lang
185563703ba5SAndreas Gohr/**
185663703ba5SAndreas Gohr * Read a preference from the DokuWiki cookie
1857646a531aSChristopher Smith * (remembering both keys & values are urlencoded)
1858140cfbcdSGerrit Uitslag *
1859140cfbcdSGerrit Uitslag * @param string $pref     preference key
1860b4b6c9a1SGerrit Uitslag * @param mixed  $default  value returned when preference not found
1861140cfbcdSGerrit Uitslag * @return string preference value
186263703ba5SAndreas Gohr */
1863554a8c9fSAdrian Langfunction get_doku_pref($pref, $default) {
1864646a531aSChristopher Smith    $enc_pref = urlencode($pref);
1865646a531aSChristopher Smith    if(strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
1866554a8c9fSAdrian Lang        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
186763703ba5SAndreas Gohr        $cnt   = count($parts);
186863703ba5SAndreas Gohr        for($i = 0; $i < $cnt; $i += 2) {
1869646a531aSChristopher Smith            if($parts[$i] == $enc_pref) {
1870646a531aSChristopher Smith                return urldecode($parts[$i + 1]);
1871554a8c9fSAdrian Lang            }
1872554a8c9fSAdrian Lang        }
1873554a8c9fSAdrian Lang    }
1874554a8c9fSAdrian Lang    return $default;
1875554a8c9fSAdrian Lang}
1876554a8c9fSAdrian Lang
18773c94d07bSAnika Henke/**
18783c94d07bSAnika Henke * Add a preference to the DokuWiki cookie
187936ec377eSChristopher Smith * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
1880140cfbcdSGerrit Uitslag *
1881140cfbcdSGerrit Uitslag * @param string $pref  preference key
1882140cfbcdSGerrit Uitslag * @param string $val   preference value
18833c94d07bSAnika Henke */
18843c94d07bSAnika Henkefunction set_doku_pref($pref, $val) {
18853c94d07bSAnika Henke    global $conf;
18863c94d07bSAnika Henke    $orig = get_doku_pref($pref, false);
18873c94d07bSAnika Henke    $cookieVal = '';
18883c94d07bSAnika Henke
18893c94d07bSAnika Henke    if($orig && ($orig != $val)) {
18903c94d07bSAnika Henke        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
18913c94d07bSAnika Henke        $cnt   = count($parts);
189236ec377eSChristopher Smith        // urlencode $pref for the comparison
189336ec377eSChristopher Smith        $enc_pref = rawurlencode($pref);
18943c94d07bSAnika Henke        for($i = 0; $i < $cnt; $i += 2) {
189536ec377eSChristopher Smith            if($parts[$i] == $enc_pref) {
189636ec377eSChristopher Smith                $parts[$i + 1] = rawurlencode($val);
189750f261f7SMichael Hamann                break;
18983c94d07bSAnika Henke            }
18993c94d07bSAnika Henke        }
19003c94d07bSAnika Henke        $cookieVal = implode('#', $parts);
19013c94d07bSAnika Henke    } else if (!$orig) {
190236ec377eSChristopher Smith        $cookieVal = ($_COOKIE['DOKU_PREFS'] ? $_COOKIE['DOKU_PREFS'].'#' : '').rawurlencode($pref).'#'.rawurlencode($val);
19033c94d07bSAnika Henke    }
19043c94d07bSAnika Henke
19053c94d07bSAnika Henke    if (!empty($cookieVal)) {
190675e4dd8aSGerrit Uitslag        $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
190775e4dd8aSGerrit Uitslag        setcookie('DOKU_PREFS', $cookieVal, time()+365*24*3600, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
19083c94d07bSAnika Henke    }
19093c94d07bSAnika Henke}
19103c94d07bSAnika Henke
1911f8fb2d18SAndreas Gohr/**
1912f8fb2d18SAndreas Gohr * Strips source mapping declarations from given text #601
1913f8fb2d18SAndreas Gohr *
1914f8fb2d18SAndreas Gohr * @param &string $text reference to the CSS or JavaScript code to clean
1915f8fb2d18SAndreas Gohr */
1916f8fb2d18SAndreas Gohrfunction stripsourcemaps(&$text){
1917f8fb2d18SAndreas Gohr    $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text);
1918f8fb2d18SAndreas Gohr}
1919f8fb2d18SAndreas Gohr
1920e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1921