xref: /dokuwiki/inc/common.php (revision 3a97088971109f1611a03329d12e5296a8c3c515)
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 *
5242ea7f44SGerrit 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
6542ea7f44SGerrit Uitslag *
66634d7150SAndreas Gohr * @return  string
67634d7150SAndreas Gohr */
68634d7150SAndreas Gohrfunction getSecurityToken() {
69585bf44eSChristopher Smith    /** @var Input $INPUT */
70585bf44eSChristopher Smith    global $INPUT;
71585bf44eSChristopher Smith    return PassHash::hmac('md5', session_id().$INPUT->server->str('REMOTE_USER'), auth_cookiesalt());
72634d7150SAndreas Gohr}
73634d7150SAndreas Gohr
74634d7150SAndreas Gohr/**
75634d7150SAndreas Gohr * Check the secret CSRF token
76140cfbcdSGerrit Uitslag *
77140cfbcdSGerrit Uitslag * @param null|string $token security token or null to read it from request variable
78140cfbcdSGerrit Uitslag * @return bool success if the token matched
79634d7150SAndreas Gohr */
80634d7150SAndreas Gohrfunction checkSecurityToken($token = null) {
81585bf44eSChristopher Smith    /** @var Input $INPUT */
827d01a0eaSTom N Harris    global $INPUT;
83585bf44eSChristopher Smith    if(!$INPUT->server->str('REMOTE_USER')) return true; // no logged in user, no need for a check
84df97eaacSAndreas Gohr
857d01a0eaSTom N Harris    if(is_null($token)) $token = $INPUT->str('sectok');
86634d7150SAndreas Gohr    if(getSecurityToken() != $token) {
87634d7150SAndreas Gohr        msg('Security Token did not match. Possible CSRF attack.', -1);
88634d7150SAndreas Gohr        return false;
89634d7150SAndreas Gohr    }
90634d7150SAndreas Gohr    return true;
91634d7150SAndreas Gohr}
92634d7150SAndreas Gohr
93634d7150SAndreas Gohr/**
94634d7150SAndreas Gohr * Print a hidden form field with a secret CSRF token
95634d7150SAndreas Gohr *
96634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
97140cfbcdSGerrit Uitslag *
98140cfbcdSGerrit Uitslag * @param bool $print  if true print the field, otherwise html of the field is returned
9942ea7f44SGerrit Uitslag * @return string html of hidden form field
100634d7150SAndreas Gohr */
101634d7150SAndreas Gohrfunction formSecurityToken($print = true) {
1022404d0edSAnika Henke    $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
1033272d797SAndreas Gohr    if($print) echo $ret;
104634d7150SAndreas Gohr    return $ret;
105634d7150SAndreas Gohr}
106634d7150SAndreas Gohr
107634d7150SAndreas Gohr/**
1081015a57dSChristopher Smith * Determine basic information for a request of $id
10915fae107Sandi *
11015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1117e87a794SChristopher Smith * @author Chris Smith <chris@jalakai.co.uk>
112140cfbcdSGerrit Uitslag *
113140cfbcdSGerrit Uitslag * @param string $id         pageid
114140cfbcdSGerrit Uitslag * @param bool   $htmlClient add info about whether is mobile browser
115140cfbcdSGerrit Uitslag * @return array with info for a request of $id
116140cfbcdSGerrit Uitslag *
117f3f0262cSandi */
1181015a57dSChristopher Smithfunction basicinfo($id, $htmlClient=true){
119f3f0262cSandi    global $USERINFO;
120585bf44eSChristopher Smith    /* @var Input $INPUT */
121585bf44eSChristopher Smith    global $INPUT;
1226afe8dcaSchris
123c66972f2SAdrian Lang    // set info about manager/admin status.
12459bc3b48SGerrit Uitslag    $info = array();
125c66972f2SAdrian Lang    $info['isadmin']   = false;
126c66972f2SAdrian Lang    $info['ismanager'] = false;
127585bf44eSChristopher Smith    if($INPUT->server->has('REMOTE_USER')) {
128f3f0262cSandi        $info['userinfo']   = $USERINFO;
1291015a57dSChristopher Smith        $info['perm']       = auth_quickaclcheck($id);
130585bf44eSChristopher Smith        $info['client']     = $INPUT->server->str('REMOTE_USER');
13117ee7f66SAndreas Gohr
132f8cc712eSAndreas Gohr        if($info['perm'] == AUTH_ADMIN) {
133f8cc712eSAndreas Gohr            $info['isadmin']   = true;
134f8cc712eSAndreas Gohr            $info['ismanager'] = true;
135f8cc712eSAndreas Gohr        } elseif(auth_ismanager()) {
136f8cc712eSAndreas Gohr            $info['ismanager'] = true;
137f8cc712eSAndreas Gohr        }
138f8cc712eSAndreas Gohr
13917ee7f66SAndreas Gohr        // if some outside auth were used only REMOTE_USER is set
14017ee7f66SAndreas Gohr        if(!$info['userinfo']['name']) {
141585bf44eSChristopher Smith            $info['userinfo']['name'] = $INPUT->server->str('REMOTE_USER');
14217ee7f66SAndreas Gohr        }
143ee4c4a1bSAndreas Gohr
144f3f0262cSandi    } else {
1451015a57dSChristopher Smith        $info['perm']       = auth_aclcheck($id, '', null);
146ee4c4a1bSAndreas Gohr        $info['client']     = clientIP(true);
147f3f0262cSandi    }
148f3f0262cSandi
1491015a57dSChristopher Smith    $info['namespace'] = getNS($id);
1501015a57dSChristopher Smith
1511015a57dSChristopher Smith    // mobile detection
1521015a57dSChristopher Smith    if ($htmlClient) {
1531015a57dSChristopher Smith        $info['ismobile'] = clientismobile();
1541015a57dSChristopher Smith    }
1551015a57dSChristopher Smith
1561015a57dSChristopher Smith    return $info;
1571015a57dSChristopher Smith }
1581015a57dSChristopher Smith
1591015a57dSChristopher Smith/**
1601015a57dSChristopher Smith * Return info about the current document as associative
1611015a57dSChristopher Smith * array.
1621015a57dSChristopher Smith *
1631015a57dSChristopher Smith * @author Andreas Gohr <andi@splitbrain.org>
164140cfbcdSGerrit Uitslag *
165140cfbcdSGerrit Uitslag * @return array with info about current document
1661015a57dSChristopher Smith */
1671015a57dSChristopher Smithfunction pageinfo() {
1681015a57dSChristopher Smith    global $ID;
1691015a57dSChristopher Smith    global $REV;
1701015a57dSChristopher Smith    global $RANGE;
1711015a57dSChristopher Smith    global $lang;
172585bf44eSChristopher Smith    /* @var Input $INPUT */
173585bf44eSChristopher Smith    global $INPUT;
1741015a57dSChristopher Smith
1751015a57dSChristopher Smith    $info = basicinfo($ID);
1761015a57dSChristopher Smith
1771015a57dSChristopher Smith    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
1781015a57dSChristopher Smith    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
1791015a57dSChristopher Smith    $info['id']  = $ID;
1801015a57dSChristopher Smith    $info['rev'] = $REV;
1811015a57dSChristopher Smith
182585bf44eSChristopher Smith    if($INPUT->server->has('REMOTE_USER')) {
1837e87a794SChristopher Smith        $sub = new Subscription();
1847e87a794SChristopher Smith        $info['subscribed'] = $sub->user_subscription();
1857e87a794SChristopher Smith    } else {
1867e87a794SChristopher Smith        $info['subscribed'] = false;
1877e87a794SChristopher Smith    }
1887e87a794SChristopher Smith
189f3f0262cSandi    $info['locked']     = checklock($ID);
19000976812SAndreas Gohr    $info['filepath']   = fullpath(wikiFN($ID));
19179e79377SAndreas Gohr    $info['exists']     = file_exists($info['filepath']);
19201c9a118SAndreas Gohr    $info['currentrev'] = @filemtime($info['filepath']);
1932ca9d91cSBen Coburn    if($REV) {
1942ca9d91cSBen Coburn        //check if current revision was meant
19501c9a118SAndreas Gohr        if($info['exists'] && ($info['currentrev'] == $REV)) {
1962ca9d91cSBen Coburn            $REV = '';
1977b3a6803SAndreas Gohr        } elseif($RANGE) {
1987b3a6803SAndreas Gohr            //section editing does not work with old revisions!
1997b3a6803SAndreas Gohr            $REV   = '';
2007b3a6803SAndreas Gohr            $RANGE = '';
2017b3a6803SAndreas Gohr            msg($lang['nosecedit'], 0);
2022ca9d91cSBen Coburn        } else {
2032ca9d91cSBen Coburn            //really use old revision
20400976812SAndreas Gohr            $info['filepath'] = fullpath(wikiFN($ID, $REV));
20579e79377SAndreas Gohr            $info['exists']   = file_exists($info['filepath']);
206f3f0262cSandi        }
207f3f0262cSandi    }
208c112d578Sandi    $info['rev'] = $REV;
209f3f0262cSandi    if($info['exists']) {
210f3f0262cSandi        $info['writable'] = (is_writable($info['filepath']) &&
211f3f0262cSandi            ($info['perm'] >= AUTH_EDIT));
212f3f0262cSandi    } else {
213f3f0262cSandi        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
214f3f0262cSandi    }
21550e988b1SAndreas Gohr    $info['editable'] = ($info['writable'] && empty($info['locked']));
216f3f0262cSandi    $info['lastmod']  = @filemtime($info['filepath']);
217f3f0262cSandi
21871726d78SBen Coburn    //load page meta data
21971726d78SBen Coburn    $info['meta'] = p_get_metadata($ID);
22071726d78SBen Coburn
221652610a2Sandi    //who's the editor
222047bad06SGerrit Uitslag    $pagelog = new PageChangeLog($ID, 1024);
223652610a2Sandi    if($REV) {
224f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($REV);
225652610a2Sandi    } else {
2260e80bb5eSChristopher Smith        if(!empty($info['meta']['last_change']) && is_array($info['meta']['last_change'])) {
227aa27cf05SAndreas Gohr            $revinfo = $info['meta']['last_change'];
228aa27cf05SAndreas Gohr        } else {
229f523c971SGerrit Uitslag            $revinfo = $pagelog->getRevisionInfo($info['lastmod']);
230cd00a034SBen Coburn            // cache most recent changelog line in metadata if missing and still valid
231cd00a034SBen Coburn            if($revinfo !== false) {
232cd00a034SBen Coburn                $info['meta']['last_change'] = $revinfo;
233cd00a034SBen Coburn                p_set_metadata($ID, array('last_change' => $revinfo));
234cd00a034SBen Coburn            }
235cd00a034SBen Coburn        }
236cd00a034SBen Coburn    }
237cd00a034SBen Coburn    //and check for an external edit
238cd00a034SBen Coburn    if($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
239cd00a034SBen Coburn        // cached changelog line no longer valid
240cd00a034SBen Coburn        $revinfo                     = false;
241cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
242cd00a034SBen Coburn        p_set_metadata($ID, array('last_change' => $revinfo));
243652610a2Sandi    }
244bb4866bdSchris
245652610a2Sandi    $info['ip']   = $revinfo['ip'];
246652610a2Sandi    $info['user'] = $revinfo['user'];
247652610a2Sandi    $info['sum']  = $revinfo['sum'];
24871726d78SBen Coburn    // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
249ebf1501fSBen Coburn    // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
25059f257aeSchris
25188f522e9Sandi    if($revinfo['user']) {
25288f522e9Sandi        $info['editor'] = $revinfo['user'];
25388f522e9Sandi    } else {
25488f522e9Sandi        $info['editor'] = $revinfo['ip'];
25588f522e9Sandi    }
256652610a2Sandi
257ee4c4a1bSAndreas Gohr    // draft
258ee4c4a1bSAndreas Gohr    $draft = getCacheName($info['client'].$ID, '.draft');
25979e79377SAndreas Gohr    if(file_exists($draft)) {
260ee4c4a1bSAndreas Gohr        if(@filemtime($draft) < @filemtime(wikiFN($ID))) {
261ee4c4a1bSAndreas Gohr            // remove stale draft
262ee4c4a1bSAndreas Gohr            @unlink($draft);
263ee4c4a1bSAndreas Gohr        } else {
264ee4c4a1bSAndreas Gohr            $info['draft'] = $draft;
265ee4c4a1bSAndreas Gohr        }
266ee4c4a1bSAndreas Gohr    }
267ee4c4a1bSAndreas Gohr
2681015a57dSChristopher Smith    return $info;
2691015a57dSChristopher Smith}
2701015a57dSChristopher Smith
2711015a57dSChristopher Smith/**
2721015a57dSChristopher Smith * Return information about the current media item as an associative array.
273140cfbcdSGerrit Uitslag *
274140cfbcdSGerrit Uitslag * @return array with info about current media item
2751015a57dSChristopher Smith */
2761015a57dSChristopher Smithfunction mediainfo(){
2771015a57dSChristopher Smith    global $NS;
2781015a57dSChristopher Smith    global $IMG;
2791015a57dSChristopher Smith
2801015a57dSChristopher Smith    $info = basicinfo("$NS:*");
2811015a57dSChristopher Smith    $info['image'] = $IMG;
2821c548ebeSAndreas Gohr
283f3f0262cSandi    return $info;
284f3f0262cSandi}
285f3f0262cSandi
286f3f0262cSandi/**
2872684e50aSAndreas Gohr * Build an string of URL parameters
2882684e50aSAndreas Gohr *
2892684e50aSAndreas Gohr * @author Andreas Gohr
290140cfbcdSGerrit Uitslag *
291140cfbcdSGerrit Uitslag * @param array  $params    array with key-value pairs
292140cfbcdSGerrit Uitslag * @param string $sep       series of pairs are separated by this character
293140cfbcdSGerrit Uitslag * @return string query string
2942684e50aSAndreas Gohr */
295b174aeaeSchrisfunction buildURLparams($params, $sep = '&amp;') {
2962684e50aSAndreas Gohr    $url = '';
2972684e50aSAndreas Gohr    $amp = false;
2982684e50aSAndreas Gohr    foreach($params as $key => $val) {
299b174aeaeSchris        if($amp) $url .= $sep;
3002684e50aSAndreas Gohr
30185e6871fSAdrian Lang        $url .= rawurlencode($key).'=';
3023a50618cSgweissbach        $url .= rawurlencode((string) $val);
3032684e50aSAndreas Gohr        $amp = true;
3042684e50aSAndreas Gohr    }
3052684e50aSAndreas Gohr    return $url;
3062684e50aSAndreas Gohr}
3072684e50aSAndreas Gohr
3082684e50aSAndreas Gohr/**
3092684e50aSAndreas Gohr * Build an string of html tag attributes
3102684e50aSAndreas Gohr *
3117bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
3127bff22c0SAndreas Gohr *
3132684e50aSAndreas Gohr * @author Andreas Gohr
314140cfbcdSGerrit Uitslag *
315140cfbcdSGerrit Uitslag * @param array $params    array with (attribute name-attribute value) pairs
316140cfbcdSGerrit Uitslag * @param bool  $skipempty skip empty string values?
317140cfbcdSGerrit Uitslag * @return string
3182684e50aSAndreas Gohr */
3194b030ce7SAndreas Gohrfunction buildAttributes($params, $skipempty = false) {
3202684e50aSAndreas Gohr    $url   = '';
3219063ec14SAdrian Lang    $white = false;
3222684e50aSAndreas Gohr    foreach($params as $key => $val) {
3237bff22c0SAndreas Gohr        if($key{0} == '_') continue;
324b1c94f1dSAndreas Gohr        if($val === '' && $skipempty) continue;
3259063ec14SAdrian Lang        if($white) $url .= ' ';
3267bff22c0SAndreas Gohr
3272684e50aSAndreas Gohr        $url .= $key.'="';
3282684e50aSAndreas Gohr        $url .= htmlspecialchars($val);
3292684e50aSAndreas Gohr        $url .= '"';
3309063ec14SAdrian Lang        $white = true;
3312684e50aSAndreas Gohr    }
3322684e50aSAndreas Gohr    return $url;
3332684e50aSAndreas Gohr}
3342684e50aSAndreas Gohr
3352684e50aSAndreas Gohr/**
33615fae107Sandi * This builds the breadcrumb trail and returns it as array
33715fae107Sandi *
33815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
339140cfbcdSGerrit Uitslag *
340e3710957SGerrit Uitslag * @return string[] with the data: array(pageid=>name, ... )
341f3f0262cSandi */
342f3f0262cSandifunction breadcrumbs() {
3438746e727Sandi    // we prepare the breadcrumbs early for quick session closing
3448746e727Sandi    static $crumbs = null;
3458746e727Sandi    if($crumbs != null) return $crumbs;
3468746e727Sandi
347f3f0262cSandi    global $ID;
348f3f0262cSandi    global $ACT;
349f3f0262cSandi    global $conf;
350f3f0262cSandi
351f3f0262cSandi    //first visit?
352c66972f2SAdrian Lang    $crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array();
353f3f0262cSandi    //we only save on show and existing wiki documents
354a77f5846Sjan    $file = wikiFN($ID);
35579e79377SAndreas Gohr    if($ACT != 'show' || !file_exists($file)) {
356e71ce681SAndreas Gohr        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
357f3f0262cSandi        return $crumbs;
358f3f0262cSandi    }
359a77f5846Sjan
360a77f5846Sjan    // page names
3611a84a0f3SAnika Henke    $name = noNSorNS($ID);
362fe9ec250SChris Smith    if(useHeading('navigation')) {
363a77f5846Sjan        // get page title
36467c15eceSMichael Hamann        $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
365a77f5846Sjan        if($title) {
366a77f5846Sjan            $name = $title;
367a77f5846Sjan        }
368a77f5846Sjan    }
369a77f5846Sjan
370f3f0262cSandi    //remove ID from array
371a77f5846Sjan    if(isset($crumbs[$ID])) {
372a77f5846Sjan        unset($crumbs[$ID]);
373f3f0262cSandi    }
374f3f0262cSandi
375f3f0262cSandi    //add to array
376a77f5846Sjan    $crumbs[$ID] = $name;
377f3f0262cSandi    //reduce size
378f3f0262cSandi    while(count($crumbs) > $conf['breadcrumbs']) {
379f3f0262cSandi        array_shift($crumbs);
380f3f0262cSandi    }
381f3f0262cSandi    //save to session
382e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
383f3f0262cSandi    return $crumbs;
384f3f0262cSandi}
385f3f0262cSandi
386f3f0262cSandi/**
38715fae107Sandi * Filter for page IDs
38815fae107Sandi *
389f3f0262cSandi * This is run on a ID before it is outputted somewhere
390f3f0262cSandi * currently used to replace the colon with something else
391907f24f7SAndreas Gohr * on Windows (non-IIS) systems and to have proper URL encoding
392907f24f7SAndreas Gohr *
393907f24f7SAndreas Gohr * See discussions at https://github.com/splitbrain/dokuwiki/pull/84 and
394907f24f7SAndreas Gohr * https://github.com/splitbrain/dokuwiki/pull/173 why we use a whitelist of
395907f24f7SAndreas Gohr * unaffected servers instead of blacklisting affected servers here.
39615fae107Sandi *
39749c713a3Sandi * Urlencoding is ommitted when the second parameter is false
39849c713a3Sandi *
39915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
400140cfbcdSGerrit Uitslag *
401140cfbcdSGerrit Uitslag * @param string $id pageid being filtered
402140cfbcdSGerrit Uitslag * @param bool   $ue apply urlencoding?
403140cfbcdSGerrit Uitslag * @return string
404f3f0262cSandi */
40549c713a3Sandifunction idfilter($id, $ue = true) {
406f3f0262cSandi    global $conf;
407585bf44eSChristopher Smith    /* @var Input $INPUT */
408585bf44eSChristopher Smith    global $INPUT;
409585bf44eSChristopher Smith
410f3f0262cSandi    if($conf['useslash'] && $conf['userewrite']) {
411f3f0262cSandi        $id = strtr($id, ':', '/');
412f3f0262cSandi    } elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
41358bedc8aSborekb        $conf['userewrite'] &&
414585bf44eSChristopher Smith        strpos($INPUT->server->str('SERVER_SOFTWARE'), 'Microsoft-IIS') === false
4153272d797SAndreas Gohr    ) {
416f3f0262cSandi        $id = strtr($id, ':', ';');
417f3f0262cSandi    }
41849c713a3Sandi    if($ue) {
419b6c6979fSAndreas Gohr        $id = rawurlencode($id);
420f3f0262cSandi        $id = str_replace('%3A', ':', $id); //keep as colon
421edd95259SGerrit Uitslag        $id = str_replace('%3B', ';', $id); //keep as semicolon
422f3f0262cSandi        $id = str_replace('%2F', '/', $id); //keep as slash
42349c713a3Sandi    }
424f3f0262cSandi    return $id;
425f3f0262cSandi}
426f3f0262cSandi
427f3f0262cSandi/**
428ed7b5f09Sandi * This builds a link to a wikipage
42915fae107Sandi *
4304bc480e5SAndreas Gohr * It handles URL rewriting and adds additional parameters
4316c7843b5Sandi *
43215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
4334bc480e5SAndreas Gohr *
4344bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
4354bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
4364bc480e5SAndreas Gohr * @param bool         $absolute       request an absolute URL instead of relative
4374bc480e5SAndreas Gohr * @param string       $separator      parameter separator
4384bc480e5SAndreas Gohr * @return string
439f3f0262cSandi */
44016f15a81SDominik Eckelmannfunction wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;') {
441f3f0262cSandi    global $conf;
44216f15a81SDominik Eckelmann    if(is_array($urlParameters)) {
4434bde2196Slisps        if(isset($urlParameters['rev']) && !$urlParameters['rev']) unset($urlParameters['rev']);
4447b62b42dSlisps        if(isset($urlParameters['at']) && $conf['date_at_format']) $urlParameters['at'] = date($conf['date_at_format'],$urlParameters['at']);
44516f15a81SDominik Eckelmann        $urlParameters = buildURLparams($urlParameters, $separator);
4466de3759aSAndreas Gohr    } else {
44716f15a81SDominik Eckelmann        $urlParameters = str_replace(',', $separator, $urlParameters);
4486de3759aSAndreas Gohr    }
44916f15a81SDominik Eckelmann    if($id === '') {
45016f15a81SDominik Eckelmann        $id = $conf['start'];
45116f15a81SDominik Eckelmann    }
452f3f0262cSandi    $id = idfilter($id);
45316f15a81SDominik Eckelmann    if($absolute) {
454ed7b5f09Sandi        $xlink = DOKU_URL;
455ed7b5f09Sandi    } else {
456ed7b5f09Sandi        $xlink = DOKU_BASE;
457ed7b5f09Sandi    }
458f3f0262cSandi
4596c7843b5Sandi    if($conf['userewrite'] == 2) {
4606c7843b5Sandi        $xlink .= DOKU_SCRIPT.'/'.$id;
46116f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
4626c7843b5Sandi    } elseif($conf['userewrite']) {
463f3f0262cSandi        $xlink .= $id;
46416f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
465bce3726dSAndreas Gohr    } elseif($id) {
4666c7843b5Sandi        $xlink .= DOKU_SCRIPT.'?id='.$id;
46716f15a81SDominik Eckelmann        if($urlParameters) $xlink .= $separator.$urlParameters;
468bce3726dSAndreas Gohr    } else {
469bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
47016f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
471f3f0262cSandi    }
472f3f0262cSandi
473f3f0262cSandi    return $xlink;
474f3f0262cSandi}
475f3f0262cSandi
476f3f0262cSandi/**
477f5c2808fSBen Coburn * This builds a link to an alternate page format
478f5c2808fSBen Coburn *
479f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
480f5c2808fSBen Coburn *
481f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
4824bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
4834bc480e5SAndreas Gohr * @param string       $format         the export renderer to use
4844bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
4854bc480e5SAndreas Gohr * @param bool         $abs            request an absolute URL instead of relative
4864bc480e5SAndreas Gohr * @param string       $sep            parameter separator
4874bc480e5SAndreas Gohr * @return string
488f5c2808fSBen Coburn */
4894bc480e5SAndreas Gohrfunction exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;') {
490f5c2808fSBen Coburn    global $conf;
4914bc480e5SAndreas Gohr    if(is_array($urlParameters)) {
4924bc480e5SAndreas Gohr        $urlParameters = buildURLparams($urlParameters, $sep);
493f5c2808fSBen Coburn    } else {
4944bc480e5SAndreas Gohr        $urlParameters = str_replace(',', $sep, $urlParameters);
495f5c2808fSBen Coburn    }
496f5c2808fSBen Coburn
497f5c2808fSBen Coburn    $format = rawurlencode($format);
498f5c2808fSBen Coburn    $id     = idfilter($id);
499f5c2808fSBen Coburn    if($abs) {
500f5c2808fSBen Coburn        $xlink = DOKU_URL;
501f5c2808fSBen Coburn    } else {
502f5c2808fSBen Coburn        $xlink = DOKU_BASE;
503f5c2808fSBen Coburn    }
504f5c2808fSBen Coburn
505f5c2808fSBen Coburn    if($conf['userewrite'] == 2) {
506f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
5074bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
508f5c2808fSBen Coburn    } elseif($conf['userewrite'] == 1) {
509f5c2808fSBen Coburn        $xlink .= '_export/'.$format.'/'.$id;
5104bc480e5SAndreas Gohr        if($urlParameters) $xlink .= '?'.$urlParameters;
511f5c2808fSBen Coburn    } else {
512f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
5134bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
514f5c2808fSBen Coburn    }
515f5c2808fSBen Coburn
516f5c2808fSBen Coburn    return $xlink;
517f5c2808fSBen Coburn}
518f5c2808fSBen Coburn
519f5c2808fSBen Coburn/**
5206de3759aSAndreas Gohr * Build a link to a media file
5216de3759aSAndreas Gohr *
5226de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
5238c08db0aSAndreas Gohr *
5248c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
5258c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
5268c08db0aSAndreas Gohr *
5273272d797SAndreas Gohr * @param string  $id     the media file id or URL
5283272d797SAndreas Gohr * @param mixed   $more   string or array with additional parameters
5293272d797SAndreas Gohr * @param bool    $direct link to detail page if false
5303272d797SAndreas Gohr * @param string  $sep    URL parameter separator
5313272d797SAndreas Gohr * @param bool    $abs    Create an absolute URL
5323272d797SAndreas Gohr * @return string
5336de3759aSAndreas Gohr */
53455b2b31bSAndreas Gohrfunction ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false) {
5356de3759aSAndreas Gohr    global $conf;
536b9ee6a44SKlap-in    $isexternalimage = media_isexternal($id);
537826d2766SKlap-in    if(!$isexternalimage) {
538826d2766SKlap-in        $id = cleanID($id);
539826d2766SKlap-in    }
540826d2766SKlap-in
5416de3759aSAndreas Gohr    if(is_array($more)) {
5420f4e0092SChristopher Smith        // add token for resized images
543443e135dSChristopher Smith        if(!empty($more['w']) || !empty($more['h']) || $isexternalimage){
5440f4e0092SChristopher Smith            $more['tok'] = media_get_token($id,$more['w'],$more['h']);
5450f4e0092SChristopher Smith        }
5468c08db0aSAndreas Gohr        // strip defaults for shorter URLs
5478c08db0aSAndreas Gohr        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
548443e135dSChristopher Smith        if(empty($more['w'])) unset($more['w']);
549443e135dSChristopher Smith        if(empty($more['h'])) unset($more['h']);
5508c08db0aSAndreas Gohr        if(isset($more['id']) && $direct) unset($more['id']);
55178b874e6Slisps        if(isset($more['rev']) && !$more['rev']) unset($more['rev']);
552b174aeaeSchris        $more = buildURLparams($more, $sep);
5536de3759aSAndreas Gohr    } else {
5545e7db1e2SChristopher Smith        $matches = array();
555cc036f74SKlap-in        if (preg_match_all('/\b(w|h)=(\d*)\b/',$more,$matches,PREG_SET_ORDER) || $isexternalimage){
5565e7db1e2SChristopher Smith            $resize = array('w'=>0, 'h'=>0);
5575e7db1e2SChristopher Smith            foreach ($matches as $match){
5585e7db1e2SChristopher Smith                $resize[$match[1]] = $match[2];
5595e7db1e2SChristopher Smith            }
560cc036f74SKlap-in            $more .= $more === '' ? '' : $sep;
561cc036f74SKlap-in            $more .= 'tok='.media_get_token($id,$resize['w'],$resize['h']);
5625e7db1e2SChristopher Smith        }
5638c08db0aSAndreas Gohr        $more = str_replace('cache=cache', '', $more); //skip default
5648c08db0aSAndreas Gohr        $more = str_replace(',,', ',', $more);
565b174aeaeSchris        $more = str_replace(',', $sep, $more);
5666de3759aSAndreas Gohr    }
5676de3759aSAndreas Gohr
56855b2b31bSAndreas Gohr    if($abs) {
56955b2b31bSAndreas Gohr        $xlink = DOKU_URL;
57055b2b31bSAndreas Gohr    } else {
5716de3759aSAndreas Gohr        $xlink = DOKU_BASE;
57255b2b31bSAndreas Gohr    }
5736de3759aSAndreas Gohr
5746de3759aSAndreas Gohr    // external URLs are always direct without rewriting
575826d2766SKlap-in    if($isexternalimage) {
5766de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
577cc036f74SKlap-in        $xlink .= '?'.$more;
578b174aeaeSchris        $xlink .= $sep.'media='.rawurlencode($id);
5796de3759aSAndreas Gohr        return $xlink;
5806de3759aSAndreas Gohr    }
5816de3759aSAndreas Gohr
5826de3759aSAndreas Gohr    $id = idfilter($id);
5836de3759aSAndreas Gohr
5846de3759aSAndreas Gohr    // decide on scriptname
5856de3759aSAndreas Gohr    if($direct) {
5866de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
5876de3759aSAndreas Gohr            $script = '_media';
5886de3759aSAndreas Gohr        } else {
5896de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
5906de3759aSAndreas Gohr        }
5916de3759aSAndreas Gohr    } else {
5926de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
5936de3759aSAndreas Gohr            $script = '_detail';
5946de3759aSAndreas Gohr        } else {
5956de3759aSAndreas Gohr            $script = 'lib/exe/detail.php';
5966de3759aSAndreas Gohr        }
5976de3759aSAndreas Gohr    }
5986de3759aSAndreas Gohr
5996de3759aSAndreas Gohr    // build URL based on rewrite mode
6006de3759aSAndreas Gohr    if($conf['userewrite']) {
6016de3759aSAndreas Gohr        $xlink .= $script.'/'.$id;
6026de3759aSAndreas Gohr        if($more) $xlink .= '?'.$more;
6036de3759aSAndreas Gohr    } else {
6046de3759aSAndreas Gohr        if($more) {
605a99d3236SEsther Brunner            $xlink .= $script.'?'.$more;
606b174aeaeSchris            $xlink .= $sep.'media='.$id;
6076de3759aSAndreas Gohr        } else {
608a99d3236SEsther Brunner            $xlink .= $script.'?media='.$id;
6096de3759aSAndreas Gohr        }
6106de3759aSAndreas Gohr    }
6116de3759aSAndreas Gohr
6126de3759aSAndreas Gohr    return $xlink;
6136de3759aSAndreas Gohr}
6146de3759aSAndreas Gohr
6156de3759aSAndreas Gohr/**
61625ca5b17SAndreas Gohr * Returns the URL to the DokuWiki base script
61715fae107Sandi *
61825ca5b17SAndreas Gohr * Consider using wl() instead, unless you absoutely need the doku.php endpoint
61925ca5b17SAndreas Gohr *
62015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
621140cfbcdSGerrit Uitslag *
622140cfbcdSGerrit Uitslag * @return string
623f3f0262cSandi */
62425ca5b17SAndreas Gohrfunction script() {
625ed7b5f09Sandi    return DOKU_BASE.DOKU_SCRIPT;
626f3f0262cSandi}
627f3f0262cSandi
628f3f0262cSandi/**
62915fae107Sandi * Spamcheck against wordlist
63015fae107Sandi *
631f3f0262cSandi * Checks the wikitext against a list of blocked expressions
632f3f0262cSandi * returns true if the text contains any bad words
63315fae107Sandi *
634e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
635e403cc58SMichael Klier *
636e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
637e403cc58SMichael Klier *  and gain information about the user who was blocked.
638e403cc58SMichael Klier *
639e403cc58SMichael Klier *  Event data:
640e403cc58SMichael Klier *    data['matches']  - array of matches
641e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
642e403cc58SMichael Klier *      [ip]           - ip address
643e403cc58SMichael Klier *      [user]         - username (if logged in)
644e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
645e403cc58SMichael Klier *      [name]         - real name (if logged in)
646e403cc58SMichael Klier *
64715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
6486dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
649140cfbcdSGerrit Uitslag *
6506dffa0e0SAndreas Gohr * @param  string $text - optional text to check, if not given the globals are used
6516dffa0e0SAndreas Gohr * @return bool         - true if a spam word was found
652f3f0262cSandi */
6536dffa0e0SAndreas Gohrfunction checkwordblock($text = '') {
654f3f0262cSandi    global $TEXT;
6556dffa0e0SAndreas Gohr    global $PRE;
6566dffa0e0SAndreas Gohr    global $SUF;
657e0086ca2SAndreas Gohr    global $SUM;
658f3f0262cSandi    global $conf;
659e403cc58SMichael Klier    global $INFO;
660585bf44eSChristopher Smith    /* @var Input $INPUT */
661585bf44eSChristopher Smith    global $INPUT;
662f3f0262cSandi
663f3f0262cSandi    if(!$conf['usewordblock']) return false;
664f3f0262cSandi
665e0086ca2SAndreas Gohr    if(!$text) $text = "$PRE $TEXT $SUF $SUM";
6666dffa0e0SAndreas Gohr
667041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
6686dffa0e0SAndreas Gohr    $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i', '\1http://\2 \2\3', $text);
669041d1964SAndreas Gohr
670b9ac8716Schris    $wordblocks = getWordblocks();
6713e2965d7Sandi    // how many lines to read at once (to work around some PCRE limits)
6723e2965d7Sandi    if(version_compare(phpversion(), '4.3.0', '<')) {
6733e2965d7Sandi        // old versions of PCRE define a maximum of parenthesises even if no
6743e2965d7Sandi        // backreferences are used - the maximum is 99
6753e2965d7Sandi        // this is very bad performancewise and may even be too high still
6763e2965d7Sandi        $chunksize = 40;
6773e2965d7Sandi    } else {
678a51d08efSAndreas Gohr        // read file in chunks of 200 - this should work around the
6793e2965d7Sandi        // MAX_PATTERN_SIZE in modern PCRE
680a51d08efSAndreas Gohr        $chunksize = 200;
6813e2965d7Sandi    }
682b9ac8716Schris    while($blocks = array_splice($wordblocks, 0, $chunksize)) {
683f3f0262cSandi        $re = array();
68449eb6e38SAndreas Gohr        // build regexp from blocks
685f3f0262cSandi        foreach($blocks as $block) {
686f3f0262cSandi            $block = preg_replace('/#.*$/', '', $block);
687f3f0262cSandi            $block = trim($block);
688f3f0262cSandi            if(empty($block)) continue;
689f3f0262cSandi            $re[] = $block;
690f3f0262cSandi        }
691e403cc58SMichael Klier        if(count($re) && preg_match('#('.join('|', $re).')#si', $text, $matches)) {
692e403cc58SMichael Klier            // prepare event data
69359bc3b48SGerrit Uitslag            $data = array();
694e403cc58SMichael Klier            $data['matches']        = $matches;
695585bf44eSChristopher Smith            $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
696585bf44eSChristopher Smith            if($INPUT->server->str('REMOTE_USER')) {
697585bf44eSChristopher Smith                $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
698e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
699e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
700e403cc58SMichael Klier            }
701e403cc58SMichael Klier            $callback = create_function('', 'return true;');
702e403cc58SMichael Klier            return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
703b9ac8716Schris        }
704703f6fdeSandi    }
705f3f0262cSandi    return false;
706f3f0262cSandi}
707f3f0262cSandi
708f3f0262cSandi/**
70915fae107Sandi * Return the IP of the client
71015fae107Sandi *
7116d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
71215fae107Sandi *
7136d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
7146d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
7156d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
7166d8affe6SAndreas Gohr * headers
7176d8affe6SAndreas Gohr *
71815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
719140cfbcdSGerrit Uitslag *
7203272d797SAndreas Gohr * @param  boolean $single If set only a single IP is returned
7213272d797SAndreas Gohr * @return string
722f3f0262cSandi */
7236d8affe6SAndreas Gohrfunction clientIP($single = false) {
724585bf44eSChristopher Smith    /* @var Input $INPUT */
725585bf44eSChristopher Smith    global $INPUT;
726585bf44eSChristopher Smith
7276d8affe6SAndreas Gohr    $ip   = array();
728585bf44eSChristopher Smith    $ip[] = $INPUT->server->str('REMOTE_ADDR');
729585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_FORWARDED_FOR')) {
730585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_FORWARDED_FOR'))));
731585bf44eSChristopher Smith    }
732585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_REAL_IP')) {
733585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_REAL_IP'))));
734585bf44eSChristopher Smith    }
7356d8affe6SAndreas Gohr
736dc14c6d1SGuy Brand    // some IPv4/v6 regexps borrowed from Feyd
737dc14c6d1SGuy Brand    // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
738dc14c6d1SGuy Brand    $dec_octet   = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
739dc14c6d1SGuy Brand    $hex_digit   = '[A-Fa-f0-9]';
740dc14c6d1SGuy Brand    $h16         = "{$hex_digit}{1,4}";
741dc14c6d1SGuy Brand    $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
742dc14c6d1SGuy Brand    $ls32        = "(?:$h16:$h16|$IPv4Address)";
743dc14c6d1SGuy Brand    $IPv6Address =
744dc14c6d1SGuy Brand        "(?:(?:{$IPv4Address})|(?:".
745dc14c6d1SGuy Brand            "(?:$h16:){6}$ls32".
746dc14c6d1SGuy Brand            "|::(?:$h16:){5}$ls32".
747dc14c6d1SGuy Brand            "|(?:$h16)?::(?:$h16:){4}$ls32".
748dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32".
749dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32".
750dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32".
751dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,4}$h16)?::$ls32".
752dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,5}$h16)?::$h16".
753dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,6}$h16)?::".
754dc14c6d1SGuy Brand            ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
755dc14c6d1SGuy Brand
7566d8affe6SAndreas Gohr    // remove any non-IP stuff
7576d8affe6SAndreas Gohr    $cnt   = count($ip);
7584ff28443Schris    $match = array();
7596d8affe6SAndreas Gohr    for($i = 0; $i < $cnt; $i++) {
760dc14c6d1SGuy Brand        if(preg_match("/^$IPv4Address$/", $ip[$i], $match) || preg_match("/^$IPv6Address$/", $ip[$i], $match)) {
7614ff28443Schris            $ip[$i] = $match[0];
7624ff28443Schris        } else {
7634ff28443Schris            $ip[$i] = '';
7644ff28443Schris        }
7656d8affe6SAndreas Gohr        if(empty($ip[$i])) unset($ip[$i]);
766f3f0262cSandi    }
7676d8affe6SAndreas Gohr    $ip = array_values(array_unique($ip));
7686d8affe6SAndreas Gohr    if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
7696d8affe6SAndreas Gohr
7706d8affe6SAndreas Gohr    if(!$single) return join(',', $ip);
7716d8affe6SAndreas Gohr
7726d8affe6SAndreas Gohr    // decide which IP to use, trying to avoid local addresses
7736d8affe6SAndreas Gohr    $ip = array_reverse($ip);
7746d8affe6SAndreas Gohr    foreach($ip as $i) {
7752343a762SAndreas Gohr        if(preg_match('/^(::1|[fF][eE]80:|127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/', $i)) {
7766d8affe6SAndreas Gohr            continue;
7776d8affe6SAndreas Gohr        } else {
7786d8affe6SAndreas Gohr            return $i;
7796d8affe6SAndreas Gohr        }
7806d8affe6SAndreas Gohr    }
7816d8affe6SAndreas Gohr    // still here? just use the first (last) address
7826d8affe6SAndreas Gohr    return $ip[0];
783f3f0262cSandi}
784f3f0262cSandi
785f3f0262cSandi/**
7861c548ebeSAndreas Gohr * Check if the browser is on a mobile device
7871c548ebeSAndreas Gohr *
7881c548ebeSAndreas Gohr * Adapted from the example code at url below
7891c548ebeSAndreas Gohr *
7901c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
791140cfbcdSGerrit Uitslag *
792140cfbcdSGerrit Uitslag * @return bool if true, client is mobile browser; otherwise false
7931c548ebeSAndreas Gohr */
7941c548ebeSAndreas Gohrfunction clientismobile() {
795585bf44eSChristopher Smith    /* @var Input $INPUT */
796585bf44eSChristopher Smith    global $INPUT;
7971c548ebeSAndreas Gohr
798585bf44eSChristopher Smith    if($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
7991c548ebeSAndreas Gohr
800585bf44eSChristopher Smith    if(preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
8011c548ebeSAndreas Gohr
802585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_USER_AGENT')) return false;
8031c548ebeSAndreas Gohr
8041c548ebeSAndreas 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';
8051c548ebeSAndreas Gohr
806585bf44eSChristopher Smith    if(preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
8071c548ebeSAndreas Gohr
8081c548ebeSAndreas Gohr    return false;
8091c548ebeSAndreas Gohr}
8101c548ebeSAndreas Gohr
8111c548ebeSAndreas Gohr/**
81263211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
81363211f61SGlen Harris *
81422ef1e32SAndreas Gohr * If $conf['dnslookups'] is disabled it simply returns the input string
81522ef1e32SAndreas Gohr *
81663211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
817140cfbcdSGerrit Uitslag *
8183272d797SAndreas Gohr * @param  string $ips comma separated list of IP addresses
8193272d797SAndreas Gohr * @return string a comma separated list of hostnames
82063211f61SGlen Harris */
82163211f61SGlen Harrisfunction gethostsbyaddrs($ips) {
82222ef1e32SAndreas Gohr    global $conf;
82322ef1e32SAndreas Gohr    if(!$conf['dnslookups']) return $ips;
82422ef1e32SAndreas Gohr
82563211f61SGlen Harris    $hosts = array();
82663211f61SGlen Harris    $ips   = explode(',', $ips);
827551a720fSMichael Klier
828551a720fSMichael Klier    if(is_array($ips)) {
8293886270dSAndreas Gohr        foreach($ips as $ip) {
830551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
83163211f61SGlen Harris        }
832551a720fSMichael Klier        return join(',', $hosts);
833551a720fSMichael Klier    } else {
834551a720fSMichael Klier        return gethostbyaddr(trim($ips));
835551a720fSMichael Klier    }
83663211f61SGlen Harris}
83763211f61SGlen Harris
83863211f61SGlen Harris/**
83915fae107Sandi * Checks if a given page is currently locked.
84015fae107Sandi *
841f3f0262cSandi * removes stale lockfiles
84215fae107Sandi *
84315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
844140cfbcdSGerrit Uitslag *
845140cfbcdSGerrit Uitslag * @param string $id page id
846140cfbcdSGerrit Uitslag * @return bool page is locked?
847f3f0262cSandi */
848f3f0262cSandifunction checklock($id) {
849f3f0262cSandi    global $conf;
850585bf44eSChristopher Smith    /* @var Input $INPUT */
851585bf44eSChristopher Smith    global $INPUT;
852585bf44eSChristopher Smith
853c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
854f3f0262cSandi
855f3f0262cSandi    //no lockfile
85679e79377SAndreas Gohr    if(!file_exists($lock)) return false;
857f3f0262cSandi
858f3f0262cSandi    //lockfile expired
859f3f0262cSandi    if((time() - filemtime($lock)) > $conf['locktime']) {
860d8186216SBen Coburn        @unlink($lock);
861f3f0262cSandi        return false;
862f3f0262cSandi    }
863f3f0262cSandi
864f3f0262cSandi    //my own lock
8656d2af55dSChristopher Smith    @list($ip, $session) = explode("\n", io_readFile($lock));
8660712fefaSAndreas Gohr    if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || (session_id() && $session == session_id())) {
867f3f0262cSandi        return false;
868f3f0262cSandi    }
869f3f0262cSandi
870f3f0262cSandi    return $ip;
871f3f0262cSandi}
872f3f0262cSandi
873f3f0262cSandi/**
87415fae107Sandi * Lock a page for editing
87515fae107Sandi *
87615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
877140cfbcdSGerrit Uitslag *
878140cfbcdSGerrit Uitslag * @param string $id page id to lock
879f3f0262cSandi */
880f3f0262cSandifunction lock($id) {
881544ed901SDaniel Calviño Sánchez    global $conf;
882585bf44eSChristopher Smith    /* @var Input $INPUT */
883585bf44eSChristopher Smith    global $INPUT;
884544ed901SDaniel Calviño Sánchez
885544ed901SDaniel Calviño Sánchez    if($conf['locktime'] == 0) {
886544ed901SDaniel Calviño Sánchez        return;
887544ed901SDaniel Calviño Sánchez    }
888544ed901SDaniel Calviño Sánchez
889c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
890585bf44eSChristopher Smith    if($INPUT->server->str('REMOTE_USER')) {
891585bf44eSChristopher Smith        io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
892f3f0262cSandi    } else {
89385fef7e2SAndreas Gohr        io_saveFile($lock, clientIP()."\n".session_id());
894f3f0262cSandi    }
895f3f0262cSandi}
896f3f0262cSandi
897f3f0262cSandi/**
89815fae107Sandi * Unlock a page if it was locked by the user
899f3f0262cSandi *
90015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
901140cfbcdSGerrit Uitslag *
9023272d797SAndreas Gohr * @param string $id page id to unlock
90315fae107Sandi * @return bool true if a lock was removed
904f3f0262cSandi */
905f3f0262cSandifunction unlock($id) {
906585bf44eSChristopher Smith    /* @var Input $INPUT */
907585bf44eSChristopher Smith    global $INPUT;
908585bf44eSChristopher Smith
909c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
91079e79377SAndreas Gohr    if(file_exists($lock)) {
9116d2af55dSChristopher Smith        @list($ip, $session) = explode("\n", io_readFile($lock));
912585bf44eSChristopher Smith        if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || $session == session_id()) {
913f3f0262cSandi            @unlink($lock);
914f3f0262cSandi            return true;
915f3f0262cSandi        }
916f3f0262cSandi    }
917f3f0262cSandi    return false;
918f3f0262cSandi}
919f3f0262cSandi
920f3f0262cSandi/**
921f3f0262cSandi * convert line ending to unix format
922f3f0262cSandi *
9236db7468bSAndreas Gohr * also makes sure the given text is valid UTF-8
9246db7468bSAndreas Gohr *
92515fae107Sandi * @see    formText() for 2crlf conversion
92615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
927140cfbcdSGerrit Uitslag *
928140cfbcdSGerrit Uitslag * @param string $text
929140cfbcdSGerrit Uitslag * @return string
930f3f0262cSandi */
931f3f0262cSandifunction cleanText($text) {
932f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
9336db7468bSAndreas Gohr
9346db7468bSAndreas Gohr    // if the text is not valid UTF-8 we simply assume latin1
9356db7468bSAndreas Gohr    // this won't break any worse than it breaks with the wrong encoding
9366db7468bSAndreas Gohr    // but might actually fix the problem in many cases
9376db7468bSAndreas Gohr    if(!utf8_check($text)) $text = utf8_encode($text);
9386db7468bSAndreas Gohr
939f3f0262cSandi    return $text;
940f3f0262cSandi}
941f3f0262cSandi
942f3f0262cSandi/**
943f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
944f3f0262cSandi * It also converts line endings to Windows format which is
945f3f0262cSandi * pseudo standard for webforms.
946f3f0262cSandi *
94715fae107Sandi * @see    cleanText() for 2unix conversion
94815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
949140cfbcdSGerrit Uitslag *
950140cfbcdSGerrit Uitslag * @param string $text
951140cfbcdSGerrit Uitslag * @return string
952f3f0262cSandi */
953f3f0262cSandifunction formText($text) {
9545b7d45a5SAndreas Gohr    $text = str_replace("\012", "\015\012", $text);
955f3f0262cSandi    return htmlspecialchars($text);
956f3f0262cSandi}
957f3f0262cSandi
958f3f0262cSandi/**
95915fae107Sandi * Returns the specified local text in raw format
96015fae107Sandi *
96115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
962140cfbcdSGerrit Uitslag *
963140cfbcdSGerrit Uitslag * @param string $id   page id
964140cfbcdSGerrit Uitslag * @param string $ext  extension of file being read, default 'txt'
965140cfbcdSGerrit Uitslag * @return string
966f3f0262cSandi */
9672adaf2b8SAndreas Gohrfunction rawLocale($id, $ext = 'txt') {
9682adaf2b8SAndreas Gohr    return io_readFile(localeFN($id, $ext));
969f3f0262cSandi}
970f3f0262cSandi
971f3f0262cSandi/**
972f3f0262cSandi * Returns the raw WikiText
97315fae107Sandi *
97415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
975140cfbcdSGerrit Uitslag *
976140cfbcdSGerrit Uitslag * @param string $id   page id
977e0c26282SGerrit Uitslag * @param string|int $rev  timestamp when a revision of wikitext is desired
978140cfbcdSGerrit Uitslag * @return string
979f3f0262cSandi */
980f3f0262cSandifunction rawWiki($id, $rev = '') {
981cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
982f3f0262cSandi}
983f3f0262cSandi
984f3f0262cSandi/**
9857146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
9867146cee2SAndreas Gohr *
9877b84afa2SAndreas Gohr * @triggers COMMON_PAGETPL_LOAD
9887146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
989140cfbcdSGerrit Uitslag *
990140cfbcdSGerrit Uitslag * @param string $id the id of the page to be created
991140cfbcdSGerrit Uitslag * @return string parsed pagetemplate content
9927146cee2SAndreas Gohr */
993fe17917eSAdrian Langfunction pageTemplate($id) {
994a15ce62dSEsther Brunner    global $conf;
995e29549feSAndreas Gohr
996fe17917eSAdrian Lang    if(is_array($id)) $id = $id[0];
997e29549feSAndreas Gohr
9987b84afa2SAndreas Gohr    // prepare initial event data
9997b84afa2SAndreas Gohr    $data = array(
10007b84afa2SAndreas Gohr        'id'        => $id, // the id of the page to be created
10017b84afa2SAndreas Gohr        'tpl'       => '', // the text used as template
10027b84afa2SAndreas Gohr        'tplfile'   => '', // the file above text was/should be loaded from
10037b84afa2SAndreas Gohr        'doreplace' => true // should wildcard replacements be done on the text?
10047b84afa2SAndreas Gohr    );
10057b84afa2SAndreas Gohr
10067b84afa2SAndreas Gohr    $evt = new Doku_Event('COMMON_PAGETPL_LOAD', $data);
10077b84afa2SAndreas Gohr    if($evt->advise_before(true)) {
10087b84afa2SAndreas Gohr        // the before event might have loaded the content already
10097b84afa2SAndreas Gohr        if(empty($data['tpl'])) {
10107b84afa2SAndreas Gohr            // if the before event did not set a template file, try to find one
10117b84afa2SAndreas Gohr            if(empty($data['tplfile'])) {
1012fe17917eSAdrian Lang                $path = dirname(wikiFN($id));
101379e79377SAndreas Gohr                if(file_exists($path.'/_template.txt')) {
10147b84afa2SAndreas Gohr                    $data['tplfile'] = $path.'/_template.txt';
1015e29549feSAndreas Gohr                } else {
1016e29549feSAndreas Gohr                    // search upper namespaces for templates
1017e29549feSAndreas Gohr                    $len = strlen(rtrim($conf['datadir'], '/'));
1018e29549feSAndreas Gohr                    while(strlen($path) >= $len) {
101979e79377SAndreas Gohr                        if(file_exists($path.'/__template.txt')) {
10207b84afa2SAndreas Gohr                            $data['tplfile'] = $path.'/__template.txt';
1021e29549feSAndreas Gohr                            break;
1022e29549feSAndreas Gohr                        }
1023e29549feSAndreas Gohr                        $path = substr($path, 0, strrpos($path, '/'));
1024e29549feSAndreas Gohr                    }
1025e29549feSAndreas Gohr                }
10267b84afa2SAndreas Gohr            }
10277b84afa2SAndreas Gohr            // load the content
10283d7ac595SMichael Hamann            $data['tpl'] = io_readFile($data['tplfile']);
10297b84afa2SAndreas Gohr        }
1030a1bbd05bSMichael Hamann        if($data['doreplace']) parsePageTemplate($data);
10317b84afa2SAndreas Gohr    }
10327b84afa2SAndreas Gohr    $evt->advise_after();
10337b84afa2SAndreas Gohr    unset($evt);
10347b84afa2SAndreas Gohr
1035fe17917eSAdrian Lang    return $data['tpl'];
10362b1223ecSAdrian Lang}
10372b1223ecSAdrian Lang
10382b1223ecSAdrian Lang/**
10392b1223ecSAdrian Lang * Performs common page template replacements
10407b84afa2SAndreas Gohr * This works on data from COMMON_PAGETPL_LOAD
10412b1223ecSAdrian Lang *
10422b1223ecSAdrian Lang * @author Andreas Gohr <andi@splitbrain.org>
1043140cfbcdSGerrit Uitslag *
1044140cfbcdSGerrit Uitslag * @param array $data array with event data
1045140cfbcdSGerrit Uitslag * @return string
10462b1223ecSAdrian Lang */
1047d535a2e9Sstretchyboyfunction parsePageTemplate(&$data) {
10483272d797SAndreas Gohr    /**
10493272d797SAndreas Gohr     * @var string $id        the id of the page to be created
10503272d797SAndreas Gohr     * @var string $tpl       the text used as template
10513272d797SAndreas Gohr     * @var string $tplfile   the file above text was/should be loaded from
10523272d797SAndreas Gohr     * @var bool   $doreplace should wildcard replacements be done on the text?
10533272d797SAndreas Gohr     */
1054fe17917eSAdrian Lang    extract($data);
1055fe17917eSAdrian Lang
1056b856f7dfSAdrian Lang    global $USERINFO;
1057bce53b1fSAdrian Lang    global $conf;
1058585bf44eSChristopher Smith    /* @var Input $INPUT */
1059585bf44eSChristopher Smith    global $INPUT;
1060e29549feSAndreas Gohr
1061e29549feSAndreas Gohr    // replace placeholders
106226ece5a7SAndreas Gohr    $file = noNS($id);
106337c1acbdSAdrian Lang    $page = strtr($file, $conf['sepchar'], ' ');
106426ece5a7SAndreas Gohr
10653272d797SAndreas Gohr    $tpl = str_replace(
10663272d797SAndreas Gohr        array(
106726ece5a7SAndreas Gohr             '@ID@',
106826ece5a7SAndreas Gohr             '@NS@',
106926ece5a7SAndreas Gohr             '@FILE@',
107026ece5a7SAndreas Gohr             '@!FILE@',
107126ece5a7SAndreas Gohr             '@!FILE!@',
107226ece5a7SAndreas Gohr             '@PAGE@',
107326ece5a7SAndreas Gohr             '@!PAGE@',
107426ece5a7SAndreas Gohr             '@!!PAGE@',
107526ece5a7SAndreas Gohr             '@!PAGE!@',
107626ece5a7SAndreas Gohr             '@USER@',
107726ece5a7SAndreas Gohr             '@NAME@',
107826ece5a7SAndreas Gohr             '@MAIL@',
107926ece5a7SAndreas Gohr             '@DATE@',
108026ece5a7SAndreas Gohr        ),
108126ece5a7SAndreas Gohr        array(
108226ece5a7SAndreas Gohr             $id,
108326ece5a7SAndreas Gohr             getNS($id),
108426ece5a7SAndreas Gohr             $file,
108526ece5a7SAndreas Gohr             utf8_ucfirst($file),
108626ece5a7SAndreas Gohr             utf8_strtoupper($file),
108726ece5a7SAndreas Gohr             $page,
108826ece5a7SAndreas Gohr             utf8_ucfirst($page),
108926ece5a7SAndreas Gohr             utf8_ucwords($page),
109026ece5a7SAndreas Gohr             utf8_strtoupper($page),
1091585bf44eSChristopher Smith             $INPUT->server->str('REMOTE_USER'),
1092b856f7dfSAdrian Lang             $USERINFO['name'],
1093b856f7dfSAdrian Lang             $USERINFO['mail'],
109426ece5a7SAndreas Gohr             $conf['dformat'],
10953272d797SAndreas Gohr        ), $tpl
10963272d797SAndreas Gohr    );
109726ece5a7SAndreas Gohr
10987d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
10997d644fc8SAndreas Gohr    $tpl         = preg_replace_callback('/%./', create_function('$m', 'return strftime($m[0]);'), $tpl);
1100d535a2e9Sstretchyboy    $data['tpl'] = $tpl;
1101a15ce62dSEsther Brunner    return $tpl;
11027146cee2SAndreas Gohr}
11037146cee2SAndreas Gohr
11047146cee2SAndreas Gohr/**
110515fae107Sandi * Returns the raw Wiki Text in three slices.
110615fae107Sandi *
110715fae107Sandi * The range parameter needs to have the form "from-to"
110815cfe303Sandi * and gives the range of the section in bytes - no
110915cfe303Sandi * UTF-8 awareness is needed.
1110f3f0262cSandi * The returned order is prefix, section and suffix.
111115fae107Sandi *
111215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1113140cfbcdSGerrit Uitslag *
1114140cfbcdSGerrit Uitslag * @param string $range in form "from-to"
1115140cfbcdSGerrit Uitslag * @param string $id    page id
1116140cfbcdSGerrit Uitslag * @param string $rev   optional, the revision timestamp
111742ea7f44SGerrit Uitslag * @return string[] with three slices
1118f3f0262cSandi */
1119f3f0262cSandifunction rawWikiSlices($range, $id, $rev = '') {
1120cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1121f3f0262cSandi
112280fcb268SAdrian Lang    // Parse range
112380fcb268SAdrian Lang    list($from, $to) = explode('-', $range, 2);
112480fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
112580fcb268SAdrian Lang    $from = !$from ? 0 : ($from - 1);
112680fcb268SAdrian Lang    $to   = !$to ? strlen($text) : ($to - 1);
112780fcb268SAdrian Lang
112859bc3b48SGerrit Uitslag    $slices = array();
112980fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
113080fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to - $from);
113115cfe303Sandi    $slices[2] = substr($text, $to);
1132f3f0262cSandi    return $slices;
1133f3f0262cSandi}
1134f3f0262cSandi
1135f3f0262cSandi/**
113615fae107Sandi * Joins wiki text slices
113715fae107Sandi *
113880fcb268SAdrian Lang * function to join the text slices.
1139f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
1140f3f0262cSandi * lines between sections if needed (used on saving).
114115fae107Sandi *
114215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1143140cfbcdSGerrit Uitslag *
1144140cfbcdSGerrit Uitslag * @param string $pre   prefix
1145140cfbcdSGerrit Uitslag * @param string $text  text in the middle
1146140cfbcdSGerrit Uitslag * @param string $suf   suffix
1147140cfbcdSGerrit Uitslag * @param bool $pretty add additional empty lines between sections
1148140cfbcdSGerrit Uitslag * @return string
1149f3f0262cSandi */
1150f3f0262cSandifunction con($pre, $text, $suf, $pretty = false) {
1151f3f0262cSandi    if($pretty) {
115280fcb268SAdrian Lang        if($pre !== '' && substr($pre, -1) !== "\n" &&
11533272d797SAndreas Gohr            substr($text, 0, 1) !== "\n"
11543272d797SAndreas Gohr        ) {
115580fcb268SAdrian Lang            $pre .= "\n";
115680fcb268SAdrian Lang        }
115780fcb268SAdrian Lang        if($suf !== '' && substr($text, -1) !== "\n" &&
11583272d797SAndreas Gohr            substr($suf, 0, 1) !== "\n"
11593272d797SAndreas Gohr        ) {
116080fcb268SAdrian Lang            $text .= "\n";
116180fcb268SAdrian Lang        }
1162f3f0262cSandi    }
1163f3f0262cSandi
1164f3f0262cSandi    return $pre.$text.$suf;
1165f3f0262cSandi}
1166f3f0262cSandi
1167f3f0262cSandi/**
1168a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
1169a701424fSBen Coburn * Also directs changelog and attic updates.
117015fae107Sandi *
117115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
117271726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
1173140cfbcdSGerrit Uitslag *
1174140cfbcdSGerrit Uitslag * @param string $id       page id
1175140cfbcdSGerrit Uitslag * @param string $text     wikitext being saved
1176140cfbcdSGerrit Uitslag * @param string $summary  summary of text update
1177140cfbcdSGerrit Uitslag * @param bool   $minor    mark this saved version as minor update
1178f3f0262cSandi */
1179b6912aeaSAndreas Gohrfunction saveWikiText($id, $text, $summary, $minor = false) {
1180a701424fSBen Coburn    /* Note to developers:
1181a701424fSBen Coburn       This code is subtle and delicate. Test the behavior of
1182a701424fSBen Coburn       the attic and changelog with dokuwiki and external edits
1183a701424fSBen Coburn       after any changes. External edits change the wiki page
1184a701424fSBen Coburn       directly without using php or dokuwiki.
1185a701424fSBen Coburn     */
1186f3f0262cSandi    global $conf;
1187f3f0262cSandi    global $lang;
118871726d78SBen Coburn    global $REV;
1189585bf44eSChristopher Smith    /* @var Input $INPUT */
1190585bf44eSChristopher Smith    global $INPUT;
1191585bf44eSChristopher Smith
1192f3f0262cSandi    // ignore if no changes were made
1193f3f0262cSandi    if($text == rawWiki($id, '')) {
1194f3f0262cSandi        return;
1195f3f0262cSandi    }
1196f3f0262cSandi
1197f3f0262cSandi    $file        = wikiFN($id);
1198a701424fSBen Coburn    $old         = @filemtime($file); // from page
1199407e65b9SAndreas Gohr    $wasRemoved  = (trim($text) == ''); // check for empty or whitespace only
120079e79377SAndreas Gohr    $wasCreated  = !file_exists($file);
120171726d78SBen Coburn    $wasReverted = ($REV == true);
1202047bad06SGerrit Uitslag    $pagelog     = new PageChangeLog($id, 1024);
1203e45b34cdSBen Coburn    $newRev      = false;
1204f523c971SGerrit Uitslag    $oldRev      = $pagelog->getRevisions(-1, 1); // from changelog
1205a701424fSBen Coburn    $oldRev      = (int) (empty($oldRev) ? 0 : $oldRev[0]);
120679e79377SAndreas Gohr    if(!file_exists(wikiFN($id, $old)) && file_exists($file) && $old >= $oldRev) {
120746844156SBen Coburn        // add old revision to the attic if missing
120846844156SBen Coburn        saveOldRevision($id);
120946844156SBen Coburn        // add a changelog entry if this edit came from outside dokuwiki
1210a701424fSBen Coburn        if($old > $oldRev) {
1211ebf1501fSBen Coburn            addLogEntry($old, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=> true));
121246844156SBen Coburn            // remove soon to be stale instructions
121346844156SBen Coburn            $cache = new cache_instructions($id, $file);
121446844156SBen Coburn            $cache->removeCache();
121546844156SBen Coburn        }
121646844156SBen Coburn    }
1217f3f0262cSandi
121871726d78SBen Coburn    if($wasRemoved) {
121930725328SGabriel Birke        // Send "update" event with empty data, so plugins can react to page deletion
122030725328SGabriel Birke        $data = array(array($file, '', false), getNS($id), noNS($id), false);
122130725328SGabriel Birke        trigger_event('IO_WIKIPAGE_WRITE', $data);
1222e45b34cdSBen Coburn        // pre-save deleted revision
1223e45b34cdSBen Coburn        @touch($file);
122446844156SBen Coburn        clearstatcache();
1225e45b34cdSBen Coburn        $newRev = saveOldRevision($id);
1226e1f3d9e1SEsther Brunner        // remove empty file
1227f3f0262cSandi        @unlink($file);
1228c5f92742SMichael Hamann        // don't remove old meta info as it should be saved, plugins can use IO_WIKIPAGE_WRITE for removing their metadata...
1229c5f92742SMichael Hamann        // purge non-persistant meta data
12303d1f9ec3SMichael Klier        p_purge_metadata($id);
1231f3f0262cSandi        $del = true;
12323ce054b3Sandi        // autoset summary on deletion
12333ce054b3Sandi        if(empty($summary)) $summary = $lang['deleted'];
123453d6ccfeSandi        // remove empty namespaces
1235cc7d0c94SBen Coburn        io_sweepNS($id, 'datadir');
1236cc7d0c94SBen Coburn        io_sweepNS($id, 'mediadir');
1237f3f0262cSandi    } else {
1238cc7d0c94SBen Coburn        // save file (namespace dir is created in io_writeWikiPage)
1239cc7d0c94SBen Coburn        io_writeWikiPage($file, $text, $id);
124046844156SBen Coburn        // pre-save the revision, to keep the attic in sync
124146844156SBen Coburn        $newRev = saveOldRevision($id);
1242f3f0262cSandi        $del    = false;
1243f3f0262cSandi    }
1244f3f0262cSandi
124571726d78SBen Coburn    // select changelog line type
124671726d78SBen Coburn    $extra = '';
1247ebf1501fSBen Coburn    $type  = DOKU_CHANGE_TYPE_EDIT;
124871726d78SBen Coburn    if($wasReverted) {
1249ebf1501fSBen Coburn        $type  = DOKU_CHANGE_TYPE_REVERT;
125071726d78SBen Coburn        $extra = $REV;
12513272d797SAndreas Gohr    } else if($wasCreated) {
12523272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_CREATE;
12533272d797SAndreas Gohr    } else if($wasRemoved) {
12543272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_DELETE;
1255585bf44eSChristopher Smith    } else if($minor && $conf['useacl'] && $INPUT->server->str('REMOTE_USER')) {
12563272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_MINOR_EDIT;
12573272d797SAndreas Gohr    } //minor edits only for logged in users
125871726d78SBen Coburn
1259e45b34cdSBen Coburn    addLogEntry($newRev, $id, $type, $summary, $extra);
126026a0801fSAndreas Gohr    // send notify mails
126190033e9dSAndreas Gohr    notify($id, 'admin', $old, $summary, $minor);
126290033e9dSAndreas Gohr    notify($id, 'subscribers', $old, $summary, $minor);
1263f3f0262cSandi
1264ce6b63d9Schris    // update the purgefile (timestamp of the last time anything within the wiki was changed)
126598407a7aSandi    io_saveFile($conf['cachedir'].'/purgefile', time());
12662eccbdaaSGina Haeussge
12672eccbdaaSGina Haeussge    // if useheading is enabled, purge the cache of all linking pages
1268fe9ec250SChris Smith    if(useHeading('content')) {
126907ff0babSMichael Hamann        $pages = ft_backlinks($id, true);
12702eccbdaaSGina Haeussge        foreach($pages as $page) {
12712eccbdaaSGina Haeussge            $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
12722eccbdaaSGina Haeussge            $cache->removeCache();
12732eccbdaaSGina Haeussge        }
12742eccbdaaSGina Haeussge    }
1275f3f0262cSandi}
1276f3f0262cSandi
1277f3f0262cSandi/**
1278f3f0262cSandi * moves the current version to the attic and returns its
1279f3f0262cSandi * revision date
128015fae107Sandi *
128115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1282140cfbcdSGerrit Uitslag *
1283140cfbcdSGerrit Uitslag * @param string $id page id
1284140cfbcdSGerrit Uitslag * @return int|string revision timestamp
1285f3f0262cSandi */
1286f3f0262cSandifunction saveOldRevision($id) {
1287f3f0262cSandi    $oldf = wikiFN($id);
128879e79377SAndreas Gohr    if(!file_exists($oldf)) return '';
1289f3f0262cSandi    $date = filemtime($oldf);
1290f3f0262cSandi    $newf = wikiFN($id, $date);
1291cc7d0c94SBen Coburn    io_writeWikiPage($newf, rawWiki($id), $id, $date);
1292f3f0262cSandi    return $date;
1293f3f0262cSandi}
1294f3f0262cSandi
1295f3f0262cSandi/**
1296fde10de4SAdrian Lang * Sends a notify mail on page change or registration
129726a0801fSAndreas Gohr *
129826a0801fSAndreas Gohr * @param string     $id       The changed page
1299fde10de4SAdrian Lang * @param string     $who      Who to notify (admin|subscribers|register)
13003272d797SAndreas Gohr * @param int|string $rev Old page revision
130126a0801fSAndreas Gohr * @param string     $summary  What changed
130290033e9dSAndreas Gohr * @param boolean    $minor    Is this a minor edit?
130342ea7f44SGerrit Uitslag * @param string[]   $replace  Additional string substitutions, @KEY@ to be replaced by value
13043272d797SAndreas Gohr * @return bool
1305140cfbcdSGerrit Uitslag *
130615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1307f3f0262cSandi */
130802a498e7Schrisfunction notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array()) {
1309f3f0262cSandi    global $conf;
1310585bf44eSChristopher Smith    /* @var Input $INPUT */
1311585bf44eSChristopher Smith    global $INPUT;
1312b158d625SSteven Danz
13136df843eeSAndreas Gohr    // decide if there is something to do, eg. whom to mail
131426a0801fSAndreas Gohr    if($who == 'admin') {
13153272d797SAndreas Gohr        if(empty($conf['notify'])) return false; //notify enabled?
13162ed38036SAndreas Gohr        $tpl = 'mailtext';
131726a0801fSAndreas Gohr        $to  = $conf['notify'];
131826a0801fSAndreas Gohr    } elseif($who == 'subscribers') {
131984c1127cSAndreas Gohr        if(!actionOK('subscribe')) return false; //subscribers enabled?
1320585bf44eSChristopher Smith        if($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
13210bb37868SGerrit Uitslag        $data = array('id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace);
13223272d797SAndreas Gohr        trigger_event(
13233272d797SAndreas Gohr            'COMMON_NOTIFY_ADDRESSLIST', $data,
1324835242b0SAndreas Gohr            array(new Subscription(), 'notifyaddresses')
13253272d797SAndreas Gohr        );
13262ed38036SAndreas Gohr        $to = $data['addresslist'];
13272ed38036SAndreas Gohr        if(empty($to)) return false;
13282ed38036SAndreas Gohr        $tpl = 'subscr_single';
132926a0801fSAndreas Gohr    } else {
13303272d797SAndreas Gohr        return false; //just to be safe
133126a0801fSAndreas Gohr    }
133226a0801fSAndreas Gohr
13336df843eeSAndreas Gohr    // prepare content
13342ed38036SAndreas Gohr    $subscription = new Subscription();
13352ed38036SAndreas Gohr    return $subscription->send_diff($to, $tpl, $id, $rev, $summary);
1336f3f0262cSandi}
13372ed38036SAndreas Gohr
133815fae107Sandi/**
133971f7bde7SAndreas Gohr * extracts the query from a search engine referrer
134015fae107Sandi *
134115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
134271f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1343140cfbcdSGerrit Uitslag *
1344140cfbcdSGerrit Uitslag * @return array|string
1345f3f0262cSandi */
1346f3f0262cSandifunction getGoogleQuery() {
1347585bf44eSChristopher Smith    /* @var Input $INPUT */
1348585bf44eSChristopher Smith    global $INPUT;
1349585bf44eSChristopher Smith
1350585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_REFERER')) {
1351c66972f2SAdrian Lang        return '';
1352c66972f2SAdrian Lang    }
1353585bf44eSChristopher Smith    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1354f3f0262cSandi
1355079b3ac1SAndreas Gohr    // only handle common SEs
1356079b3ac1SAndreas Gohr    if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/',$url['host'])) return '';
1357e4d8a516SKazutaka Miyasaka
1358079b3ac1SAndreas Gohr    $query = array();
1359e4d8a516SKazutaka Miyasaka    // temporary workaround against PHP bug #49733
1360e4d8a516SKazutaka Miyasaka    // see http://bugs.php.net/bug.php?id=49733
1361e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) $enc = mb_internal_encoding();
1362f3f0262cSandi    parse_str($url['query'], $query);
1363e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) mb_internal_encoding($enc);
1364e4d8a516SKazutaka Miyasaka
1365c66972f2SAdrian Lang    $q = '';
1366079b3ac1SAndreas Gohr    if(isset($query['q'])){
1367079b3ac1SAndreas Gohr        $q = $query['q'];
1368079b3ac1SAndreas Gohr    }elseif(isset($query['p'])){
1369079b3ac1SAndreas Gohr        $q = $query['p'];
1370079b3ac1SAndreas Gohr    }elseif(isset($query['query'])){
1371079b3ac1SAndreas Gohr        $q = $query['query'];
1372079b3ac1SAndreas Gohr    }
1373079b3ac1SAndreas Gohr    $q = trim($q);
1374f3f0262cSandi
1375079b3ac1SAndreas Gohr    if(!$q) return '';
13766531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1377f93b3b50SAndreas Gohr    return $q;
1378f3f0262cSandi}
1379f3f0262cSandi
1380f3f0262cSandi/**
1381f3f0262cSandi * Return the human readable size of a file
1382f3f0262cSandi *
1383f3f0262cSandi * @param int $size A file size
1384f3f0262cSandi * @param int $dec A number of decimal places
138574160ca1SGerrit Uitslag * @return string human readable size
1386140cfbcdSGerrit Uitslag *
1387f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1388f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1389f3f0262cSandi * @version     1.0.0
1390f3f0262cSandi */
1391f31d5b73Sandifunction filesize_h($size, $dec = 1) {
1392f3f0262cSandi    $sizes = array('B', 'KB', 'MB', 'GB');
1393f3f0262cSandi    $count = count($sizes);
1394f3f0262cSandi    $i     = 0;
1395f3f0262cSandi
1396f3f0262cSandi    while($size >= 1024 && ($i < $count - 1)) {
1397f3f0262cSandi        $size /= 1024;
1398f3f0262cSandi        $i++;
1399f3f0262cSandi    }
1400f3f0262cSandi
1401f3f0262cSandi    return round($size, $dec).' '.$sizes[$i];
1402f3f0262cSandi}
1403f3f0262cSandi
140415fae107Sandi/**
1405c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1406c57e365eSAndreas Gohr *
1407c57e365eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1408140cfbcdSGerrit Uitslag *
1409140cfbcdSGerrit Uitslag * @param int $dt timestamp
1410140cfbcdSGerrit Uitslag * @return string
1411c57e365eSAndreas Gohr */
1412c57e365eSAndreas Gohrfunction datetime_h($dt) {
1413c57e365eSAndreas Gohr    global $lang;
1414c57e365eSAndreas Gohr
1415c57e365eSAndreas Gohr    $ago = time() - $dt;
1416c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1417c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1418c57e365eSAndreas Gohr    }
1419c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 2) {
1420c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1421c57e365eSAndreas Gohr    }
1422c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 7 * 2) {
1423c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1424c57e365eSAndreas Gohr    }
1425c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 2) {
1426c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1427c57e365eSAndreas Gohr    }
1428c57e365eSAndreas Gohr    if($ago > 60 * 60 * 2) {
1429c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago / (60 * 60)));
1430c57e365eSAndreas Gohr    }
1431c57e365eSAndreas Gohr    if($ago > 60 * 2) {
1432c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago / (60)));
1433c57e365eSAndreas Gohr    }
1434c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1435c57e365eSAndreas Gohr}
1436c57e365eSAndreas Gohr
1437c57e365eSAndreas Gohr/**
1438f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1439f2263577SAndreas Gohr *
1440f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1441f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1442f2263577SAndreas Gohr *
1443f2263577SAndreas Gohr * @see datetime_h
1444f2263577SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1445140cfbcdSGerrit Uitslag *
1446140cfbcdSGerrit Uitslag * @param int|null $dt      timestamp when given, null will take current timestamp
1447140cfbcdSGerrit Uitslag * @param string   $format  empty default to $conf['dformat'], or provide format as recognized by strftime()
1448140cfbcdSGerrit Uitslag * @return string
1449f2263577SAndreas Gohr */
1450f2263577SAndreas Gohrfunction dformat($dt = null, $format = '') {
1451f2263577SAndreas Gohr    global $conf;
1452f2263577SAndreas Gohr
1453f2263577SAndreas Gohr    if(is_null($dt)) $dt = time();
1454f2263577SAndreas Gohr    $dt = (int) $dt;
1455f2263577SAndreas Gohr    if(!$format) $format = $conf['dformat'];
1456f2263577SAndreas Gohr
1457f2263577SAndreas Gohr    $format = str_replace('%f', datetime_h($dt), $format);
1458f2263577SAndreas Gohr    return strftime($format, $dt);
1459f2263577SAndreas Gohr}
1460f2263577SAndreas Gohr
1461f2263577SAndreas Gohr/**
1462c4f79b71SMichael Hamann * Formats a timestamp as ISO 8601 date
1463c4f79b71SMichael Hamann *
1464c4f79b71SMichael Hamann * @author <ungu at terong dot com>
1465c4f79b71SMichael Hamann * @link http://www.php.net/manual/en/function.date.php#54072
1466140cfbcdSGerrit Uitslag *
14677e8500eeSGerrit Uitslag * @param int $int_date current date in UNIX timestamp
14683272d797SAndreas Gohr * @return string
1469c4f79b71SMichael Hamann */
1470c4f79b71SMichael Hamannfunction date_iso8601($int_date) {
1471c4f79b71SMichael Hamann    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1472c4f79b71SMichael Hamann    $pre_timezone = date('O', $int_date);
1473c4f79b71SMichael Hamann    $time_zone    = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1474c4f79b71SMichael Hamann    $date_mod .= $time_zone;
1475c4f79b71SMichael Hamann    return $date_mod;
1476c4f79b71SMichael Hamann}
1477c4f79b71SMichael Hamann
1478c4f79b71SMichael Hamann/**
147900a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
148000a7b5adSEsther Brunner *
148100a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
148200a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
1483140cfbcdSGerrit Uitslag *
1484140cfbcdSGerrit Uitslag * @param string $email email address
1485140cfbcdSGerrit Uitslag * @return string
148600a7b5adSEsther Brunner */
148700a7b5adSEsther Brunnerfunction obfuscate($email) {
148800a7b5adSEsther Brunner    global $conf;
148900a7b5adSEsther Brunner
149000a7b5adSEsther Brunner    switch($conf['mailguard']) {
149100a7b5adSEsther Brunner        case 'visible' :
149200a7b5adSEsther Brunner            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
149300a7b5adSEsther Brunner            return strtr($email, $obfuscate);
149400a7b5adSEsther Brunner
149500a7b5adSEsther Brunner        case 'hex' :
149600a7b5adSEsther Brunner            $encode = '';
149749eb6e38SAndreas Gohr            $len    = strlen($email);
149849eb6e38SAndreas Gohr            for($x = 0; $x < $len; $x++) {
149949eb6e38SAndreas Gohr                $encode .= '&#x'.bin2hex($email{$x}).';';
150049eb6e38SAndreas Gohr            }
150100a7b5adSEsther Brunner            return $encode;
150200a7b5adSEsther Brunner
150300a7b5adSEsther Brunner        case 'none' :
150400a7b5adSEsther Brunner        default :
150500a7b5adSEsther Brunner            return $email;
150600a7b5adSEsther Brunner    }
150700a7b5adSEsther Brunner}
150800a7b5adSEsther Brunner
150900a7b5adSEsther Brunner/**
151089541d4bSAndreas Gohr * Removes quoting backslashes
151189541d4bSAndreas Gohr *
151289541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1513140cfbcdSGerrit Uitslag *
1514140cfbcdSGerrit Uitslag * @param string $string
1515140cfbcdSGerrit Uitslag * @param string $char backslashed character
1516140cfbcdSGerrit Uitslag * @return string
151789541d4bSAndreas Gohr */
151889541d4bSAndreas Gohrfunction unslash($string, $char = "'") {
151989541d4bSAndreas Gohr    return str_replace('\\'.$char, $char, $string);
152089541d4bSAndreas Gohr}
152189541d4bSAndreas Gohr
152273038c47SAndreas Gohr/**
152373038c47SAndreas Gohr * Convert php.ini shorthands to byte
152473038c47SAndreas Gohr *
152573038c47SAndreas Gohr * @author <gilthans dot NO dot SPAM at gmail dot com>
152673038c47SAndreas Gohr * @link   http://de3.php.net/manual/en/ini.core.php#79564
1527140cfbcdSGerrit Uitslag *
1528140cfbcdSGerrit Uitslag * @param string $v shorthands
1529140cfbcdSGerrit Uitslag * @return int|string
153073038c47SAndreas Gohr */
153173038c47SAndreas Gohrfunction php_to_byte($v) {
153273038c47SAndreas Gohr    $l   = substr($v, -1);
153373038c47SAndreas Gohr    $ret = substr($v, 0, -1);
153473038c47SAndreas Gohr    switch(strtoupper($l)) {
153574160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
153673038c47SAndreas Gohr        case 'P':
153773038c47SAndreas Gohr            $ret *= 1024;
153874160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
153973038c47SAndreas Gohr        case 'T':
154073038c47SAndreas Gohr            $ret *= 1024;
154174160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
154273038c47SAndreas Gohr        case 'G':
154373038c47SAndreas Gohr            $ret *= 1024;
154474160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
154573038c47SAndreas Gohr        case 'M':
154673038c47SAndreas Gohr            $ret *= 1024;
1547f168548cSGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
154873038c47SAndreas Gohr        case 'K':
154973038c47SAndreas Gohr            $ret *= 1024;
155073038c47SAndreas Gohr            break;
155149cbd23eSOtto Vainio        default;
155249cbd23eSOtto Vainio            $ret *= 10;
155349cbd23eSOtto Vainio            break;
155473038c47SAndreas Gohr    }
155573038c47SAndreas Gohr    return $ret;
155673038c47SAndreas Gohr}
155773038c47SAndreas Gohr
1558546d3a99SAndreas Gohr/**
1559546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1560140cfbcdSGerrit Uitslag *
1561140cfbcdSGerrit Uitslag * @param string $string
1562140cfbcdSGerrit Uitslag * @return string
1563546d3a99SAndreas Gohr */
1564546d3a99SAndreas Gohrfunction preg_quote_cb($string) {
1565546d3a99SAndreas Gohr    return preg_quote($string, '/');
1566546d3a99SAndreas Gohr}
156773038c47SAndreas Gohr
1568bd2f6c2fSAndreas Gohr/**
1569bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1570bd2f6c2fSAndreas Gohr *
1571c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1572bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1573bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1574bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1575bd2f6c2fSAndreas Gohr *
1576bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1577bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1578bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1579bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1580bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
15813272d797SAndreas Gohr * @return string
1582bd2f6c2fSAndreas Gohr */
1583a5d27328SAndreas Gohrfunction shorten($keep, $short, $max, $min = 9, $char = '…') {
1584bd2f6c2fSAndreas Gohr    $max = $max - utf8_strlen($keep);
1585bd2f6c2fSAndreas Gohr    if($max < $min) return $keep;
1586bd2f6c2fSAndreas Gohr    $len = utf8_strlen($short);
1587bd2f6c2fSAndreas Gohr    if($len <= $max) return $keep.$short;
1588bd2f6c2fSAndreas Gohr    $half = floor($max / 2);
1589bd2f6c2fSAndreas Gohr    return $keep.utf8_substr($short, 0, $half - 1).$char.utf8_substr($short, $len - $half);
1590bd2f6c2fSAndreas Gohr}
1591bd2f6c2fSAndreas Gohr
1592dc58b6f4SAndy Webber/**
1593dc58b6f4SAndy Webber * Return the users real name or e-mail address for use
1594dc58b6f4SAndy Webber * in page footer and recent changes pages
1595dc58b6f4SAndy Webber *
1596b4b6c9a1SGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
159715f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1598c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
159915f3bc49SGerrit Uitslag *
1600dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1601dc58b6f4SAndy Webber */
160215f3bc49SGerrit Uitslagfunction editorinfo($username, $textonly = false) {
1603cd4635eeSGerrit Uitslag    return userlink($username, $textonly);
1604dc58b6f4SAndy Webber}
1605dc58b6f4SAndy Webber
160660a396c8SGerrit Uitslag/**
160760a396c8SGerrit Uitslag * Returns users realname w/o link
160860a396c8SGerrit Uitslag *
1609f168548cSGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
161015f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1611c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
161260a396c8SGerrit Uitslag *
161360a396c8SGerrit Uitslag * @triggers COMMON_USER_LINK
161460a396c8SGerrit Uitslag */
1615cd4635eeSGerrit Uitslagfunction userlink($username = null, $textonly = false) {
161660a396c8SGerrit Uitslag    global $conf, $INFO;
161760a396c8SGerrit Uitslag    /** @var DokuWiki_Auth_Plugin $auth */
161860a396c8SGerrit Uitslag    global $auth;
161930f6ec4bSGerrit Uitslag    /** @var Input $INPUT */
162030f6ec4bSGerrit Uitslag    global $INPUT;
162160a396c8SGerrit Uitslag
162260a396c8SGerrit Uitslag    // prepare initial event data
162360a396c8SGerrit Uitslag    $data = array(
162460a396c8SGerrit Uitslag        'username' => $username, // the unique user name
162560a396c8SGerrit Uitslag        'name' => '',
162660a396c8SGerrit Uitslag        'link' => array( //setting 'link' to false disables linking
162760a396c8SGerrit Uitslag                         'target' => '',
162860a396c8SGerrit Uitslag                         'pre' => '',
162960a396c8SGerrit Uitslag                         'suf' => '',
163060a396c8SGerrit Uitslag                         'style' => '',
163160a396c8SGerrit Uitslag                         'more' => '',
163260a396c8SGerrit Uitslag                         'url' => '',
163360a396c8SGerrit Uitslag                         'title' => '',
163460a396c8SGerrit Uitslag                         'class' => ''
163560a396c8SGerrit Uitslag        ),
16364d5fc927SGerrit Uitslag        'userlink' => '', // formatted user name as will be returned
163715f3bc49SGerrit Uitslag        'textonly' => $textonly
163860a396c8SGerrit Uitslag    );
163962c8004eSGerrit Uitslag    if($username === null) {
164030f6ec4bSGerrit Uitslag        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
164115f3bc49SGerrit Uitslag        if($textonly){
164215f3bc49SGerrit Uitslag            $data['name'] = $INFO['userinfo']['name']. ' (' . $INPUT->server->str('REMOTE_USER') . ')';
164315f3bc49SGerrit Uitslag        }else {
164430f6ec4bSGerrit Uitslag            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> (<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
164560a396c8SGerrit Uitslag        }
164615f3bc49SGerrit Uitslag    }
164760a396c8SGerrit Uitslag
164860a396c8SGerrit Uitslag    $evt = new Doku_Event('COMMON_USER_LINK', $data);
164960a396c8SGerrit Uitslag    if($evt->advise_before(true)) {
165060a396c8SGerrit Uitslag        if(empty($data['name'])) {
165160a396c8SGerrit Uitslag            if($auth) $info = $auth->getUserData($username);
165265833968SGerrit Uitslag            if($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1653dc58b6f4SAndy Webber                switch($conf['showuseras']) {
1654dc58b6f4SAndy Webber                    case 'username':
16557f081821SGerrit Uitslag                    case 'username_link':
165615f3bc49SGerrit Uitslag                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
165760a396c8SGerrit Uitslag                        break;
1658dc58b6f4SAndy Webber                    case 'email':
1659dc58b6f4SAndy Webber                    case 'email_link':
166060a396c8SGerrit Uitslag                        $data['name'] = obfuscate($info['mail']);
166160a396c8SGerrit Uitslag                        break;
1662dc58b6f4SAndy Webber                }
166365833968SGerrit Uitslag            } else {
166465833968SGerrit Uitslag                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
166560a396c8SGerrit Uitslag            }
166660a396c8SGerrit Uitslag        }
16677f081821SGerrit Uitslag
16687f081821SGerrit Uitslag        /** @var Doku_Renderer_xhtml $xhtml_renderer */
16697f081821SGerrit Uitslag        static $xhtml_renderer = null;
16707f081821SGerrit Uitslag
167115f3bc49SGerrit Uitslag        if(!$data['textonly'] && empty($data['link']['url'])) {
16727f081821SGerrit Uitslag
16737f081821SGerrit Uitslag            if(in_array($conf['showuseras'], array('email_link', 'username_link'))) {
167460a396c8SGerrit Uitslag                if(!isset($info)) {
167560a396c8SGerrit Uitslag                    if($auth) $info = $auth->getUserData($username);
167660a396c8SGerrit Uitslag                }
167760a396c8SGerrit Uitslag                if(isset($info) && $info) {
16787f081821SGerrit Uitslag                    if($conf['showuseras'] == 'email_link') {
167960a396c8SGerrit Uitslag                        $data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
1680dc58b6f4SAndy Webber                    } else {
16817f081821SGerrit Uitslag                        if(is_null($xhtml_renderer)) {
16827f081821SGerrit Uitslag                            $xhtml_renderer = p_get_renderer('xhtml');
16837f081821SGerrit Uitslag                        }
16847f081821SGerrit Uitslag                        if(empty($xhtml_renderer->interwiki)) {
16857f081821SGerrit Uitslag                            $xhtml_renderer->interwiki = getInterwiki();
16867f081821SGerrit Uitslag                        }
16877f081821SGerrit Uitslag                        $shortcut = 'user';
1688533772e1SGerrit Uitslag                        $exists = null;
16896496c33fSGerrit Uitslag                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
16902a2a43c4SGerrit Uitslag                        $data['link']['class'] .= ' interwiki iw_user';
16916496c33fSGerrit Uitslag                        if($exists !== null) {
16926496c33fSGerrit Uitslag                            if($exists) {
16936496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink1';
16946496c33fSGerrit Uitslag                            } else {
16956496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink2';
16966496c33fSGerrit Uitslag                                $data['link']['rel'] = 'nofollow';
16976496c33fSGerrit Uitslag                            }
16986496c33fSGerrit Uitslag                        }
1699dc58b6f4SAndy Webber                    }
1700dc58b6f4SAndy Webber                } else {
170115f3bc49SGerrit Uitslag                    $data['textonly'] = true;
1702dc58b6f4SAndy Webber                }
170360a396c8SGerrit Uitslag
170460a396c8SGerrit Uitslag            } else {
170515f3bc49SGerrit Uitslag                $data['textonly'] = true;
170660a396c8SGerrit Uitslag            }
170760a396c8SGerrit Uitslag        }
170860a396c8SGerrit Uitslag
170915f3bc49SGerrit Uitslag        if($data['textonly']) {
17104d5fc927SGerrit Uitslag            $data['userlink'] = $data['name'];
171160a396c8SGerrit Uitslag        } else {
171260a396c8SGerrit Uitslag            $data['link']['name'] = $data['name'];
171360a396c8SGerrit Uitslag            if(is_null($xhtml_renderer)) {
171460a396c8SGerrit Uitslag                $xhtml_renderer = p_get_renderer('xhtml');
171560a396c8SGerrit Uitslag            }
17164d5fc927SGerrit Uitslag            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
171760a396c8SGerrit Uitslag        }
171860a396c8SGerrit Uitslag    }
171960a396c8SGerrit Uitslag    $evt->advise_after();
172060a396c8SGerrit Uitslag    unset($evt);
172160a396c8SGerrit Uitslag
17224d5fc927SGerrit Uitslag    return $data['userlink'];
1723066fee30SAndreas Gohr}
1724066fee30SAndreas Gohr
1725066fee30SAndreas Gohr/**
1726066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1727066fee30SAndreas Gohr * When no image exists, returns an empty string
1728066fee30SAndreas Gohr *
1729066fee30SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1730140cfbcdSGerrit Uitslag *
1731066fee30SAndreas Gohr * @param  string $type - type of image 'badge' or 'button'
17323272d797SAndreas Gohr * @return string
1733066fee30SAndreas Gohr */
1734066fee30SAndreas Gohrfunction license_img($type) {
1735066fee30SAndreas Gohr    global $license;
1736066fee30SAndreas Gohr    global $conf;
1737066fee30SAndreas Gohr    if(!$conf['license']) return '';
1738066fee30SAndreas Gohr    if(!is_array($license[$conf['license']])) return '';
1739066fee30SAndreas Gohr    $try   = array();
1740066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1741066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1742066fee30SAndreas Gohr    if(substr($conf['license'], 0, 3) == 'cc-') {
1743066fee30SAndreas Gohr        $try[] = 'lib/images/license/'.$type.'/cc.png';
1744066fee30SAndreas Gohr    }
1745066fee30SAndreas Gohr    foreach($try as $src) {
174679e79377SAndreas Gohr        if(file_exists(DOKU_INC.$src)) return $src;
1747066fee30SAndreas Gohr    }
1748066fee30SAndreas Gohr    return '';
1749dc58b6f4SAndy Webber}
1750dc58b6f4SAndy Webber
175113c08e2fSMichael Klier/**
175213c08e2fSMichael Klier * Checks if the given amount of memory is available
175313c08e2fSMichael Klier *
175413c08e2fSMichael Klier * If the memory_get_usage() function is not available the
175513c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
175613c08e2fSMichael Klier *
175713c08e2fSMichael Klier * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
175813c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
17593272d797SAndreas Gohr *
17603272d797SAndreas Gohr * @param int  $mem    Size of memory you want to allocate in bytes
1761140cfbcdSGerrit Uitslag * @param int  $bytes  already allocated memory (see above)
17623272d797SAndreas Gohr * @return bool
176313c08e2fSMichael Klier */
176413c08e2fSMichael Klierfunction is_mem_available($mem, $bytes = 1048576) {
176513c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
176613c08e2fSMichael Klier    if(empty($limit)) return true; // no limit set!
176713c08e2fSMichael Klier
176813c08e2fSMichael Klier    // parse limit to bytes
176913c08e2fSMichael Klier    $limit = php_to_byte($limit);
177013c08e2fSMichael Klier
177113c08e2fSMichael Klier    // get used memory if possible
177213c08e2fSMichael Klier    if(function_exists('memory_get_usage')) {
177313c08e2fSMichael Klier        $used = memory_get_usage();
177449eb6e38SAndreas Gohr    } else {
177549eb6e38SAndreas Gohr        $used = $bytes;
177613c08e2fSMichael Klier    }
177713c08e2fSMichael Klier
177813c08e2fSMichael Klier    if($used + $mem > $limit) {
177913c08e2fSMichael Klier        return false;
178013c08e2fSMichael Klier    }
178113c08e2fSMichael Klier
178213c08e2fSMichael Klier    return true;
178313c08e2fSMichael Klier}
178413c08e2fSMichael Klier
1785af2408d5SAndreas Gohr/**
1786af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1787af2408d5SAndreas Gohr *
1788af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1789af2408d5SAndreas Gohr *
1790af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1791af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1792140cfbcdSGerrit Uitslag *
1793140cfbcdSGerrit Uitslag * @param string $url url being directed to
1794af2408d5SAndreas Gohr */
1795af2408d5SAndreas Gohrfunction send_redirect($url) {
1796585bf44eSChristopher Smith    /* @var Input $INPUT */
1797585bf44eSChristopher Smith    global $INPUT;
1798585bf44eSChristopher Smith
17990181f021SAndreas Gohr    //are there any undisplayed messages? keep them in session for display
18000181f021SAndreas Gohr    global $MSG;
18010181f021SAndreas Gohr    if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
18020181f021SAndreas Gohr        //reopen session, store data and close session again
18030181f021SAndreas Gohr        @session_start();
18040181f021SAndreas Gohr        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
18050181f021SAndreas Gohr    }
18060181f021SAndreas Gohr
1807d4869846SAndreas Gohr    // always close the session
1808d4869846SAndreas Gohr    session_write_close();
1809d4869846SAndreas Gohr
1810af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
1811585bf44eSChristopher Smith    if($INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1812585bf44eSChristopher Smith        (strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) &&
1813585bf44eSChristopher Smith        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
18143272d797SAndreas Gohr        $matches[1] < 6
18153272d797SAndreas Gohr    ) {
1816af2408d5SAndreas Gohr        header('Refresh: 0;url='.$url);
1817af2408d5SAndreas Gohr    } else {
1818af2408d5SAndreas Gohr        header('Location: '.$url);
1819af2408d5SAndreas Gohr    }
182081781cb6SAndreas Gohr
182181781cb6SAndreas Gohr    if(defined('DOKU_UNITTEST')) return; // no exits during unit tests
1822af2408d5SAndreas Gohr    exit;
1823af2408d5SAndreas Gohr}
1824af2408d5SAndreas Gohr
18255b75cd1fSAdrian Lang/**
18265b75cd1fSAdrian Lang * Validate a value using a set of valid values
18275b75cd1fSAdrian Lang *
18285b75cd1fSAdrian Lang * This function checks whether a specified value is set and in the array
18295b75cd1fSAdrian Lang * $valid_values. If not, the function returns a default value or, if no
18305b75cd1fSAdrian Lang * default is specified, throws an exception.
18315b75cd1fSAdrian Lang *
18325b75cd1fSAdrian Lang * @param string $param        The name of the parameter
18335b75cd1fSAdrian Lang * @param array  $valid_values A set of valid values; Optionally a default may
18345b75cd1fSAdrian Lang *                             be marked by the key “default”.
18355b75cd1fSAdrian Lang * @param array  $array        The array containing the value (typically $_POST
18365b75cd1fSAdrian Lang *                             or $_GET)
18375b75cd1fSAdrian Lang * @param string $exc          The text of the raised exception
18385b75cd1fSAdrian Lang *
18393272d797SAndreas Gohr * @throws Exception
18403272d797SAndreas Gohr * @return mixed
18415b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
18425b75cd1fSAdrian Lang */
18435b75cd1fSAdrian Langfunction valid_input_set($param, $valid_values, $array, $exc = '') {
18445b75cd1fSAdrian Lang    if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
18455b75cd1fSAdrian Lang        return $array[$param];
18465b75cd1fSAdrian Lang    } elseif(isset($valid_values['default'])) {
18475b75cd1fSAdrian Lang        return $valid_values['default'];
18485b75cd1fSAdrian Lang    } else {
18495b75cd1fSAdrian Lang        throw new Exception($exc);
18505b75cd1fSAdrian Lang    }
18515b75cd1fSAdrian Lang}
18525b75cd1fSAdrian Lang
185363703ba5SAndreas Gohr/**
185463703ba5SAndreas Gohr * Read a preference from the DokuWiki cookie
1855646a531aSChristopher Smith * (remembering both keys & values are urlencoded)
1856140cfbcdSGerrit Uitslag *
1857140cfbcdSGerrit Uitslag * @param string $pref     preference key
1858b4b6c9a1SGerrit Uitslag * @param mixed  $default  value returned when preference not found
1859140cfbcdSGerrit Uitslag * @return string preference value
186063703ba5SAndreas Gohr */
1861554a8c9fSAdrian Langfunction get_doku_pref($pref, $default) {
1862646a531aSChristopher Smith    $enc_pref = urlencode($pref);
1863646a531aSChristopher Smith    if(strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
1864554a8c9fSAdrian Lang        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
186563703ba5SAndreas Gohr        $cnt   = count($parts);
186663703ba5SAndreas Gohr        for($i = 0; $i < $cnt; $i += 2) {
1867646a531aSChristopher Smith            if($parts[$i] == $enc_pref) {
1868646a531aSChristopher Smith                return urldecode($parts[$i + 1]);
1869554a8c9fSAdrian Lang            }
1870554a8c9fSAdrian Lang        }
1871554a8c9fSAdrian Lang    }
1872554a8c9fSAdrian Lang    return $default;
1873554a8c9fSAdrian Lang}
1874554a8c9fSAdrian Lang
18753c94d07bSAnika Henke/**
18763c94d07bSAnika Henke * Add a preference to the DokuWiki cookie
187736ec377eSChristopher Smith * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
1878*3a970889SAnika Henke * Remove it by setting $val to false
1879140cfbcdSGerrit Uitslag *
1880140cfbcdSGerrit Uitslag * @param string $pref  preference key
1881140cfbcdSGerrit Uitslag * @param string $val   preference value
18823c94d07bSAnika Henke */
18833c94d07bSAnika Henkefunction set_doku_pref($pref, $val) {
18843c94d07bSAnika Henke    global $conf;
18853c94d07bSAnika Henke    $orig = get_doku_pref($pref, false);
18863c94d07bSAnika Henke    $cookieVal = '';
18873c94d07bSAnika Henke
18883c94d07bSAnika Henke    if($orig && ($orig != $val)) {
18893c94d07bSAnika Henke        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
18903c94d07bSAnika Henke        $cnt   = count($parts);
189136ec377eSChristopher Smith        // urlencode $pref for the comparison
189236ec377eSChristopher Smith        $enc_pref = rawurlencode($pref);
18933c94d07bSAnika Henke        for($i = 0; $i < $cnt; $i += 2) {
189436ec377eSChristopher Smith            if($parts[$i] == $enc_pref) {
1895*3a970889SAnika Henke                if ($val !== false) {
189636ec377eSChristopher Smith                    $parts[$i + 1] = rawurlencode($val);
1897*3a970889SAnika Henke                } else {
1898*3a970889SAnika Henke                    unset($parts[$i]);
1899*3a970889SAnika Henke                    unset($parts[$i + 1]);
1900*3a970889SAnika Henke                }
190150f261f7SMichael Hamann                break;
19023c94d07bSAnika Henke            }
19033c94d07bSAnika Henke        }
19043c94d07bSAnika Henke        $cookieVal = implode('#', $parts);
1905*3a970889SAnika Henke    } else if (!$orig && $val !== false) {
190636ec377eSChristopher Smith        $cookieVal = ($_COOKIE['DOKU_PREFS'] ? $_COOKIE['DOKU_PREFS'].'#' : '').rawurlencode($pref).'#'.rawurlencode($val);
19073c94d07bSAnika Henke    }
19083c94d07bSAnika Henke
19093c94d07bSAnika Henke    if (!empty($cookieVal)) {
191075e4dd8aSGerrit Uitslag        $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
191175e4dd8aSGerrit Uitslag        setcookie('DOKU_PREFS', $cookieVal, time()+365*24*3600, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
19123c94d07bSAnika Henke    }
19133c94d07bSAnika Henke}
19143c94d07bSAnika Henke
1915f8fb2d18SAndreas Gohr/**
1916f8fb2d18SAndreas Gohr * Strips source mapping declarations from given text #601
1917f8fb2d18SAndreas Gohr *
191842ea7f44SGerrit Uitslag * @param string &$text reference to the CSS or JavaScript code to clean
1919f8fb2d18SAndreas Gohr */
1920f8fb2d18SAndreas Gohrfunction stripsourcemaps(&$text){
1921f8fb2d18SAndreas Gohr    $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text);
1922f8fb2d18SAndreas Gohr}
1923f8fb2d18SAndreas Gohr
1924e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1925