xref: /dokuwiki/inc/common.php (revision 59bc3b48fdffb76ee65a4b630be3ffa1f6c20c80)
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.
123*59bc3b48SGerrit Uitslag    $info = array();
124c66972f2SAdrian Lang    $info['isadmin']   = false;
125c66972f2SAdrian Lang    $info['ismanager'] = false;
126585bf44eSChristopher Smith    if($INPUT->server->has('REMOTE_USER')) {
127f3f0262cSandi        $info['userinfo']   = $USERINFO;
1281015a57dSChristopher Smith        $info['perm']       = auth_quickaclcheck($id);
129585bf44eSChristopher Smith        $info['client']     = $INPUT->server->str('REMOTE_USER');
13017ee7f66SAndreas Gohr
131f8cc712eSAndreas Gohr        if($info['perm'] == AUTH_ADMIN) {
132f8cc712eSAndreas Gohr            $info['isadmin']   = true;
133f8cc712eSAndreas Gohr            $info['ismanager'] = true;
134f8cc712eSAndreas Gohr        } elseif(auth_ismanager()) {
135f8cc712eSAndreas Gohr            $info['ismanager'] = true;
136f8cc712eSAndreas Gohr        }
137f8cc712eSAndreas Gohr
13817ee7f66SAndreas Gohr        // if some outside auth were used only REMOTE_USER is set
13917ee7f66SAndreas Gohr        if(!$info['userinfo']['name']) {
140585bf44eSChristopher Smith            $info['userinfo']['name'] = $INPUT->server->str('REMOTE_USER');
14117ee7f66SAndreas Gohr        }
142ee4c4a1bSAndreas Gohr
143f3f0262cSandi    } else {
1441015a57dSChristopher Smith        $info['perm']       = auth_aclcheck($id, '', null);
145ee4c4a1bSAndreas Gohr        $info['client']     = clientIP(true);
146f3f0262cSandi    }
147f3f0262cSandi
1481015a57dSChristopher Smith    $info['namespace'] = getNS($id);
1491015a57dSChristopher Smith
1501015a57dSChristopher Smith    // mobile detection
1511015a57dSChristopher Smith    if ($htmlClient) {
1521015a57dSChristopher Smith        $info['ismobile'] = clientismobile();
1531015a57dSChristopher Smith    }
1541015a57dSChristopher Smith
1551015a57dSChristopher Smith    return $info;
1561015a57dSChristopher Smith }
1571015a57dSChristopher Smith
1581015a57dSChristopher Smith/**
1591015a57dSChristopher Smith * Return info about the current document as associative
1601015a57dSChristopher Smith * array.
1611015a57dSChristopher Smith *
1621015a57dSChristopher Smith * @author Andreas Gohr <andi@splitbrain.org>
163140cfbcdSGerrit Uitslag *
164140cfbcdSGerrit Uitslag * @return array with info about current document
1651015a57dSChristopher Smith */
1661015a57dSChristopher Smithfunction pageinfo() {
1671015a57dSChristopher Smith    global $ID;
1681015a57dSChristopher Smith    global $REV;
1691015a57dSChristopher Smith    global $RANGE;
1701015a57dSChristopher Smith    global $lang;
171585bf44eSChristopher Smith    /* @var Input $INPUT */
172585bf44eSChristopher Smith    global $INPUT;
1731015a57dSChristopher Smith
1741015a57dSChristopher Smith    $info = basicinfo($ID);
1751015a57dSChristopher Smith
1761015a57dSChristopher Smith    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
1771015a57dSChristopher Smith    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
1781015a57dSChristopher Smith    $info['id']  = $ID;
1791015a57dSChristopher Smith    $info['rev'] = $REV;
1801015a57dSChristopher Smith
181585bf44eSChristopher Smith    if($INPUT->server->has('REMOTE_USER')) {
1827e87a794SChristopher Smith        $sub = new Subscription();
1837e87a794SChristopher Smith        $info['subscribed'] = $sub->user_subscription();
1847e87a794SChristopher Smith    } else {
1857e87a794SChristopher Smith        $info['subscribed'] = false;
1867e87a794SChristopher Smith    }
1877e87a794SChristopher Smith
188f3f0262cSandi    $info['locked']     = checklock($ID);
18900976812SAndreas Gohr    $info['filepath']   = fullpath(wikiFN($ID));
1902ca9d91cSBen Coburn    $info['exists']     = @file_exists($info['filepath']);
19101c9a118SAndreas Gohr    $info['currentrev'] = @filemtime($info['filepath']);
1922ca9d91cSBen Coburn    if($REV) {
1932ca9d91cSBen Coburn        //check if current revision was meant
19401c9a118SAndreas Gohr        if($info['exists'] && ($info['currentrev'] == $REV)) {
1952ca9d91cSBen Coburn            $REV = '';
1967b3a6803SAndreas Gohr        } elseif($RANGE) {
1977b3a6803SAndreas Gohr            //section editing does not work with old revisions!
1987b3a6803SAndreas Gohr            $REV   = '';
1997b3a6803SAndreas Gohr            $RANGE = '';
2007b3a6803SAndreas Gohr            msg($lang['nosecedit'], 0);
2012ca9d91cSBen Coburn        } else {
2022ca9d91cSBen Coburn            //really use old revision
20300976812SAndreas Gohr            $info['filepath'] = fullpath(wikiFN($ID, $REV));
204f3f0262cSandi            $info['exists']   = @file_exists($info['filepath']);
205f3f0262cSandi        }
206f3f0262cSandi    }
207c112d578Sandi    $info['rev'] = $REV;
208f3f0262cSandi    if($info['exists']) {
209f3f0262cSandi        $info['writable'] = (is_writable($info['filepath']) &&
210f3f0262cSandi            ($info['perm'] >= AUTH_EDIT));
211f3f0262cSandi    } else {
212f3f0262cSandi        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
213f3f0262cSandi    }
21450e988b1SAndreas Gohr    $info['editable'] = ($info['writable'] && empty($info['locked']));
215f3f0262cSandi    $info['lastmod']  = @filemtime($info['filepath']);
216f3f0262cSandi
21771726d78SBen Coburn    //load page meta data
21871726d78SBen Coburn    $info['meta'] = p_get_metadata($ID);
21971726d78SBen Coburn
220652610a2Sandi    //who's the editor
221047bad06SGerrit Uitslag    $pagelog = new PageChangeLog($ID, 1024);
222652610a2Sandi    if($REV) {
223f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($REV);
224652610a2Sandi    } else {
2250e80bb5eSChristopher Smith        if(!empty($info['meta']['last_change']) && is_array($info['meta']['last_change'])) {
226aa27cf05SAndreas Gohr            $revinfo = $info['meta']['last_change'];
227aa27cf05SAndreas Gohr        } else {
228f523c971SGerrit Uitslag            $revinfo = $pagelog->getRevisionInfo($info['lastmod']);
229cd00a034SBen Coburn            // cache most recent changelog line in metadata if missing and still valid
230cd00a034SBen Coburn            if($revinfo !== false) {
231cd00a034SBen Coburn                $info['meta']['last_change'] = $revinfo;
232cd00a034SBen Coburn                p_set_metadata($ID, array('last_change' => $revinfo));
233cd00a034SBen Coburn            }
234cd00a034SBen Coburn        }
235cd00a034SBen Coburn    }
236cd00a034SBen Coburn    //and check for an external edit
237cd00a034SBen Coburn    if($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
238cd00a034SBen Coburn        // cached changelog line no longer valid
239cd00a034SBen Coburn        $revinfo                     = false;
240cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
241cd00a034SBen Coburn        p_set_metadata($ID, array('last_change' => $revinfo));
242652610a2Sandi    }
243bb4866bdSchris
244652610a2Sandi    $info['ip']   = $revinfo['ip'];
245652610a2Sandi    $info['user'] = $revinfo['user'];
246652610a2Sandi    $info['sum']  = $revinfo['sum'];
24771726d78SBen Coburn    // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
248ebf1501fSBen Coburn    // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
24959f257aeSchris
25088f522e9Sandi    if($revinfo['user']) {
25188f522e9Sandi        $info['editor'] = $revinfo['user'];
25288f522e9Sandi    } else {
25388f522e9Sandi        $info['editor'] = $revinfo['ip'];
25488f522e9Sandi    }
255652610a2Sandi
256ee4c4a1bSAndreas Gohr    // draft
257ee4c4a1bSAndreas Gohr    $draft = getCacheName($info['client'].$ID, '.draft');
258ee4c4a1bSAndreas Gohr    if(@file_exists($draft)) {
259ee4c4a1bSAndreas Gohr        if(@filemtime($draft) < @filemtime(wikiFN($ID))) {
260ee4c4a1bSAndreas Gohr            // remove stale draft
261ee4c4a1bSAndreas Gohr            @unlink($draft);
262ee4c4a1bSAndreas Gohr        } else {
263ee4c4a1bSAndreas Gohr            $info['draft'] = $draft;
264ee4c4a1bSAndreas Gohr        }
265ee4c4a1bSAndreas Gohr    }
266ee4c4a1bSAndreas Gohr
2671015a57dSChristopher Smith    return $info;
2681015a57dSChristopher Smith}
2691015a57dSChristopher Smith
2701015a57dSChristopher Smith/**
2711015a57dSChristopher Smith * Return information about the current media item as an associative array.
272140cfbcdSGerrit Uitslag *
273140cfbcdSGerrit Uitslag * @return array with info about current media item
2741015a57dSChristopher Smith */
2751015a57dSChristopher Smithfunction mediainfo(){
2761015a57dSChristopher Smith    global $NS;
2771015a57dSChristopher Smith    global $IMG;
2781015a57dSChristopher Smith
2791015a57dSChristopher Smith    $info = basicinfo("$NS:*");
2801015a57dSChristopher Smith    $info['image'] = $IMG;
2811c548ebeSAndreas Gohr
282f3f0262cSandi    return $info;
283f3f0262cSandi}
284f3f0262cSandi
285f3f0262cSandi/**
2862684e50aSAndreas Gohr * Build an string of URL parameters
2872684e50aSAndreas Gohr *
2882684e50aSAndreas Gohr * @author Andreas Gohr
289140cfbcdSGerrit Uitslag *
290140cfbcdSGerrit Uitslag * @param array  $params    array with key-value pairs
291140cfbcdSGerrit Uitslag * @param string $sep       series of pairs are separated by this character
292140cfbcdSGerrit Uitslag * @return string query string
2932684e50aSAndreas Gohr */
294b174aeaeSchrisfunction buildURLparams($params, $sep = '&amp;') {
2952684e50aSAndreas Gohr    $url = '';
2962684e50aSAndreas Gohr    $amp = false;
2972684e50aSAndreas Gohr    foreach($params as $key => $val) {
298b174aeaeSchris        if($amp) $url .= $sep;
2992684e50aSAndreas Gohr
30085e6871fSAdrian Lang        $url .= rawurlencode($key).'=';
3013a50618cSgweissbach        $url .= rawurlencode((string) $val);
3022684e50aSAndreas Gohr        $amp = true;
3032684e50aSAndreas Gohr    }
3042684e50aSAndreas Gohr    return $url;
3052684e50aSAndreas Gohr}
3062684e50aSAndreas Gohr
3072684e50aSAndreas Gohr/**
3082684e50aSAndreas Gohr * Build an string of html tag attributes
3092684e50aSAndreas Gohr *
3107bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
3117bff22c0SAndreas Gohr *
3122684e50aSAndreas Gohr * @author Andreas Gohr
313140cfbcdSGerrit Uitslag *
314140cfbcdSGerrit Uitslag * @param array $params    array with (attribute name-attribute value) pairs
315140cfbcdSGerrit Uitslag * @param bool  $skipempty skip empty string values?
316140cfbcdSGerrit Uitslag * @return string
3172684e50aSAndreas Gohr */
3184b030ce7SAndreas Gohrfunction buildAttributes($params, $skipempty = false) {
3192684e50aSAndreas Gohr    $url   = '';
3209063ec14SAdrian Lang    $white = false;
3212684e50aSAndreas Gohr    foreach($params as $key => $val) {
3227bff22c0SAndreas Gohr        if($key{0} == '_') continue;
323b1c94f1dSAndreas Gohr        if($val === '' && $skipempty) continue;
3249063ec14SAdrian Lang        if($white) $url .= ' ';
3257bff22c0SAndreas Gohr
3262684e50aSAndreas Gohr        $url .= $key.'="';
3272684e50aSAndreas Gohr        $url .= htmlspecialchars($val);
3282684e50aSAndreas Gohr        $url .= '"';
3299063ec14SAdrian Lang        $white = true;
3302684e50aSAndreas Gohr    }
3312684e50aSAndreas Gohr    return $url;
3322684e50aSAndreas Gohr}
3332684e50aSAndreas Gohr
3342684e50aSAndreas Gohr/**
33515fae107Sandi * This builds the breadcrumb trail and returns it as array
33615fae107Sandi *
33715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
338140cfbcdSGerrit Uitslag *
339140cfbcdSGerrit Uitslag * @return array(pageid=>name, ... )
340f3f0262cSandi */
341f3f0262cSandifunction breadcrumbs() {
3428746e727Sandi    // we prepare the breadcrumbs early for quick session closing
3438746e727Sandi    static $crumbs = null;
3448746e727Sandi    if($crumbs != null) return $crumbs;
3458746e727Sandi
346f3f0262cSandi    global $ID;
347f3f0262cSandi    global $ACT;
348f3f0262cSandi    global $conf;
349f3f0262cSandi
350f3f0262cSandi    //first visit?
351c66972f2SAdrian Lang    $crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array();
352f3f0262cSandi    //we only save on show and existing wiki documents
353a77f5846Sjan    $file = wikiFN($ID);
354a77f5846Sjan    if($ACT != 'show' || !@file_exists($file)) {
355e71ce681SAndreas Gohr        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
356f3f0262cSandi        return $crumbs;
357f3f0262cSandi    }
358a77f5846Sjan
359a77f5846Sjan    // page names
3601a84a0f3SAnika Henke    $name = noNSorNS($ID);
361fe9ec250SChris Smith    if(useHeading('navigation')) {
362a77f5846Sjan        // get page title
36367c15eceSMichael Hamann        $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
364a77f5846Sjan        if($title) {
365a77f5846Sjan            $name = $title;
366a77f5846Sjan        }
367a77f5846Sjan    }
368a77f5846Sjan
369f3f0262cSandi    //remove ID from array
370a77f5846Sjan    if(isset($crumbs[$ID])) {
371a77f5846Sjan        unset($crumbs[$ID]);
372f3f0262cSandi    }
373f3f0262cSandi
374f3f0262cSandi    //add to array
375a77f5846Sjan    $crumbs[$ID] = $name;
376f3f0262cSandi    //reduce size
377f3f0262cSandi    while(count($crumbs) > $conf['breadcrumbs']) {
378f3f0262cSandi        array_shift($crumbs);
379f3f0262cSandi    }
380f3f0262cSandi    //save to session
381e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
382f3f0262cSandi    return $crumbs;
383f3f0262cSandi}
384f3f0262cSandi
385f3f0262cSandi/**
38615fae107Sandi * Filter for page IDs
38715fae107Sandi *
388f3f0262cSandi * This is run on a ID before it is outputted somewhere
389f3f0262cSandi * currently used to replace the colon with something else
390907f24f7SAndreas Gohr * on Windows (non-IIS) systems and to have proper URL encoding
391907f24f7SAndreas Gohr *
392907f24f7SAndreas Gohr * See discussions at https://github.com/splitbrain/dokuwiki/pull/84 and
393907f24f7SAndreas Gohr * https://github.com/splitbrain/dokuwiki/pull/173 why we use a whitelist of
394907f24f7SAndreas Gohr * unaffected servers instead of blacklisting affected servers here.
39515fae107Sandi *
39649c713a3Sandi * Urlencoding is ommitted when the second parameter is false
39749c713a3Sandi *
39815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
399140cfbcdSGerrit Uitslag *
400140cfbcdSGerrit Uitslag * @param string $id pageid being filtered
401140cfbcdSGerrit Uitslag * @param bool   $ue apply urlencoding?
402140cfbcdSGerrit Uitslag * @return string
403f3f0262cSandi */
40449c713a3Sandifunction idfilter($id, $ue = true) {
405f3f0262cSandi    global $conf;
406585bf44eSChristopher Smith    /* @var Input $INPUT */
407585bf44eSChristopher Smith    global $INPUT;
408585bf44eSChristopher Smith
409f3f0262cSandi    if($conf['useslash'] && $conf['userewrite']) {
410f3f0262cSandi        $id = strtr($id, ':', '/');
411f3f0262cSandi    } elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
41258bedc8aSborekb        $conf['userewrite'] &&
413585bf44eSChristopher Smith        strpos($INPUT->server->str('SERVER_SOFTWARE'), 'Microsoft-IIS') === false
4143272d797SAndreas Gohr    ) {
415f3f0262cSandi        $id = strtr($id, ':', ';');
416f3f0262cSandi    }
41749c713a3Sandi    if($ue) {
418b6c6979fSAndreas Gohr        $id = rawurlencode($id);
419f3f0262cSandi        $id = str_replace('%3A', ':', $id); //keep as colon
420edd95259SGerrit Uitslag        $id = str_replace('%3B', ';', $id); //keep as semicolon
421f3f0262cSandi        $id = str_replace('%2F', '/', $id); //keep as slash
42249c713a3Sandi    }
423f3f0262cSandi    return $id;
424f3f0262cSandi}
425f3f0262cSandi
426f3f0262cSandi/**
427ed7b5f09Sandi * This builds a link to a wikipage
42815fae107Sandi *
4294bc480e5SAndreas Gohr * It handles URL rewriting and adds additional parameters
4306c7843b5Sandi *
43115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
4324bc480e5SAndreas Gohr *
4334bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
4344bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
4354bc480e5SAndreas Gohr * @param bool         $absolute       request an absolute URL instead of relative
4364bc480e5SAndreas Gohr * @param string       $separator      parameter separator
4374bc480e5SAndreas Gohr * @return string
438f3f0262cSandi */
43916f15a81SDominik Eckelmannfunction wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;') {
440f3f0262cSandi    global $conf;
44116f15a81SDominik Eckelmann    if(is_array($urlParameters)) {
44216f15a81SDominik Eckelmann        $urlParameters = buildURLparams($urlParameters, $separator);
4436de3759aSAndreas Gohr    } else {
44416f15a81SDominik Eckelmann        $urlParameters = str_replace(',', $separator, $urlParameters);
4456de3759aSAndreas Gohr    }
44616f15a81SDominik Eckelmann    if($id === '') {
44716f15a81SDominik Eckelmann        $id = $conf['start'];
44816f15a81SDominik Eckelmann    }
449f3f0262cSandi    $id = idfilter($id);
45016f15a81SDominik Eckelmann    if($absolute) {
451ed7b5f09Sandi        $xlink = DOKU_URL;
452ed7b5f09Sandi    } else {
453ed7b5f09Sandi        $xlink = DOKU_BASE;
454ed7b5f09Sandi    }
455f3f0262cSandi
4566c7843b5Sandi    if($conf['userewrite'] == 2) {
4576c7843b5Sandi        $xlink .= DOKU_SCRIPT.'/'.$id;
45816f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
4596c7843b5Sandi    } elseif($conf['userewrite']) {
460f3f0262cSandi        $xlink .= $id;
46116f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
462bce3726dSAndreas Gohr    } elseif($id) {
4636c7843b5Sandi        $xlink .= DOKU_SCRIPT.'?id='.$id;
46416f15a81SDominik Eckelmann        if($urlParameters) $xlink .= $separator.$urlParameters;
465bce3726dSAndreas Gohr    } else {
466bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
46716f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
468f3f0262cSandi    }
469f3f0262cSandi
470f3f0262cSandi    return $xlink;
471f3f0262cSandi}
472f3f0262cSandi
473f3f0262cSandi/**
474f5c2808fSBen Coburn * This builds a link to an alternate page format
475f5c2808fSBen Coburn *
476f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
477f5c2808fSBen Coburn *
478f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
4794bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
4804bc480e5SAndreas Gohr * @param string       $format         the export renderer to use
4814bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
4824bc480e5SAndreas Gohr * @param bool         $abs            request an absolute URL instead of relative
4834bc480e5SAndreas Gohr * @param string       $sep            parameter separator
4844bc480e5SAndreas Gohr * @return string
485f5c2808fSBen Coburn */
4864bc480e5SAndreas Gohrfunction exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;') {
487f5c2808fSBen Coburn    global $conf;
4884bc480e5SAndreas Gohr    if(is_array($urlParameters)) {
4894bc480e5SAndreas Gohr        $urlParameters = buildURLparams($urlParameters, $sep);
490f5c2808fSBen Coburn    } else {
4914bc480e5SAndreas Gohr        $urlParameters = str_replace(',', $sep, $urlParameters);
492f5c2808fSBen Coburn    }
493f5c2808fSBen Coburn
494f5c2808fSBen Coburn    $format = rawurlencode($format);
495f5c2808fSBen Coburn    $id     = idfilter($id);
496f5c2808fSBen Coburn    if($abs) {
497f5c2808fSBen Coburn        $xlink = DOKU_URL;
498f5c2808fSBen Coburn    } else {
499f5c2808fSBen Coburn        $xlink = DOKU_BASE;
500f5c2808fSBen Coburn    }
501f5c2808fSBen Coburn
502f5c2808fSBen Coburn    if($conf['userewrite'] == 2) {
503f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
5044bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
505f5c2808fSBen Coburn    } elseif($conf['userewrite'] == 1) {
506f5c2808fSBen Coburn        $xlink .= '_export/'.$format.'/'.$id;
5074bc480e5SAndreas Gohr        if($urlParameters) $xlink .= '?'.$urlParameters;
508f5c2808fSBen Coburn    } else {
509f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
5104bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
511f5c2808fSBen Coburn    }
512f5c2808fSBen Coburn
513f5c2808fSBen Coburn    return $xlink;
514f5c2808fSBen Coburn}
515f5c2808fSBen Coburn
516f5c2808fSBen Coburn/**
5176de3759aSAndreas Gohr * Build a link to a media file
5186de3759aSAndreas Gohr *
5196de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
5208c08db0aSAndreas Gohr *
5218c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
5228c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
5238c08db0aSAndreas Gohr *
5243272d797SAndreas Gohr * @param string  $id     the media file id or URL
5253272d797SAndreas Gohr * @param mixed   $more   string or array with additional parameters
5263272d797SAndreas Gohr * @param bool    $direct link to detail page if false
5273272d797SAndreas Gohr * @param string  $sep    URL parameter separator
5283272d797SAndreas Gohr * @param bool    $abs    Create an absolute URL
5293272d797SAndreas Gohr * @return string
5306de3759aSAndreas Gohr */
53155b2b31bSAndreas Gohrfunction ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false) {
5326de3759aSAndreas Gohr    global $conf;
533b9ee6a44SKlap-in    $isexternalimage = media_isexternal($id);
534826d2766SKlap-in    if(!$isexternalimage) {
535826d2766SKlap-in        $id = cleanID($id);
536826d2766SKlap-in    }
537826d2766SKlap-in
5386de3759aSAndreas Gohr    if(is_array($more)) {
5390f4e0092SChristopher Smith        // add token for resized images
540443e135dSChristopher Smith        if(!empty($more['w']) || !empty($more['h']) || $isexternalimage){
5410f4e0092SChristopher Smith            $more['tok'] = media_get_token($id,$more['w'],$more['h']);
5420f4e0092SChristopher Smith        }
5438c08db0aSAndreas Gohr        // strip defaults for shorter URLs
5448c08db0aSAndreas Gohr        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
545443e135dSChristopher Smith        if(empty($more['w'])) unset($more['w']);
546443e135dSChristopher Smith        if(empty($more['h'])) unset($more['h']);
5478c08db0aSAndreas Gohr        if(isset($more['id']) && $direct) unset($more['id']);
548b174aeaeSchris        $more = buildURLparams($more, $sep);
5496de3759aSAndreas Gohr    } else {
5505e7db1e2SChristopher Smith        $matches = array();
551cc036f74SKlap-in        if (preg_match_all('/\b(w|h)=(\d*)\b/',$more,$matches,PREG_SET_ORDER) || $isexternalimage){
5525e7db1e2SChristopher Smith            $resize = array('w'=>0, 'h'=>0);
5535e7db1e2SChristopher Smith            foreach ($matches as $match){
5545e7db1e2SChristopher Smith                $resize[$match[1]] = $match[2];
5555e7db1e2SChristopher Smith            }
556cc036f74SKlap-in            $more .= $more === '' ? '' : $sep;
557cc036f74SKlap-in            $more .= 'tok='.media_get_token($id,$resize['w'],$resize['h']);
5585e7db1e2SChristopher Smith        }
5598c08db0aSAndreas Gohr        $more = str_replace('cache=cache', '', $more); //skip default
5608c08db0aSAndreas Gohr        $more = str_replace(',,', ',', $more);
561b174aeaeSchris        $more = str_replace(',', $sep, $more);
5626de3759aSAndreas Gohr    }
5636de3759aSAndreas Gohr
56455b2b31bSAndreas Gohr    if($abs) {
56555b2b31bSAndreas Gohr        $xlink = DOKU_URL;
56655b2b31bSAndreas Gohr    } else {
5676de3759aSAndreas Gohr        $xlink = DOKU_BASE;
56855b2b31bSAndreas Gohr    }
5696de3759aSAndreas Gohr
5706de3759aSAndreas Gohr    // external URLs are always direct without rewriting
571826d2766SKlap-in    if($isexternalimage) {
5726de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
573cc036f74SKlap-in        $xlink .= '?'.$more;
574b174aeaeSchris        $xlink .= $sep.'media='.rawurlencode($id);
5756de3759aSAndreas Gohr        return $xlink;
5766de3759aSAndreas Gohr    }
5776de3759aSAndreas Gohr
5786de3759aSAndreas Gohr    $id = idfilter($id);
5796de3759aSAndreas Gohr
5806de3759aSAndreas Gohr    // decide on scriptname
5816de3759aSAndreas Gohr    if($direct) {
5826de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
5836de3759aSAndreas Gohr            $script = '_media';
5846de3759aSAndreas Gohr        } else {
5856de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
5866de3759aSAndreas Gohr        }
5876de3759aSAndreas Gohr    } else {
5886de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
5896de3759aSAndreas Gohr            $script = '_detail';
5906de3759aSAndreas Gohr        } else {
5916de3759aSAndreas Gohr            $script = 'lib/exe/detail.php';
5926de3759aSAndreas Gohr        }
5936de3759aSAndreas Gohr    }
5946de3759aSAndreas Gohr
5956de3759aSAndreas Gohr    // build URL based on rewrite mode
5966de3759aSAndreas Gohr    if($conf['userewrite']) {
5976de3759aSAndreas Gohr        $xlink .= $script.'/'.$id;
5986de3759aSAndreas Gohr        if($more) $xlink .= '?'.$more;
5996de3759aSAndreas Gohr    } else {
6006de3759aSAndreas Gohr        if($more) {
601a99d3236SEsther Brunner            $xlink .= $script.'?'.$more;
602b174aeaeSchris            $xlink .= $sep.'media='.$id;
6036de3759aSAndreas Gohr        } else {
604a99d3236SEsther Brunner            $xlink .= $script.'?media='.$id;
6056de3759aSAndreas Gohr        }
6066de3759aSAndreas Gohr    }
6076de3759aSAndreas Gohr
6086de3759aSAndreas Gohr    return $xlink;
6096de3759aSAndreas Gohr}
6106de3759aSAndreas Gohr
6116de3759aSAndreas Gohr/**
61225ca5b17SAndreas Gohr * Returns the URL to the DokuWiki base script
61315fae107Sandi *
61425ca5b17SAndreas Gohr * Consider using wl() instead, unless you absoutely need the doku.php endpoint
61525ca5b17SAndreas Gohr *
61615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
617140cfbcdSGerrit Uitslag *
618140cfbcdSGerrit Uitslag * @return string
619f3f0262cSandi */
62025ca5b17SAndreas Gohrfunction script() {
621ed7b5f09Sandi    return DOKU_BASE.DOKU_SCRIPT;
622f3f0262cSandi}
623f3f0262cSandi
624f3f0262cSandi/**
62515fae107Sandi * Spamcheck against wordlist
62615fae107Sandi *
627f3f0262cSandi * Checks the wikitext against a list of blocked expressions
628f3f0262cSandi * returns true if the text contains any bad words
62915fae107Sandi *
630e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
631e403cc58SMichael Klier *
632e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
633e403cc58SMichael Klier *  and gain information about the user who was blocked.
634e403cc58SMichael Klier *
635e403cc58SMichael Klier *  Event data:
636e403cc58SMichael Klier *    data['matches']  - array of matches
637e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
638e403cc58SMichael Klier *      [ip]           - ip address
639e403cc58SMichael Klier *      [user]         - username (if logged in)
640e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
641e403cc58SMichael Klier *      [name]         - real name (if logged in)
642e403cc58SMichael Klier *
64315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
6446dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
645140cfbcdSGerrit Uitslag *
6466dffa0e0SAndreas Gohr * @param  string $text - optional text to check, if not given the globals are used
6476dffa0e0SAndreas Gohr * @return bool         - true if a spam word was found
648f3f0262cSandi */
6496dffa0e0SAndreas Gohrfunction checkwordblock($text = '') {
650f3f0262cSandi    global $TEXT;
6516dffa0e0SAndreas Gohr    global $PRE;
6526dffa0e0SAndreas Gohr    global $SUF;
653e0086ca2SAndreas Gohr    global $SUM;
654f3f0262cSandi    global $conf;
655e403cc58SMichael Klier    global $INFO;
656585bf44eSChristopher Smith    /* @var Input $INPUT */
657585bf44eSChristopher Smith    global $INPUT;
658f3f0262cSandi
659f3f0262cSandi    if(!$conf['usewordblock']) return false;
660f3f0262cSandi
661e0086ca2SAndreas Gohr    if(!$text) $text = "$PRE $TEXT $SUF $SUM";
6626dffa0e0SAndreas Gohr
663041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
6646dffa0e0SAndreas Gohr    $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i', '\1http://\2 \2\3', $text);
665041d1964SAndreas Gohr
666b9ac8716Schris    $wordblocks = getWordblocks();
6673e2965d7Sandi    // how many lines to read at once (to work around some PCRE limits)
6683e2965d7Sandi    if(version_compare(phpversion(), '4.3.0', '<')) {
6693e2965d7Sandi        // old versions of PCRE define a maximum of parenthesises even if no
6703e2965d7Sandi        // backreferences are used - the maximum is 99
6713e2965d7Sandi        // this is very bad performancewise and may even be too high still
6723e2965d7Sandi        $chunksize = 40;
6733e2965d7Sandi    } else {
674a51d08efSAndreas Gohr        // read file in chunks of 200 - this should work around the
6753e2965d7Sandi        // MAX_PATTERN_SIZE in modern PCRE
676a51d08efSAndreas Gohr        $chunksize = 200;
6773e2965d7Sandi    }
678b9ac8716Schris    while($blocks = array_splice($wordblocks, 0, $chunksize)) {
679f3f0262cSandi        $re = array();
68049eb6e38SAndreas Gohr        // build regexp from blocks
681f3f0262cSandi        foreach($blocks as $block) {
682f3f0262cSandi            $block = preg_replace('/#.*$/', '', $block);
683f3f0262cSandi            $block = trim($block);
684f3f0262cSandi            if(empty($block)) continue;
685f3f0262cSandi            $re[] = $block;
686f3f0262cSandi        }
687e403cc58SMichael Klier        if(count($re) && preg_match('#('.join('|', $re).')#si', $text, $matches)) {
688e403cc58SMichael Klier            // prepare event data
689*59bc3b48SGerrit Uitslag            $data = array();
690e403cc58SMichael Klier            $data['matches']        = $matches;
691585bf44eSChristopher Smith            $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
692585bf44eSChristopher Smith            if($INPUT->server->str('REMOTE_USER')) {
693585bf44eSChristopher Smith                $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
694e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
695e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
696e403cc58SMichael Klier            }
697e403cc58SMichael Klier            $callback = create_function('', 'return true;');
698e403cc58SMichael Klier            return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
699b9ac8716Schris        }
700703f6fdeSandi    }
701f3f0262cSandi    return false;
702f3f0262cSandi}
703f3f0262cSandi
704f3f0262cSandi/**
70515fae107Sandi * Return the IP of the client
70615fae107Sandi *
7076d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
70815fae107Sandi *
7096d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
7106d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
7116d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
7126d8affe6SAndreas Gohr * headers
7136d8affe6SAndreas Gohr *
71415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
715140cfbcdSGerrit Uitslag *
7163272d797SAndreas Gohr * @param  boolean $single If set only a single IP is returned
7173272d797SAndreas Gohr * @return string
718f3f0262cSandi */
7196d8affe6SAndreas Gohrfunction clientIP($single = false) {
720585bf44eSChristopher Smith    /* @var Input $INPUT */
721585bf44eSChristopher Smith    global $INPUT;
722585bf44eSChristopher Smith
7236d8affe6SAndreas Gohr    $ip   = array();
724585bf44eSChristopher Smith    $ip[] = $INPUT->server->str('REMOTE_ADDR');
725585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_FORWARDED_FOR')) {
726585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_FORWARDED_FOR'))));
727585bf44eSChristopher Smith    }
728585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_REAL_IP')) {
729585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_REAL_IP'))));
730585bf44eSChristopher Smith    }
7316d8affe6SAndreas Gohr
732dc14c6d1SGuy Brand    // some IPv4/v6 regexps borrowed from Feyd
733dc14c6d1SGuy Brand    // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
734dc14c6d1SGuy Brand    $dec_octet   = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
735dc14c6d1SGuy Brand    $hex_digit   = '[A-Fa-f0-9]';
736dc14c6d1SGuy Brand    $h16         = "{$hex_digit}{1,4}";
737dc14c6d1SGuy Brand    $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
738dc14c6d1SGuy Brand    $ls32        = "(?:$h16:$h16|$IPv4Address)";
739dc14c6d1SGuy Brand    $IPv6Address =
740dc14c6d1SGuy Brand        "(?:(?:{$IPv4Address})|(?:".
741dc14c6d1SGuy Brand            "(?:$h16:){6}$ls32".
742dc14c6d1SGuy Brand            "|::(?:$h16:){5}$ls32".
743dc14c6d1SGuy Brand            "|(?:$h16)?::(?:$h16:){4}$ls32".
744dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32".
745dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32".
746dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32".
747dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,4}$h16)?::$ls32".
748dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,5}$h16)?::$h16".
749dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,6}$h16)?::".
750dc14c6d1SGuy Brand            ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
751dc14c6d1SGuy Brand
7526d8affe6SAndreas Gohr    // remove any non-IP stuff
7536d8affe6SAndreas Gohr    $cnt   = count($ip);
7544ff28443Schris    $match = array();
7556d8affe6SAndreas Gohr    for($i = 0; $i < $cnt; $i++) {
756dc14c6d1SGuy Brand        if(preg_match("/^$IPv4Address$/", $ip[$i], $match) || preg_match("/^$IPv6Address$/", $ip[$i], $match)) {
7574ff28443Schris            $ip[$i] = $match[0];
7584ff28443Schris        } else {
7594ff28443Schris            $ip[$i] = '';
7604ff28443Schris        }
7616d8affe6SAndreas Gohr        if(empty($ip[$i])) unset($ip[$i]);
762f3f0262cSandi    }
7636d8affe6SAndreas Gohr    $ip = array_values(array_unique($ip));
7646d8affe6SAndreas Gohr    if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
7656d8affe6SAndreas Gohr
7666d8affe6SAndreas Gohr    if(!$single) return join(',', $ip);
7676d8affe6SAndreas Gohr
7686d8affe6SAndreas Gohr    // decide which IP to use, trying to avoid local addresses
7696d8affe6SAndreas Gohr    $ip = array_reverse($ip);
7706d8affe6SAndreas Gohr    foreach($ip as $i) {
7712343a762SAndreas Gohr        if(preg_match('/^(::1|[fF][eE]80:|127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/', $i)) {
7726d8affe6SAndreas Gohr            continue;
7736d8affe6SAndreas Gohr        } else {
7746d8affe6SAndreas Gohr            return $i;
7756d8affe6SAndreas Gohr        }
7766d8affe6SAndreas Gohr    }
7776d8affe6SAndreas Gohr    // still here? just use the first (last) address
7786d8affe6SAndreas Gohr    return $ip[0];
779f3f0262cSandi}
780f3f0262cSandi
781f3f0262cSandi/**
7821c548ebeSAndreas Gohr * Check if the browser is on a mobile device
7831c548ebeSAndreas Gohr *
7841c548ebeSAndreas Gohr * Adapted from the example code at url below
7851c548ebeSAndreas Gohr *
7861c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
787140cfbcdSGerrit Uitslag *
788140cfbcdSGerrit Uitslag * @return bool if true, client is mobile browser; otherwise false
7891c548ebeSAndreas Gohr */
7901c548ebeSAndreas Gohrfunction clientismobile() {
791585bf44eSChristopher Smith    /* @var Input $INPUT */
792585bf44eSChristopher Smith    global $INPUT;
7931c548ebeSAndreas Gohr
794585bf44eSChristopher Smith    if($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
7951c548ebeSAndreas Gohr
796585bf44eSChristopher Smith    if(preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
7971c548ebeSAndreas Gohr
798585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_USER_AGENT')) return false;
7991c548ebeSAndreas Gohr
8001c548ebeSAndreas 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';
8011c548ebeSAndreas Gohr
802585bf44eSChristopher Smith    if(preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
8031c548ebeSAndreas Gohr
8041c548ebeSAndreas Gohr    return false;
8051c548ebeSAndreas Gohr}
8061c548ebeSAndreas Gohr
8071c548ebeSAndreas Gohr/**
80863211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
80963211f61SGlen Harris *
81022ef1e32SAndreas Gohr * If $conf['dnslookups'] is disabled it simply returns the input string
81122ef1e32SAndreas Gohr *
81263211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
813140cfbcdSGerrit Uitslag *
8143272d797SAndreas Gohr * @param  string $ips comma separated list of IP addresses
8153272d797SAndreas Gohr * @return string a comma separated list of hostnames
81663211f61SGlen Harris */
81763211f61SGlen Harrisfunction gethostsbyaddrs($ips) {
81822ef1e32SAndreas Gohr    global $conf;
81922ef1e32SAndreas Gohr    if(!$conf['dnslookups']) return $ips;
82022ef1e32SAndreas Gohr
82163211f61SGlen Harris    $hosts = array();
82263211f61SGlen Harris    $ips   = explode(',', $ips);
823551a720fSMichael Klier
824551a720fSMichael Klier    if(is_array($ips)) {
8253886270dSAndreas Gohr        foreach($ips as $ip) {
826551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
82763211f61SGlen Harris        }
828551a720fSMichael Klier        return join(',', $hosts);
829551a720fSMichael Klier    } else {
830551a720fSMichael Klier        return gethostbyaddr(trim($ips));
831551a720fSMichael Klier    }
83263211f61SGlen Harris}
83363211f61SGlen Harris
83463211f61SGlen Harris/**
83515fae107Sandi * Checks if a given page is currently locked.
83615fae107Sandi *
837f3f0262cSandi * removes stale lockfiles
83815fae107Sandi *
83915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
840140cfbcdSGerrit Uitslag *
841140cfbcdSGerrit Uitslag * @param string $id page id
842140cfbcdSGerrit Uitslag * @return bool page is locked?
843f3f0262cSandi */
844f3f0262cSandifunction checklock($id) {
845f3f0262cSandi    global $conf;
846585bf44eSChristopher Smith    /* @var Input $INPUT */
847585bf44eSChristopher Smith    global $INPUT;
848585bf44eSChristopher Smith
849c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
850f3f0262cSandi
851f3f0262cSandi    //no lockfile
852f3f0262cSandi    if(!@file_exists($lock)) return false;
853f3f0262cSandi
854f3f0262cSandi    //lockfile expired
855f3f0262cSandi    if((time() - filemtime($lock)) > $conf['locktime']) {
856d8186216SBen Coburn        @unlink($lock);
857f3f0262cSandi        return false;
858f3f0262cSandi    }
859f3f0262cSandi
860f3f0262cSandi    //my own lock
8616d2af55dSChristopher Smith    @list($ip, $session) = explode("\n", io_readFile($lock));
8620712fefaSAndreas Gohr    if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || (session_id() && $session == session_id())) {
863f3f0262cSandi        return false;
864f3f0262cSandi    }
865f3f0262cSandi
866f3f0262cSandi    return $ip;
867f3f0262cSandi}
868f3f0262cSandi
869f3f0262cSandi/**
87015fae107Sandi * Lock a page for editing
87115fae107Sandi *
87215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
873140cfbcdSGerrit Uitslag *
874140cfbcdSGerrit Uitslag * @param string $id page id to lock
875f3f0262cSandi */
876f3f0262cSandifunction lock($id) {
877544ed901SDaniel Calviño Sánchez    global $conf;
878585bf44eSChristopher Smith    /* @var Input $INPUT */
879585bf44eSChristopher Smith    global $INPUT;
880544ed901SDaniel Calviño Sánchez
881544ed901SDaniel Calviño Sánchez    if($conf['locktime'] == 0) {
882544ed901SDaniel Calviño Sánchez        return;
883544ed901SDaniel Calviño Sánchez    }
884544ed901SDaniel Calviño Sánchez
885c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
886585bf44eSChristopher Smith    if($INPUT->server->str('REMOTE_USER')) {
887585bf44eSChristopher Smith        io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
888f3f0262cSandi    } else {
88985fef7e2SAndreas Gohr        io_saveFile($lock, clientIP()."\n".session_id());
890f3f0262cSandi    }
891f3f0262cSandi}
892f3f0262cSandi
893f3f0262cSandi/**
89415fae107Sandi * Unlock a page if it was locked by the user
895f3f0262cSandi *
89615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
897140cfbcdSGerrit Uitslag *
8983272d797SAndreas Gohr * @param string $id page id to unlock
89915fae107Sandi * @return bool true if a lock was removed
900f3f0262cSandi */
901f3f0262cSandifunction unlock($id) {
902585bf44eSChristopher Smith    /* @var Input $INPUT */
903585bf44eSChristopher Smith    global $INPUT;
904585bf44eSChristopher Smith
905c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
906f3f0262cSandi    if(@file_exists($lock)) {
9076d2af55dSChristopher Smith        @list($ip, $session) = explode("\n", io_readFile($lock));
908585bf44eSChristopher Smith        if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || $session == session_id()) {
909f3f0262cSandi            @unlink($lock);
910f3f0262cSandi            return true;
911f3f0262cSandi        }
912f3f0262cSandi    }
913f3f0262cSandi    return false;
914f3f0262cSandi}
915f3f0262cSandi
916f3f0262cSandi/**
917f3f0262cSandi * convert line ending to unix format
918f3f0262cSandi *
9196db7468bSAndreas Gohr * also makes sure the given text is valid UTF-8
9206db7468bSAndreas Gohr *
92115fae107Sandi * @see    formText() for 2crlf conversion
92215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
923140cfbcdSGerrit Uitslag *
924140cfbcdSGerrit Uitslag * @param string $text
925140cfbcdSGerrit Uitslag * @return string
926f3f0262cSandi */
927f3f0262cSandifunction cleanText($text) {
928f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
9296db7468bSAndreas Gohr
9306db7468bSAndreas Gohr    // if the text is not valid UTF-8 we simply assume latin1
9316db7468bSAndreas Gohr    // this won't break any worse than it breaks with the wrong encoding
9326db7468bSAndreas Gohr    // but might actually fix the problem in many cases
9336db7468bSAndreas Gohr    if(!utf8_check($text)) $text = utf8_encode($text);
9346db7468bSAndreas Gohr
935f3f0262cSandi    return $text;
936f3f0262cSandi}
937f3f0262cSandi
938f3f0262cSandi/**
939f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
940f3f0262cSandi * It also converts line endings to Windows format which is
941f3f0262cSandi * pseudo standard for webforms.
942f3f0262cSandi *
94315fae107Sandi * @see    cleanText() for 2unix conversion
94415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
945140cfbcdSGerrit Uitslag *
946140cfbcdSGerrit Uitslag * @param string $text
947140cfbcdSGerrit Uitslag * @return string
948f3f0262cSandi */
949f3f0262cSandifunction formText($text) {
9505b7d45a5SAndreas Gohr    $text = str_replace("\012", "\015\012", $text);
951f3f0262cSandi    return htmlspecialchars($text);
952f3f0262cSandi}
953f3f0262cSandi
954f3f0262cSandi/**
95515fae107Sandi * Returns the specified local text in raw format
95615fae107Sandi *
95715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
958140cfbcdSGerrit Uitslag *
959140cfbcdSGerrit Uitslag * @param string $id   page id
960140cfbcdSGerrit Uitslag * @param string $ext  extension of file being read, default 'txt'
961140cfbcdSGerrit Uitslag * @return string
962f3f0262cSandi */
9632adaf2b8SAndreas Gohrfunction rawLocale($id, $ext = 'txt') {
9642adaf2b8SAndreas Gohr    return io_readFile(localeFN($id, $ext));
965f3f0262cSandi}
966f3f0262cSandi
967f3f0262cSandi/**
968f3f0262cSandi * Returns the raw WikiText
96915fae107Sandi *
97015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
971140cfbcdSGerrit Uitslag *
972140cfbcdSGerrit Uitslag * @param string $id   page id
973e0c26282SGerrit Uitslag * @param string|int $rev  timestamp when a revision of wikitext is desired
974140cfbcdSGerrit Uitslag * @return string
975f3f0262cSandi */
976f3f0262cSandifunction rawWiki($id, $rev = '') {
977cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
978f3f0262cSandi}
979f3f0262cSandi
980f3f0262cSandi/**
9817146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
9827146cee2SAndreas Gohr *
9837b84afa2SAndreas Gohr * @triggers COMMON_PAGETPL_LOAD
9847146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
985140cfbcdSGerrit Uitslag *
986140cfbcdSGerrit Uitslag * @param string $id the id of the page to be created
987140cfbcdSGerrit Uitslag * @return string parsed pagetemplate content
9887146cee2SAndreas Gohr */
989fe17917eSAdrian Langfunction pageTemplate($id) {
990a15ce62dSEsther Brunner    global $conf;
991e29549feSAndreas Gohr
992fe17917eSAdrian Lang    if(is_array($id)) $id = $id[0];
993e29549feSAndreas Gohr
9947b84afa2SAndreas Gohr    // prepare initial event data
9957b84afa2SAndreas Gohr    $data = array(
9967b84afa2SAndreas Gohr        'id'        => $id, // the id of the page to be created
9977b84afa2SAndreas Gohr        'tpl'       => '', // the text used as template
9987b84afa2SAndreas Gohr        'tplfile'   => '', // the file above text was/should be loaded from
9997b84afa2SAndreas Gohr        'doreplace' => true // should wildcard replacements be done on the text?
10007b84afa2SAndreas Gohr    );
10017b84afa2SAndreas Gohr
10027b84afa2SAndreas Gohr    $evt = new Doku_Event('COMMON_PAGETPL_LOAD', $data);
10037b84afa2SAndreas Gohr    if($evt->advise_before(true)) {
10047b84afa2SAndreas Gohr        // the before event might have loaded the content already
10057b84afa2SAndreas Gohr        if(empty($data['tpl'])) {
10067b84afa2SAndreas Gohr            // if the before event did not set a template file, try to find one
10077b84afa2SAndreas Gohr            if(empty($data['tplfile'])) {
1008fe17917eSAdrian Lang                $path = dirname(wikiFN($id));
1009e29549feSAndreas Gohr                if(@file_exists($path.'/_template.txt')) {
10107b84afa2SAndreas Gohr                    $data['tplfile'] = $path.'/_template.txt';
1011e29549feSAndreas Gohr                } else {
1012e29549feSAndreas Gohr                    // search upper namespaces for templates
1013e29549feSAndreas Gohr                    $len = strlen(rtrim($conf['datadir'], '/'));
1014e29549feSAndreas Gohr                    while(strlen($path) >= $len) {
1015e29549feSAndreas Gohr                        if(@file_exists($path.'/__template.txt')) {
10167b84afa2SAndreas Gohr                            $data['tplfile'] = $path.'/__template.txt';
1017e29549feSAndreas Gohr                            break;
1018e29549feSAndreas Gohr                        }
1019e29549feSAndreas Gohr                        $path = substr($path, 0, strrpos($path, '/'));
1020e29549feSAndreas Gohr                    }
1021e29549feSAndreas Gohr                }
10227b84afa2SAndreas Gohr            }
10237b84afa2SAndreas Gohr            // load the content
10243d7ac595SMichael Hamann            $data['tpl'] = io_readFile($data['tplfile']);
10257b84afa2SAndreas Gohr        }
1026a1bbd05bSMichael Hamann        if($data['doreplace']) parsePageTemplate($data);
10277b84afa2SAndreas Gohr    }
10287b84afa2SAndreas Gohr    $evt->advise_after();
10297b84afa2SAndreas Gohr    unset($evt);
10307b84afa2SAndreas Gohr
1031fe17917eSAdrian Lang    return $data['tpl'];
10322b1223ecSAdrian Lang}
10332b1223ecSAdrian Lang
10342b1223ecSAdrian Lang/**
10352b1223ecSAdrian Lang * Performs common page template replacements
10367b84afa2SAndreas Gohr * This works on data from COMMON_PAGETPL_LOAD
10372b1223ecSAdrian Lang *
10382b1223ecSAdrian Lang * @author Andreas Gohr <andi@splitbrain.org>
1039140cfbcdSGerrit Uitslag *
1040140cfbcdSGerrit Uitslag * @param array $data array with event data
1041140cfbcdSGerrit Uitslag * @return string
10422b1223ecSAdrian Lang */
1043d535a2e9Sstretchyboyfunction parsePageTemplate(&$data) {
10443272d797SAndreas Gohr    /**
10453272d797SAndreas Gohr     * @var string $id        the id of the page to be created
10463272d797SAndreas Gohr     * @var string $tpl       the text used as template
10473272d797SAndreas Gohr     * @var string $tplfile   the file above text was/should be loaded from
10483272d797SAndreas Gohr     * @var bool   $doreplace should wildcard replacements be done on the text?
10493272d797SAndreas Gohr     */
1050fe17917eSAdrian Lang    extract($data);
1051fe17917eSAdrian Lang
1052b856f7dfSAdrian Lang    global $USERINFO;
1053bce53b1fSAdrian Lang    global $conf;
1054585bf44eSChristopher Smith    /* @var Input $INPUT */
1055585bf44eSChristopher Smith    global $INPUT;
1056e29549feSAndreas Gohr
1057e29549feSAndreas Gohr    // replace placeholders
105826ece5a7SAndreas Gohr    $file = noNS($id);
105937c1acbdSAdrian Lang    $page = strtr($file, $conf['sepchar'], ' ');
106026ece5a7SAndreas Gohr
10613272d797SAndreas Gohr    $tpl = str_replace(
10623272d797SAndreas Gohr        array(
106326ece5a7SAndreas Gohr             '@ID@',
106426ece5a7SAndreas Gohr             '@NS@',
106526ece5a7SAndreas Gohr             '@FILE@',
106626ece5a7SAndreas Gohr             '@!FILE@',
106726ece5a7SAndreas Gohr             '@!FILE!@',
106826ece5a7SAndreas Gohr             '@PAGE@',
106926ece5a7SAndreas Gohr             '@!PAGE@',
107026ece5a7SAndreas Gohr             '@!!PAGE@',
107126ece5a7SAndreas Gohr             '@!PAGE!@',
107226ece5a7SAndreas Gohr             '@USER@',
107326ece5a7SAndreas Gohr             '@NAME@',
107426ece5a7SAndreas Gohr             '@MAIL@',
107526ece5a7SAndreas Gohr             '@DATE@',
107626ece5a7SAndreas Gohr        ),
107726ece5a7SAndreas Gohr        array(
107826ece5a7SAndreas Gohr             $id,
107926ece5a7SAndreas Gohr             getNS($id),
108026ece5a7SAndreas Gohr             $file,
108126ece5a7SAndreas Gohr             utf8_ucfirst($file),
108226ece5a7SAndreas Gohr             utf8_strtoupper($file),
108326ece5a7SAndreas Gohr             $page,
108426ece5a7SAndreas Gohr             utf8_ucfirst($page),
108526ece5a7SAndreas Gohr             utf8_ucwords($page),
108626ece5a7SAndreas Gohr             utf8_strtoupper($page),
1087585bf44eSChristopher Smith             $INPUT->server->str('REMOTE_USER'),
1088b856f7dfSAdrian Lang             $USERINFO['name'],
1089b856f7dfSAdrian Lang             $USERINFO['mail'],
109026ece5a7SAndreas Gohr             $conf['dformat'],
10913272d797SAndreas Gohr        ), $tpl
10923272d797SAndreas Gohr    );
109326ece5a7SAndreas Gohr
10947d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
10957d644fc8SAndreas Gohr    $tpl         = preg_replace_callback('/%./', create_function('$m', 'return strftime($m[0]);'), $tpl);
1096d535a2e9Sstretchyboy    $data['tpl'] = $tpl;
1097a15ce62dSEsther Brunner    return $tpl;
10987146cee2SAndreas Gohr}
10997146cee2SAndreas Gohr
11007146cee2SAndreas Gohr/**
110115fae107Sandi * Returns the raw Wiki Text in three slices.
110215fae107Sandi *
110315fae107Sandi * The range parameter needs to have the form "from-to"
110415cfe303Sandi * and gives the range of the section in bytes - no
110515cfe303Sandi * UTF-8 awareness is needed.
1106f3f0262cSandi * The returned order is prefix, section and suffix.
110715fae107Sandi *
110815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1109140cfbcdSGerrit Uitslag *
1110140cfbcdSGerrit Uitslag * @param string $range in form "from-to"
1111140cfbcdSGerrit Uitslag * @param string $id    page id
1112140cfbcdSGerrit Uitslag * @param string $rev   optional, the revision timestamp
1113140cfbcdSGerrit Uitslag * @return array with three slices
1114f3f0262cSandi */
1115f3f0262cSandifunction rawWikiSlices($range, $id, $rev = '') {
1116cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1117f3f0262cSandi
111880fcb268SAdrian Lang    // Parse range
111980fcb268SAdrian Lang    list($from, $to) = explode('-', $range, 2);
112080fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
112180fcb268SAdrian Lang    $from = !$from ? 0 : ($from - 1);
112280fcb268SAdrian Lang    $to   = !$to ? strlen($text) : ($to - 1);
112380fcb268SAdrian Lang
1124*59bc3b48SGerrit Uitslag    $slices = array();
112580fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
112680fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to - $from);
112715cfe303Sandi    $slices[2] = substr($text, $to);
1128f3f0262cSandi    return $slices;
1129f3f0262cSandi}
1130f3f0262cSandi
1131f3f0262cSandi/**
113215fae107Sandi * Joins wiki text slices
113315fae107Sandi *
113480fcb268SAdrian Lang * function to join the text slices.
1135f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
1136f3f0262cSandi * lines between sections if needed (used on saving).
113715fae107Sandi *
113815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1139140cfbcdSGerrit Uitslag *
1140140cfbcdSGerrit Uitslag * @param string $pre   prefix
1141140cfbcdSGerrit Uitslag * @param string $text  text in the middle
1142140cfbcdSGerrit Uitslag * @param string $suf   suffix
1143140cfbcdSGerrit Uitslag * @param bool $pretty add additional empty lines between sections
1144140cfbcdSGerrit Uitslag * @return string
1145f3f0262cSandi */
1146f3f0262cSandifunction con($pre, $text, $suf, $pretty = false) {
1147f3f0262cSandi    if($pretty) {
114880fcb268SAdrian Lang        if($pre !== '' && substr($pre, -1) !== "\n" &&
11493272d797SAndreas Gohr            substr($text, 0, 1) !== "\n"
11503272d797SAndreas Gohr        ) {
115180fcb268SAdrian Lang            $pre .= "\n";
115280fcb268SAdrian Lang        }
115380fcb268SAdrian Lang        if($suf !== '' && substr($text, -1) !== "\n" &&
11543272d797SAndreas Gohr            substr($suf, 0, 1) !== "\n"
11553272d797SAndreas Gohr        ) {
115680fcb268SAdrian Lang            $text .= "\n";
115780fcb268SAdrian Lang        }
1158f3f0262cSandi    }
1159f3f0262cSandi
1160f3f0262cSandi    return $pre.$text.$suf;
1161f3f0262cSandi}
1162f3f0262cSandi
1163f3f0262cSandi/**
1164a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
1165a701424fSBen Coburn * Also directs changelog and attic updates.
116615fae107Sandi *
116715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
116871726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
1169140cfbcdSGerrit Uitslag *
1170140cfbcdSGerrit Uitslag * @param string $id       page id
1171140cfbcdSGerrit Uitslag * @param string $text     wikitext being saved
1172140cfbcdSGerrit Uitslag * @param string $summary  summary of text update
1173140cfbcdSGerrit Uitslag * @param bool   $minor    mark this saved version as minor update
1174f3f0262cSandi */
1175b6912aeaSAndreas Gohrfunction saveWikiText($id, $text, $summary, $minor = false) {
1176a701424fSBen Coburn    /* Note to developers:
1177a701424fSBen Coburn       This code is subtle and delicate. Test the behavior of
1178a701424fSBen Coburn       the attic and changelog with dokuwiki and external edits
1179a701424fSBen Coburn       after any changes. External edits change the wiki page
1180a701424fSBen Coburn       directly without using php or dokuwiki.
1181a701424fSBen Coburn     */
1182f3f0262cSandi    global $conf;
1183f3f0262cSandi    global $lang;
118471726d78SBen Coburn    global $REV;
1185585bf44eSChristopher Smith    /* @var Input $INPUT */
1186585bf44eSChristopher Smith    global $INPUT;
1187585bf44eSChristopher Smith
1188f3f0262cSandi    // ignore if no changes were made
1189f3f0262cSandi    if($text == rawWiki($id, '')) {
1190f3f0262cSandi        return;
1191f3f0262cSandi    }
1192f3f0262cSandi
1193f3f0262cSandi    $file        = wikiFN($id);
1194a701424fSBen Coburn    $old         = @filemtime($file); // from page
1195407e65b9SAndreas Gohr    $wasRemoved  = (trim($text) == ''); // check for empty or whitespace only
1196d8186216SBen Coburn    $wasCreated  = !@file_exists($file);
119771726d78SBen Coburn    $wasReverted = ($REV == true);
1198047bad06SGerrit Uitslag    $pagelog     = new PageChangeLog($id, 1024);
1199e45b34cdSBen Coburn    $newRev      = false;
1200f523c971SGerrit Uitslag    $oldRev      = $pagelog->getRevisions(-1, 1); // from changelog
1201a701424fSBen Coburn    $oldRev      = (int) (empty($oldRev) ? 0 : $oldRev[0]);
1202a701424fSBen Coburn    if(!@file_exists(wikiFN($id, $old)) && @file_exists($file) && $old >= $oldRev) {
120346844156SBen Coburn        // add old revision to the attic if missing
120446844156SBen Coburn        saveOldRevision($id);
120546844156SBen Coburn        // add a changelog entry if this edit came from outside dokuwiki
1206a701424fSBen Coburn        if($old > $oldRev) {
1207ebf1501fSBen Coburn            addLogEntry($old, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=> true));
120846844156SBen Coburn            // remove soon to be stale instructions
120946844156SBen Coburn            $cache = new cache_instructions($id, $file);
121046844156SBen Coburn            $cache->removeCache();
121146844156SBen Coburn        }
121246844156SBen Coburn    }
1213f3f0262cSandi
121471726d78SBen Coburn    if($wasRemoved) {
121530725328SGabriel Birke        // Send "update" event with empty data, so plugins can react to page deletion
121630725328SGabriel Birke        $data = array(array($file, '', false), getNS($id), noNS($id), false);
121730725328SGabriel Birke        trigger_event('IO_WIKIPAGE_WRITE', $data);
1218e45b34cdSBen Coburn        // pre-save deleted revision
1219e45b34cdSBen Coburn        @touch($file);
122046844156SBen Coburn        clearstatcache();
1221e45b34cdSBen Coburn        $newRev = saveOldRevision($id);
1222e1f3d9e1SEsther Brunner        // remove empty file
1223f3f0262cSandi        @unlink($file);
1224c5f92742SMichael Hamann        // don't remove old meta info as it should be saved, plugins can use IO_WIKIPAGE_WRITE for removing their metadata...
1225c5f92742SMichael Hamann        // purge non-persistant meta data
12263d1f9ec3SMichael Klier        p_purge_metadata($id);
1227f3f0262cSandi        $del = true;
12283ce054b3Sandi        // autoset summary on deletion
12293ce054b3Sandi        if(empty($summary)) $summary = $lang['deleted'];
123053d6ccfeSandi        // remove empty namespaces
1231cc7d0c94SBen Coburn        io_sweepNS($id, 'datadir');
1232cc7d0c94SBen Coburn        io_sweepNS($id, 'mediadir');
1233f3f0262cSandi    } else {
1234cc7d0c94SBen Coburn        // save file (namespace dir is created in io_writeWikiPage)
1235cc7d0c94SBen Coburn        io_writeWikiPage($file, $text, $id);
123646844156SBen Coburn        // pre-save the revision, to keep the attic in sync
123746844156SBen Coburn        $newRev = saveOldRevision($id);
1238f3f0262cSandi        $del    = false;
1239f3f0262cSandi    }
1240f3f0262cSandi
124171726d78SBen Coburn    // select changelog line type
124271726d78SBen Coburn    $extra = '';
1243ebf1501fSBen Coburn    $type  = DOKU_CHANGE_TYPE_EDIT;
124471726d78SBen Coburn    if($wasReverted) {
1245ebf1501fSBen Coburn        $type  = DOKU_CHANGE_TYPE_REVERT;
124671726d78SBen Coburn        $extra = $REV;
12473272d797SAndreas Gohr    } else if($wasCreated) {
12483272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_CREATE;
12493272d797SAndreas Gohr    } else if($wasRemoved) {
12503272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_DELETE;
1251585bf44eSChristopher Smith    } else if($minor && $conf['useacl'] && $INPUT->server->str('REMOTE_USER')) {
12523272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_MINOR_EDIT;
12533272d797SAndreas Gohr    } //minor edits only for logged in users
125471726d78SBen Coburn
1255e45b34cdSBen Coburn    addLogEntry($newRev, $id, $type, $summary, $extra);
125626a0801fSAndreas Gohr    // send notify mails
125790033e9dSAndreas Gohr    notify($id, 'admin', $old, $summary, $minor);
125890033e9dSAndreas Gohr    notify($id, 'subscribers', $old, $summary, $minor);
1259f3f0262cSandi
1260ce6b63d9Schris    // update the purgefile (timestamp of the last time anything within the wiki was changed)
126198407a7aSandi    io_saveFile($conf['cachedir'].'/purgefile', time());
12622eccbdaaSGina Haeussge
12632eccbdaaSGina Haeussge    // if useheading is enabled, purge the cache of all linking pages
1264fe9ec250SChris Smith    if(useHeading('content')) {
126507ff0babSMichael Hamann        $pages = ft_backlinks($id, true);
12662eccbdaaSGina Haeussge        foreach($pages as $page) {
12672eccbdaaSGina Haeussge            $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
12682eccbdaaSGina Haeussge            $cache->removeCache();
12692eccbdaaSGina Haeussge        }
12702eccbdaaSGina Haeussge    }
1271f3f0262cSandi}
1272f3f0262cSandi
1273f3f0262cSandi/**
1274f3f0262cSandi * moves the current version to the attic and returns its
1275f3f0262cSandi * revision date
127615fae107Sandi *
127715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1278140cfbcdSGerrit Uitslag *
1279140cfbcdSGerrit Uitslag * @param string $id page id
1280140cfbcdSGerrit Uitslag * @return int|string revision timestamp
1281f3f0262cSandi */
1282f3f0262cSandifunction saveOldRevision($id) {
1283f3f0262cSandi    $oldf = wikiFN($id);
1284f3f0262cSandi    if(!@file_exists($oldf)) return '';
1285f3f0262cSandi    $date = filemtime($oldf);
1286f3f0262cSandi    $newf = wikiFN($id, $date);
1287cc7d0c94SBen Coburn    io_writeWikiPage($newf, rawWiki($id), $id, $date);
1288f3f0262cSandi    return $date;
1289f3f0262cSandi}
1290f3f0262cSandi
1291f3f0262cSandi/**
1292fde10de4SAdrian Lang * Sends a notify mail on page change or registration
129326a0801fSAndreas Gohr *
129426a0801fSAndreas Gohr * @param string     $id       The changed page
1295fde10de4SAdrian Lang * @param string     $who      Who to notify (admin|subscribers|register)
12963272d797SAndreas Gohr * @param int|string $rev Old page revision
129726a0801fSAndreas Gohr * @param string     $summary  What changed
129890033e9dSAndreas Gohr * @param boolean    $minor    Is this a minor edit?
129902a498e7Schris * @param array      $replace  Additional string substitutions, @KEY@ to be replaced by value
13003272d797SAndreas Gohr * @return bool
1301140cfbcdSGerrit Uitslag *
130215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1303f3f0262cSandi */
130402a498e7Schrisfunction notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array()) {
1305f3f0262cSandi    global $conf;
1306585bf44eSChristopher Smith    /* @var Input $INPUT */
1307585bf44eSChristopher Smith    global $INPUT;
1308b158d625SSteven Danz
13096df843eeSAndreas Gohr    // decide if there is something to do, eg. whom to mail
131026a0801fSAndreas Gohr    if($who == 'admin') {
13113272d797SAndreas Gohr        if(empty($conf['notify'])) return false; //notify enabled?
13122ed38036SAndreas Gohr        $tpl = 'mailtext';
131326a0801fSAndreas Gohr        $to  = $conf['notify'];
131426a0801fSAndreas Gohr    } elseif($who == 'subscribers') {
131584c1127cSAndreas Gohr        if(!actionOK('subscribe')) return false; //subscribers enabled?
1316585bf44eSChristopher Smith        if($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
13170bb37868SGerrit Uitslag        $data = array('id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace);
13183272d797SAndreas Gohr        trigger_event(
13193272d797SAndreas Gohr            'COMMON_NOTIFY_ADDRESSLIST', $data,
1320835242b0SAndreas Gohr            array(new Subscription(), 'notifyaddresses')
13213272d797SAndreas Gohr        );
13222ed38036SAndreas Gohr        $to = $data['addresslist'];
13232ed38036SAndreas Gohr        if(empty($to)) return false;
13242ed38036SAndreas Gohr        $tpl = 'subscr_single';
132526a0801fSAndreas Gohr    } else {
13263272d797SAndreas Gohr        return false; //just to be safe
132726a0801fSAndreas Gohr    }
132826a0801fSAndreas Gohr
13296df843eeSAndreas Gohr    // prepare content
13302ed38036SAndreas Gohr    $subscription = new Subscription();
13312ed38036SAndreas Gohr    return $subscription->send_diff($to, $tpl, $id, $rev, $summary);
1332f3f0262cSandi}
13332ed38036SAndreas Gohr
133415fae107Sandi/**
133571f7bde7SAndreas Gohr * extracts the query from a search engine referrer
133615fae107Sandi *
133715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
133871f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1339140cfbcdSGerrit Uitslag *
1340140cfbcdSGerrit Uitslag * @return array|string
1341f3f0262cSandi */
1342f3f0262cSandifunction getGoogleQuery() {
1343585bf44eSChristopher Smith    /* @var Input $INPUT */
1344585bf44eSChristopher Smith    global $INPUT;
1345585bf44eSChristopher Smith
1346585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_REFERER')) {
1347c66972f2SAdrian Lang        return '';
1348c66972f2SAdrian Lang    }
1349585bf44eSChristopher Smith    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1350f3f0262cSandi
1351079b3ac1SAndreas Gohr    // only handle common SEs
1352079b3ac1SAndreas Gohr    if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/',$url['host'])) return '';
1353e4d8a516SKazutaka Miyasaka
1354079b3ac1SAndreas Gohr    $query = array();
1355e4d8a516SKazutaka Miyasaka    // temporary workaround against PHP bug #49733
1356e4d8a516SKazutaka Miyasaka    // see http://bugs.php.net/bug.php?id=49733
1357e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) $enc = mb_internal_encoding();
1358f3f0262cSandi    parse_str($url['query'], $query);
1359e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) mb_internal_encoding($enc);
1360e4d8a516SKazutaka Miyasaka
1361c66972f2SAdrian Lang    $q = '';
1362079b3ac1SAndreas Gohr    if(isset($query['q'])){
1363079b3ac1SAndreas Gohr        $q = $query['q'];
1364079b3ac1SAndreas Gohr    }elseif(isset($query['p'])){
1365079b3ac1SAndreas Gohr        $q = $query['p'];
1366079b3ac1SAndreas Gohr    }elseif(isset($query['query'])){
1367079b3ac1SAndreas Gohr        $q = $query['query'];
1368079b3ac1SAndreas Gohr    }
1369079b3ac1SAndreas Gohr    $q = trim($q);
1370f3f0262cSandi
1371079b3ac1SAndreas Gohr    if(!$q) return '';
13726531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1373f93b3b50SAndreas Gohr    return $q;
1374f3f0262cSandi}
1375f3f0262cSandi
1376f3f0262cSandi/**
1377f3f0262cSandi * Return the human readable size of a file
1378f3f0262cSandi *
1379f3f0262cSandi * @param       int $size A file size
1380f3f0262cSandi * @param       int $dec A number of decimal places
138174160ca1SGerrit Uitslag * @return string human readable size
1382140cfbcdSGerrit Uitslag *
1383f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1384f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1385f3f0262cSandi * @version     1.0.0
1386f3f0262cSandi */
1387f31d5b73Sandifunction filesize_h($size, $dec = 1) {
1388f3f0262cSandi    $sizes = array('B', 'KB', 'MB', 'GB');
1389f3f0262cSandi    $count = count($sizes);
1390f3f0262cSandi    $i     = 0;
1391f3f0262cSandi
1392f3f0262cSandi    while($size >= 1024 && ($i < $count - 1)) {
1393f3f0262cSandi        $size /= 1024;
1394f3f0262cSandi        $i++;
1395f3f0262cSandi    }
1396f3f0262cSandi
1397f3f0262cSandi    return round($size, $dec).' '.$sizes[$i];
1398f3f0262cSandi}
1399f3f0262cSandi
140015fae107Sandi/**
1401c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1402c57e365eSAndreas Gohr *
1403c57e365eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1404140cfbcdSGerrit Uitslag *
1405140cfbcdSGerrit Uitslag * @param int $dt timestamp
1406140cfbcdSGerrit Uitslag * @return string
1407c57e365eSAndreas Gohr */
1408c57e365eSAndreas Gohrfunction datetime_h($dt) {
1409c57e365eSAndreas Gohr    global $lang;
1410c57e365eSAndreas Gohr
1411c57e365eSAndreas Gohr    $ago = time() - $dt;
1412c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1413c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1414c57e365eSAndreas Gohr    }
1415c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 2) {
1416c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1417c57e365eSAndreas Gohr    }
1418c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 7 * 2) {
1419c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1420c57e365eSAndreas Gohr    }
1421c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 2) {
1422c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1423c57e365eSAndreas Gohr    }
1424c57e365eSAndreas Gohr    if($ago > 60 * 60 * 2) {
1425c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago / (60 * 60)));
1426c57e365eSAndreas Gohr    }
1427c57e365eSAndreas Gohr    if($ago > 60 * 2) {
1428c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago / (60)));
1429c57e365eSAndreas Gohr    }
1430c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1431c57e365eSAndreas Gohr}
1432c57e365eSAndreas Gohr
1433c57e365eSAndreas Gohr/**
1434f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1435f2263577SAndreas Gohr *
1436f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1437f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1438f2263577SAndreas Gohr *
1439f2263577SAndreas Gohr * @see datetime_h
1440f2263577SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1441140cfbcdSGerrit Uitslag *
1442140cfbcdSGerrit Uitslag * @param int|null $dt      timestamp when given, null will take current timestamp
1443140cfbcdSGerrit Uitslag * @param string   $format  empty default to $conf['dformat'], or provide format as recognized by strftime()
1444140cfbcdSGerrit Uitslag * @return string
1445f2263577SAndreas Gohr */
1446f2263577SAndreas Gohrfunction dformat($dt = null, $format = '') {
1447f2263577SAndreas Gohr    global $conf;
1448f2263577SAndreas Gohr
1449f2263577SAndreas Gohr    if(is_null($dt)) $dt = time();
1450f2263577SAndreas Gohr    $dt = (int) $dt;
1451f2263577SAndreas Gohr    if(!$format) $format = $conf['dformat'];
1452f2263577SAndreas Gohr
1453f2263577SAndreas Gohr    $format = str_replace('%f', datetime_h($dt), $format);
1454f2263577SAndreas Gohr    return strftime($format, $dt);
1455f2263577SAndreas Gohr}
1456f2263577SAndreas Gohr
1457f2263577SAndreas Gohr/**
1458c4f79b71SMichael Hamann * Formats a timestamp as ISO 8601 date
1459c4f79b71SMichael Hamann *
1460c4f79b71SMichael Hamann * @author <ungu at terong dot com>
1461c4f79b71SMichael Hamann * @link http://www.php.net/manual/en/function.date.php#54072
1462140cfbcdSGerrit Uitslag *
146363703ba5SAndreas Gohr * @param int $int_date: current date in UNIX timestamp
14643272d797SAndreas Gohr * @return string
1465c4f79b71SMichael Hamann */
1466c4f79b71SMichael Hamannfunction date_iso8601($int_date) {
1467c4f79b71SMichael Hamann    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1468c4f79b71SMichael Hamann    $pre_timezone = date('O', $int_date);
1469c4f79b71SMichael Hamann    $time_zone    = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1470c4f79b71SMichael Hamann    $date_mod .= $time_zone;
1471c4f79b71SMichael Hamann    return $date_mod;
1472c4f79b71SMichael Hamann}
1473c4f79b71SMichael Hamann
1474c4f79b71SMichael Hamann/**
147500a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
147600a7b5adSEsther Brunner *
147700a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
147800a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
1479140cfbcdSGerrit Uitslag *
1480140cfbcdSGerrit Uitslag * @param string $email email address
1481140cfbcdSGerrit Uitslag * @return string
148200a7b5adSEsther Brunner */
148300a7b5adSEsther Brunnerfunction obfuscate($email) {
148400a7b5adSEsther Brunner    global $conf;
148500a7b5adSEsther Brunner
148600a7b5adSEsther Brunner    switch($conf['mailguard']) {
148700a7b5adSEsther Brunner        case 'visible' :
148800a7b5adSEsther Brunner            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
148900a7b5adSEsther Brunner            return strtr($email, $obfuscate);
149000a7b5adSEsther Brunner
149100a7b5adSEsther Brunner        case 'hex' :
149200a7b5adSEsther Brunner            $encode = '';
149349eb6e38SAndreas Gohr            $len    = strlen($email);
149449eb6e38SAndreas Gohr            for($x = 0; $x < $len; $x++) {
149549eb6e38SAndreas Gohr                $encode .= '&#x'.bin2hex($email{$x}).';';
149649eb6e38SAndreas Gohr            }
149700a7b5adSEsther Brunner            return $encode;
149800a7b5adSEsther Brunner
149900a7b5adSEsther Brunner        case 'none' :
150000a7b5adSEsther Brunner        default :
150100a7b5adSEsther Brunner            return $email;
150200a7b5adSEsther Brunner    }
150300a7b5adSEsther Brunner}
150400a7b5adSEsther Brunner
150500a7b5adSEsther Brunner/**
150689541d4bSAndreas Gohr * Removes quoting backslashes
150789541d4bSAndreas Gohr *
150889541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1509140cfbcdSGerrit Uitslag *
1510140cfbcdSGerrit Uitslag * @param string $string
1511140cfbcdSGerrit Uitslag * @param string $char backslashed character
1512140cfbcdSGerrit Uitslag * @return string
151389541d4bSAndreas Gohr */
151489541d4bSAndreas Gohrfunction unslash($string, $char = "'") {
151589541d4bSAndreas Gohr    return str_replace('\\'.$char, $char, $string);
151689541d4bSAndreas Gohr}
151789541d4bSAndreas Gohr
151873038c47SAndreas Gohr/**
151973038c47SAndreas Gohr * Convert php.ini shorthands to byte
152073038c47SAndreas Gohr *
152173038c47SAndreas Gohr * @author <gilthans dot NO dot SPAM at gmail dot com>
152273038c47SAndreas Gohr * @link   http://de3.php.net/manual/en/ini.core.php#79564
1523140cfbcdSGerrit Uitslag *
1524140cfbcdSGerrit Uitslag * @param string $v shorthands
1525140cfbcdSGerrit Uitslag * @return int|string
152673038c47SAndreas Gohr */
152773038c47SAndreas Gohrfunction php_to_byte($v) {
152873038c47SAndreas Gohr    $l   = substr($v, -1);
152973038c47SAndreas Gohr    $ret = substr($v, 0, -1);
153073038c47SAndreas Gohr    switch(strtoupper($l)) {
153174160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
153273038c47SAndreas Gohr        case 'P':
153373038c47SAndreas Gohr            $ret *= 1024;
153474160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
153573038c47SAndreas Gohr        case 'T':
153673038c47SAndreas Gohr            $ret *= 1024;
153774160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
153873038c47SAndreas Gohr        case 'G':
153973038c47SAndreas Gohr            $ret *= 1024;
154074160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
154173038c47SAndreas Gohr        case 'M':
154273038c47SAndreas Gohr            $ret *= 1024;
1543f168548cSGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
154473038c47SAndreas Gohr        case 'K':
154573038c47SAndreas Gohr            $ret *= 1024;
154673038c47SAndreas Gohr            break;
154749cbd23eSOtto Vainio        default;
154849cbd23eSOtto Vainio            $ret *= 10;
154949cbd23eSOtto Vainio            break;
155073038c47SAndreas Gohr    }
155173038c47SAndreas Gohr    return $ret;
155273038c47SAndreas Gohr}
155373038c47SAndreas Gohr
1554546d3a99SAndreas Gohr/**
1555546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1556140cfbcdSGerrit Uitslag *
1557140cfbcdSGerrit Uitslag * @param string $string
1558140cfbcdSGerrit Uitslag * @return string
1559546d3a99SAndreas Gohr */
1560546d3a99SAndreas Gohrfunction preg_quote_cb($string) {
1561546d3a99SAndreas Gohr    return preg_quote($string, '/');
1562546d3a99SAndreas Gohr}
156373038c47SAndreas Gohr
1564bd2f6c2fSAndreas Gohr/**
1565bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1566bd2f6c2fSAndreas Gohr *
1567c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1568bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1569bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1570bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1571bd2f6c2fSAndreas Gohr *
1572bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1573bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1574bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1575bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1576bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
15773272d797SAndreas Gohr * @return string
1578bd2f6c2fSAndreas Gohr */
1579a5d27328SAndreas Gohrfunction shorten($keep, $short, $max, $min = 9, $char = '…') {
1580bd2f6c2fSAndreas Gohr    $max = $max - utf8_strlen($keep);
1581bd2f6c2fSAndreas Gohr    if($max < $min) return $keep;
1582bd2f6c2fSAndreas Gohr    $len = utf8_strlen($short);
1583bd2f6c2fSAndreas Gohr    if($len <= $max) return $keep.$short;
1584bd2f6c2fSAndreas Gohr    $half = floor($max / 2);
1585bd2f6c2fSAndreas Gohr    return $keep.utf8_substr($short, 0, $half - 1).$char.utf8_substr($short, $len - $half);
1586bd2f6c2fSAndreas Gohr}
1587bd2f6c2fSAndreas Gohr
1588dc58b6f4SAndy Webber/**
1589dc58b6f4SAndy Webber * Return the users real name or e-mail address for use
1590dc58b6f4SAndy Webber * in page footer and recent changes pages
1591dc58b6f4SAndy Webber *
1592b4b6c9a1SGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
159315f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1594c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
159515f3bc49SGerrit Uitslag *
1596dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1597dc58b6f4SAndy Webber */
159815f3bc49SGerrit Uitslagfunction editorinfo($username, $textonly = false) {
1599cd4635eeSGerrit Uitslag    return userlink($username, $textonly);
1600dc58b6f4SAndy Webber}
1601dc58b6f4SAndy Webber
160260a396c8SGerrit Uitslag/**
160360a396c8SGerrit Uitslag * Returns users realname w/o link
160460a396c8SGerrit Uitslag *
1605f168548cSGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
160615f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1607c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
160860a396c8SGerrit Uitslag *
160960a396c8SGerrit Uitslag * @triggers COMMON_USER_LINK
161060a396c8SGerrit Uitslag */
1611cd4635eeSGerrit Uitslagfunction userlink($username = null, $textonly = false) {
161260a396c8SGerrit Uitslag    global $conf, $INFO;
161360a396c8SGerrit Uitslag    /** @var DokuWiki_Auth_Plugin $auth */
161460a396c8SGerrit Uitslag    global $auth;
161530f6ec4bSGerrit Uitslag    /** @var Input $INPUT */
161630f6ec4bSGerrit Uitslag    global $INPUT;
161760a396c8SGerrit Uitslag
161860a396c8SGerrit Uitslag    // prepare initial event data
161960a396c8SGerrit Uitslag    $data = array(
162060a396c8SGerrit Uitslag        'username' => $username, // the unique user name
162160a396c8SGerrit Uitslag        'name' => '',
162260a396c8SGerrit Uitslag        'link' => array( //setting 'link' to false disables linking
162360a396c8SGerrit Uitslag                         'target' => '',
162460a396c8SGerrit Uitslag                         'pre' => '',
162560a396c8SGerrit Uitslag                         'suf' => '',
162660a396c8SGerrit Uitslag                         'style' => '',
162760a396c8SGerrit Uitslag                         'more' => '',
162860a396c8SGerrit Uitslag                         'url' => '',
162960a396c8SGerrit Uitslag                         'title' => '',
163060a396c8SGerrit Uitslag                         'class' => ''
163160a396c8SGerrit Uitslag        ),
16324d5fc927SGerrit Uitslag        'userlink' => '', // formatted user name as will be returned
163315f3bc49SGerrit Uitslag        'textonly' => $textonly
163460a396c8SGerrit Uitslag    );
163562c8004eSGerrit Uitslag    if($username === null) {
163630f6ec4bSGerrit Uitslag        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
163715f3bc49SGerrit Uitslag        if($textonly){
163815f3bc49SGerrit Uitslag            $data['name'] = $INFO['userinfo']['name']. ' (' . $INPUT->server->str('REMOTE_USER') . ')';
163915f3bc49SGerrit Uitslag        }else {
164030f6ec4bSGerrit Uitslag            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> (<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
164160a396c8SGerrit Uitslag        }
164215f3bc49SGerrit Uitslag    }
164360a396c8SGerrit Uitslag
164460a396c8SGerrit Uitslag    $evt = new Doku_Event('COMMON_USER_LINK', $data);
164560a396c8SGerrit Uitslag    if($evt->advise_before(true)) {
164660a396c8SGerrit Uitslag        if(empty($data['name'])) {
164760a396c8SGerrit Uitslag            if($auth) $info = $auth->getUserData($username);
164865833968SGerrit Uitslag            if($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1649dc58b6f4SAndy Webber                switch($conf['showuseras']) {
1650dc58b6f4SAndy Webber                    case 'username':
16517f081821SGerrit Uitslag                    case 'username_link':
165215f3bc49SGerrit Uitslag                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
165360a396c8SGerrit Uitslag                        break;
1654dc58b6f4SAndy Webber                    case 'email':
1655dc58b6f4SAndy Webber                    case 'email_link':
165660a396c8SGerrit Uitslag                        $data['name'] = obfuscate($info['mail']);
165760a396c8SGerrit Uitslag                        break;
1658dc58b6f4SAndy Webber                }
165965833968SGerrit Uitslag            } else {
166065833968SGerrit Uitslag                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
166160a396c8SGerrit Uitslag            }
166260a396c8SGerrit Uitslag        }
16637f081821SGerrit Uitslag
16647f081821SGerrit Uitslag        /** @var Doku_Renderer_xhtml $xhtml_renderer */
16657f081821SGerrit Uitslag        static $xhtml_renderer = null;
16667f081821SGerrit Uitslag
166715f3bc49SGerrit Uitslag        if(!$data['textonly'] && empty($data['link']['url'])) {
16687f081821SGerrit Uitslag
16697f081821SGerrit Uitslag            if(in_array($conf['showuseras'], array('email_link', 'username_link'))) {
167060a396c8SGerrit Uitslag                if(!isset($info)) {
167160a396c8SGerrit Uitslag                    if($auth) $info = $auth->getUserData($username);
167260a396c8SGerrit Uitslag                }
167360a396c8SGerrit Uitslag                if(isset($info) && $info) {
16747f081821SGerrit Uitslag                    if($conf['showuseras'] == 'email_link') {
167560a396c8SGerrit Uitslag                        $data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
1676dc58b6f4SAndy Webber                    } else {
16777f081821SGerrit Uitslag                        if(is_null($xhtml_renderer)) {
16787f081821SGerrit Uitslag                            $xhtml_renderer = p_get_renderer('xhtml');
16797f081821SGerrit Uitslag                        }
16807f081821SGerrit Uitslag                        if(empty($xhtml_renderer->interwiki)) {
16817f081821SGerrit Uitslag                            $xhtml_renderer->interwiki = getInterwiki();
16827f081821SGerrit Uitslag                        }
16837f081821SGerrit Uitslag                        $shortcut = 'user';
1684533772e1SGerrit Uitslag                        $exists = null;
16856496c33fSGerrit Uitslag                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
16862a2a43c4SGerrit Uitslag                        $data['link']['class'] .= ' interwiki iw_user';
16876496c33fSGerrit Uitslag                        if($exists !== null) {
16886496c33fSGerrit Uitslag                            if($exists) {
16896496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink1';
16906496c33fSGerrit Uitslag                            } else {
16916496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink2';
16926496c33fSGerrit Uitslag                                $data['link']['rel'] = 'nofollow';
16936496c33fSGerrit Uitslag                            }
16946496c33fSGerrit Uitslag                        }
1695dc58b6f4SAndy Webber                    }
1696dc58b6f4SAndy Webber                } else {
169715f3bc49SGerrit Uitslag                    $data['textonly'] = true;
1698dc58b6f4SAndy Webber                }
169960a396c8SGerrit Uitslag
170060a396c8SGerrit Uitslag            } else {
170115f3bc49SGerrit Uitslag                $data['textonly'] = true;
170260a396c8SGerrit Uitslag            }
170360a396c8SGerrit Uitslag        }
170460a396c8SGerrit Uitslag
170515f3bc49SGerrit Uitslag        if($data['textonly']) {
17064d5fc927SGerrit Uitslag            $data['userlink'] = $data['name'];
170760a396c8SGerrit Uitslag        } else {
170860a396c8SGerrit Uitslag            $data['link']['name'] = $data['name'];
170960a396c8SGerrit Uitslag            if(is_null($xhtml_renderer)) {
171060a396c8SGerrit Uitslag                $xhtml_renderer = p_get_renderer('xhtml');
171160a396c8SGerrit Uitslag            }
17124d5fc927SGerrit Uitslag            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
171360a396c8SGerrit Uitslag        }
171460a396c8SGerrit Uitslag    }
171560a396c8SGerrit Uitslag    $evt->advise_after();
171660a396c8SGerrit Uitslag    unset($evt);
171760a396c8SGerrit Uitslag
17184d5fc927SGerrit Uitslag    return $data['userlink'];
1719066fee30SAndreas Gohr}
1720066fee30SAndreas Gohr
1721066fee30SAndreas Gohr/**
1722066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1723066fee30SAndreas Gohr * When no image exists, returns an empty string
1724066fee30SAndreas Gohr *
1725066fee30SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1726140cfbcdSGerrit Uitslag *
1727066fee30SAndreas Gohr * @param  string $type - type of image 'badge' or 'button'
17283272d797SAndreas Gohr * @return string
1729066fee30SAndreas Gohr */
1730066fee30SAndreas Gohrfunction license_img($type) {
1731066fee30SAndreas Gohr    global $license;
1732066fee30SAndreas Gohr    global $conf;
1733066fee30SAndreas Gohr    if(!$conf['license']) return '';
1734066fee30SAndreas Gohr    if(!is_array($license[$conf['license']])) return '';
1735066fee30SAndreas Gohr    $try   = array();
1736066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1737066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1738066fee30SAndreas Gohr    if(substr($conf['license'], 0, 3) == 'cc-') {
1739066fee30SAndreas Gohr        $try[] = 'lib/images/license/'.$type.'/cc.png';
1740066fee30SAndreas Gohr    }
1741066fee30SAndreas Gohr    foreach($try as $src) {
1742066fee30SAndreas Gohr        if(@file_exists(DOKU_INC.$src)) return $src;
1743066fee30SAndreas Gohr    }
1744066fee30SAndreas Gohr    return '';
1745dc58b6f4SAndy Webber}
1746dc58b6f4SAndy Webber
174713c08e2fSMichael Klier/**
174813c08e2fSMichael Klier * Checks if the given amount of memory is available
174913c08e2fSMichael Klier *
175013c08e2fSMichael Klier * If the memory_get_usage() function is not available the
175113c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
175213c08e2fSMichael Klier *
175313c08e2fSMichael Klier * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
175413c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
17553272d797SAndreas Gohr *
17563272d797SAndreas Gohr * @param int  $mem    Size of memory you want to allocate in bytes
1757140cfbcdSGerrit Uitslag * @param int  $bytes  already allocated memory (see above)
17583272d797SAndreas Gohr * @return bool
175913c08e2fSMichael Klier */
176013c08e2fSMichael Klierfunction is_mem_available($mem, $bytes = 1048576) {
176113c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
176213c08e2fSMichael Klier    if(empty($limit)) return true; // no limit set!
176313c08e2fSMichael Klier
176413c08e2fSMichael Klier    // parse limit to bytes
176513c08e2fSMichael Klier    $limit = php_to_byte($limit);
176613c08e2fSMichael Klier
176713c08e2fSMichael Klier    // get used memory if possible
176813c08e2fSMichael Klier    if(function_exists('memory_get_usage')) {
176913c08e2fSMichael Klier        $used = memory_get_usage();
177049eb6e38SAndreas Gohr    } else {
177149eb6e38SAndreas Gohr        $used = $bytes;
177213c08e2fSMichael Klier    }
177313c08e2fSMichael Klier
177413c08e2fSMichael Klier    if($used + $mem > $limit) {
177513c08e2fSMichael Klier        return false;
177613c08e2fSMichael Klier    }
177713c08e2fSMichael Klier
177813c08e2fSMichael Klier    return true;
177913c08e2fSMichael Klier}
178013c08e2fSMichael Klier
1781af2408d5SAndreas Gohr/**
1782af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1783af2408d5SAndreas Gohr *
1784af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1785af2408d5SAndreas Gohr *
1786af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1787af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1788140cfbcdSGerrit Uitslag *
1789140cfbcdSGerrit Uitslag * @param string $url url being directed to
1790af2408d5SAndreas Gohr */
1791af2408d5SAndreas Gohrfunction send_redirect($url) {
1792585bf44eSChristopher Smith    /* @var Input $INPUT */
1793585bf44eSChristopher Smith    global $INPUT;
1794585bf44eSChristopher Smith
17950181f021SAndreas Gohr    //are there any undisplayed messages? keep them in session for display
17960181f021SAndreas Gohr    global $MSG;
17970181f021SAndreas Gohr    if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
17980181f021SAndreas Gohr        //reopen session, store data and close session again
17990181f021SAndreas Gohr        @session_start();
18000181f021SAndreas Gohr        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
18010181f021SAndreas Gohr    }
18020181f021SAndreas Gohr
1803d4869846SAndreas Gohr    // always close the session
1804d4869846SAndreas Gohr    session_write_close();
1805d4869846SAndreas Gohr
1806c10dcb7dSAndreas Gohr    // work around IE bug
1807c10dcb7dSAndreas Gohr    // http://www.ianhoar.com/2008/11/16/internet-explorer-6-and-redirected-anchor-links/
18086d2af55dSChristopher Smith    @list($url, $hash) = explode('#', $url);
1809c10dcb7dSAndreas Gohr    if($hash) {
1810c10dcb7dSAndreas Gohr        if(strpos($url, '?')) {
1811c10dcb7dSAndreas Gohr            $url = $url.'&#'.$hash;
1812c10dcb7dSAndreas Gohr        } else {
1813c10dcb7dSAndreas Gohr            $url = $url.'?&#'.$hash;
1814c10dcb7dSAndreas Gohr        }
1815c10dcb7dSAndreas Gohr    }
1816c10dcb7dSAndreas Gohr
1817af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
1818585bf44eSChristopher Smith    if($INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1819585bf44eSChristopher Smith        (strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) &&
1820585bf44eSChristopher Smith        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
18213272d797SAndreas Gohr        $matches[1] < 6
18223272d797SAndreas Gohr    ) {
1823af2408d5SAndreas Gohr        header('Refresh: 0;url='.$url);
1824af2408d5SAndreas Gohr    } else {
1825af2408d5SAndreas Gohr        header('Location: '.$url);
1826af2408d5SAndreas Gohr    }
1827af2408d5SAndreas Gohr    exit;
1828af2408d5SAndreas Gohr}
1829af2408d5SAndreas Gohr
18305b75cd1fSAdrian Lang/**
18315b75cd1fSAdrian Lang * Validate a value using a set of valid values
18325b75cd1fSAdrian Lang *
18335b75cd1fSAdrian Lang * This function checks whether a specified value is set and in the array
18345b75cd1fSAdrian Lang * $valid_values. If not, the function returns a default value or, if no
18355b75cd1fSAdrian Lang * default is specified, throws an exception.
18365b75cd1fSAdrian Lang *
18375b75cd1fSAdrian Lang * @param string $param        The name of the parameter
18385b75cd1fSAdrian Lang * @param array  $valid_values A set of valid values; Optionally a default may
18395b75cd1fSAdrian Lang *                             be marked by the key “default”.
18405b75cd1fSAdrian Lang * @param array  $array        The array containing the value (typically $_POST
18415b75cd1fSAdrian Lang *                             or $_GET)
18425b75cd1fSAdrian Lang * @param string $exc          The text of the raised exception
18435b75cd1fSAdrian Lang *
18443272d797SAndreas Gohr * @throws Exception
18453272d797SAndreas Gohr * @return mixed
18465b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
18475b75cd1fSAdrian Lang */
18485b75cd1fSAdrian Langfunction valid_input_set($param, $valid_values, $array, $exc = '') {
18495b75cd1fSAdrian Lang    if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
18505b75cd1fSAdrian Lang        return $array[$param];
18515b75cd1fSAdrian Lang    } elseif(isset($valid_values['default'])) {
18525b75cd1fSAdrian Lang        return $valid_values['default'];
18535b75cd1fSAdrian Lang    } else {
18545b75cd1fSAdrian Lang        throw new Exception($exc);
18555b75cd1fSAdrian Lang    }
18565b75cd1fSAdrian Lang}
18575b75cd1fSAdrian Lang
185863703ba5SAndreas Gohr/**
185963703ba5SAndreas Gohr * Read a preference from the DokuWiki cookie
1860646a531aSChristopher Smith * (remembering both keys & values are urlencoded)
1861140cfbcdSGerrit Uitslag *
1862140cfbcdSGerrit Uitslag * @param string $pref     preference key
1863b4b6c9a1SGerrit Uitslag * @param mixed  $default  value returned when preference not found
1864140cfbcdSGerrit Uitslag * @return string preference value
186563703ba5SAndreas Gohr */
1866554a8c9fSAdrian Langfunction get_doku_pref($pref, $default) {
1867646a531aSChristopher Smith    $enc_pref = urlencode($pref);
1868646a531aSChristopher Smith    if(strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
1869554a8c9fSAdrian Lang        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
187063703ba5SAndreas Gohr        $cnt   = count($parts);
187163703ba5SAndreas Gohr        for($i = 0; $i < $cnt; $i += 2) {
1872646a531aSChristopher Smith            if($parts[$i] == $enc_pref) {
1873646a531aSChristopher Smith                return urldecode($parts[$i + 1]);
1874554a8c9fSAdrian Lang            }
1875554a8c9fSAdrian Lang        }
1876554a8c9fSAdrian Lang    }
1877554a8c9fSAdrian Lang    return $default;
1878554a8c9fSAdrian Lang}
1879554a8c9fSAdrian Lang
18803c94d07bSAnika Henke/**
18813c94d07bSAnika Henke * Add a preference to the DokuWiki cookie
188236ec377eSChristopher Smith * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
1883140cfbcdSGerrit Uitslag *
1884140cfbcdSGerrit Uitslag * @param string $pref  preference key
1885140cfbcdSGerrit Uitslag * @param string $val   preference value
18863c94d07bSAnika Henke */
18873c94d07bSAnika Henkefunction set_doku_pref($pref, $val) {
18883c94d07bSAnika Henke    global $conf;
18893c94d07bSAnika Henke    $orig = get_doku_pref($pref, false);
18903c94d07bSAnika Henke    $cookieVal = '';
18913c94d07bSAnika Henke
18923c94d07bSAnika Henke    if($orig && ($orig != $val)) {
18933c94d07bSAnika Henke        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
18943c94d07bSAnika Henke        $cnt   = count($parts);
189536ec377eSChristopher Smith        // urlencode $pref for the comparison
189636ec377eSChristopher Smith        $enc_pref = rawurlencode($pref);
18973c94d07bSAnika Henke        for($i = 0; $i < $cnt; $i += 2) {
189836ec377eSChristopher Smith            if($parts[$i] == $enc_pref) {
189936ec377eSChristopher Smith                $parts[$i + 1] = rawurlencode($val);
190050f261f7SMichael Hamann                break;
19013c94d07bSAnika Henke            }
19023c94d07bSAnika Henke        }
19033c94d07bSAnika Henke        $cookieVal = implode('#', $parts);
19043c94d07bSAnika Henke    } else if (!$orig) {
190536ec377eSChristopher Smith        $cookieVal = ($_COOKIE['DOKU_PREFS'] ? $_COOKIE['DOKU_PREFS'].'#' : '').rawurlencode($pref).'#'.rawurlencode($val);
19063c94d07bSAnika Henke    }
19073c94d07bSAnika Henke
19083c94d07bSAnika Henke    if (!empty($cookieVal)) {
190975e4dd8aSGerrit Uitslag        $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
191075e4dd8aSGerrit Uitslag        setcookie('DOKU_PREFS', $cookieVal, time()+365*24*3600, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
19113c94d07bSAnika Henke    }
19123c94d07bSAnika Henke}
19133c94d07bSAnika Henke
1914f8fb2d18SAndreas Gohr/**
1915f8fb2d18SAndreas Gohr * Strips source mapping declarations from given text #601
1916f8fb2d18SAndreas Gohr *
1917f8fb2d18SAndreas Gohr * @param &string $text reference to the CSS or JavaScript code to clean
1918f8fb2d18SAndreas Gohr */
1919f8fb2d18SAndreas Gohrfunction stripsourcemaps(&$text){
1920f8fb2d18SAndreas Gohr    $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text);
1921f8fb2d18SAndreas Gohr}
1922f8fb2d18SAndreas Gohr
1923e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1924