xref: /dokuwiki/inc/common.php (revision 42ea7f447f39fbc2f79eaaec31f8c10ede59c5d0)
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 *
52*42ea7f44SGerrit 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
65*42ea7f44SGerrit 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
99*42ea7f44SGerrit 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));
1912ca9d91cSBen Coburn    $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));
205f3f0262cSandi            $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');
259ee4c4a1bSAndreas 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 *
340*42ea7f44SGerrit Uitslag * @return string[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);
355a77f5846Sjan    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)) {
44316f15a81SDominik Eckelmann        $urlParameters = buildURLparams($urlParameters, $separator);
4446de3759aSAndreas Gohr    } else {
44516f15a81SDominik Eckelmann        $urlParameters = str_replace(',', $separator, $urlParameters);
4466de3759aSAndreas Gohr    }
44716f15a81SDominik Eckelmann    if($id === '') {
44816f15a81SDominik Eckelmann        $id = $conf['start'];
44916f15a81SDominik Eckelmann    }
450f3f0262cSandi    $id = idfilter($id);
45116f15a81SDominik Eckelmann    if($absolute) {
452ed7b5f09Sandi        $xlink = DOKU_URL;
453ed7b5f09Sandi    } else {
454ed7b5f09Sandi        $xlink = DOKU_BASE;
455ed7b5f09Sandi    }
456f3f0262cSandi
4576c7843b5Sandi    if($conf['userewrite'] == 2) {
4586c7843b5Sandi        $xlink .= DOKU_SCRIPT.'/'.$id;
45916f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
4606c7843b5Sandi    } elseif($conf['userewrite']) {
461f3f0262cSandi        $xlink .= $id;
46216f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
463bce3726dSAndreas Gohr    } elseif($id) {
4646c7843b5Sandi        $xlink .= DOKU_SCRIPT.'?id='.$id;
46516f15a81SDominik Eckelmann        if($urlParameters) $xlink .= $separator.$urlParameters;
466bce3726dSAndreas Gohr    } else {
467bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
46816f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
469f3f0262cSandi    }
470f3f0262cSandi
471f3f0262cSandi    return $xlink;
472f3f0262cSandi}
473f3f0262cSandi
474f3f0262cSandi/**
475f5c2808fSBen Coburn * This builds a link to an alternate page format
476f5c2808fSBen Coburn *
477f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
478f5c2808fSBen Coburn *
479f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
4804bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
4814bc480e5SAndreas Gohr * @param string       $format         the export renderer to use
4824bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
4834bc480e5SAndreas Gohr * @param bool         $abs            request an absolute URL instead of relative
4844bc480e5SAndreas Gohr * @param string       $sep            parameter separator
4854bc480e5SAndreas Gohr * @return string
486f5c2808fSBen Coburn */
4874bc480e5SAndreas Gohrfunction exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;') {
488f5c2808fSBen Coburn    global $conf;
4894bc480e5SAndreas Gohr    if(is_array($urlParameters)) {
4904bc480e5SAndreas Gohr        $urlParameters = buildURLparams($urlParameters, $sep);
491f5c2808fSBen Coburn    } else {
4924bc480e5SAndreas Gohr        $urlParameters = str_replace(',', $sep, $urlParameters);
493f5c2808fSBen Coburn    }
494f5c2808fSBen Coburn
495f5c2808fSBen Coburn    $format = rawurlencode($format);
496f5c2808fSBen Coburn    $id     = idfilter($id);
497f5c2808fSBen Coburn    if($abs) {
498f5c2808fSBen Coburn        $xlink = DOKU_URL;
499f5c2808fSBen Coburn    } else {
500f5c2808fSBen Coburn        $xlink = DOKU_BASE;
501f5c2808fSBen Coburn    }
502f5c2808fSBen Coburn
503f5c2808fSBen Coburn    if($conf['userewrite'] == 2) {
504f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
5054bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
506f5c2808fSBen Coburn    } elseif($conf['userewrite'] == 1) {
507f5c2808fSBen Coburn        $xlink .= '_export/'.$format.'/'.$id;
5084bc480e5SAndreas Gohr        if($urlParameters) $xlink .= '?'.$urlParameters;
509f5c2808fSBen Coburn    } else {
510f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
5114bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
512f5c2808fSBen Coburn    }
513f5c2808fSBen Coburn
514f5c2808fSBen Coburn    return $xlink;
515f5c2808fSBen Coburn}
516f5c2808fSBen Coburn
517f5c2808fSBen Coburn/**
5186de3759aSAndreas Gohr * Build a link to a media file
5196de3759aSAndreas Gohr *
5206de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
5218c08db0aSAndreas Gohr *
5228c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
5238c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
5248c08db0aSAndreas Gohr *
5253272d797SAndreas Gohr * @param string  $id     the media file id or URL
5263272d797SAndreas Gohr * @param mixed   $more   string or array with additional parameters
5273272d797SAndreas Gohr * @param bool    $direct link to detail page if false
5283272d797SAndreas Gohr * @param string  $sep    URL parameter separator
5293272d797SAndreas Gohr * @param bool    $abs    Create an absolute URL
5303272d797SAndreas Gohr * @return string
5316de3759aSAndreas Gohr */
53255b2b31bSAndreas Gohrfunction ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false) {
5336de3759aSAndreas Gohr    global $conf;
534b9ee6a44SKlap-in    $isexternalimage = media_isexternal($id);
535826d2766SKlap-in    if(!$isexternalimage) {
536826d2766SKlap-in        $id = cleanID($id);
537826d2766SKlap-in    }
538826d2766SKlap-in
5396de3759aSAndreas Gohr    if(is_array($more)) {
5400f4e0092SChristopher Smith        // add token for resized images
541443e135dSChristopher Smith        if(!empty($more['w']) || !empty($more['h']) || $isexternalimage){
5420f4e0092SChristopher Smith            $more['tok'] = media_get_token($id,$more['w'],$more['h']);
5430f4e0092SChristopher Smith        }
5448c08db0aSAndreas Gohr        // strip defaults for shorter URLs
5458c08db0aSAndreas Gohr        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
546443e135dSChristopher Smith        if(empty($more['w'])) unset($more['w']);
547443e135dSChristopher Smith        if(empty($more['h'])) unset($more['h']);
5488c08db0aSAndreas Gohr        if(isset($more['id']) && $direct) unset($more['id']);
549b174aeaeSchris        $more = buildURLparams($more, $sep);
5506de3759aSAndreas Gohr    } else {
5515e7db1e2SChristopher Smith        $matches = array();
552cc036f74SKlap-in        if (preg_match_all('/\b(w|h)=(\d*)\b/',$more,$matches,PREG_SET_ORDER) || $isexternalimage){
5535e7db1e2SChristopher Smith            $resize = array('w'=>0, 'h'=>0);
5545e7db1e2SChristopher Smith            foreach ($matches as $match){
5555e7db1e2SChristopher Smith                $resize[$match[1]] = $match[2];
5565e7db1e2SChristopher Smith            }
557cc036f74SKlap-in            $more .= $more === '' ? '' : $sep;
558cc036f74SKlap-in            $more .= 'tok='.media_get_token($id,$resize['w'],$resize['h']);
5595e7db1e2SChristopher Smith        }
5608c08db0aSAndreas Gohr        $more = str_replace('cache=cache', '', $more); //skip default
5618c08db0aSAndreas Gohr        $more = str_replace(',,', ',', $more);
562b174aeaeSchris        $more = str_replace(',', $sep, $more);
5636de3759aSAndreas Gohr    }
5646de3759aSAndreas Gohr
56555b2b31bSAndreas Gohr    if($abs) {
56655b2b31bSAndreas Gohr        $xlink = DOKU_URL;
56755b2b31bSAndreas Gohr    } else {
5686de3759aSAndreas Gohr        $xlink = DOKU_BASE;
56955b2b31bSAndreas Gohr    }
5706de3759aSAndreas Gohr
5716de3759aSAndreas Gohr    // external URLs are always direct without rewriting
572826d2766SKlap-in    if($isexternalimage) {
5736de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
574cc036f74SKlap-in        $xlink .= '?'.$more;
575b174aeaeSchris        $xlink .= $sep.'media='.rawurlencode($id);
5766de3759aSAndreas Gohr        return $xlink;
5776de3759aSAndreas Gohr    }
5786de3759aSAndreas Gohr
5796de3759aSAndreas Gohr    $id = idfilter($id);
5806de3759aSAndreas Gohr
5816de3759aSAndreas Gohr    // decide on scriptname
5826de3759aSAndreas Gohr    if($direct) {
5836de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
5846de3759aSAndreas Gohr            $script = '_media';
5856de3759aSAndreas Gohr        } else {
5866de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
5876de3759aSAndreas Gohr        }
5886de3759aSAndreas Gohr    } else {
5896de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
5906de3759aSAndreas Gohr            $script = '_detail';
5916de3759aSAndreas Gohr        } else {
5926de3759aSAndreas Gohr            $script = 'lib/exe/detail.php';
5936de3759aSAndreas Gohr        }
5946de3759aSAndreas Gohr    }
5956de3759aSAndreas Gohr
5966de3759aSAndreas Gohr    // build URL based on rewrite mode
5976de3759aSAndreas Gohr    if($conf['userewrite']) {
5986de3759aSAndreas Gohr        $xlink .= $script.'/'.$id;
5996de3759aSAndreas Gohr        if($more) $xlink .= '?'.$more;
6006de3759aSAndreas Gohr    } else {
6016de3759aSAndreas Gohr        if($more) {
602a99d3236SEsther Brunner            $xlink .= $script.'?'.$more;
603b174aeaeSchris            $xlink .= $sep.'media='.$id;
6046de3759aSAndreas Gohr        } else {
605a99d3236SEsther Brunner            $xlink .= $script.'?media='.$id;
6066de3759aSAndreas Gohr        }
6076de3759aSAndreas Gohr    }
6086de3759aSAndreas Gohr
6096de3759aSAndreas Gohr    return $xlink;
6106de3759aSAndreas Gohr}
6116de3759aSAndreas Gohr
6126de3759aSAndreas Gohr/**
61325ca5b17SAndreas Gohr * Returns the URL to the DokuWiki base script
61415fae107Sandi *
61525ca5b17SAndreas Gohr * Consider using wl() instead, unless you absoutely need the doku.php endpoint
61625ca5b17SAndreas Gohr *
61715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
618140cfbcdSGerrit Uitslag *
619140cfbcdSGerrit Uitslag * @return string
620f3f0262cSandi */
62125ca5b17SAndreas Gohrfunction script() {
622ed7b5f09Sandi    return DOKU_BASE.DOKU_SCRIPT;
623f3f0262cSandi}
624f3f0262cSandi
625f3f0262cSandi/**
62615fae107Sandi * Spamcheck against wordlist
62715fae107Sandi *
628f3f0262cSandi * Checks the wikitext against a list of blocked expressions
629f3f0262cSandi * returns true if the text contains any bad words
63015fae107Sandi *
631e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
632e403cc58SMichael Klier *
633e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
634e403cc58SMichael Klier *  and gain information about the user who was blocked.
635e403cc58SMichael Klier *
636e403cc58SMichael Klier *  Event data:
637e403cc58SMichael Klier *    data['matches']  - array of matches
638e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
639e403cc58SMichael Klier *      [ip]           - ip address
640e403cc58SMichael Klier *      [user]         - username (if logged in)
641e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
642e403cc58SMichael Klier *      [name]         - real name (if logged in)
643e403cc58SMichael Klier *
64415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
6456dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
646140cfbcdSGerrit Uitslag *
6476dffa0e0SAndreas Gohr * @param  string $text - optional text to check, if not given the globals are used
6486dffa0e0SAndreas Gohr * @return bool         - true if a spam word was found
649f3f0262cSandi */
6506dffa0e0SAndreas Gohrfunction checkwordblock($text = '') {
651f3f0262cSandi    global $TEXT;
6526dffa0e0SAndreas Gohr    global $PRE;
6536dffa0e0SAndreas Gohr    global $SUF;
654e0086ca2SAndreas Gohr    global $SUM;
655f3f0262cSandi    global $conf;
656e403cc58SMichael Klier    global $INFO;
657585bf44eSChristopher Smith    /* @var Input $INPUT */
658585bf44eSChristopher Smith    global $INPUT;
659f3f0262cSandi
660f3f0262cSandi    if(!$conf['usewordblock']) return false;
661f3f0262cSandi
662e0086ca2SAndreas Gohr    if(!$text) $text = "$PRE $TEXT $SUF $SUM";
6636dffa0e0SAndreas Gohr
664041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
6656dffa0e0SAndreas Gohr    $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i', '\1http://\2 \2\3', $text);
666041d1964SAndreas Gohr
667b9ac8716Schris    $wordblocks = getWordblocks();
6683e2965d7Sandi    // how many lines to read at once (to work around some PCRE limits)
6693e2965d7Sandi    if(version_compare(phpversion(), '4.3.0', '<')) {
6703e2965d7Sandi        // old versions of PCRE define a maximum of parenthesises even if no
6713e2965d7Sandi        // backreferences are used - the maximum is 99
6723e2965d7Sandi        // this is very bad performancewise and may even be too high still
6733e2965d7Sandi        $chunksize = 40;
6743e2965d7Sandi    } else {
675a51d08efSAndreas Gohr        // read file in chunks of 200 - this should work around the
6763e2965d7Sandi        // MAX_PATTERN_SIZE in modern PCRE
677a51d08efSAndreas Gohr        $chunksize = 200;
6783e2965d7Sandi    }
679b9ac8716Schris    while($blocks = array_splice($wordblocks, 0, $chunksize)) {
680f3f0262cSandi        $re = array();
68149eb6e38SAndreas Gohr        // build regexp from blocks
682f3f0262cSandi        foreach($blocks as $block) {
683f3f0262cSandi            $block = preg_replace('/#.*$/', '', $block);
684f3f0262cSandi            $block = trim($block);
685f3f0262cSandi            if(empty($block)) continue;
686f3f0262cSandi            $re[] = $block;
687f3f0262cSandi        }
688e403cc58SMichael Klier        if(count($re) && preg_match('#('.join('|', $re).')#si', $text, $matches)) {
689e403cc58SMichael Klier            // prepare event data
69059bc3b48SGerrit Uitslag            $data = array();
691e403cc58SMichael Klier            $data['matches']        = $matches;
692585bf44eSChristopher Smith            $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
693585bf44eSChristopher Smith            if($INPUT->server->str('REMOTE_USER')) {
694585bf44eSChristopher Smith                $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
695e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
696e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
697e403cc58SMichael Klier            }
698e403cc58SMichael Klier            $callback = create_function('', 'return true;');
699e403cc58SMichael Klier            return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
700b9ac8716Schris        }
701703f6fdeSandi    }
702f3f0262cSandi    return false;
703f3f0262cSandi}
704f3f0262cSandi
705f3f0262cSandi/**
70615fae107Sandi * Return the IP of the client
70715fae107Sandi *
7086d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
70915fae107Sandi *
7106d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
7116d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
7126d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
7136d8affe6SAndreas Gohr * headers
7146d8affe6SAndreas Gohr *
71515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
716140cfbcdSGerrit Uitslag *
7173272d797SAndreas Gohr * @param  boolean $single If set only a single IP is returned
7183272d797SAndreas Gohr * @return string
719f3f0262cSandi */
7206d8affe6SAndreas Gohrfunction clientIP($single = false) {
721585bf44eSChristopher Smith    /* @var Input $INPUT */
722585bf44eSChristopher Smith    global $INPUT;
723585bf44eSChristopher Smith
7246d8affe6SAndreas Gohr    $ip   = array();
725585bf44eSChristopher Smith    $ip[] = $INPUT->server->str('REMOTE_ADDR');
726585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_FORWARDED_FOR')) {
727585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_FORWARDED_FOR'))));
728585bf44eSChristopher Smith    }
729585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_REAL_IP')) {
730585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_REAL_IP'))));
731585bf44eSChristopher Smith    }
7326d8affe6SAndreas Gohr
733dc14c6d1SGuy Brand    // some IPv4/v6 regexps borrowed from Feyd
734dc14c6d1SGuy Brand    // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
735dc14c6d1SGuy Brand    $dec_octet   = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
736dc14c6d1SGuy Brand    $hex_digit   = '[A-Fa-f0-9]';
737dc14c6d1SGuy Brand    $h16         = "{$hex_digit}{1,4}";
738dc14c6d1SGuy Brand    $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
739dc14c6d1SGuy Brand    $ls32        = "(?:$h16:$h16|$IPv4Address)";
740dc14c6d1SGuy Brand    $IPv6Address =
741dc14c6d1SGuy Brand        "(?:(?:{$IPv4Address})|(?:".
742dc14c6d1SGuy Brand            "(?:$h16:){6}$ls32".
743dc14c6d1SGuy Brand            "|::(?:$h16:){5}$ls32".
744dc14c6d1SGuy Brand            "|(?:$h16)?::(?:$h16:){4}$ls32".
745dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32".
746dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32".
747dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32".
748dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,4}$h16)?::$ls32".
749dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,5}$h16)?::$h16".
750dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,6}$h16)?::".
751dc14c6d1SGuy Brand            ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
752dc14c6d1SGuy Brand
7536d8affe6SAndreas Gohr    // remove any non-IP stuff
7546d8affe6SAndreas Gohr    $cnt   = count($ip);
7554ff28443Schris    $match = array();
7566d8affe6SAndreas Gohr    for($i = 0; $i < $cnt; $i++) {
757dc14c6d1SGuy Brand        if(preg_match("/^$IPv4Address$/", $ip[$i], $match) || preg_match("/^$IPv6Address$/", $ip[$i], $match)) {
7584ff28443Schris            $ip[$i] = $match[0];
7594ff28443Schris        } else {
7604ff28443Schris            $ip[$i] = '';
7614ff28443Schris        }
7626d8affe6SAndreas Gohr        if(empty($ip[$i])) unset($ip[$i]);
763f3f0262cSandi    }
7646d8affe6SAndreas Gohr    $ip = array_values(array_unique($ip));
7656d8affe6SAndreas Gohr    if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
7666d8affe6SAndreas Gohr
7676d8affe6SAndreas Gohr    if(!$single) return join(',', $ip);
7686d8affe6SAndreas Gohr
7696d8affe6SAndreas Gohr    // decide which IP to use, trying to avoid local addresses
7706d8affe6SAndreas Gohr    $ip = array_reverse($ip);
7716d8affe6SAndreas Gohr    foreach($ip as $i) {
7722343a762SAndreas Gohr        if(preg_match('/^(::1|[fF][eE]80:|127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/', $i)) {
7736d8affe6SAndreas Gohr            continue;
7746d8affe6SAndreas Gohr        } else {
7756d8affe6SAndreas Gohr            return $i;
7766d8affe6SAndreas Gohr        }
7776d8affe6SAndreas Gohr    }
7786d8affe6SAndreas Gohr    // still here? just use the first (last) address
7796d8affe6SAndreas Gohr    return $ip[0];
780f3f0262cSandi}
781f3f0262cSandi
782f3f0262cSandi/**
7831c548ebeSAndreas Gohr * Check if the browser is on a mobile device
7841c548ebeSAndreas Gohr *
7851c548ebeSAndreas Gohr * Adapted from the example code at url below
7861c548ebeSAndreas Gohr *
7871c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
788140cfbcdSGerrit Uitslag *
789140cfbcdSGerrit Uitslag * @return bool if true, client is mobile browser; otherwise false
7901c548ebeSAndreas Gohr */
7911c548ebeSAndreas Gohrfunction clientismobile() {
792585bf44eSChristopher Smith    /* @var Input $INPUT */
793585bf44eSChristopher Smith    global $INPUT;
7941c548ebeSAndreas Gohr
795585bf44eSChristopher Smith    if($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
7961c548ebeSAndreas Gohr
797585bf44eSChristopher Smith    if(preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
7981c548ebeSAndreas Gohr
799585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_USER_AGENT')) return false;
8001c548ebeSAndreas Gohr
8011c548ebeSAndreas 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';
8021c548ebeSAndreas Gohr
803585bf44eSChristopher Smith    if(preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
8041c548ebeSAndreas Gohr
8051c548ebeSAndreas Gohr    return false;
8061c548ebeSAndreas Gohr}
8071c548ebeSAndreas Gohr
8081c548ebeSAndreas Gohr/**
80963211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
81063211f61SGlen Harris *
81122ef1e32SAndreas Gohr * If $conf['dnslookups'] is disabled it simply returns the input string
81222ef1e32SAndreas Gohr *
81363211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
814140cfbcdSGerrit Uitslag *
8153272d797SAndreas Gohr * @param  string $ips comma separated list of IP addresses
8163272d797SAndreas Gohr * @return string a comma separated list of hostnames
81763211f61SGlen Harris */
81863211f61SGlen Harrisfunction gethostsbyaddrs($ips) {
81922ef1e32SAndreas Gohr    global $conf;
82022ef1e32SAndreas Gohr    if(!$conf['dnslookups']) return $ips;
82122ef1e32SAndreas Gohr
82263211f61SGlen Harris    $hosts = array();
82363211f61SGlen Harris    $ips   = explode(',', $ips);
824551a720fSMichael Klier
825551a720fSMichael Klier    if(is_array($ips)) {
8263886270dSAndreas Gohr        foreach($ips as $ip) {
827551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
82863211f61SGlen Harris        }
829551a720fSMichael Klier        return join(',', $hosts);
830551a720fSMichael Klier    } else {
831551a720fSMichael Klier        return gethostbyaddr(trim($ips));
832551a720fSMichael Klier    }
83363211f61SGlen Harris}
83463211f61SGlen Harris
83563211f61SGlen Harris/**
83615fae107Sandi * Checks if a given page is currently locked.
83715fae107Sandi *
838f3f0262cSandi * removes stale lockfiles
83915fae107Sandi *
84015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
841140cfbcdSGerrit Uitslag *
842140cfbcdSGerrit Uitslag * @param string $id page id
843140cfbcdSGerrit Uitslag * @return bool page is locked?
844f3f0262cSandi */
845f3f0262cSandifunction checklock($id) {
846f3f0262cSandi    global $conf;
847585bf44eSChristopher Smith    /* @var Input $INPUT */
848585bf44eSChristopher Smith    global $INPUT;
849585bf44eSChristopher Smith
850c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
851f3f0262cSandi
852f3f0262cSandi    //no lockfile
853f3f0262cSandi    if(!@file_exists($lock)) return false;
854f3f0262cSandi
855f3f0262cSandi    //lockfile expired
856f3f0262cSandi    if((time() - filemtime($lock)) > $conf['locktime']) {
857d8186216SBen Coburn        @unlink($lock);
858f3f0262cSandi        return false;
859f3f0262cSandi    }
860f3f0262cSandi
861f3f0262cSandi    //my own lock
8626d2af55dSChristopher Smith    @list($ip, $session) = explode("\n", io_readFile($lock));
8630712fefaSAndreas Gohr    if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || (session_id() && $session == session_id())) {
864f3f0262cSandi        return false;
865f3f0262cSandi    }
866f3f0262cSandi
867f3f0262cSandi    return $ip;
868f3f0262cSandi}
869f3f0262cSandi
870f3f0262cSandi/**
87115fae107Sandi * Lock a page for editing
87215fae107Sandi *
87315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
874140cfbcdSGerrit Uitslag *
875140cfbcdSGerrit Uitslag * @param string $id page id to lock
876f3f0262cSandi */
877f3f0262cSandifunction lock($id) {
878544ed901SDaniel Calviño Sánchez    global $conf;
879585bf44eSChristopher Smith    /* @var Input $INPUT */
880585bf44eSChristopher Smith    global $INPUT;
881544ed901SDaniel Calviño Sánchez
882544ed901SDaniel Calviño Sánchez    if($conf['locktime'] == 0) {
883544ed901SDaniel Calviño Sánchez        return;
884544ed901SDaniel Calviño Sánchez    }
885544ed901SDaniel Calviño Sánchez
886c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
887585bf44eSChristopher Smith    if($INPUT->server->str('REMOTE_USER')) {
888585bf44eSChristopher Smith        io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
889f3f0262cSandi    } else {
89085fef7e2SAndreas Gohr        io_saveFile($lock, clientIP()."\n".session_id());
891f3f0262cSandi    }
892f3f0262cSandi}
893f3f0262cSandi
894f3f0262cSandi/**
89515fae107Sandi * Unlock a page if it was locked by the user
896f3f0262cSandi *
89715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
898140cfbcdSGerrit Uitslag *
8993272d797SAndreas Gohr * @param string $id page id to unlock
90015fae107Sandi * @return bool true if a lock was removed
901f3f0262cSandi */
902f3f0262cSandifunction unlock($id) {
903585bf44eSChristopher Smith    /* @var Input $INPUT */
904585bf44eSChristopher Smith    global $INPUT;
905585bf44eSChristopher Smith
906c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
907f3f0262cSandi    if(@file_exists($lock)) {
9086d2af55dSChristopher Smith        @list($ip, $session) = explode("\n", io_readFile($lock));
909585bf44eSChristopher Smith        if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || $session == session_id()) {
910f3f0262cSandi            @unlink($lock);
911f3f0262cSandi            return true;
912f3f0262cSandi        }
913f3f0262cSandi    }
914f3f0262cSandi    return false;
915f3f0262cSandi}
916f3f0262cSandi
917f3f0262cSandi/**
918f3f0262cSandi * convert line ending to unix format
919f3f0262cSandi *
9206db7468bSAndreas Gohr * also makes sure the given text is valid UTF-8
9216db7468bSAndreas Gohr *
92215fae107Sandi * @see    formText() for 2crlf conversion
92315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
924140cfbcdSGerrit Uitslag *
925140cfbcdSGerrit Uitslag * @param string $text
926140cfbcdSGerrit Uitslag * @return string
927f3f0262cSandi */
928f3f0262cSandifunction cleanText($text) {
929f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
9306db7468bSAndreas Gohr
9316db7468bSAndreas Gohr    // if the text is not valid UTF-8 we simply assume latin1
9326db7468bSAndreas Gohr    // this won't break any worse than it breaks with the wrong encoding
9336db7468bSAndreas Gohr    // but might actually fix the problem in many cases
9346db7468bSAndreas Gohr    if(!utf8_check($text)) $text = utf8_encode($text);
9356db7468bSAndreas Gohr
936f3f0262cSandi    return $text;
937f3f0262cSandi}
938f3f0262cSandi
939f3f0262cSandi/**
940f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
941f3f0262cSandi * It also converts line endings to Windows format which is
942f3f0262cSandi * pseudo standard for webforms.
943f3f0262cSandi *
94415fae107Sandi * @see    cleanText() for 2unix conversion
94515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
946140cfbcdSGerrit Uitslag *
947140cfbcdSGerrit Uitslag * @param string $text
948140cfbcdSGerrit Uitslag * @return string
949f3f0262cSandi */
950f3f0262cSandifunction formText($text) {
9515b7d45a5SAndreas Gohr    $text = str_replace("\012", "\015\012", $text);
952f3f0262cSandi    return htmlspecialchars($text);
953f3f0262cSandi}
954f3f0262cSandi
955f3f0262cSandi/**
95615fae107Sandi * Returns the specified local text in raw format
95715fae107Sandi *
95815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
959140cfbcdSGerrit Uitslag *
960140cfbcdSGerrit Uitslag * @param string $id   page id
961140cfbcdSGerrit Uitslag * @param string $ext  extension of file being read, default 'txt'
962140cfbcdSGerrit Uitslag * @return string
963f3f0262cSandi */
9642adaf2b8SAndreas Gohrfunction rawLocale($id, $ext = 'txt') {
9652adaf2b8SAndreas Gohr    return io_readFile(localeFN($id, $ext));
966f3f0262cSandi}
967f3f0262cSandi
968f3f0262cSandi/**
969f3f0262cSandi * Returns the raw WikiText
97015fae107Sandi *
97115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
972140cfbcdSGerrit Uitslag *
973140cfbcdSGerrit Uitslag * @param string $id   page id
974e0c26282SGerrit Uitslag * @param string|int $rev  timestamp when a revision of wikitext is desired
975140cfbcdSGerrit Uitslag * @return string
976f3f0262cSandi */
977f3f0262cSandifunction rawWiki($id, $rev = '') {
978cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
979f3f0262cSandi}
980f3f0262cSandi
981f3f0262cSandi/**
9827146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
9837146cee2SAndreas Gohr *
9847b84afa2SAndreas Gohr * @triggers COMMON_PAGETPL_LOAD
9857146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
986140cfbcdSGerrit Uitslag *
987140cfbcdSGerrit Uitslag * @param string $id the id of the page to be created
988140cfbcdSGerrit Uitslag * @return string parsed pagetemplate content
9897146cee2SAndreas Gohr */
990fe17917eSAdrian Langfunction pageTemplate($id) {
991a15ce62dSEsther Brunner    global $conf;
992e29549feSAndreas Gohr
993fe17917eSAdrian Lang    if(is_array($id)) $id = $id[0];
994e29549feSAndreas Gohr
9957b84afa2SAndreas Gohr    // prepare initial event data
9967b84afa2SAndreas Gohr    $data = array(
9977b84afa2SAndreas Gohr        'id'        => $id, // the id of the page to be created
9987b84afa2SAndreas Gohr        'tpl'       => '', // the text used as template
9997b84afa2SAndreas Gohr        'tplfile'   => '', // the file above text was/should be loaded from
10007b84afa2SAndreas Gohr        'doreplace' => true // should wildcard replacements be done on the text?
10017b84afa2SAndreas Gohr    );
10027b84afa2SAndreas Gohr
10037b84afa2SAndreas Gohr    $evt = new Doku_Event('COMMON_PAGETPL_LOAD', $data);
10047b84afa2SAndreas Gohr    if($evt->advise_before(true)) {
10057b84afa2SAndreas Gohr        // the before event might have loaded the content already
10067b84afa2SAndreas Gohr        if(empty($data['tpl'])) {
10077b84afa2SAndreas Gohr            // if the before event did not set a template file, try to find one
10087b84afa2SAndreas Gohr            if(empty($data['tplfile'])) {
1009fe17917eSAdrian Lang                $path = dirname(wikiFN($id));
1010e29549feSAndreas Gohr                if(@file_exists($path.'/_template.txt')) {
10117b84afa2SAndreas Gohr                    $data['tplfile'] = $path.'/_template.txt';
1012e29549feSAndreas Gohr                } else {
1013e29549feSAndreas Gohr                    // search upper namespaces for templates
1014e29549feSAndreas Gohr                    $len = strlen(rtrim($conf['datadir'], '/'));
1015e29549feSAndreas Gohr                    while(strlen($path) >= $len) {
1016e29549feSAndreas Gohr                        if(@file_exists($path.'/__template.txt')) {
10177b84afa2SAndreas Gohr                            $data['tplfile'] = $path.'/__template.txt';
1018e29549feSAndreas Gohr                            break;
1019e29549feSAndreas Gohr                        }
1020e29549feSAndreas Gohr                        $path = substr($path, 0, strrpos($path, '/'));
1021e29549feSAndreas Gohr                    }
1022e29549feSAndreas Gohr                }
10237b84afa2SAndreas Gohr            }
10247b84afa2SAndreas Gohr            // load the content
10253d7ac595SMichael Hamann            $data['tpl'] = io_readFile($data['tplfile']);
10267b84afa2SAndreas Gohr        }
1027a1bbd05bSMichael Hamann        if($data['doreplace']) parsePageTemplate($data);
10287b84afa2SAndreas Gohr    }
10297b84afa2SAndreas Gohr    $evt->advise_after();
10307b84afa2SAndreas Gohr    unset($evt);
10317b84afa2SAndreas Gohr
1032fe17917eSAdrian Lang    return $data['tpl'];
10332b1223ecSAdrian Lang}
10342b1223ecSAdrian Lang
10352b1223ecSAdrian Lang/**
10362b1223ecSAdrian Lang * Performs common page template replacements
10377b84afa2SAndreas Gohr * This works on data from COMMON_PAGETPL_LOAD
10382b1223ecSAdrian Lang *
10392b1223ecSAdrian Lang * @author Andreas Gohr <andi@splitbrain.org>
1040140cfbcdSGerrit Uitslag *
1041140cfbcdSGerrit Uitslag * @param array $data array with event data
1042140cfbcdSGerrit Uitslag * @return string
10432b1223ecSAdrian Lang */
1044d535a2e9Sstretchyboyfunction parsePageTemplate(&$data) {
10453272d797SAndreas Gohr    /**
10463272d797SAndreas Gohr     * @var string $id        the id of the page to be created
10473272d797SAndreas Gohr     * @var string $tpl       the text used as template
10483272d797SAndreas Gohr     * @var string $tplfile   the file above text was/should be loaded from
10493272d797SAndreas Gohr     * @var bool   $doreplace should wildcard replacements be done on the text?
10503272d797SAndreas Gohr     */
1051fe17917eSAdrian Lang    extract($data);
1052fe17917eSAdrian Lang
1053b856f7dfSAdrian Lang    global $USERINFO;
1054bce53b1fSAdrian Lang    global $conf;
1055585bf44eSChristopher Smith    /* @var Input $INPUT */
1056585bf44eSChristopher Smith    global $INPUT;
1057e29549feSAndreas Gohr
1058e29549feSAndreas Gohr    // replace placeholders
105926ece5a7SAndreas Gohr    $file = noNS($id);
106037c1acbdSAdrian Lang    $page = strtr($file, $conf['sepchar'], ' ');
106126ece5a7SAndreas Gohr
10623272d797SAndreas Gohr    $tpl = str_replace(
10633272d797SAndreas Gohr        array(
106426ece5a7SAndreas Gohr             '@ID@',
106526ece5a7SAndreas Gohr             '@NS@',
106626ece5a7SAndreas Gohr             '@FILE@',
106726ece5a7SAndreas Gohr             '@!FILE@',
106826ece5a7SAndreas Gohr             '@!FILE!@',
106926ece5a7SAndreas Gohr             '@PAGE@',
107026ece5a7SAndreas Gohr             '@!PAGE@',
107126ece5a7SAndreas Gohr             '@!!PAGE@',
107226ece5a7SAndreas Gohr             '@!PAGE!@',
107326ece5a7SAndreas Gohr             '@USER@',
107426ece5a7SAndreas Gohr             '@NAME@',
107526ece5a7SAndreas Gohr             '@MAIL@',
107626ece5a7SAndreas Gohr             '@DATE@',
107726ece5a7SAndreas Gohr        ),
107826ece5a7SAndreas Gohr        array(
107926ece5a7SAndreas Gohr             $id,
108026ece5a7SAndreas Gohr             getNS($id),
108126ece5a7SAndreas Gohr             $file,
108226ece5a7SAndreas Gohr             utf8_ucfirst($file),
108326ece5a7SAndreas Gohr             utf8_strtoupper($file),
108426ece5a7SAndreas Gohr             $page,
108526ece5a7SAndreas Gohr             utf8_ucfirst($page),
108626ece5a7SAndreas Gohr             utf8_ucwords($page),
108726ece5a7SAndreas Gohr             utf8_strtoupper($page),
1088585bf44eSChristopher Smith             $INPUT->server->str('REMOTE_USER'),
1089b856f7dfSAdrian Lang             $USERINFO['name'],
1090b856f7dfSAdrian Lang             $USERINFO['mail'],
109126ece5a7SAndreas Gohr             $conf['dformat'],
10923272d797SAndreas Gohr        ), $tpl
10933272d797SAndreas Gohr    );
109426ece5a7SAndreas Gohr
10957d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
10967d644fc8SAndreas Gohr    $tpl         = preg_replace_callback('/%./', create_function('$m', 'return strftime($m[0]);'), $tpl);
1097d535a2e9Sstretchyboy    $data['tpl'] = $tpl;
1098a15ce62dSEsther Brunner    return $tpl;
10997146cee2SAndreas Gohr}
11007146cee2SAndreas Gohr
11017146cee2SAndreas Gohr/**
110215fae107Sandi * Returns the raw Wiki Text in three slices.
110315fae107Sandi *
110415fae107Sandi * The range parameter needs to have the form "from-to"
110515cfe303Sandi * and gives the range of the section in bytes - no
110615cfe303Sandi * UTF-8 awareness is needed.
1107f3f0262cSandi * The returned order is prefix, section and suffix.
110815fae107Sandi *
110915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1110140cfbcdSGerrit Uitslag *
1111140cfbcdSGerrit Uitslag * @param string $range in form "from-to"
1112140cfbcdSGerrit Uitslag * @param string $id    page id
1113140cfbcdSGerrit Uitslag * @param string $rev   optional, the revision timestamp
1114*42ea7f44SGerrit Uitslag * @return string[] with three slices
1115f3f0262cSandi */
1116f3f0262cSandifunction rawWikiSlices($range, $id, $rev = '') {
1117cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1118f3f0262cSandi
111980fcb268SAdrian Lang    // Parse range
112080fcb268SAdrian Lang    list($from, $to) = explode('-', $range, 2);
112180fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
112280fcb268SAdrian Lang    $from = !$from ? 0 : ($from - 1);
112380fcb268SAdrian Lang    $to   = !$to ? strlen($text) : ($to - 1);
112480fcb268SAdrian Lang
112559bc3b48SGerrit Uitslag    $slices = array();
112680fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
112780fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to - $from);
112815cfe303Sandi    $slices[2] = substr($text, $to);
1129f3f0262cSandi    return $slices;
1130f3f0262cSandi}
1131f3f0262cSandi
1132f3f0262cSandi/**
113315fae107Sandi * Joins wiki text slices
113415fae107Sandi *
113580fcb268SAdrian Lang * function to join the text slices.
1136f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
1137f3f0262cSandi * lines between sections if needed (used on saving).
113815fae107Sandi *
113915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1140140cfbcdSGerrit Uitslag *
1141140cfbcdSGerrit Uitslag * @param string $pre   prefix
1142140cfbcdSGerrit Uitslag * @param string $text  text in the middle
1143140cfbcdSGerrit Uitslag * @param string $suf   suffix
1144140cfbcdSGerrit Uitslag * @param bool $pretty add additional empty lines between sections
1145140cfbcdSGerrit Uitslag * @return string
1146f3f0262cSandi */
1147f3f0262cSandifunction con($pre, $text, $suf, $pretty = false) {
1148f3f0262cSandi    if($pretty) {
114980fcb268SAdrian Lang        if($pre !== '' && substr($pre, -1) !== "\n" &&
11503272d797SAndreas Gohr            substr($text, 0, 1) !== "\n"
11513272d797SAndreas Gohr        ) {
115280fcb268SAdrian Lang            $pre .= "\n";
115380fcb268SAdrian Lang        }
115480fcb268SAdrian Lang        if($suf !== '' && substr($text, -1) !== "\n" &&
11553272d797SAndreas Gohr            substr($suf, 0, 1) !== "\n"
11563272d797SAndreas Gohr        ) {
115780fcb268SAdrian Lang            $text .= "\n";
115880fcb268SAdrian Lang        }
1159f3f0262cSandi    }
1160f3f0262cSandi
1161f3f0262cSandi    return $pre.$text.$suf;
1162f3f0262cSandi}
1163f3f0262cSandi
1164f3f0262cSandi/**
1165a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
1166a701424fSBen Coburn * Also directs changelog and attic updates.
116715fae107Sandi *
116815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
116971726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
1170140cfbcdSGerrit Uitslag *
1171140cfbcdSGerrit Uitslag * @param string $id       page id
1172140cfbcdSGerrit Uitslag * @param string $text     wikitext being saved
1173140cfbcdSGerrit Uitslag * @param string $summary  summary of text update
1174140cfbcdSGerrit Uitslag * @param bool   $minor    mark this saved version as minor update
1175f3f0262cSandi */
1176b6912aeaSAndreas Gohrfunction saveWikiText($id, $text, $summary, $minor = false) {
1177a701424fSBen Coburn    /* Note to developers:
1178a701424fSBen Coburn       This code is subtle and delicate. Test the behavior of
1179a701424fSBen Coburn       the attic and changelog with dokuwiki and external edits
1180a701424fSBen Coburn       after any changes. External edits change the wiki page
1181a701424fSBen Coburn       directly without using php or dokuwiki.
1182a701424fSBen Coburn     */
1183f3f0262cSandi    global $conf;
1184f3f0262cSandi    global $lang;
118571726d78SBen Coburn    global $REV;
1186585bf44eSChristopher Smith    /* @var Input $INPUT */
1187585bf44eSChristopher Smith    global $INPUT;
1188585bf44eSChristopher Smith
1189f3f0262cSandi    // ignore if no changes were made
1190f3f0262cSandi    if($text == rawWiki($id, '')) {
1191f3f0262cSandi        return;
1192f3f0262cSandi    }
1193f3f0262cSandi
1194f3f0262cSandi    $file        = wikiFN($id);
1195a701424fSBen Coburn    $old         = @filemtime($file); // from page
1196407e65b9SAndreas Gohr    $wasRemoved  = (trim($text) == ''); // check for empty or whitespace only
1197d8186216SBen Coburn    $wasCreated  = !@file_exists($file);
119871726d78SBen Coburn    $wasReverted = ($REV == true);
1199047bad06SGerrit Uitslag    $pagelog     = new PageChangeLog($id, 1024);
1200e45b34cdSBen Coburn    $newRev      = false;
1201f523c971SGerrit Uitslag    $oldRev      = $pagelog->getRevisions(-1, 1); // from changelog
1202a701424fSBen Coburn    $oldRev      = (int) (empty($oldRev) ? 0 : $oldRev[0]);
1203a701424fSBen Coburn    if(!@file_exists(wikiFN($id, $old)) && @file_exists($file) && $old >= $oldRev) {
120446844156SBen Coburn        // add old revision to the attic if missing
120546844156SBen Coburn        saveOldRevision($id);
120646844156SBen Coburn        // add a changelog entry if this edit came from outside dokuwiki
1207a701424fSBen Coburn        if($old > $oldRev) {
1208ebf1501fSBen Coburn            addLogEntry($old, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=> true));
120946844156SBen Coburn            // remove soon to be stale instructions
121046844156SBen Coburn            $cache = new cache_instructions($id, $file);
121146844156SBen Coburn            $cache->removeCache();
121246844156SBen Coburn        }
121346844156SBen Coburn    }
1214f3f0262cSandi
121571726d78SBen Coburn    if($wasRemoved) {
121630725328SGabriel Birke        // Send "update" event with empty data, so plugins can react to page deletion
121730725328SGabriel Birke        $data = array(array($file, '', false), getNS($id), noNS($id), false);
121830725328SGabriel Birke        trigger_event('IO_WIKIPAGE_WRITE', $data);
1219e45b34cdSBen Coburn        // pre-save deleted revision
1220e45b34cdSBen Coburn        @touch($file);
122146844156SBen Coburn        clearstatcache();
1222e45b34cdSBen Coburn        $newRev = saveOldRevision($id);
1223e1f3d9e1SEsther Brunner        // remove empty file
1224f3f0262cSandi        @unlink($file);
1225c5f92742SMichael Hamann        // don't remove old meta info as it should be saved, plugins can use IO_WIKIPAGE_WRITE for removing their metadata...
1226c5f92742SMichael Hamann        // purge non-persistant meta data
12273d1f9ec3SMichael Klier        p_purge_metadata($id);
1228f3f0262cSandi        $del = true;
12293ce054b3Sandi        // autoset summary on deletion
12303ce054b3Sandi        if(empty($summary)) $summary = $lang['deleted'];
123153d6ccfeSandi        // remove empty namespaces
1232cc7d0c94SBen Coburn        io_sweepNS($id, 'datadir');
1233cc7d0c94SBen Coburn        io_sweepNS($id, 'mediadir');
1234f3f0262cSandi    } else {
1235cc7d0c94SBen Coburn        // save file (namespace dir is created in io_writeWikiPage)
1236cc7d0c94SBen Coburn        io_writeWikiPage($file, $text, $id);
123746844156SBen Coburn        // pre-save the revision, to keep the attic in sync
123846844156SBen Coburn        $newRev = saveOldRevision($id);
1239f3f0262cSandi        $del    = false;
1240f3f0262cSandi    }
1241f3f0262cSandi
124271726d78SBen Coburn    // select changelog line type
124371726d78SBen Coburn    $extra = '';
1244ebf1501fSBen Coburn    $type  = DOKU_CHANGE_TYPE_EDIT;
124571726d78SBen Coburn    if($wasReverted) {
1246ebf1501fSBen Coburn        $type  = DOKU_CHANGE_TYPE_REVERT;
124771726d78SBen Coburn        $extra = $REV;
12483272d797SAndreas Gohr    } else if($wasCreated) {
12493272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_CREATE;
12503272d797SAndreas Gohr    } else if($wasRemoved) {
12513272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_DELETE;
1252585bf44eSChristopher Smith    } else if($minor && $conf['useacl'] && $INPUT->server->str('REMOTE_USER')) {
12533272d797SAndreas Gohr        $type = DOKU_CHANGE_TYPE_MINOR_EDIT;
12543272d797SAndreas Gohr    } //minor edits only for logged in users
125571726d78SBen Coburn
1256e45b34cdSBen Coburn    addLogEntry($newRev, $id, $type, $summary, $extra);
125726a0801fSAndreas Gohr    // send notify mails
125890033e9dSAndreas Gohr    notify($id, 'admin', $old, $summary, $minor);
125990033e9dSAndreas Gohr    notify($id, 'subscribers', $old, $summary, $minor);
1260f3f0262cSandi
1261ce6b63d9Schris    // update the purgefile (timestamp of the last time anything within the wiki was changed)
126298407a7aSandi    io_saveFile($conf['cachedir'].'/purgefile', time());
12632eccbdaaSGina Haeussge
12642eccbdaaSGina Haeussge    // if useheading is enabled, purge the cache of all linking pages
1265fe9ec250SChris Smith    if(useHeading('content')) {
126607ff0babSMichael Hamann        $pages = ft_backlinks($id, true);
12672eccbdaaSGina Haeussge        foreach($pages as $page) {
12682eccbdaaSGina Haeussge            $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
12692eccbdaaSGina Haeussge            $cache->removeCache();
12702eccbdaaSGina Haeussge        }
12712eccbdaaSGina Haeussge    }
1272f3f0262cSandi}
1273f3f0262cSandi
1274f3f0262cSandi/**
1275f3f0262cSandi * moves the current version to the attic and returns its
1276f3f0262cSandi * revision date
127715fae107Sandi *
127815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1279140cfbcdSGerrit Uitslag *
1280140cfbcdSGerrit Uitslag * @param string $id page id
1281140cfbcdSGerrit Uitslag * @return int|string revision timestamp
1282f3f0262cSandi */
1283f3f0262cSandifunction saveOldRevision($id) {
1284f3f0262cSandi    $oldf = wikiFN($id);
1285f3f0262cSandi    if(!@file_exists($oldf)) return '';
1286f3f0262cSandi    $date = filemtime($oldf);
1287f3f0262cSandi    $newf = wikiFN($id, $date);
1288cc7d0c94SBen Coburn    io_writeWikiPage($newf, rawWiki($id), $id, $date);
1289f3f0262cSandi    return $date;
1290f3f0262cSandi}
1291f3f0262cSandi
1292f3f0262cSandi/**
1293fde10de4SAdrian Lang * Sends a notify mail on page change or registration
129426a0801fSAndreas Gohr *
129526a0801fSAndreas Gohr * @param string     $id       The changed page
1296fde10de4SAdrian Lang * @param string     $who      Who to notify (admin|subscribers|register)
12973272d797SAndreas Gohr * @param int|string $rev Old page revision
129826a0801fSAndreas Gohr * @param string     $summary  What changed
129990033e9dSAndreas Gohr * @param boolean    $minor    Is this a minor edit?
1300*42ea7f44SGerrit Uitslag * @param string[]   $replace  Additional string substitutions, @KEY@ to be replaced by value
13013272d797SAndreas Gohr * @return bool
1302140cfbcdSGerrit Uitslag *
130315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1304f3f0262cSandi */
130502a498e7Schrisfunction notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array()) {
1306f3f0262cSandi    global $conf;
1307585bf44eSChristopher Smith    /* @var Input $INPUT */
1308585bf44eSChristopher Smith    global $INPUT;
1309b158d625SSteven Danz
13106df843eeSAndreas Gohr    // decide if there is something to do, eg. whom to mail
131126a0801fSAndreas Gohr    if($who == 'admin') {
13123272d797SAndreas Gohr        if(empty($conf['notify'])) return false; //notify enabled?
13132ed38036SAndreas Gohr        $tpl = 'mailtext';
131426a0801fSAndreas Gohr        $to  = $conf['notify'];
131526a0801fSAndreas Gohr    } elseif($who == 'subscribers') {
131684c1127cSAndreas Gohr        if(!actionOK('subscribe')) return false; //subscribers enabled?
1317585bf44eSChristopher Smith        if($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
13180bb37868SGerrit Uitslag        $data = array('id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace);
13193272d797SAndreas Gohr        trigger_event(
13203272d797SAndreas Gohr            'COMMON_NOTIFY_ADDRESSLIST', $data,
1321835242b0SAndreas Gohr            array(new Subscription(), 'notifyaddresses')
13223272d797SAndreas Gohr        );
13232ed38036SAndreas Gohr        $to = $data['addresslist'];
13242ed38036SAndreas Gohr        if(empty($to)) return false;
13252ed38036SAndreas Gohr        $tpl = 'subscr_single';
132626a0801fSAndreas Gohr    } else {
13273272d797SAndreas Gohr        return false; //just to be safe
132826a0801fSAndreas Gohr    }
132926a0801fSAndreas Gohr
13306df843eeSAndreas Gohr    // prepare content
13312ed38036SAndreas Gohr    $subscription = new Subscription();
13322ed38036SAndreas Gohr    return $subscription->send_diff($to, $tpl, $id, $rev, $summary);
1333f3f0262cSandi}
13342ed38036SAndreas Gohr
133515fae107Sandi/**
133671f7bde7SAndreas Gohr * extracts the query from a search engine referrer
133715fae107Sandi *
133815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
133971f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1340140cfbcdSGerrit Uitslag *
1341140cfbcdSGerrit Uitslag * @return array|string
1342f3f0262cSandi */
1343f3f0262cSandifunction getGoogleQuery() {
1344585bf44eSChristopher Smith    /* @var Input $INPUT */
1345585bf44eSChristopher Smith    global $INPUT;
1346585bf44eSChristopher Smith
1347585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_REFERER')) {
1348c66972f2SAdrian Lang        return '';
1349c66972f2SAdrian Lang    }
1350585bf44eSChristopher Smith    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1351f3f0262cSandi
1352079b3ac1SAndreas Gohr    // only handle common SEs
1353079b3ac1SAndreas Gohr    if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/',$url['host'])) return '';
1354e4d8a516SKazutaka Miyasaka
1355079b3ac1SAndreas Gohr    $query = array();
1356e4d8a516SKazutaka Miyasaka    // temporary workaround against PHP bug #49733
1357e4d8a516SKazutaka Miyasaka    // see http://bugs.php.net/bug.php?id=49733
1358e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) $enc = mb_internal_encoding();
1359f3f0262cSandi    parse_str($url['query'], $query);
1360e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) mb_internal_encoding($enc);
1361e4d8a516SKazutaka Miyasaka
1362c66972f2SAdrian Lang    $q = '';
1363079b3ac1SAndreas Gohr    if(isset($query['q'])){
1364079b3ac1SAndreas Gohr        $q = $query['q'];
1365079b3ac1SAndreas Gohr    }elseif(isset($query['p'])){
1366079b3ac1SAndreas Gohr        $q = $query['p'];
1367079b3ac1SAndreas Gohr    }elseif(isset($query['query'])){
1368079b3ac1SAndreas Gohr        $q = $query['query'];
1369079b3ac1SAndreas Gohr    }
1370079b3ac1SAndreas Gohr    $q = trim($q);
1371f3f0262cSandi
1372079b3ac1SAndreas Gohr    if(!$q) return '';
13736531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1374f93b3b50SAndreas Gohr    return $q;
1375f3f0262cSandi}
1376f3f0262cSandi
1377f3f0262cSandi/**
1378f3f0262cSandi * Return the human readable size of a file
1379f3f0262cSandi *
1380f3f0262cSandi * @param int $size A file size
1381f3f0262cSandi * @param int $dec A number of decimal places
138274160ca1SGerrit Uitslag * @return string human readable size
1383140cfbcdSGerrit Uitslag *
1384f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1385f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1386f3f0262cSandi * @version     1.0.0
1387f3f0262cSandi */
1388f31d5b73Sandifunction filesize_h($size, $dec = 1) {
1389f3f0262cSandi    $sizes = array('B', 'KB', 'MB', 'GB');
1390f3f0262cSandi    $count = count($sizes);
1391f3f0262cSandi    $i     = 0;
1392f3f0262cSandi
1393f3f0262cSandi    while($size >= 1024 && ($i < $count - 1)) {
1394f3f0262cSandi        $size /= 1024;
1395f3f0262cSandi        $i++;
1396f3f0262cSandi    }
1397f3f0262cSandi
1398f3f0262cSandi    return round($size, $dec).' '.$sizes[$i];
1399f3f0262cSandi}
1400f3f0262cSandi
140115fae107Sandi/**
1402c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1403c57e365eSAndreas Gohr *
1404c57e365eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1405140cfbcdSGerrit Uitslag *
1406140cfbcdSGerrit Uitslag * @param int $dt timestamp
1407140cfbcdSGerrit Uitslag * @return string
1408c57e365eSAndreas Gohr */
1409c57e365eSAndreas Gohrfunction datetime_h($dt) {
1410c57e365eSAndreas Gohr    global $lang;
1411c57e365eSAndreas Gohr
1412c57e365eSAndreas Gohr    $ago = time() - $dt;
1413c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1414c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1415c57e365eSAndreas Gohr    }
1416c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 2) {
1417c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1418c57e365eSAndreas Gohr    }
1419c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 7 * 2) {
1420c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1421c57e365eSAndreas Gohr    }
1422c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 2) {
1423c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1424c57e365eSAndreas Gohr    }
1425c57e365eSAndreas Gohr    if($ago > 60 * 60 * 2) {
1426c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago / (60 * 60)));
1427c57e365eSAndreas Gohr    }
1428c57e365eSAndreas Gohr    if($ago > 60 * 2) {
1429c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago / (60)));
1430c57e365eSAndreas Gohr    }
1431c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1432c57e365eSAndreas Gohr}
1433c57e365eSAndreas Gohr
1434c57e365eSAndreas Gohr/**
1435f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1436f2263577SAndreas Gohr *
1437f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1438f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1439f2263577SAndreas Gohr *
1440f2263577SAndreas Gohr * @see datetime_h
1441f2263577SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1442140cfbcdSGerrit Uitslag *
1443140cfbcdSGerrit Uitslag * @param int|null $dt      timestamp when given, null will take current timestamp
1444140cfbcdSGerrit Uitslag * @param string   $format  empty default to $conf['dformat'], or provide format as recognized by strftime()
1445140cfbcdSGerrit Uitslag * @return string
1446f2263577SAndreas Gohr */
1447f2263577SAndreas Gohrfunction dformat($dt = null, $format = '') {
1448f2263577SAndreas Gohr    global $conf;
1449f2263577SAndreas Gohr
1450f2263577SAndreas Gohr    if(is_null($dt)) $dt = time();
1451f2263577SAndreas Gohr    $dt = (int) $dt;
1452f2263577SAndreas Gohr    if(!$format) $format = $conf['dformat'];
1453f2263577SAndreas Gohr
1454f2263577SAndreas Gohr    $format = str_replace('%f', datetime_h($dt), $format);
1455f2263577SAndreas Gohr    return strftime($format, $dt);
1456f2263577SAndreas Gohr}
1457f2263577SAndreas Gohr
1458f2263577SAndreas Gohr/**
1459c4f79b71SMichael Hamann * Formats a timestamp as ISO 8601 date
1460c4f79b71SMichael Hamann *
1461c4f79b71SMichael Hamann * @author <ungu at terong dot com>
1462c4f79b71SMichael Hamann * @link http://www.php.net/manual/en/function.date.php#54072
1463140cfbcdSGerrit Uitslag *
146463703ba5SAndreas Gohr * @param int $int_date: current date in UNIX timestamp
14653272d797SAndreas Gohr * @return string
1466c4f79b71SMichael Hamann */
1467c4f79b71SMichael Hamannfunction date_iso8601($int_date) {
1468c4f79b71SMichael Hamann    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1469c4f79b71SMichael Hamann    $pre_timezone = date('O', $int_date);
1470c4f79b71SMichael Hamann    $time_zone    = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1471c4f79b71SMichael Hamann    $date_mod .= $time_zone;
1472c4f79b71SMichael Hamann    return $date_mod;
1473c4f79b71SMichael Hamann}
1474c4f79b71SMichael Hamann
1475c4f79b71SMichael Hamann/**
147600a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
147700a7b5adSEsther Brunner *
147800a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
147900a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
1480140cfbcdSGerrit Uitslag *
1481140cfbcdSGerrit Uitslag * @param string $email email address
1482140cfbcdSGerrit Uitslag * @return string
148300a7b5adSEsther Brunner */
148400a7b5adSEsther Brunnerfunction obfuscate($email) {
148500a7b5adSEsther Brunner    global $conf;
148600a7b5adSEsther Brunner
148700a7b5adSEsther Brunner    switch($conf['mailguard']) {
148800a7b5adSEsther Brunner        case 'visible' :
148900a7b5adSEsther Brunner            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
149000a7b5adSEsther Brunner            return strtr($email, $obfuscate);
149100a7b5adSEsther Brunner
149200a7b5adSEsther Brunner        case 'hex' :
149300a7b5adSEsther Brunner            $encode = '';
149449eb6e38SAndreas Gohr            $len    = strlen($email);
149549eb6e38SAndreas Gohr            for($x = 0; $x < $len; $x++) {
149649eb6e38SAndreas Gohr                $encode .= '&#x'.bin2hex($email{$x}).';';
149749eb6e38SAndreas Gohr            }
149800a7b5adSEsther Brunner            return $encode;
149900a7b5adSEsther Brunner
150000a7b5adSEsther Brunner        case 'none' :
150100a7b5adSEsther Brunner        default :
150200a7b5adSEsther Brunner            return $email;
150300a7b5adSEsther Brunner    }
150400a7b5adSEsther Brunner}
150500a7b5adSEsther Brunner
150600a7b5adSEsther Brunner/**
150789541d4bSAndreas Gohr * Removes quoting backslashes
150889541d4bSAndreas Gohr *
150989541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1510140cfbcdSGerrit Uitslag *
1511140cfbcdSGerrit Uitslag * @param string $string
1512140cfbcdSGerrit Uitslag * @param string $char backslashed character
1513140cfbcdSGerrit Uitslag * @return string
151489541d4bSAndreas Gohr */
151589541d4bSAndreas Gohrfunction unslash($string, $char = "'") {
151689541d4bSAndreas Gohr    return str_replace('\\'.$char, $char, $string);
151789541d4bSAndreas Gohr}
151889541d4bSAndreas Gohr
151973038c47SAndreas Gohr/**
152073038c47SAndreas Gohr * Convert php.ini shorthands to byte
152173038c47SAndreas Gohr *
152273038c47SAndreas Gohr * @author <gilthans dot NO dot SPAM at gmail dot com>
152373038c47SAndreas Gohr * @link   http://de3.php.net/manual/en/ini.core.php#79564
1524140cfbcdSGerrit Uitslag *
1525140cfbcdSGerrit Uitslag * @param string $v shorthands
1526140cfbcdSGerrit Uitslag * @return int|string
152773038c47SAndreas Gohr */
152873038c47SAndreas Gohrfunction php_to_byte($v) {
152973038c47SAndreas Gohr    $l   = substr($v, -1);
153073038c47SAndreas Gohr    $ret = substr($v, 0, -1);
153173038c47SAndreas Gohr    switch(strtoupper($l)) {
153274160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
153373038c47SAndreas Gohr        case 'P':
153473038c47SAndreas Gohr            $ret *= 1024;
153574160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
153673038c47SAndreas Gohr        case 'T':
153773038c47SAndreas Gohr            $ret *= 1024;
153874160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
153973038c47SAndreas Gohr        case 'G':
154073038c47SAndreas Gohr            $ret *= 1024;
154174160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
154273038c47SAndreas Gohr        case 'M':
154373038c47SAndreas Gohr            $ret *= 1024;
1544f168548cSGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
154573038c47SAndreas Gohr        case 'K':
154673038c47SAndreas Gohr            $ret *= 1024;
154773038c47SAndreas Gohr            break;
154849cbd23eSOtto Vainio        default;
154949cbd23eSOtto Vainio            $ret *= 10;
155049cbd23eSOtto Vainio            break;
155173038c47SAndreas Gohr    }
155273038c47SAndreas Gohr    return $ret;
155373038c47SAndreas Gohr}
155473038c47SAndreas Gohr
1555546d3a99SAndreas Gohr/**
1556546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1557140cfbcdSGerrit Uitslag *
1558140cfbcdSGerrit Uitslag * @param string $string
1559140cfbcdSGerrit Uitslag * @return string
1560546d3a99SAndreas Gohr */
1561546d3a99SAndreas Gohrfunction preg_quote_cb($string) {
1562546d3a99SAndreas Gohr    return preg_quote($string, '/');
1563546d3a99SAndreas Gohr}
156473038c47SAndreas Gohr
1565bd2f6c2fSAndreas Gohr/**
1566bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1567bd2f6c2fSAndreas Gohr *
1568c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1569bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1570bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1571bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1572bd2f6c2fSAndreas Gohr *
1573bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1574bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1575bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1576bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1577bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
15783272d797SAndreas Gohr * @return string
1579bd2f6c2fSAndreas Gohr */
1580a5d27328SAndreas Gohrfunction shorten($keep, $short, $max, $min = 9, $char = '…') {
1581bd2f6c2fSAndreas Gohr    $max = $max - utf8_strlen($keep);
1582bd2f6c2fSAndreas Gohr    if($max < $min) return $keep;
1583bd2f6c2fSAndreas Gohr    $len = utf8_strlen($short);
1584bd2f6c2fSAndreas Gohr    if($len <= $max) return $keep.$short;
1585bd2f6c2fSAndreas Gohr    $half = floor($max / 2);
1586bd2f6c2fSAndreas Gohr    return $keep.utf8_substr($short, 0, $half - 1).$char.utf8_substr($short, $len - $half);
1587bd2f6c2fSAndreas Gohr}
1588bd2f6c2fSAndreas Gohr
1589dc58b6f4SAndy Webber/**
1590dc58b6f4SAndy Webber * Return the users real name or e-mail address for use
1591dc58b6f4SAndy Webber * in page footer and recent changes pages
1592dc58b6f4SAndy Webber *
1593b4b6c9a1SGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
159415f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1595c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
159615f3bc49SGerrit Uitslag *
1597dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1598dc58b6f4SAndy Webber */
159915f3bc49SGerrit Uitslagfunction editorinfo($username, $textonly = false) {
1600cd4635eeSGerrit Uitslag    return userlink($username, $textonly);
1601dc58b6f4SAndy Webber}
1602dc58b6f4SAndy Webber
160360a396c8SGerrit Uitslag/**
160460a396c8SGerrit Uitslag * Returns users realname w/o link
160560a396c8SGerrit Uitslag *
1606f168548cSGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
160715f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1608c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
160960a396c8SGerrit Uitslag *
161060a396c8SGerrit Uitslag * @triggers COMMON_USER_LINK
161160a396c8SGerrit Uitslag */
1612cd4635eeSGerrit Uitslagfunction userlink($username = null, $textonly = false) {
161360a396c8SGerrit Uitslag    global $conf, $INFO;
161460a396c8SGerrit Uitslag    /** @var DokuWiki_Auth_Plugin $auth */
161560a396c8SGerrit Uitslag    global $auth;
161630f6ec4bSGerrit Uitslag    /** @var Input $INPUT */
161730f6ec4bSGerrit Uitslag    global $INPUT;
161860a396c8SGerrit Uitslag
161960a396c8SGerrit Uitslag    // prepare initial event data
162060a396c8SGerrit Uitslag    $data = array(
162160a396c8SGerrit Uitslag        'username' => $username, // the unique user name
162260a396c8SGerrit Uitslag        'name' => '',
162360a396c8SGerrit Uitslag        'link' => array( //setting 'link' to false disables linking
162460a396c8SGerrit Uitslag                         'target' => '',
162560a396c8SGerrit Uitslag                         'pre' => '',
162660a396c8SGerrit Uitslag                         'suf' => '',
162760a396c8SGerrit Uitslag                         'style' => '',
162860a396c8SGerrit Uitslag                         'more' => '',
162960a396c8SGerrit Uitslag                         'url' => '',
163060a396c8SGerrit Uitslag                         'title' => '',
163160a396c8SGerrit Uitslag                         'class' => ''
163260a396c8SGerrit Uitslag        ),
16334d5fc927SGerrit Uitslag        'userlink' => '', // formatted user name as will be returned
163415f3bc49SGerrit Uitslag        'textonly' => $textonly
163560a396c8SGerrit Uitslag    );
163662c8004eSGerrit Uitslag    if($username === null) {
163730f6ec4bSGerrit Uitslag        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
163815f3bc49SGerrit Uitslag        if($textonly){
163915f3bc49SGerrit Uitslag            $data['name'] = $INFO['userinfo']['name']. ' (' . $INPUT->server->str('REMOTE_USER') . ')';
164015f3bc49SGerrit Uitslag        }else {
164130f6ec4bSGerrit Uitslag            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> (<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
164260a396c8SGerrit Uitslag        }
164315f3bc49SGerrit Uitslag    }
164460a396c8SGerrit Uitslag
164560a396c8SGerrit Uitslag    $evt = new Doku_Event('COMMON_USER_LINK', $data);
164660a396c8SGerrit Uitslag    if($evt->advise_before(true)) {
164760a396c8SGerrit Uitslag        if(empty($data['name'])) {
164860a396c8SGerrit Uitslag            if($auth) $info = $auth->getUserData($username);
164965833968SGerrit Uitslag            if($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1650dc58b6f4SAndy Webber                switch($conf['showuseras']) {
1651dc58b6f4SAndy Webber                    case 'username':
16527f081821SGerrit Uitslag                    case 'username_link':
165315f3bc49SGerrit Uitslag                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
165460a396c8SGerrit Uitslag                        break;
1655dc58b6f4SAndy Webber                    case 'email':
1656dc58b6f4SAndy Webber                    case 'email_link':
165760a396c8SGerrit Uitslag                        $data['name'] = obfuscate($info['mail']);
165860a396c8SGerrit Uitslag                        break;
1659dc58b6f4SAndy Webber                }
166065833968SGerrit Uitslag            } else {
166165833968SGerrit Uitslag                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
166260a396c8SGerrit Uitslag            }
166360a396c8SGerrit Uitslag        }
16647f081821SGerrit Uitslag
16657f081821SGerrit Uitslag        /** @var Doku_Renderer_xhtml $xhtml_renderer */
16667f081821SGerrit Uitslag        static $xhtml_renderer = null;
16677f081821SGerrit Uitslag
166815f3bc49SGerrit Uitslag        if(!$data['textonly'] && empty($data['link']['url'])) {
16697f081821SGerrit Uitslag
16707f081821SGerrit Uitslag            if(in_array($conf['showuseras'], array('email_link', 'username_link'))) {
167160a396c8SGerrit Uitslag                if(!isset($info)) {
167260a396c8SGerrit Uitslag                    if($auth) $info = $auth->getUserData($username);
167360a396c8SGerrit Uitslag                }
167460a396c8SGerrit Uitslag                if(isset($info) && $info) {
16757f081821SGerrit Uitslag                    if($conf['showuseras'] == 'email_link') {
167660a396c8SGerrit Uitslag                        $data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
1677dc58b6f4SAndy Webber                    } else {
16787f081821SGerrit Uitslag                        if(is_null($xhtml_renderer)) {
16797f081821SGerrit Uitslag                            $xhtml_renderer = p_get_renderer('xhtml');
16807f081821SGerrit Uitslag                        }
16817f081821SGerrit Uitslag                        if(empty($xhtml_renderer->interwiki)) {
16827f081821SGerrit Uitslag                            $xhtml_renderer->interwiki = getInterwiki();
16837f081821SGerrit Uitslag                        }
16847f081821SGerrit Uitslag                        $shortcut = 'user';
1685533772e1SGerrit Uitslag                        $exists = null;
16866496c33fSGerrit Uitslag                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
16872a2a43c4SGerrit Uitslag                        $data['link']['class'] .= ' interwiki iw_user';
16886496c33fSGerrit Uitslag                        if($exists !== null) {
16896496c33fSGerrit Uitslag                            if($exists) {
16906496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink1';
16916496c33fSGerrit Uitslag                            } else {
16926496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink2';
16936496c33fSGerrit Uitslag                                $data['link']['rel'] = 'nofollow';
16946496c33fSGerrit Uitslag                            }
16956496c33fSGerrit Uitslag                        }
1696dc58b6f4SAndy Webber                    }
1697dc58b6f4SAndy Webber                } else {
169815f3bc49SGerrit Uitslag                    $data['textonly'] = true;
1699dc58b6f4SAndy Webber                }
170060a396c8SGerrit Uitslag
170160a396c8SGerrit Uitslag            } else {
170215f3bc49SGerrit Uitslag                $data['textonly'] = true;
170360a396c8SGerrit Uitslag            }
170460a396c8SGerrit Uitslag        }
170560a396c8SGerrit Uitslag
170615f3bc49SGerrit Uitslag        if($data['textonly']) {
17074d5fc927SGerrit Uitslag            $data['userlink'] = $data['name'];
170860a396c8SGerrit Uitslag        } else {
170960a396c8SGerrit Uitslag            $data['link']['name'] = $data['name'];
171060a396c8SGerrit Uitslag            if(is_null($xhtml_renderer)) {
171160a396c8SGerrit Uitslag                $xhtml_renderer = p_get_renderer('xhtml');
171260a396c8SGerrit Uitslag            }
17134d5fc927SGerrit Uitslag            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
171460a396c8SGerrit Uitslag        }
171560a396c8SGerrit Uitslag    }
171660a396c8SGerrit Uitslag    $evt->advise_after();
171760a396c8SGerrit Uitslag    unset($evt);
171860a396c8SGerrit Uitslag
17194d5fc927SGerrit Uitslag    return $data['userlink'];
1720066fee30SAndreas Gohr}
1721066fee30SAndreas Gohr
1722066fee30SAndreas Gohr/**
1723066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1724066fee30SAndreas Gohr * When no image exists, returns an empty string
1725066fee30SAndreas Gohr *
1726066fee30SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1727140cfbcdSGerrit Uitslag *
1728066fee30SAndreas Gohr * @param  string $type - type of image 'badge' or 'button'
17293272d797SAndreas Gohr * @return string
1730066fee30SAndreas Gohr */
1731066fee30SAndreas Gohrfunction license_img($type) {
1732066fee30SAndreas Gohr    global $license;
1733066fee30SAndreas Gohr    global $conf;
1734066fee30SAndreas Gohr    if(!$conf['license']) return '';
1735066fee30SAndreas Gohr    if(!is_array($license[$conf['license']])) return '';
1736066fee30SAndreas Gohr    $try   = array();
1737066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1738066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1739066fee30SAndreas Gohr    if(substr($conf['license'], 0, 3) == 'cc-') {
1740066fee30SAndreas Gohr        $try[] = 'lib/images/license/'.$type.'/cc.png';
1741066fee30SAndreas Gohr    }
1742066fee30SAndreas Gohr    foreach($try as $src) {
1743066fee30SAndreas Gohr        if(@file_exists(DOKU_INC.$src)) return $src;
1744066fee30SAndreas Gohr    }
1745066fee30SAndreas Gohr    return '';
1746dc58b6f4SAndy Webber}
1747dc58b6f4SAndy Webber
174813c08e2fSMichael Klier/**
174913c08e2fSMichael Klier * Checks if the given amount of memory is available
175013c08e2fSMichael Klier *
175113c08e2fSMichael Klier * If the memory_get_usage() function is not available the
175213c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
175313c08e2fSMichael Klier *
175413c08e2fSMichael Klier * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
175513c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
17563272d797SAndreas Gohr *
17573272d797SAndreas Gohr * @param int  $mem    Size of memory you want to allocate in bytes
1758140cfbcdSGerrit Uitslag * @param int  $bytes  already allocated memory (see above)
17593272d797SAndreas Gohr * @return bool
176013c08e2fSMichael Klier */
176113c08e2fSMichael Klierfunction is_mem_available($mem, $bytes = 1048576) {
176213c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
176313c08e2fSMichael Klier    if(empty($limit)) return true; // no limit set!
176413c08e2fSMichael Klier
176513c08e2fSMichael Klier    // parse limit to bytes
176613c08e2fSMichael Klier    $limit = php_to_byte($limit);
176713c08e2fSMichael Klier
176813c08e2fSMichael Klier    // get used memory if possible
176913c08e2fSMichael Klier    if(function_exists('memory_get_usage')) {
177013c08e2fSMichael Klier        $used = memory_get_usage();
177149eb6e38SAndreas Gohr    } else {
177249eb6e38SAndreas Gohr        $used = $bytes;
177313c08e2fSMichael Klier    }
177413c08e2fSMichael Klier
177513c08e2fSMichael Klier    if($used + $mem > $limit) {
177613c08e2fSMichael Klier        return false;
177713c08e2fSMichael Klier    }
177813c08e2fSMichael Klier
177913c08e2fSMichael Klier    return true;
178013c08e2fSMichael Klier}
178113c08e2fSMichael Klier
1782af2408d5SAndreas Gohr/**
1783af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1784af2408d5SAndreas Gohr *
1785af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1786af2408d5SAndreas Gohr *
1787af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1788af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1789140cfbcdSGerrit Uitslag *
1790140cfbcdSGerrit Uitslag * @param string $url url being directed to
1791af2408d5SAndreas Gohr */
1792af2408d5SAndreas Gohrfunction send_redirect($url) {
1793585bf44eSChristopher Smith    /* @var Input $INPUT */
1794585bf44eSChristopher Smith    global $INPUT;
1795585bf44eSChristopher Smith
17960181f021SAndreas Gohr    //are there any undisplayed messages? keep them in session for display
17970181f021SAndreas Gohr    global $MSG;
17980181f021SAndreas Gohr    if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
17990181f021SAndreas Gohr        //reopen session, store data and close session again
18000181f021SAndreas Gohr        @session_start();
18010181f021SAndreas Gohr        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
18020181f021SAndreas Gohr    }
18030181f021SAndreas Gohr
1804d4869846SAndreas Gohr    // always close the session
1805d4869846SAndreas Gohr    session_write_close();
1806d4869846SAndreas Gohr
1807c10dcb7dSAndreas Gohr    // work around IE bug
1808c10dcb7dSAndreas Gohr    // http://www.ianhoar.com/2008/11/16/internet-explorer-6-and-redirected-anchor-links/
18096d2af55dSChristopher Smith    @list($url, $hash) = explode('#', $url);
1810c10dcb7dSAndreas Gohr    if($hash) {
1811c10dcb7dSAndreas Gohr        if(strpos($url, '?')) {
1812c10dcb7dSAndreas Gohr            $url = $url.'&#'.$hash;
1813c10dcb7dSAndreas Gohr        } else {
1814c10dcb7dSAndreas Gohr            $url = $url.'?&#'.$hash;
1815c10dcb7dSAndreas Gohr        }
1816c10dcb7dSAndreas Gohr    }
1817c10dcb7dSAndreas Gohr
1818af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
1819585bf44eSChristopher Smith    if($INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1820585bf44eSChristopher Smith        (strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) &&
1821585bf44eSChristopher Smith        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
18223272d797SAndreas Gohr        $matches[1] < 6
18233272d797SAndreas Gohr    ) {
1824af2408d5SAndreas Gohr        header('Refresh: 0;url='.$url);
1825af2408d5SAndreas Gohr    } else {
1826af2408d5SAndreas Gohr        header('Location: '.$url);
1827af2408d5SAndreas Gohr    }
1828af2408d5SAndreas Gohr    exit;
1829af2408d5SAndreas Gohr}
1830af2408d5SAndreas Gohr
18315b75cd1fSAdrian Lang/**
18325b75cd1fSAdrian Lang * Validate a value using a set of valid values
18335b75cd1fSAdrian Lang *
18345b75cd1fSAdrian Lang * This function checks whether a specified value is set and in the array
18355b75cd1fSAdrian Lang * $valid_values. If not, the function returns a default value or, if no
18365b75cd1fSAdrian Lang * default is specified, throws an exception.
18375b75cd1fSAdrian Lang *
18385b75cd1fSAdrian Lang * @param string $param        The name of the parameter
18395b75cd1fSAdrian Lang * @param array  $valid_values A set of valid values; Optionally a default may
18405b75cd1fSAdrian Lang *                             be marked by the key “default”.
18415b75cd1fSAdrian Lang * @param array  $array        The array containing the value (typically $_POST
18425b75cd1fSAdrian Lang *                             or $_GET)
18435b75cd1fSAdrian Lang * @param string $exc          The text of the raised exception
18445b75cd1fSAdrian Lang *
18453272d797SAndreas Gohr * @throws Exception
18463272d797SAndreas Gohr * @return mixed
18475b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
18485b75cd1fSAdrian Lang */
18495b75cd1fSAdrian Langfunction valid_input_set($param, $valid_values, $array, $exc = '') {
18505b75cd1fSAdrian Lang    if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
18515b75cd1fSAdrian Lang        return $array[$param];
18525b75cd1fSAdrian Lang    } elseif(isset($valid_values['default'])) {
18535b75cd1fSAdrian Lang        return $valid_values['default'];
18545b75cd1fSAdrian Lang    } else {
18555b75cd1fSAdrian Lang        throw new Exception($exc);
18565b75cd1fSAdrian Lang    }
18575b75cd1fSAdrian Lang}
18585b75cd1fSAdrian Lang
185963703ba5SAndreas Gohr/**
186063703ba5SAndreas Gohr * Read a preference from the DokuWiki cookie
1861646a531aSChristopher Smith * (remembering both keys & values are urlencoded)
1862140cfbcdSGerrit Uitslag *
1863140cfbcdSGerrit Uitslag * @param string $pref     preference key
1864b4b6c9a1SGerrit Uitslag * @param mixed  $default  value returned when preference not found
1865140cfbcdSGerrit Uitslag * @return string preference value
186663703ba5SAndreas Gohr */
1867554a8c9fSAdrian Langfunction get_doku_pref($pref, $default) {
1868646a531aSChristopher Smith    $enc_pref = urlencode($pref);
1869646a531aSChristopher Smith    if(strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
1870554a8c9fSAdrian Lang        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
187163703ba5SAndreas Gohr        $cnt   = count($parts);
187263703ba5SAndreas Gohr        for($i = 0; $i < $cnt; $i += 2) {
1873646a531aSChristopher Smith            if($parts[$i] == $enc_pref) {
1874646a531aSChristopher Smith                return urldecode($parts[$i + 1]);
1875554a8c9fSAdrian Lang            }
1876554a8c9fSAdrian Lang        }
1877554a8c9fSAdrian Lang    }
1878554a8c9fSAdrian Lang    return $default;
1879554a8c9fSAdrian Lang}
1880554a8c9fSAdrian Lang
18813c94d07bSAnika Henke/**
18823c94d07bSAnika Henke * Add a preference to the DokuWiki cookie
188336ec377eSChristopher Smith * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
1884140cfbcdSGerrit Uitslag *
1885140cfbcdSGerrit Uitslag * @param string $pref  preference key
1886140cfbcdSGerrit Uitslag * @param string $val   preference value
18873c94d07bSAnika Henke */
18883c94d07bSAnika Henkefunction set_doku_pref($pref, $val) {
18893c94d07bSAnika Henke    global $conf;
18903c94d07bSAnika Henke    $orig = get_doku_pref($pref, false);
18913c94d07bSAnika Henke    $cookieVal = '';
18923c94d07bSAnika Henke
18933c94d07bSAnika Henke    if($orig && ($orig != $val)) {
18943c94d07bSAnika Henke        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
18953c94d07bSAnika Henke        $cnt   = count($parts);
189636ec377eSChristopher Smith        // urlencode $pref for the comparison
189736ec377eSChristopher Smith        $enc_pref = rawurlencode($pref);
18983c94d07bSAnika Henke        for($i = 0; $i < $cnt; $i += 2) {
189936ec377eSChristopher Smith            if($parts[$i] == $enc_pref) {
190036ec377eSChristopher Smith                $parts[$i + 1] = rawurlencode($val);
190150f261f7SMichael Hamann                break;
19023c94d07bSAnika Henke            }
19033c94d07bSAnika Henke        }
19043c94d07bSAnika Henke        $cookieVal = implode('#', $parts);
19053c94d07bSAnika Henke    } else if (!$orig) {
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 *
1918*42ea7f44SGerrit 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