xref: /dokuwiki/inc/common.php (revision 655ddc1d0545524aa2a3c91b80b32536ae3bab52)
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/**
345b571377SAndreas Gohr * Checks if the given input is blank
355b571377SAndreas Gohr *
365b571377SAndreas Gohr * This is similar to empty() but will return false for "0".
375b571377SAndreas Gohr *
3867234204SAndreas Gohr * Please note: when you pass uninitialized variables, they will implicitly be created
3967234204SAndreas Gohr * with a NULL value without warning.
4067234204SAndreas Gohr *
4167234204SAndreas Gohr * To avoid this it's recommended to guard the call with isset like this:
4267234204SAndreas Gohr *
4367234204SAndreas Gohr * (isset($foo) && !blank($foo))
4467234204SAndreas Gohr * (!isset($foo) || blank($foo))
4567234204SAndreas Gohr *
465b571377SAndreas Gohr * @param $in
475b571377SAndreas Gohr * @param bool $trim Consider a string of whitespace to be blank
485b571377SAndreas Gohr * @return bool
495b571377SAndreas Gohr */
505b571377SAndreas Gohrfunction blank(&$in, $trim = false) {
515b571377SAndreas Gohr    if(is_null($in)) return true;
525b571377SAndreas Gohr    if(is_array($in)) return empty($in);
535b571377SAndreas Gohr    if($in === "\0") return true;
545b571377SAndreas Gohr    if($trim && trim($in) === '') return true;
555b571377SAndreas Gohr    if(strlen($in) > 0) return false;
565b571377SAndreas Gohr    return empty($in);
575b571377SAndreas Gohr}
585b571377SAndreas Gohr
595b571377SAndreas Gohr/**
60d5197206Schris * print a newline terminated string
61d5197206Schris *
62d5197206Schris * You can give an indention as optional parameter
63d5197206Schris *
64d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
65140cfbcdSGerrit Uitslag *
66140cfbcdSGerrit Uitslag * @param string $string  line of text
67140cfbcdSGerrit Uitslag * @param int    $indent  number of spaces indention
68d5197206Schris */
6925ec097bSChris Smithfunction ptln($string, $indent = 0) {
7025ec097bSChris Smith    echo str_repeat(' ', $indent)."$string\n";
7102b0b681SAndreas Gohr}
7202b0b681SAndreas Gohr
7302b0b681SAndreas Gohr/**
7402b0b681SAndreas Gohr * strips control characters (<32) from the given string
7502b0b681SAndreas Gohr *
7602b0b681SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
77140cfbcdSGerrit Uitslag *
7842ea7f44SGerrit Uitslag * @param string $string being stripped
79140cfbcdSGerrit Uitslag * @return string
8002b0b681SAndreas Gohr */
8102b0b681SAndreas Gohrfunction stripctl($string) {
8202b0b681SAndreas Gohr    return preg_replace('/[\x00-\x1F]+/s', '', $string);
83d5197206Schris}
84d5197206Schris
85d5197206Schris/**
86634d7150SAndreas Gohr * Return a secret token to be used for CSRF attack prevention
87634d7150SAndreas Gohr *
88634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
89634d7150SAndreas Gohr * @link    http://en.wikipedia.org/wiki/Cross-site_request_forgery
90634d7150SAndreas Gohr * @link    http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
9142ea7f44SGerrit Uitslag *
92634d7150SAndreas Gohr * @return  string
93634d7150SAndreas Gohr */
94634d7150SAndreas Gohrfunction getSecurityToken() {
95585bf44eSChristopher Smith    /** @var Input $INPUT */
96585bf44eSChristopher Smith    global $INPUT;
97585bf44eSChristopher Smith    return PassHash::hmac('md5', session_id().$INPUT->server->str('REMOTE_USER'), auth_cookiesalt());
98634d7150SAndreas Gohr}
99634d7150SAndreas Gohr
100634d7150SAndreas Gohr/**
101634d7150SAndreas Gohr * Check the secret CSRF token
102140cfbcdSGerrit Uitslag *
103140cfbcdSGerrit Uitslag * @param null|string $token security token or null to read it from request variable
104140cfbcdSGerrit Uitslag * @return bool success if the token matched
105634d7150SAndreas Gohr */
106634d7150SAndreas Gohrfunction checkSecurityToken($token = null) {
107585bf44eSChristopher Smith    /** @var Input $INPUT */
1087d01a0eaSTom N Harris    global $INPUT;
109585bf44eSChristopher Smith    if(!$INPUT->server->str('REMOTE_USER')) return true; // no logged in user, no need for a check
110df97eaacSAndreas Gohr
1117d01a0eaSTom N Harris    if(is_null($token)) $token = $INPUT->str('sectok');
112634d7150SAndreas Gohr    if(getSecurityToken() != $token) {
113634d7150SAndreas Gohr        msg('Security Token did not match. Possible CSRF attack.', -1);
114634d7150SAndreas Gohr        return false;
115634d7150SAndreas Gohr    }
116634d7150SAndreas Gohr    return true;
117634d7150SAndreas Gohr}
118634d7150SAndreas Gohr
119634d7150SAndreas Gohr/**
120634d7150SAndreas Gohr * Print a hidden form field with a secret CSRF token
121634d7150SAndreas Gohr *
122634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
123140cfbcdSGerrit Uitslag *
124140cfbcdSGerrit Uitslag * @param bool $print  if true print the field, otherwise html of the field is returned
12542ea7f44SGerrit Uitslag * @return string html of hidden form field
126634d7150SAndreas Gohr */
127634d7150SAndreas Gohrfunction formSecurityToken($print = true) {
1282404d0edSAnika Henke    $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
1293272d797SAndreas Gohr    if($print) echo $ret;
130634d7150SAndreas Gohr    return $ret;
131634d7150SAndreas Gohr}
132634d7150SAndreas Gohr
133634d7150SAndreas Gohr/**
1341015a57dSChristopher Smith * Determine basic information for a request of $id
13515fae107Sandi *
13615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1377e87a794SChristopher Smith * @author Chris Smith <chris@jalakai.co.uk>
138140cfbcdSGerrit Uitslag *
139140cfbcdSGerrit Uitslag * @param string $id         pageid
140140cfbcdSGerrit Uitslag * @param bool   $htmlClient add info about whether is mobile browser
141140cfbcdSGerrit Uitslag * @return array with info for a request of $id
142140cfbcdSGerrit Uitslag *
143f3f0262cSandi */
1441015a57dSChristopher Smithfunction basicinfo($id, $htmlClient=true){
145f3f0262cSandi    global $USERINFO;
146585bf44eSChristopher Smith    /* @var Input $INPUT */
147585bf44eSChristopher Smith    global $INPUT;
1486afe8dcaSchris
149c66972f2SAdrian Lang    // set info about manager/admin status.
15059bc3b48SGerrit Uitslag    $info = array();
151c66972f2SAdrian Lang    $info['isadmin']   = false;
152c66972f2SAdrian Lang    $info['ismanager'] = false;
153585bf44eSChristopher Smith    if($INPUT->server->has('REMOTE_USER')) {
154f3f0262cSandi        $info['userinfo']   = $USERINFO;
1551015a57dSChristopher Smith        $info['perm']       = auth_quickaclcheck($id);
156585bf44eSChristopher Smith        $info['client']     = $INPUT->server->str('REMOTE_USER');
15717ee7f66SAndreas Gohr
158f8cc712eSAndreas Gohr        if($info['perm'] == AUTH_ADMIN) {
159f8cc712eSAndreas Gohr            $info['isadmin']   = true;
160f8cc712eSAndreas Gohr            $info['ismanager'] = true;
161f8cc712eSAndreas Gohr        } elseif(auth_ismanager()) {
162f8cc712eSAndreas Gohr            $info['ismanager'] = true;
163f8cc712eSAndreas Gohr        }
164f8cc712eSAndreas Gohr
16517ee7f66SAndreas Gohr        // if some outside auth were used only REMOTE_USER is set
16617ee7f66SAndreas Gohr        if(!$info['userinfo']['name']) {
167585bf44eSChristopher Smith            $info['userinfo']['name'] = $INPUT->server->str('REMOTE_USER');
16817ee7f66SAndreas Gohr        }
169ee4c4a1bSAndreas Gohr
170f3f0262cSandi    } else {
1711015a57dSChristopher Smith        $info['perm']       = auth_aclcheck($id, '', null);
172ee4c4a1bSAndreas Gohr        $info['client']     = clientIP(true);
173f3f0262cSandi    }
174f3f0262cSandi
1751015a57dSChristopher Smith    $info['namespace'] = getNS($id);
1761015a57dSChristopher Smith
1771015a57dSChristopher Smith    // mobile detection
1781015a57dSChristopher Smith    if ($htmlClient) {
1791015a57dSChristopher Smith        $info['ismobile'] = clientismobile();
1801015a57dSChristopher Smith    }
1811015a57dSChristopher Smith
1821015a57dSChristopher Smith    return $info;
1831015a57dSChristopher Smith }
1841015a57dSChristopher Smith
1851015a57dSChristopher Smith/**
1861015a57dSChristopher Smith * Return info about the current document as associative
1871015a57dSChristopher Smith * array.
1881015a57dSChristopher Smith *
1891015a57dSChristopher Smith * @author Andreas Gohr <andi@splitbrain.org>
190140cfbcdSGerrit Uitslag *
191140cfbcdSGerrit Uitslag * @return array with info about current document
1921015a57dSChristopher Smith */
1931015a57dSChristopher Smithfunction pageinfo() {
1941015a57dSChristopher Smith    global $ID;
1951015a57dSChristopher Smith    global $REV;
1961015a57dSChristopher Smith    global $RANGE;
1971015a57dSChristopher Smith    global $lang;
198585bf44eSChristopher Smith    /* @var Input $INPUT */
199585bf44eSChristopher Smith    global $INPUT;
2001015a57dSChristopher Smith
2011015a57dSChristopher Smith    $info = basicinfo($ID);
2021015a57dSChristopher Smith
2031015a57dSChristopher Smith    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
2041015a57dSChristopher Smith    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
2051015a57dSChristopher Smith    $info['id']  = $ID;
2061015a57dSChristopher Smith    $info['rev'] = $REV;
2071015a57dSChristopher Smith
208585bf44eSChristopher Smith    if($INPUT->server->has('REMOTE_USER')) {
2097e87a794SChristopher Smith        $sub = new Subscription();
2107e87a794SChristopher Smith        $info['subscribed'] = $sub->user_subscription();
2117e87a794SChristopher Smith    } else {
2127e87a794SChristopher Smith        $info['subscribed'] = false;
2137e87a794SChristopher Smith    }
2147e87a794SChristopher Smith
215f3f0262cSandi    $info['locked']     = checklock($ID);
21600976812SAndreas Gohr    $info['filepath']   = fullpath(wikiFN($ID));
21779e79377SAndreas Gohr    $info['exists']     = file_exists($info['filepath']);
21801c9a118SAndreas Gohr    $info['currentrev'] = @filemtime($info['filepath']);
2192ca9d91cSBen Coburn    if($REV) {
2202ca9d91cSBen Coburn        //check if current revision was meant
22101c9a118SAndreas Gohr        if($info['exists'] && ($info['currentrev'] == $REV)) {
2222ca9d91cSBen Coburn            $REV = '';
2237b3a6803SAndreas Gohr        } elseif($RANGE) {
2247b3a6803SAndreas Gohr            //section editing does not work with old revisions!
2257b3a6803SAndreas Gohr            $REV   = '';
2267b3a6803SAndreas Gohr            $RANGE = '';
2277b3a6803SAndreas Gohr            msg($lang['nosecedit'], 0);
2282ca9d91cSBen Coburn        } else {
2292ca9d91cSBen Coburn            //really use old revision
23000976812SAndreas Gohr            $info['filepath'] = fullpath(wikiFN($ID, $REV));
23179e79377SAndreas Gohr            $info['exists']   = file_exists($info['filepath']);
232f3f0262cSandi        }
233f3f0262cSandi    }
234c112d578Sandi    $info['rev'] = $REV;
235f3f0262cSandi    if($info['exists']) {
236f3f0262cSandi        $info['writable'] = (is_writable($info['filepath']) &&
237f3f0262cSandi            ($info['perm'] >= AUTH_EDIT));
238f3f0262cSandi    } else {
239f3f0262cSandi        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
240f3f0262cSandi    }
24150e988b1SAndreas Gohr    $info['editable'] = ($info['writable'] && empty($info['locked']));
242f3f0262cSandi    $info['lastmod']  = @filemtime($info['filepath']);
243f3f0262cSandi
24471726d78SBen Coburn    //load page meta data
24571726d78SBen Coburn    $info['meta'] = p_get_metadata($ID);
24671726d78SBen Coburn
247652610a2Sandi    //who's the editor
248047bad06SGerrit Uitslag    $pagelog = new PageChangeLog($ID, 1024);
249652610a2Sandi    if($REV) {
250f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($REV);
251652610a2Sandi    } else {
2520e80bb5eSChristopher Smith        if(!empty($info['meta']['last_change']) && is_array($info['meta']['last_change'])) {
253aa27cf05SAndreas Gohr            $revinfo = $info['meta']['last_change'];
254aa27cf05SAndreas Gohr        } else {
255f523c971SGerrit Uitslag            $revinfo = $pagelog->getRevisionInfo($info['lastmod']);
256cd00a034SBen Coburn            // cache most recent changelog line in metadata if missing and still valid
257cd00a034SBen Coburn            if($revinfo !== false) {
258cd00a034SBen Coburn                $info['meta']['last_change'] = $revinfo;
259cd00a034SBen Coburn                p_set_metadata($ID, array('last_change' => $revinfo));
260cd00a034SBen Coburn            }
261cd00a034SBen Coburn        }
262cd00a034SBen Coburn    }
263cd00a034SBen Coburn    //and check for an external edit
264cd00a034SBen Coburn    if($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
265cd00a034SBen Coburn        // cached changelog line no longer valid
266cd00a034SBen Coburn        $revinfo                     = false;
267cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
268cd00a034SBen Coburn        p_set_metadata($ID, array('last_change' => $revinfo));
269652610a2Sandi    }
270bb4866bdSchris
271652610a2Sandi    $info['ip']   = $revinfo['ip'];
272652610a2Sandi    $info['user'] = $revinfo['user'];
273652610a2Sandi    $info['sum']  = $revinfo['sum'];
27471726d78SBen Coburn    // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
275ebf1501fSBen Coburn    // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
27659f257aeSchris
27788f522e9Sandi    if($revinfo['user']) {
27888f522e9Sandi        $info['editor'] = $revinfo['user'];
27988f522e9Sandi    } else {
28088f522e9Sandi        $info['editor'] = $revinfo['ip'];
28188f522e9Sandi    }
282652610a2Sandi
283ee4c4a1bSAndreas Gohr    // draft
284ee4c4a1bSAndreas Gohr    $draft = getCacheName($info['client'].$ID, '.draft');
28579e79377SAndreas Gohr    if(file_exists($draft)) {
286ee4c4a1bSAndreas Gohr        if(@filemtime($draft) < @filemtime(wikiFN($ID))) {
287ee4c4a1bSAndreas Gohr            // remove stale draft
288ee4c4a1bSAndreas Gohr            @unlink($draft);
289ee4c4a1bSAndreas Gohr        } else {
290ee4c4a1bSAndreas Gohr            $info['draft'] = $draft;
291ee4c4a1bSAndreas Gohr        }
292ee4c4a1bSAndreas Gohr    }
293ee4c4a1bSAndreas Gohr
2941015a57dSChristopher Smith    return $info;
2951015a57dSChristopher Smith}
2961015a57dSChristopher Smith
2971015a57dSChristopher Smith/**
2981015a57dSChristopher Smith * Return information about the current media item as an associative array.
299140cfbcdSGerrit Uitslag *
300140cfbcdSGerrit Uitslag * @return array with info about current media item
3011015a57dSChristopher Smith */
3021015a57dSChristopher Smithfunction mediainfo(){
3031015a57dSChristopher Smith    global $NS;
3041015a57dSChristopher Smith    global $IMG;
3051015a57dSChristopher Smith
3061015a57dSChristopher Smith    $info = basicinfo("$NS:*");
3071015a57dSChristopher Smith    $info['image'] = $IMG;
3081c548ebeSAndreas Gohr
309f3f0262cSandi    return $info;
310f3f0262cSandi}
311f3f0262cSandi
312f3f0262cSandi/**
3132684e50aSAndreas Gohr * Build an string of URL parameters
3142684e50aSAndreas Gohr *
3152684e50aSAndreas Gohr * @author Andreas Gohr
316140cfbcdSGerrit Uitslag *
317140cfbcdSGerrit Uitslag * @param array  $params    array with key-value pairs
318140cfbcdSGerrit Uitslag * @param string $sep       series of pairs are separated by this character
319140cfbcdSGerrit Uitslag * @return string query string
3202684e50aSAndreas Gohr */
321b174aeaeSchrisfunction buildURLparams($params, $sep = '&amp;') {
3222684e50aSAndreas Gohr    $url = '';
3232684e50aSAndreas Gohr    $amp = false;
3242684e50aSAndreas Gohr    foreach($params as $key => $val) {
325b174aeaeSchris        if($amp) $url .= $sep;
3262684e50aSAndreas Gohr
32785e6871fSAdrian Lang        $url .= rawurlencode($key).'=';
3283a50618cSgweissbach        $url .= rawurlencode((string) $val);
3292684e50aSAndreas Gohr        $amp = true;
3302684e50aSAndreas Gohr    }
3312684e50aSAndreas Gohr    return $url;
3322684e50aSAndreas Gohr}
3332684e50aSAndreas Gohr
3342684e50aSAndreas Gohr/**
3352684e50aSAndreas Gohr * Build an string of html tag attributes
3362684e50aSAndreas Gohr *
3377bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
3387bff22c0SAndreas Gohr *
3392684e50aSAndreas Gohr * @author Andreas Gohr
340140cfbcdSGerrit Uitslag *
341140cfbcdSGerrit Uitslag * @param array $params    array with (attribute name-attribute value) pairs
342140cfbcdSGerrit Uitslag * @param bool  $skipempty skip empty string values?
343140cfbcdSGerrit Uitslag * @return string
3442684e50aSAndreas Gohr */
3454b030ce7SAndreas Gohrfunction buildAttributes($params, $skipempty = false) {
3462684e50aSAndreas Gohr    $url   = '';
3479063ec14SAdrian Lang    $white = false;
3482684e50aSAndreas Gohr    foreach($params as $key => $val) {
3497bff22c0SAndreas Gohr        if($key{0} == '_') continue;
350b1c94f1dSAndreas Gohr        if($val === '' && $skipempty) continue;
3519063ec14SAdrian Lang        if($white) $url .= ' ';
3527bff22c0SAndreas Gohr
3532684e50aSAndreas Gohr        $url .= $key.'="';
3542684e50aSAndreas Gohr        $url .= htmlspecialchars($val);
3552684e50aSAndreas Gohr        $url .= '"';
3569063ec14SAdrian Lang        $white = true;
3572684e50aSAndreas Gohr    }
3582684e50aSAndreas Gohr    return $url;
3592684e50aSAndreas Gohr}
3602684e50aSAndreas Gohr
3612684e50aSAndreas Gohr/**
36215fae107Sandi * This builds the breadcrumb trail and returns it as array
36315fae107Sandi *
36415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
365140cfbcdSGerrit Uitslag *
366e3710957SGerrit Uitslag * @return string[] with the data: array(pageid=>name, ... )
367f3f0262cSandi */
368f3f0262cSandifunction breadcrumbs() {
3698746e727Sandi    // we prepare the breadcrumbs early for quick session closing
3708746e727Sandi    static $crumbs = null;
3718746e727Sandi    if($crumbs != null) return $crumbs;
3728746e727Sandi
373f3f0262cSandi    global $ID;
374f3f0262cSandi    global $ACT;
375f3f0262cSandi    global $conf;
376f3f0262cSandi
377f3f0262cSandi    //first visit?
378c66972f2SAdrian Lang    $crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array();
379f3f0262cSandi    //we only save on show and existing wiki documents
380a77f5846Sjan    $file = wikiFN($ID);
38179e79377SAndreas Gohr    if($ACT != 'show' || !file_exists($file)) {
382e71ce681SAndreas Gohr        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
383f3f0262cSandi        return $crumbs;
384f3f0262cSandi    }
385a77f5846Sjan
386a77f5846Sjan    // page names
3871a84a0f3SAnika Henke    $name = noNSorNS($ID);
388fe9ec250SChris Smith    if(useHeading('navigation')) {
389a77f5846Sjan        // get page title
39067c15eceSMichael Hamann        $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
391a77f5846Sjan        if($title) {
392a77f5846Sjan            $name = $title;
393a77f5846Sjan        }
394a77f5846Sjan    }
395a77f5846Sjan
396f3f0262cSandi    //remove ID from array
397a77f5846Sjan    if(isset($crumbs[$ID])) {
398a77f5846Sjan        unset($crumbs[$ID]);
399f3f0262cSandi    }
400f3f0262cSandi
401f3f0262cSandi    //add to array
402a77f5846Sjan    $crumbs[$ID] = $name;
403f3f0262cSandi    //reduce size
404f3f0262cSandi    while(count($crumbs) > $conf['breadcrumbs']) {
405f3f0262cSandi        array_shift($crumbs);
406f3f0262cSandi    }
407f3f0262cSandi    //save to session
408e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
409f3f0262cSandi    return $crumbs;
410f3f0262cSandi}
411f3f0262cSandi
412f3f0262cSandi/**
41315fae107Sandi * Filter for page IDs
41415fae107Sandi *
415f3f0262cSandi * This is run on a ID before it is outputted somewhere
416f3f0262cSandi * currently used to replace the colon with something else
417907f24f7SAndreas Gohr * on Windows (non-IIS) systems and to have proper URL encoding
418907f24f7SAndreas Gohr *
419907f24f7SAndreas Gohr * See discussions at https://github.com/splitbrain/dokuwiki/pull/84 and
420907f24f7SAndreas Gohr * https://github.com/splitbrain/dokuwiki/pull/173 why we use a whitelist of
421907f24f7SAndreas Gohr * unaffected servers instead of blacklisting affected servers here.
42215fae107Sandi *
42349c713a3Sandi * Urlencoding is ommitted when the second parameter is false
42449c713a3Sandi *
42515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
426140cfbcdSGerrit Uitslag *
427140cfbcdSGerrit Uitslag * @param string $id pageid being filtered
428140cfbcdSGerrit Uitslag * @param bool   $ue apply urlencoding?
429140cfbcdSGerrit Uitslag * @return string
430f3f0262cSandi */
43149c713a3Sandifunction idfilter($id, $ue = true) {
432f3f0262cSandi    global $conf;
433585bf44eSChristopher Smith    /* @var Input $INPUT */
434585bf44eSChristopher Smith    global $INPUT;
435585bf44eSChristopher Smith
436f3f0262cSandi    if($conf['useslash'] && $conf['userewrite']) {
437f3f0262cSandi        $id = strtr($id, ':', '/');
438f3f0262cSandi    } elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
43958bedc8aSborekb        $conf['userewrite'] &&
440585bf44eSChristopher Smith        strpos($INPUT->server->str('SERVER_SOFTWARE'), 'Microsoft-IIS') === false
4413272d797SAndreas Gohr    ) {
442f3f0262cSandi        $id = strtr($id, ':', ';');
443f3f0262cSandi    }
44449c713a3Sandi    if($ue) {
445b6c6979fSAndreas Gohr        $id = rawurlencode($id);
446f3f0262cSandi        $id = str_replace('%3A', ':', $id); //keep as colon
447edd95259SGerrit Uitslag        $id = str_replace('%3B', ';', $id); //keep as semicolon
448f3f0262cSandi        $id = str_replace('%2F', '/', $id); //keep as slash
44949c713a3Sandi    }
450f3f0262cSandi    return $id;
451f3f0262cSandi}
452f3f0262cSandi
453f3f0262cSandi/**
454ed7b5f09Sandi * This builds a link to a wikipage
45515fae107Sandi *
4564bc480e5SAndreas Gohr * It handles URL rewriting and adds additional parameters
4576c7843b5Sandi *
45815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
4594bc480e5SAndreas Gohr *
4604bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
4614bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
4624bc480e5SAndreas Gohr * @param bool         $absolute       request an absolute URL instead of relative
4634bc480e5SAndreas Gohr * @param string       $separator      parameter separator
4644bc480e5SAndreas Gohr * @return string
465f3f0262cSandi */
46616f15a81SDominik Eckelmannfunction wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;') {
467f3f0262cSandi    global $conf;
46816f15a81SDominik Eckelmann    if(is_array($urlParameters)) {
4694bde2196Slisps        if(isset($urlParameters['rev']) && !$urlParameters['rev']) unset($urlParameters['rev']);
4707b62b42dSlisps        if(isset($urlParameters['at']) && $conf['date_at_format']) $urlParameters['at'] = date($conf['date_at_format'],$urlParameters['at']);
47116f15a81SDominik Eckelmann        $urlParameters = buildURLparams($urlParameters, $separator);
4726de3759aSAndreas Gohr    } else {
47316f15a81SDominik Eckelmann        $urlParameters = str_replace(',', $separator, $urlParameters);
4746de3759aSAndreas Gohr    }
47516f15a81SDominik Eckelmann    if($id === '') {
47616f15a81SDominik Eckelmann        $id = $conf['start'];
47716f15a81SDominik Eckelmann    }
478f3f0262cSandi    $id = idfilter($id);
47916f15a81SDominik Eckelmann    if($absolute) {
480ed7b5f09Sandi        $xlink = DOKU_URL;
481ed7b5f09Sandi    } else {
482ed7b5f09Sandi        $xlink = DOKU_BASE;
483ed7b5f09Sandi    }
484f3f0262cSandi
4856c7843b5Sandi    if($conf['userewrite'] == 2) {
4866c7843b5Sandi        $xlink .= DOKU_SCRIPT.'/'.$id;
48716f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
4886c7843b5Sandi    } elseif($conf['userewrite']) {
489f3f0262cSandi        $xlink .= $id;
49016f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
491bce3726dSAndreas Gohr    } elseif($id) {
4926c7843b5Sandi        $xlink .= DOKU_SCRIPT.'?id='.$id;
49316f15a81SDominik Eckelmann        if($urlParameters) $xlink .= $separator.$urlParameters;
494bce3726dSAndreas Gohr    } else {
495bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
49616f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
497f3f0262cSandi    }
498f3f0262cSandi
499f3f0262cSandi    return $xlink;
500f3f0262cSandi}
501f3f0262cSandi
502f3f0262cSandi/**
503f5c2808fSBen Coburn * This builds a link to an alternate page format
504f5c2808fSBen Coburn *
505f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
506f5c2808fSBen Coburn *
507f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
5084bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
5094bc480e5SAndreas Gohr * @param string       $format         the export renderer to use
5104bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
5114bc480e5SAndreas Gohr * @param bool         $abs            request an absolute URL instead of relative
5124bc480e5SAndreas Gohr * @param string       $sep            parameter separator
5134bc480e5SAndreas Gohr * @return string
514f5c2808fSBen Coburn */
5154bc480e5SAndreas Gohrfunction exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;') {
516f5c2808fSBen Coburn    global $conf;
5174bc480e5SAndreas Gohr    if(is_array($urlParameters)) {
5184bc480e5SAndreas Gohr        $urlParameters = buildURLparams($urlParameters, $sep);
519f5c2808fSBen Coburn    } else {
5204bc480e5SAndreas Gohr        $urlParameters = str_replace(',', $sep, $urlParameters);
521f5c2808fSBen Coburn    }
522f5c2808fSBen Coburn
523f5c2808fSBen Coburn    $format = rawurlencode($format);
524f5c2808fSBen Coburn    $id     = idfilter($id);
525f5c2808fSBen Coburn    if($abs) {
526f5c2808fSBen Coburn        $xlink = DOKU_URL;
527f5c2808fSBen Coburn    } else {
528f5c2808fSBen Coburn        $xlink = DOKU_BASE;
529f5c2808fSBen Coburn    }
530f5c2808fSBen Coburn
531f5c2808fSBen Coburn    if($conf['userewrite'] == 2) {
532f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
5334bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
534f5c2808fSBen Coburn    } elseif($conf['userewrite'] == 1) {
535f5c2808fSBen Coburn        $xlink .= '_export/'.$format.'/'.$id;
5364bc480e5SAndreas Gohr        if($urlParameters) $xlink .= '?'.$urlParameters;
537f5c2808fSBen Coburn    } else {
538f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
5394bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
540f5c2808fSBen Coburn    }
541f5c2808fSBen Coburn
542f5c2808fSBen Coburn    return $xlink;
543f5c2808fSBen Coburn}
544f5c2808fSBen Coburn
545f5c2808fSBen Coburn/**
5466de3759aSAndreas Gohr * Build a link to a media file
5476de3759aSAndreas Gohr *
5486de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
5498c08db0aSAndreas Gohr *
5508c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
5518c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
5528c08db0aSAndreas Gohr *
5533272d797SAndreas Gohr * @param string  $id     the media file id or URL
5543272d797SAndreas Gohr * @param mixed   $more   string or array with additional parameters
5553272d797SAndreas Gohr * @param bool    $direct link to detail page if false
5563272d797SAndreas Gohr * @param string  $sep    URL parameter separator
5573272d797SAndreas Gohr * @param bool    $abs    Create an absolute URL
5583272d797SAndreas Gohr * @return string
5596de3759aSAndreas Gohr */
56055b2b31bSAndreas Gohrfunction ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false) {
5616de3759aSAndreas Gohr    global $conf;
562b9ee6a44SKlap-in    $isexternalimage = media_isexternal($id);
563826d2766SKlap-in    if(!$isexternalimage) {
564826d2766SKlap-in        $id = cleanID($id);
565826d2766SKlap-in    }
566826d2766SKlap-in
5676de3759aSAndreas Gohr    if(is_array($more)) {
5680f4e0092SChristopher Smith        // add token for resized images
569443e135dSChristopher Smith        if(!empty($more['w']) || !empty($more['h']) || $isexternalimage){
5700f4e0092SChristopher Smith            $more['tok'] = media_get_token($id,$more['w'],$more['h']);
5710f4e0092SChristopher Smith        }
5728c08db0aSAndreas Gohr        // strip defaults for shorter URLs
5738c08db0aSAndreas Gohr        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
574443e135dSChristopher Smith        if(empty($more['w'])) unset($more['w']);
575443e135dSChristopher Smith        if(empty($more['h'])) unset($more['h']);
5768c08db0aSAndreas Gohr        if(isset($more['id']) && $direct) unset($more['id']);
57778b874e6Slisps        if(isset($more['rev']) && !$more['rev']) unset($more['rev']);
578b174aeaeSchris        $more = buildURLparams($more, $sep);
5796de3759aSAndreas Gohr    } else {
5805e7db1e2SChristopher Smith        $matches = array();
581cc036f74SKlap-in        if (preg_match_all('/\b(w|h)=(\d*)\b/',$more,$matches,PREG_SET_ORDER) || $isexternalimage){
5825e7db1e2SChristopher Smith            $resize = array('w'=>0, 'h'=>0);
5835e7db1e2SChristopher Smith            foreach ($matches as $match){
5845e7db1e2SChristopher Smith                $resize[$match[1]] = $match[2];
5855e7db1e2SChristopher Smith            }
586cc036f74SKlap-in            $more .= $more === '' ? '' : $sep;
587cc036f74SKlap-in            $more .= 'tok='.media_get_token($id,$resize['w'],$resize['h']);
5885e7db1e2SChristopher Smith        }
5898c08db0aSAndreas Gohr        $more = str_replace('cache=cache', '', $more); //skip default
5908c08db0aSAndreas Gohr        $more = str_replace(',,', ',', $more);
591b174aeaeSchris        $more = str_replace(',', $sep, $more);
5926de3759aSAndreas Gohr    }
5936de3759aSAndreas Gohr
59455b2b31bSAndreas Gohr    if($abs) {
59555b2b31bSAndreas Gohr        $xlink = DOKU_URL;
59655b2b31bSAndreas Gohr    } else {
5976de3759aSAndreas Gohr        $xlink = DOKU_BASE;
59855b2b31bSAndreas Gohr    }
5996de3759aSAndreas Gohr
6006de3759aSAndreas Gohr    // external URLs are always direct without rewriting
601826d2766SKlap-in    if($isexternalimage) {
6026de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
603cc036f74SKlap-in        $xlink .= '?'.$more;
604b174aeaeSchris        $xlink .= $sep.'media='.rawurlencode($id);
6056de3759aSAndreas Gohr        return $xlink;
6066de3759aSAndreas Gohr    }
6076de3759aSAndreas Gohr
6086de3759aSAndreas Gohr    $id = idfilter($id);
6096de3759aSAndreas Gohr
6106de3759aSAndreas Gohr    // decide on scriptname
6116de3759aSAndreas Gohr    if($direct) {
6126de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
6136de3759aSAndreas Gohr            $script = '_media';
6146de3759aSAndreas Gohr        } else {
6156de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
6166de3759aSAndreas Gohr        }
6176de3759aSAndreas Gohr    } else {
6186de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
6196de3759aSAndreas Gohr            $script = '_detail';
6206de3759aSAndreas Gohr        } else {
6216de3759aSAndreas Gohr            $script = 'lib/exe/detail.php';
6226de3759aSAndreas Gohr        }
6236de3759aSAndreas Gohr    }
6246de3759aSAndreas Gohr
6256de3759aSAndreas Gohr    // build URL based on rewrite mode
6266de3759aSAndreas Gohr    if($conf['userewrite']) {
6276de3759aSAndreas Gohr        $xlink .= $script.'/'.$id;
6286de3759aSAndreas Gohr        if($more) $xlink .= '?'.$more;
6296de3759aSAndreas Gohr    } else {
6306de3759aSAndreas Gohr        if($more) {
631a99d3236SEsther Brunner            $xlink .= $script.'?'.$more;
632b174aeaeSchris            $xlink .= $sep.'media='.$id;
6336de3759aSAndreas Gohr        } else {
634a99d3236SEsther Brunner            $xlink .= $script.'?media='.$id;
6356de3759aSAndreas Gohr        }
6366de3759aSAndreas Gohr    }
6376de3759aSAndreas Gohr
6386de3759aSAndreas Gohr    return $xlink;
6396de3759aSAndreas Gohr}
6406de3759aSAndreas Gohr
6416de3759aSAndreas Gohr/**
64225ca5b17SAndreas Gohr * Returns the URL to the DokuWiki base script
64315fae107Sandi *
64425ca5b17SAndreas Gohr * Consider using wl() instead, unless you absoutely need the doku.php endpoint
64525ca5b17SAndreas Gohr *
64615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
647140cfbcdSGerrit Uitslag *
648140cfbcdSGerrit Uitslag * @return string
649f3f0262cSandi */
65025ca5b17SAndreas Gohrfunction script() {
651ed7b5f09Sandi    return DOKU_BASE.DOKU_SCRIPT;
652f3f0262cSandi}
653f3f0262cSandi
654f3f0262cSandi/**
65515fae107Sandi * Spamcheck against wordlist
65615fae107Sandi *
657f3f0262cSandi * Checks the wikitext against a list of blocked expressions
658f3f0262cSandi * returns true if the text contains any bad words
65915fae107Sandi *
660e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
661e403cc58SMichael Klier *
662e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
663e403cc58SMichael Klier *  and gain information about the user who was blocked.
664e403cc58SMichael Klier *
665e403cc58SMichael Klier *  Event data:
666e403cc58SMichael Klier *    data['matches']  - array of matches
667e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
668e403cc58SMichael Klier *      [ip]           - ip address
669e403cc58SMichael Klier *      [user]         - username (if logged in)
670e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
671e403cc58SMichael Klier *      [name]         - real name (if logged in)
672e403cc58SMichael Klier *
67315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
6746dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
675140cfbcdSGerrit Uitslag *
6766dffa0e0SAndreas Gohr * @param  string $text - optional text to check, if not given the globals are used
6776dffa0e0SAndreas Gohr * @return bool         - true if a spam word was found
678f3f0262cSandi */
6796dffa0e0SAndreas Gohrfunction checkwordblock($text = '') {
680f3f0262cSandi    global $TEXT;
6816dffa0e0SAndreas Gohr    global $PRE;
6826dffa0e0SAndreas Gohr    global $SUF;
683e0086ca2SAndreas Gohr    global $SUM;
684f3f0262cSandi    global $conf;
685e403cc58SMichael Klier    global $INFO;
686585bf44eSChristopher Smith    /* @var Input $INPUT */
687585bf44eSChristopher Smith    global $INPUT;
688f3f0262cSandi
689f3f0262cSandi    if(!$conf['usewordblock']) return false;
690f3f0262cSandi
691e0086ca2SAndreas Gohr    if(!$text) $text = "$PRE $TEXT $SUF $SUM";
6926dffa0e0SAndreas Gohr
693041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
6946dffa0e0SAndreas Gohr    $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i', '\1http://\2 \2\3', $text);
695041d1964SAndreas Gohr
696b9ac8716Schris    $wordblocks = getWordblocks();
6973e2965d7Sandi    // how many lines to read at once (to work around some PCRE limits)
6983e2965d7Sandi    if(version_compare(phpversion(), '4.3.0', '<')) {
6993e2965d7Sandi        // old versions of PCRE define a maximum of parenthesises even if no
7003e2965d7Sandi        // backreferences are used - the maximum is 99
7013e2965d7Sandi        // this is very bad performancewise and may even be too high still
7023e2965d7Sandi        $chunksize = 40;
7033e2965d7Sandi    } else {
704a51d08efSAndreas Gohr        // read file in chunks of 200 - this should work around the
7053e2965d7Sandi        // MAX_PATTERN_SIZE in modern PCRE
706a51d08efSAndreas Gohr        $chunksize = 200;
7073e2965d7Sandi    }
708b9ac8716Schris    while($blocks = array_splice($wordblocks, 0, $chunksize)) {
709f3f0262cSandi        $re = array();
71049eb6e38SAndreas Gohr        // build regexp from blocks
711f3f0262cSandi        foreach($blocks as $block) {
712f3f0262cSandi            $block = preg_replace('/#.*$/', '', $block);
713f3f0262cSandi            $block = trim($block);
714f3f0262cSandi            if(empty($block)) continue;
715f3f0262cSandi            $re[] = $block;
716f3f0262cSandi        }
717e403cc58SMichael Klier        if(count($re) && preg_match('#('.join('|', $re).')#si', $text, $matches)) {
718e403cc58SMichael Klier            // prepare event data
71959bc3b48SGerrit Uitslag            $data = array();
720e403cc58SMichael Klier            $data['matches']        = $matches;
721585bf44eSChristopher Smith            $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
722585bf44eSChristopher Smith            if($INPUT->server->str('REMOTE_USER')) {
723585bf44eSChristopher Smith                $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
724e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
725e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
726e403cc58SMichael Klier            }
727e403cc58SMichael Klier            $callback = create_function('', 'return true;');
728e403cc58SMichael Klier            return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
729b9ac8716Schris        }
730703f6fdeSandi    }
731f3f0262cSandi    return false;
732f3f0262cSandi}
733f3f0262cSandi
734f3f0262cSandi/**
73515fae107Sandi * Return the IP of the client
73615fae107Sandi *
7376d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
73815fae107Sandi *
7396d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
7406d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
7416d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
7426d8affe6SAndreas Gohr * headers
7436d8affe6SAndreas Gohr *
74415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
745140cfbcdSGerrit Uitslag *
7463272d797SAndreas Gohr * @param  boolean $single If set only a single IP is returned
7473272d797SAndreas Gohr * @return string
748f3f0262cSandi */
7496d8affe6SAndreas Gohrfunction clientIP($single = false) {
750585bf44eSChristopher Smith    /* @var Input $INPUT */
751585bf44eSChristopher Smith    global $INPUT;
752585bf44eSChristopher Smith
7536d8affe6SAndreas Gohr    $ip   = array();
754585bf44eSChristopher Smith    $ip[] = $INPUT->server->str('REMOTE_ADDR');
755585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_FORWARDED_FOR')) {
756585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_FORWARDED_FOR'))));
757585bf44eSChristopher Smith    }
758585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_REAL_IP')) {
759585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_REAL_IP'))));
760585bf44eSChristopher Smith    }
7616d8affe6SAndreas Gohr
762dc14c6d1SGuy Brand    // some IPv4/v6 regexps borrowed from Feyd
763dc14c6d1SGuy Brand    // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
764dc14c6d1SGuy Brand    $dec_octet   = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
765dc14c6d1SGuy Brand    $hex_digit   = '[A-Fa-f0-9]';
766dc14c6d1SGuy Brand    $h16         = "{$hex_digit}{1,4}";
767dc14c6d1SGuy Brand    $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
768dc14c6d1SGuy Brand    $ls32        = "(?:$h16:$h16|$IPv4Address)";
769dc14c6d1SGuy Brand    $IPv6Address =
770dc14c6d1SGuy Brand        "(?:(?:{$IPv4Address})|(?:".
771dc14c6d1SGuy Brand            "(?:$h16:){6}$ls32".
772dc14c6d1SGuy Brand            "|::(?:$h16:){5}$ls32".
773dc14c6d1SGuy Brand            "|(?:$h16)?::(?:$h16:){4}$ls32".
774dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32".
775dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32".
776dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32".
777dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,4}$h16)?::$ls32".
778dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,5}$h16)?::$h16".
779dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,6}$h16)?::".
780dc14c6d1SGuy Brand            ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
781dc14c6d1SGuy Brand
7826d8affe6SAndreas Gohr    // remove any non-IP stuff
7836d8affe6SAndreas Gohr    $cnt   = count($ip);
7844ff28443Schris    $match = array();
7856d8affe6SAndreas Gohr    for($i = 0; $i < $cnt; $i++) {
786dc14c6d1SGuy Brand        if(preg_match("/^$IPv4Address$/", $ip[$i], $match) || preg_match("/^$IPv6Address$/", $ip[$i], $match)) {
7874ff28443Schris            $ip[$i] = $match[0];
7884ff28443Schris        } else {
7894ff28443Schris            $ip[$i] = '';
7904ff28443Schris        }
7916d8affe6SAndreas Gohr        if(empty($ip[$i])) unset($ip[$i]);
792f3f0262cSandi    }
7936d8affe6SAndreas Gohr    $ip = array_values(array_unique($ip));
7946d8affe6SAndreas Gohr    if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
7956d8affe6SAndreas Gohr
7966d8affe6SAndreas Gohr    if(!$single) return join(',', $ip);
7976d8affe6SAndreas Gohr
7986d8affe6SAndreas Gohr    // decide which IP to use, trying to avoid local addresses
7996d8affe6SAndreas Gohr    $ip = array_reverse($ip);
8006d8affe6SAndreas Gohr    foreach($ip as $i) {
8012343a762SAndreas Gohr        if(preg_match('/^(::1|[fF][eE]80:|127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/', $i)) {
8026d8affe6SAndreas Gohr            continue;
8036d8affe6SAndreas Gohr        } else {
8046d8affe6SAndreas Gohr            return $i;
8056d8affe6SAndreas Gohr        }
8066d8affe6SAndreas Gohr    }
8076d8affe6SAndreas Gohr    // still here? just use the first (last) address
8086d8affe6SAndreas Gohr    return $ip[0];
809f3f0262cSandi}
810f3f0262cSandi
811f3f0262cSandi/**
8121c548ebeSAndreas Gohr * Check if the browser is on a mobile device
8131c548ebeSAndreas Gohr *
8141c548ebeSAndreas Gohr * Adapted from the example code at url below
8151c548ebeSAndreas Gohr *
8161c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
817140cfbcdSGerrit Uitslag *
818140cfbcdSGerrit Uitslag * @return bool if true, client is mobile browser; otherwise false
8191c548ebeSAndreas Gohr */
8201c548ebeSAndreas Gohrfunction clientismobile() {
821585bf44eSChristopher Smith    /* @var Input $INPUT */
822585bf44eSChristopher Smith    global $INPUT;
8231c548ebeSAndreas Gohr
824585bf44eSChristopher Smith    if($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
8251c548ebeSAndreas Gohr
826585bf44eSChristopher Smith    if(preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
8271c548ebeSAndreas Gohr
828585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_USER_AGENT')) return false;
8291c548ebeSAndreas Gohr
8301c548ebeSAndreas 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';
8311c548ebeSAndreas Gohr
832585bf44eSChristopher Smith    if(preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
8331c548ebeSAndreas Gohr
8341c548ebeSAndreas Gohr    return false;
8351c548ebeSAndreas Gohr}
8361c548ebeSAndreas Gohr
8371c548ebeSAndreas Gohr/**
83863211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
83963211f61SGlen Harris *
84022ef1e32SAndreas Gohr * If $conf['dnslookups'] is disabled it simply returns the input string
84122ef1e32SAndreas Gohr *
84263211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
843140cfbcdSGerrit Uitslag *
8443272d797SAndreas Gohr * @param  string $ips comma separated list of IP addresses
8453272d797SAndreas Gohr * @return string a comma separated list of hostnames
84663211f61SGlen Harris */
84763211f61SGlen Harrisfunction gethostsbyaddrs($ips) {
84822ef1e32SAndreas Gohr    global $conf;
84922ef1e32SAndreas Gohr    if(!$conf['dnslookups']) return $ips;
85022ef1e32SAndreas Gohr
85163211f61SGlen Harris    $hosts = array();
85263211f61SGlen Harris    $ips   = explode(',', $ips);
853551a720fSMichael Klier
854551a720fSMichael Klier    if(is_array($ips)) {
8553886270dSAndreas Gohr        foreach($ips as $ip) {
856551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
85763211f61SGlen Harris        }
858551a720fSMichael Klier        return join(',', $hosts);
859551a720fSMichael Klier    } else {
860551a720fSMichael Klier        return gethostbyaddr(trim($ips));
861551a720fSMichael Klier    }
86263211f61SGlen Harris}
86363211f61SGlen Harris
86463211f61SGlen Harris/**
86515fae107Sandi * Checks if a given page is currently locked.
86615fae107Sandi *
867f3f0262cSandi * removes stale lockfiles
86815fae107Sandi *
86915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
870140cfbcdSGerrit Uitslag *
871140cfbcdSGerrit Uitslag * @param string $id page id
872140cfbcdSGerrit Uitslag * @return bool page is locked?
873f3f0262cSandi */
874f3f0262cSandifunction checklock($id) {
875f3f0262cSandi    global $conf;
876585bf44eSChristopher Smith    /* @var Input $INPUT */
877585bf44eSChristopher Smith    global $INPUT;
878585bf44eSChristopher Smith
879c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
880f3f0262cSandi
881f3f0262cSandi    //no lockfile
88279e79377SAndreas Gohr    if(!file_exists($lock)) return false;
883f3f0262cSandi
884f3f0262cSandi    //lockfile expired
885f3f0262cSandi    if((time() - filemtime($lock)) > $conf['locktime']) {
886d8186216SBen Coburn        @unlink($lock);
887f3f0262cSandi        return false;
888f3f0262cSandi    }
889f3f0262cSandi
890f3f0262cSandi    //my own lock
8916d2af55dSChristopher Smith    @list($ip, $session) = explode("\n", io_readFile($lock));
8920712fefaSAndreas Gohr    if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || (session_id() && $session == session_id())) {
893f3f0262cSandi        return false;
894f3f0262cSandi    }
895f3f0262cSandi
896f3f0262cSandi    return $ip;
897f3f0262cSandi}
898f3f0262cSandi
899f3f0262cSandi/**
90015fae107Sandi * Lock a page for editing
90115fae107Sandi *
90215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
903140cfbcdSGerrit Uitslag *
904140cfbcdSGerrit Uitslag * @param string $id page id to lock
905f3f0262cSandi */
906f3f0262cSandifunction lock($id) {
907544ed901SDaniel Calviño Sánchez    global $conf;
908585bf44eSChristopher Smith    /* @var Input $INPUT */
909585bf44eSChristopher Smith    global $INPUT;
910544ed901SDaniel Calviño Sánchez
911544ed901SDaniel Calviño Sánchez    if($conf['locktime'] == 0) {
912544ed901SDaniel Calviño Sánchez        return;
913544ed901SDaniel Calviño Sánchez    }
914544ed901SDaniel Calviño Sánchez
915c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
916585bf44eSChristopher Smith    if($INPUT->server->str('REMOTE_USER')) {
917585bf44eSChristopher Smith        io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
918f3f0262cSandi    } else {
91985fef7e2SAndreas Gohr        io_saveFile($lock, clientIP()."\n".session_id());
920f3f0262cSandi    }
921f3f0262cSandi}
922f3f0262cSandi
923f3f0262cSandi/**
92415fae107Sandi * Unlock a page if it was locked by the user
925f3f0262cSandi *
92615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
927140cfbcdSGerrit Uitslag *
9283272d797SAndreas Gohr * @param string $id page id to unlock
92915fae107Sandi * @return bool true if a lock was removed
930f3f0262cSandi */
931f3f0262cSandifunction unlock($id) {
932585bf44eSChristopher Smith    /* @var Input $INPUT */
933585bf44eSChristopher Smith    global $INPUT;
934585bf44eSChristopher Smith
935c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
93679e79377SAndreas Gohr    if(file_exists($lock)) {
9376d2af55dSChristopher Smith        @list($ip, $session) = explode("\n", io_readFile($lock));
938585bf44eSChristopher Smith        if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || $session == session_id()) {
939f3f0262cSandi            @unlink($lock);
940f3f0262cSandi            return true;
941f3f0262cSandi        }
942f3f0262cSandi    }
943f3f0262cSandi    return false;
944f3f0262cSandi}
945f3f0262cSandi
946f3f0262cSandi/**
947f3f0262cSandi * convert line ending to unix format
948f3f0262cSandi *
9496db7468bSAndreas Gohr * also makes sure the given text is valid UTF-8
9506db7468bSAndreas Gohr *
95115fae107Sandi * @see    formText() for 2crlf conversion
95215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
953140cfbcdSGerrit Uitslag *
954140cfbcdSGerrit Uitslag * @param string $text
955140cfbcdSGerrit Uitslag * @return string
956f3f0262cSandi */
957f3f0262cSandifunction cleanText($text) {
958f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
9596db7468bSAndreas Gohr
9606db7468bSAndreas Gohr    // if the text is not valid UTF-8 we simply assume latin1
9616db7468bSAndreas Gohr    // this won't break any worse than it breaks with the wrong encoding
9626db7468bSAndreas Gohr    // but might actually fix the problem in many cases
9636db7468bSAndreas Gohr    if(!utf8_check($text)) $text = utf8_encode($text);
9646db7468bSAndreas Gohr
965f3f0262cSandi    return $text;
966f3f0262cSandi}
967f3f0262cSandi
968f3f0262cSandi/**
969f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
970f3f0262cSandi * It also converts line endings to Windows format which is
971f3f0262cSandi * pseudo standard for webforms.
972f3f0262cSandi *
97315fae107Sandi * @see    cleanText() for 2unix conversion
97415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
975140cfbcdSGerrit Uitslag *
976140cfbcdSGerrit Uitslag * @param string $text
977140cfbcdSGerrit Uitslag * @return string
978f3f0262cSandi */
979f3f0262cSandifunction formText($text) {
9805b7d45a5SAndreas Gohr    $text = str_replace("\012", "\015\012", $text);
981f3f0262cSandi    return htmlspecialchars($text);
982f3f0262cSandi}
983f3f0262cSandi
984f3f0262cSandi/**
98515fae107Sandi * Returns the specified local text in raw format
98615fae107Sandi *
98715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
988140cfbcdSGerrit Uitslag *
989140cfbcdSGerrit Uitslag * @param string $id   page id
990140cfbcdSGerrit Uitslag * @param string $ext  extension of file being read, default 'txt'
991140cfbcdSGerrit Uitslag * @return string
992f3f0262cSandi */
9932adaf2b8SAndreas Gohrfunction rawLocale($id, $ext = 'txt') {
9942adaf2b8SAndreas Gohr    return io_readFile(localeFN($id, $ext));
995f3f0262cSandi}
996f3f0262cSandi
997f3f0262cSandi/**
998f3f0262cSandi * Returns the raw WikiText
99915fae107Sandi *
100015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1001140cfbcdSGerrit Uitslag *
1002140cfbcdSGerrit Uitslag * @param string $id   page id
1003e0c26282SGerrit Uitslag * @param string|int $rev  timestamp when a revision of wikitext is desired
1004140cfbcdSGerrit Uitslag * @return string
1005f3f0262cSandi */
1006f3f0262cSandifunction rawWiki($id, $rev = '') {
1007cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1008f3f0262cSandi}
1009f3f0262cSandi
1010f3f0262cSandi/**
10117146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
10127146cee2SAndreas Gohr *
10137b84afa2SAndreas Gohr * @triggers COMMON_PAGETPL_LOAD
10147146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1015140cfbcdSGerrit Uitslag *
1016140cfbcdSGerrit Uitslag * @param string $id the id of the page to be created
1017140cfbcdSGerrit Uitslag * @return string parsed pagetemplate content
10187146cee2SAndreas Gohr */
1019fe17917eSAdrian Langfunction pageTemplate($id) {
1020a15ce62dSEsther Brunner    global $conf;
1021e29549feSAndreas Gohr
1022fe17917eSAdrian Lang    if(is_array($id)) $id = $id[0];
1023e29549feSAndreas Gohr
10247b84afa2SAndreas Gohr    // prepare initial event data
10257b84afa2SAndreas Gohr    $data = array(
10267b84afa2SAndreas Gohr        'id'        => $id, // the id of the page to be created
10277b84afa2SAndreas Gohr        'tpl'       => '', // the text used as template
10287b84afa2SAndreas Gohr        'tplfile'   => '', // the file above text was/should be loaded from
10297b84afa2SAndreas Gohr        'doreplace' => true // should wildcard replacements be done on the text?
10307b84afa2SAndreas Gohr    );
10317b84afa2SAndreas Gohr
10327b84afa2SAndreas Gohr    $evt = new Doku_Event('COMMON_PAGETPL_LOAD', $data);
10337b84afa2SAndreas Gohr    if($evt->advise_before(true)) {
10347b84afa2SAndreas Gohr        // the before event might have loaded the content already
10357b84afa2SAndreas Gohr        if(empty($data['tpl'])) {
10367b84afa2SAndreas Gohr            // if the before event did not set a template file, try to find one
10377b84afa2SAndreas Gohr            if(empty($data['tplfile'])) {
1038fe17917eSAdrian Lang                $path = dirname(wikiFN($id));
103979e79377SAndreas Gohr                if(file_exists($path.'/_template.txt')) {
10407b84afa2SAndreas Gohr                    $data['tplfile'] = $path.'/_template.txt';
1041e29549feSAndreas Gohr                } else {
1042e29549feSAndreas Gohr                    // search upper namespaces for templates
1043e29549feSAndreas Gohr                    $len = strlen(rtrim($conf['datadir'], '/'));
1044e29549feSAndreas Gohr                    while(strlen($path) >= $len) {
104579e79377SAndreas Gohr                        if(file_exists($path.'/__template.txt')) {
10467b84afa2SAndreas Gohr                            $data['tplfile'] = $path.'/__template.txt';
1047e29549feSAndreas Gohr                            break;
1048e29549feSAndreas Gohr                        }
1049e29549feSAndreas Gohr                        $path = substr($path, 0, strrpos($path, '/'));
1050e29549feSAndreas Gohr                    }
1051e29549feSAndreas Gohr                }
10527b84afa2SAndreas Gohr            }
10537b84afa2SAndreas Gohr            // load the content
10543d7ac595SMichael Hamann            $data['tpl'] = io_readFile($data['tplfile']);
10557b84afa2SAndreas Gohr        }
1056a1bbd05bSMichael Hamann        if($data['doreplace']) parsePageTemplate($data);
10577b84afa2SAndreas Gohr    }
10587b84afa2SAndreas Gohr    $evt->advise_after();
10597b84afa2SAndreas Gohr    unset($evt);
10607b84afa2SAndreas Gohr
1061fe17917eSAdrian Lang    return $data['tpl'];
10622b1223ecSAdrian Lang}
10632b1223ecSAdrian Lang
10642b1223ecSAdrian Lang/**
10652b1223ecSAdrian Lang * Performs common page template replacements
10667b84afa2SAndreas Gohr * This works on data from COMMON_PAGETPL_LOAD
10672b1223ecSAdrian Lang *
10682b1223ecSAdrian Lang * @author Andreas Gohr <andi@splitbrain.org>
1069140cfbcdSGerrit Uitslag *
1070140cfbcdSGerrit Uitslag * @param array $data array with event data
1071140cfbcdSGerrit Uitslag * @return string
10722b1223ecSAdrian Lang */
1073d535a2e9Sstretchyboyfunction parsePageTemplate(&$data) {
10743272d797SAndreas Gohr    /**
10753272d797SAndreas Gohr     * @var string $id        the id of the page to be created
10763272d797SAndreas Gohr     * @var string $tpl       the text used as template
10773272d797SAndreas Gohr     * @var string $tplfile   the file above text was/should be loaded from
10783272d797SAndreas Gohr     * @var bool   $doreplace should wildcard replacements be done on the text?
10793272d797SAndreas Gohr     */
1080fe17917eSAdrian Lang    extract($data);
1081fe17917eSAdrian Lang
1082b856f7dfSAdrian Lang    global $USERINFO;
1083bce53b1fSAdrian Lang    global $conf;
1084585bf44eSChristopher Smith    /* @var Input $INPUT */
1085585bf44eSChristopher Smith    global $INPUT;
1086e29549feSAndreas Gohr
1087e29549feSAndreas Gohr    // replace placeholders
108826ece5a7SAndreas Gohr    $file = noNS($id);
108937c1acbdSAdrian Lang    $page = strtr($file, $conf['sepchar'], ' ');
109026ece5a7SAndreas Gohr
10913272d797SAndreas Gohr    $tpl = str_replace(
10923272d797SAndreas Gohr        array(
109326ece5a7SAndreas Gohr             '@ID@',
109426ece5a7SAndreas Gohr             '@NS@',
109526ece5a7SAndreas Gohr             '@FILE@',
109626ece5a7SAndreas Gohr             '@!FILE@',
109726ece5a7SAndreas Gohr             '@!FILE!@',
109826ece5a7SAndreas Gohr             '@PAGE@',
109926ece5a7SAndreas Gohr             '@!PAGE@',
110026ece5a7SAndreas Gohr             '@!!PAGE@',
110126ece5a7SAndreas Gohr             '@!PAGE!@',
110226ece5a7SAndreas Gohr             '@USER@',
110326ece5a7SAndreas Gohr             '@NAME@',
110426ece5a7SAndreas Gohr             '@MAIL@',
110526ece5a7SAndreas Gohr             '@DATE@',
110626ece5a7SAndreas Gohr        ),
110726ece5a7SAndreas Gohr        array(
110826ece5a7SAndreas Gohr             $id,
110926ece5a7SAndreas Gohr             getNS($id),
111026ece5a7SAndreas Gohr             $file,
111126ece5a7SAndreas Gohr             utf8_ucfirst($file),
111226ece5a7SAndreas Gohr             utf8_strtoupper($file),
111326ece5a7SAndreas Gohr             $page,
111426ece5a7SAndreas Gohr             utf8_ucfirst($page),
111526ece5a7SAndreas Gohr             utf8_ucwords($page),
111626ece5a7SAndreas Gohr             utf8_strtoupper($page),
1117585bf44eSChristopher Smith             $INPUT->server->str('REMOTE_USER'),
1118b856f7dfSAdrian Lang             $USERINFO['name'],
1119b856f7dfSAdrian Lang             $USERINFO['mail'],
112026ece5a7SAndreas Gohr             $conf['dformat'],
11213272d797SAndreas Gohr        ), $tpl
11223272d797SAndreas Gohr    );
112326ece5a7SAndreas Gohr
11247d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
11257d644fc8SAndreas Gohr    $tpl         = preg_replace_callback('/%./', create_function('$m', 'return strftime($m[0]);'), $tpl);
1126d535a2e9Sstretchyboy    $data['tpl'] = $tpl;
1127a15ce62dSEsther Brunner    return $tpl;
11287146cee2SAndreas Gohr}
11297146cee2SAndreas Gohr
11307146cee2SAndreas Gohr/**
113115fae107Sandi * Returns the raw Wiki Text in three slices.
113215fae107Sandi *
113315fae107Sandi * The range parameter needs to have the form "from-to"
113415cfe303Sandi * and gives the range of the section in bytes - no
113515cfe303Sandi * UTF-8 awareness is needed.
1136f3f0262cSandi * The returned order is prefix, section and suffix.
113715fae107Sandi *
113815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1139140cfbcdSGerrit Uitslag *
1140140cfbcdSGerrit Uitslag * @param string $range in form "from-to"
1141140cfbcdSGerrit Uitslag * @param string $id    page id
1142140cfbcdSGerrit Uitslag * @param string $rev   optional, the revision timestamp
114342ea7f44SGerrit Uitslag * @return string[] with three slices
1144f3f0262cSandi */
1145f3f0262cSandifunction rawWikiSlices($range, $id, $rev = '') {
1146cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1147f3f0262cSandi
114880fcb268SAdrian Lang    // Parse range
114980fcb268SAdrian Lang    list($from, $to) = explode('-', $range, 2);
115080fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
115180fcb268SAdrian Lang    $from = !$from ? 0 : ($from - 1);
115280fcb268SAdrian Lang    $to   = !$to ? strlen($text) : ($to - 1);
115380fcb268SAdrian Lang
115459bc3b48SGerrit Uitslag    $slices = array();
115580fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
115680fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to - $from);
115715cfe303Sandi    $slices[2] = substr($text, $to);
1158f3f0262cSandi    return $slices;
1159f3f0262cSandi}
1160f3f0262cSandi
1161f3f0262cSandi/**
116215fae107Sandi * Joins wiki text slices
116315fae107Sandi *
116480fcb268SAdrian Lang * function to join the text slices.
1165f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
1166f3f0262cSandi * lines between sections if needed (used on saving).
116715fae107Sandi *
116815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1169140cfbcdSGerrit Uitslag *
1170140cfbcdSGerrit Uitslag * @param string $pre   prefix
1171140cfbcdSGerrit Uitslag * @param string $text  text in the middle
1172140cfbcdSGerrit Uitslag * @param string $suf   suffix
1173140cfbcdSGerrit Uitslag * @param bool $pretty add additional empty lines between sections
1174140cfbcdSGerrit Uitslag * @return string
1175f3f0262cSandi */
1176f3f0262cSandifunction con($pre, $text, $suf, $pretty = false) {
1177f3f0262cSandi    if($pretty) {
117880fcb268SAdrian Lang        if($pre !== '' && substr($pre, -1) !== "\n" &&
11793272d797SAndreas Gohr            substr($text, 0, 1) !== "\n"
11803272d797SAndreas Gohr        ) {
118180fcb268SAdrian Lang            $pre .= "\n";
118280fcb268SAdrian Lang        }
118380fcb268SAdrian Lang        if($suf !== '' && substr($text, -1) !== "\n" &&
11843272d797SAndreas Gohr            substr($suf, 0, 1) !== "\n"
11853272d797SAndreas Gohr        ) {
118680fcb268SAdrian Lang            $text .= "\n";
118780fcb268SAdrian Lang        }
1188f3f0262cSandi    }
1189f3f0262cSandi
1190f3f0262cSandi    return $pre.$text.$suf;
1191f3f0262cSandi}
1192f3f0262cSandi
1193f3f0262cSandi/**
1194b24d9195SAndreas Gohr * Checks if the current page version is newer than the last entry in the page's
1195b24d9195SAndreas Gohr * changelog. If so, we assume it has been an external edit and we create an
1196b24d9195SAndreas Gohr * attic copy and add a proper changelog line.
1197b24d9195SAndreas Gohr *
1198b24d9195SAndreas Gohr * This check is only executed when the page is about to be saved again from the
1199b24d9195SAndreas Gohr * wiki, triggered in @see saveWikiText()
1200b24d9195SAndreas Gohr *
1201b24d9195SAndreas Gohr * @param string $id the page ID
1202b24d9195SAndreas Gohr */
1203b24d9195SAndreas Gohrfunction detectExternalEdit($id) {
1204b24d9195SAndreas Gohr    global $lang;
1205b24d9195SAndreas Gohr
1206b24d9195SAndreas Gohr    $file     = wikiFN($id);
1207b24d9195SAndreas Gohr    $old      = @filemtime($file); // from page
1208b24d9195SAndreas Gohr    $pagelog  = new PageChangeLog($id, 1024);
1209b24d9195SAndreas Gohr    $oldRev   = $pagelog->getRevisions(-1, 1); // from changelog
1210b24d9195SAndreas Gohr    $oldRev   = (int) (empty($oldRev) ? 0 : $oldRev[0]);
1211b24d9195SAndreas Gohr
1212b24d9195SAndreas Gohr    if(!file_exists(wikiFN($id, $old)) && file_exists($file) && $old >= $oldRev) {
1213b24d9195SAndreas Gohr        // add old revision to the attic if missing
1214b24d9195SAndreas Gohr        saveOldRevision($id);
1215b24d9195SAndreas Gohr        // add a changelog entry if this edit came from outside dokuwiki
1216b24d9195SAndreas Gohr        if($old > $oldRev) {
12172966355bSGerrit Uitslag            $filesize_old = filesize(wikiFN($id, $oldRev));
12182966355bSGerrit Uitslag            $filesize_new = filesize($file);
12192966355bSGerrit Uitslag            $sizechange = $filesize_new - $filesize_old;
12202966355bSGerrit Uitslag
12212966355bSGerrit Uitslag            addLogEntry($old, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=> true), $sizechange);
1222b24d9195SAndreas Gohr            // remove soon to be stale instructions
1223b24d9195SAndreas Gohr            $cache = new cache_instructions($id, $file);
1224b24d9195SAndreas Gohr            $cache->removeCache();
1225b24d9195SAndreas Gohr        }
1226b24d9195SAndreas Gohr    }
1227b24d9195SAndreas Gohr}
1228b24d9195SAndreas Gohr
1229b24d9195SAndreas Gohr/**
1230a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
1231a701424fSBen Coburn * Also directs changelog and attic updates.
123215fae107Sandi *
123315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
123471726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
1235140cfbcdSGerrit Uitslag *
1236140cfbcdSGerrit Uitslag * @param string $id       page id
1237140cfbcdSGerrit Uitslag * @param string $text     wikitext being saved
1238140cfbcdSGerrit Uitslag * @param string $summary  summary of text update
1239140cfbcdSGerrit Uitslag * @param bool   $minor    mark this saved version as minor update
1240f3f0262cSandi */
1241b6912aeaSAndreas Gohrfunction saveWikiText($id, $text, $summary, $minor = false) {
1242a701424fSBen Coburn    /* Note to developers:
1243a701424fSBen Coburn       This code is subtle and delicate. Test the behavior of
1244a701424fSBen Coburn       the attic and changelog with dokuwiki and external edits
1245a701424fSBen Coburn       after any changes. External edits change the wiki page
1246a701424fSBen Coburn       directly without using php or dokuwiki.
1247a701424fSBen Coburn     */
1248f3f0262cSandi    global $conf;
1249f3f0262cSandi    global $lang;
125071726d78SBen Coburn    global $REV;
1251585bf44eSChristopher Smith    /* @var Input $INPUT */
1252585bf44eSChristopher Smith    global $INPUT;
1253585bf44eSChristopher Smith
1254b24d9195SAndreas Gohr    // prepare data for event
1255b24d9195SAndreas Gohr    $svdta = array();
1256b24d9195SAndreas Gohr    $svdta['id']             = $id;
1257b24d9195SAndreas Gohr    $svdta['file']           = wikiFN($id);
1258b24d9195SAndreas Gohr    $svdta['revertFrom']     = $REV;
1259b24d9195SAndreas Gohr    $svdta['oldRevision']    = @filemtime($svdta['file']);
1260b24d9195SAndreas Gohr    $svdta['newRevision']    = 0;
1261b24d9195SAndreas Gohr    $svdta['newContent']     = $text;
1262b24d9195SAndreas Gohr    $svdta['oldContent']     = rawWiki($id);
1263b24d9195SAndreas Gohr    $svdta['summary']        = $summary;
1264b24d9195SAndreas Gohr    $svdta['contentChanged'] = ($svdta['newContent'] != $svdta['oldContent']);
1265b24d9195SAndreas Gohr    $svdta['changeInfo']     = '';
1266b24d9195SAndreas Gohr    $svdta['changeType']     = DOKU_CHANGE_TYPE_EDIT;
12672966355bSGerrit Uitslag    $svdta['sizechange']     = null;
1268b24d9195SAndreas Gohr
1269b24d9195SAndreas Gohr    // select changelog line type
1270b24d9195SAndreas Gohr    if($REV) {
1271b24d9195SAndreas Gohr        $svdta['changeType']  = DOKU_CHANGE_TYPE_REVERT;
1272b24d9195SAndreas Gohr        $svdta['changeInfo'] = $REV;
1273b24d9195SAndreas Gohr    } else if(!file_exists($svdta['file'])) {
1274b24d9195SAndreas Gohr        $svdta['changeType'] = DOKU_CHANGE_TYPE_CREATE;
1275b24d9195SAndreas Gohr    } else if(trim($text) == '') {
1276b24d9195SAndreas Gohr        // empty or whitespace only content deletes
1277b24d9195SAndreas Gohr        $svdta['changeType'] = DOKU_CHANGE_TYPE_DELETE;
1278b24d9195SAndreas Gohr        // autoset summary on deletion
1279*655ddc1dSGerrit Uitslag        if(blank($svdta['summary'])) {
1280*655ddc1dSGerrit Uitslag            $svdta['summary'] = $lang['deleted'];
1281*655ddc1dSGerrit Uitslag        }
1282b24d9195SAndreas Gohr    } else if($minor && $conf['useacl'] && $INPUT->server->str('REMOTE_USER')) {
1283b24d9195SAndreas Gohr        //minor edits only for logged in users
1284b24d9195SAndreas Gohr        $svdta['changeType'] = DOKU_CHANGE_TYPE_MINOR_EDIT;
1285f3f0262cSandi    }
1286f3f0262cSandi
1287b24d9195SAndreas Gohr    $event = new Doku_Event('COMMON_WIKIPAGE_SAVE', $svdta);
1288b24d9195SAndreas Gohr    if(!$event->advise_before()) return;
1289ac3ed4afSGerrit Uitslag
1290b24d9195SAndreas Gohr    // if the content has not been changed, no save happens (plugins may override this)
1291b24d9195SAndreas Gohr    if(!$svdta['contentChanged']) return;
1292ac3ed4afSGerrit Uitslag
1293b24d9195SAndreas Gohr    detectExternalEdit($id);
1294f3f0262cSandi
12952966355bSGerrit Uitslag    if($svdta['changeType'] == DOKU_CHANGE_TYPE_CREATE) {
1296ac3ed4afSGerrit Uitslag        $filesize_old = 0;
1297ac3ed4afSGerrit Uitslag    } else {
12982966355bSGerrit Uitslag        $filesize_old = filesize($svdta['file']);
1299ac3ed4afSGerrit Uitslag    }
1300b24d9195SAndreas Gohr    if($svdta['changeType'] == DOKU_CHANGE_TYPE_DELETE) {
130130725328SGabriel Birke        // Send "update" event with empty data, so plugins can react to page deletion
1302b24d9195SAndreas Gohr        $data = array(array($svdta['file'], '', false), getNS($id), noNS($id), false);
130330725328SGabriel Birke        trigger_event('IO_WIKIPAGE_WRITE', $data);
1304e45b34cdSBen Coburn        // pre-save deleted revision
1305b24d9195SAndreas Gohr        @touch($svdta['file']);
130646844156SBen Coburn        clearstatcache();
1307b24d9195SAndreas Gohr        $data['newRevision'] = saveOldRevision($id);
1308e1f3d9e1SEsther Brunner        // remove empty file
1309b24d9195SAndreas Gohr        @unlink($svdta['file']);
1310ac3ed4afSGerrit Uitslag        $filesize_new = 0;
1311c5f92742SMichael Hamann        // don't remove old meta info as it should be saved, plugins can use IO_WIKIPAGE_WRITE for removing their metadata...
1312c5f92742SMichael Hamann        // purge non-persistant meta data
13133d1f9ec3SMichael Klier        p_purge_metadata($id);
131453d6ccfeSandi        // remove empty namespaces
1315cc7d0c94SBen Coburn        io_sweepNS($id, 'datadir');
1316cc7d0c94SBen Coburn        io_sweepNS($id, 'mediadir');
1317f3f0262cSandi    } else {
1318cc7d0c94SBen Coburn        // save file (namespace dir is created in io_writeWikiPage)
1319b24d9195SAndreas Gohr        io_writeWikiPage($svdta['file'], $text, $id);
132046844156SBen Coburn        // pre-save the revision, to keep the attic in sync
1321b24d9195SAndreas Gohr        $svdta['newRevision'] = saveOldRevision($id);
13222966355bSGerrit Uitslag        $filesize_new = filesize($svdta['file']);
1323f3f0262cSandi    }
13242966355bSGerrit Uitslag    $svdta['sizechange'] = $filesize_new - $filesize_old;
1325f3f0262cSandi
1326b24d9195SAndreas Gohr    $event->advise_after();
132771726d78SBen Coburn
13282966355bSGerrit Uitslag    addLogEntry($svdta['newRevision'], $svdta['id'], $svdta['changeType'], $svdta['summary'], $svdta['changeInfo'], null, $svdta['sizechange']);
1329ac3ed4afSGerrit Uitslag
133026a0801fSAndreas Gohr    // send notify mails
1331b24d9195SAndreas Gohr    notify($svdta['id'], 'admin', $svdta['oldRevision'], $svdta['summary'], $minor);
1332b24d9195SAndreas Gohr    notify($svdta['id'], 'subscribers', $svdta['oldRevision'], $svdta['summary'], $minor);
1333f3f0262cSandi
1334ce6b63d9Schris    // update the purgefile (timestamp of the last time anything within the wiki was changed)
133598407a7aSandi    io_saveFile($conf['cachedir'].'/purgefile', time());
13362eccbdaaSGina Haeussge
13372eccbdaaSGina Haeussge    // if useheading is enabled, purge the cache of all linking pages
1338fe9ec250SChris Smith    if(useHeading('content')) {
133907ff0babSMichael Hamann        $pages = ft_backlinks($id, true);
13402eccbdaaSGina Haeussge        foreach($pages as $page) {
13412eccbdaaSGina Haeussge            $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
13422eccbdaaSGina Haeussge            $cache->removeCache();
13432eccbdaaSGina Haeussge        }
13442eccbdaaSGina Haeussge    }
1345f3f0262cSandi}
1346f3f0262cSandi
1347f3f0262cSandi/**
1348f3f0262cSandi * moves the current version to the attic and returns its
1349f3f0262cSandi * revision date
135015fae107Sandi *
135115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1352140cfbcdSGerrit Uitslag *
1353140cfbcdSGerrit Uitslag * @param string $id page id
1354140cfbcdSGerrit Uitslag * @return int|string revision timestamp
1355f3f0262cSandi */
1356f3f0262cSandifunction saveOldRevision($id) {
1357f3f0262cSandi    $oldf = wikiFN($id);
135879e79377SAndreas Gohr    if(!file_exists($oldf)) return '';
1359f3f0262cSandi    $date = filemtime($oldf);
1360f3f0262cSandi    $newf = wikiFN($id, $date);
1361cc7d0c94SBen Coburn    io_writeWikiPage($newf, rawWiki($id), $id, $date);
1362f3f0262cSandi    return $date;
1363f3f0262cSandi}
1364f3f0262cSandi
1365f3f0262cSandi/**
1366fde10de4SAdrian Lang * Sends a notify mail on page change or registration
136726a0801fSAndreas Gohr *
136826a0801fSAndreas Gohr * @param string     $id       The changed page
1369fde10de4SAdrian Lang * @param string     $who      Who to notify (admin|subscribers|register)
13703272d797SAndreas Gohr * @param int|string $rev Old page revision
137126a0801fSAndreas Gohr * @param string     $summary  What changed
137290033e9dSAndreas Gohr * @param boolean    $minor    Is this a minor edit?
137342ea7f44SGerrit Uitslag * @param string[]   $replace  Additional string substitutions, @KEY@ to be replaced by value
13743272d797SAndreas Gohr * @return bool
1375140cfbcdSGerrit Uitslag *
137615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1377f3f0262cSandi */
137802a498e7Schrisfunction notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array()) {
1379f3f0262cSandi    global $conf;
1380585bf44eSChristopher Smith    /* @var Input $INPUT */
1381585bf44eSChristopher Smith    global $INPUT;
1382b158d625SSteven Danz
13836df843eeSAndreas Gohr    // decide if there is something to do, eg. whom to mail
138426a0801fSAndreas Gohr    if($who == 'admin') {
13853272d797SAndreas Gohr        if(empty($conf['notify'])) return false; //notify enabled?
13862ed38036SAndreas Gohr        $tpl = 'mailtext';
138726a0801fSAndreas Gohr        $to  = $conf['notify'];
138826a0801fSAndreas Gohr    } elseif($who == 'subscribers') {
138984c1127cSAndreas Gohr        if(!actionOK('subscribe')) return false; //subscribers enabled?
1390585bf44eSChristopher Smith        if($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
13910bb37868SGerrit Uitslag        $data = array('id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace);
13923272d797SAndreas Gohr        trigger_event(
13933272d797SAndreas Gohr            'COMMON_NOTIFY_ADDRESSLIST', $data,
1394835242b0SAndreas Gohr            array(new Subscription(), 'notifyaddresses')
13953272d797SAndreas Gohr        );
13962ed38036SAndreas Gohr        $to = $data['addresslist'];
13972ed38036SAndreas Gohr        if(empty($to)) return false;
13982ed38036SAndreas Gohr        $tpl = 'subscr_single';
139926a0801fSAndreas Gohr    } else {
14003272d797SAndreas Gohr        return false; //just to be safe
140126a0801fSAndreas Gohr    }
140226a0801fSAndreas Gohr
14036df843eeSAndreas Gohr    // prepare content
14042ed38036SAndreas Gohr    $subscription = new Subscription();
14052ed38036SAndreas Gohr    return $subscription->send_diff($to, $tpl, $id, $rev, $summary);
1406f3f0262cSandi}
14072ed38036SAndreas Gohr
140815fae107Sandi/**
140971f7bde7SAndreas Gohr * extracts the query from a search engine referrer
141015fae107Sandi *
141115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
141271f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1413140cfbcdSGerrit Uitslag *
1414140cfbcdSGerrit Uitslag * @return array|string
1415f3f0262cSandi */
1416f3f0262cSandifunction getGoogleQuery() {
1417585bf44eSChristopher Smith    /* @var Input $INPUT */
1418585bf44eSChristopher Smith    global $INPUT;
1419585bf44eSChristopher Smith
1420585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_REFERER')) {
1421c66972f2SAdrian Lang        return '';
1422c66972f2SAdrian Lang    }
1423585bf44eSChristopher Smith    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1424f3f0262cSandi
1425079b3ac1SAndreas Gohr    // only handle common SEs
1426079b3ac1SAndreas Gohr    if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/',$url['host'])) return '';
1427e4d8a516SKazutaka Miyasaka
1428079b3ac1SAndreas Gohr    $query = array();
1429e4d8a516SKazutaka Miyasaka    // temporary workaround against PHP bug #49733
1430e4d8a516SKazutaka Miyasaka    // see http://bugs.php.net/bug.php?id=49733
1431e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) $enc = mb_internal_encoding();
1432f3f0262cSandi    parse_str($url['query'], $query);
1433e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) mb_internal_encoding($enc);
1434e4d8a516SKazutaka Miyasaka
1435c66972f2SAdrian Lang    $q = '';
1436079b3ac1SAndreas Gohr    if(isset($query['q'])){
1437079b3ac1SAndreas Gohr        $q = $query['q'];
1438079b3ac1SAndreas Gohr    }elseif(isset($query['p'])){
1439079b3ac1SAndreas Gohr        $q = $query['p'];
1440079b3ac1SAndreas Gohr    }elseif(isset($query['query'])){
1441079b3ac1SAndreas Gohr        $q = $query['query'];
1442079b3ac1SAndreas Gohr    }
1443079b3ac1SAndreas Gohr    $q = trim($q);
1444f3f0262cSandi
1445079b3ac1SAndreas Gohr    if(!$q) return '';
14466531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1447f93b3b50SAndreas Gohr    return $q;
1448f3f0262cSandi}
1449f3f0262cSandi
1450f3f0262cSandi/**
1451f3f0262cSandi * Return the human readable size of a file
1452f3f0262cSandi *
1453f3f0262cSandi * @param int $size A file size
1454f3f0262cSandi * @param int $dec A number of decimal places
145574160ca1SGerrit Uitslag * @return string human readable size
1456140cfbcdSGerrit Uitslag *
1457f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1458f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1459f3f0262cSandi * @version     1.0.0
1460f3f0262cSandi */
1461f31d5b73Sandifunction filesize_h($size, $dec = 1) {
1462f3f0262cSandi    $sizes = array('B', 'KB', 'MB', 'GB');
1463f3f0262cSandi    $count = count($sizes);
1464f3f0262cSandi    $i     = 0;
1465f3f0262cSandi
1466f3f0262cSandi    while($size >= 1024 && ($i < $count - 1)) {
1467f3f0262cSandi        $size /= 1024;
1468f3f0262cSandi        $i++;
1469f3f0262cSandi    }
1470f3f0262cSandi
1471f3f0262cSandi    return round($size, $dec).' '.$sizes[$i];
1472f3f0262cSandi}
1473f3f0262cSandi
147415fae107Sandi/**
1475c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1476c57e365eSAndreas Gohr *
1477c57e365eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1478140cfbcdSGerrit Uitslag *
1479140cfbcdSGerrit Uitslag * @param int $dt timestamp
1480140cfbcdSGerrit Uitslag * @return string
1481c57e365eSAndreas Gohr */
1482c57e365eSAndreas Gohrfunction datetime_h($dt) {
1483c57e365eSAndreas Gohr    global $lang;
1484c57e365eSAndreas Gohr
1485c57e365eSAndreas Gohr    $ago = time() - $dt;
1486c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1487c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1488c57e365eSAndreas Gohr    }
1489c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 2) {
1490c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1491c57e365eSAndreas Gohr    }
1492c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 7 * 2) {
1493c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1494c57e365eSAndreas Gohr    }
1495c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 2) {
1496c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1497c57e365eSAndreas Gohr    }
1498c57e365eSAndreas Gohr    if($ago > 60 * 60 * 2) {
1499c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago / (60 * 60)));
1500c57e365eSAndreas Gohr    }
1501c57e365eSAndreas Gohr    if($ago > 60 * 2) {
1502c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago / (60)));
1503c57e365eSAndreas Gohr    }
1504c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1505c57e365eSAndreas Gohr}
1506c57e365eSAndreas Gohr
1507c57e365eSAndreas Gohr/**
1508f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1509f2263577SAndreas Gohr *
1510f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1511f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1512f2263577SAndreas Gohr *
1513f2263577SAndreas Gohr * @see datetime_h
1514f2263577SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1515140cfbcdSGerrit Uitslag *
1516140cfbcdSGerrit Uitslag * @param int|null $dt      timestamp when given, null will take current timestamp
1517140cfbcdSGerrit Uitslag * @param string   $format  empty default to $conf['dformat'], or provide format as recognized by strftime()
1518140cfbcdSGerrit Uitslag * @return string
1519f2263577SAndreas Gohr */
1520f2263577SAndreas Gohrfunction dformat($dt = null, $format = '') {
1521f2263577SAndreas Gohr    global $conf;
1522f2263577SAndreas Gohr
1523f2263577SAndreas Gohr    if(is_null($dt)) $dt = time();
1524f2263577SAndreas Gohr    $dt = (int) $dt;
1525f2263577SAndreas Gohr    if(!$format) $format = $conf['dformat'];
1526f2263577SAndreas Gohr
1527f2263577SAndreas Gohr    $format = str_replace('%f', datetime_h($dt), $format);
1528f2263577SAndreas Gohr    return strftime($format, $dt);
1529f2263577SAndreas Gohr}
1530f2263577SAndreas Gohr
1531f2263577SAndreas Gohr/**
1532c4f79b71SMichael Hamann * Formats a timestamp as ISO 8601 date
1533c4f79b71SMichael Hamann *
1534c4f79b71SMichael Hamann * @author <ungu at terong dot com>
1535c4f79b71SMichael Hamann * @link http://www.php.net/manual/en/function.date.php#54072
1536140cfbcdSGerrit Uitslag *
15377e8500eeSGerrit Uitslag * @param int $int_date current date in UNIX timestamp
15383272d797SAndreas Gohr * @return string
1539c4f79b71SMichael Hamann */
1540c4f79b71SMichael Hamannfunction date_iso8601($int_date) {
1541c4f79b71SMichael Hamann    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1542c4f79b71SMichael Hamann    $pre_timezone = date('O', $int_date);
1543c4f79b71SMichael Hamann    $time_zone    = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1544c4f79b71SMichael Hamann    $date_mod .= $time_zone;
1545c4f79b71SMichael Hamann    return $date_mod;
1546c4f79b71SMichael Hamann}
1547c4f79b71SMichael Hamann
1548c4f79b71SMichael Hamann/**
154900a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
155000a7b5adSEsther Brunner *
155100a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
155200a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
1553140cfbcdSGerrit Uitslag *
1554140cfbcdSGerrit Uitslag * @param string $email email address
1555140cfbcdSGerrit Uitslag * @return string
155600a7b5adSEsther Brunner */
155700a7b5adSEsther Brunnerfunction obfuscate($email) {
155800a7b5adSEsther Brunner    global $conf;
155900a7b5adSEsther Brunner
156000a7b5adSEsther Brunner    switch($conf['mailguard']) {
156100a7b5adSEsther Brunner        case 'visible' :
156200a7b5adSEsther Brunner            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
156300a7b5adSEsther Brunner            return strtr($email, $obfuscate);
156400a7b5adSEsther Brunner
156500a7b5adSEsther Brunner        case 'hex' :
156600a7b5adSEsther Brunner            $encode = '';
156749eb6e38SAndreas Gohr            $len    = strlen($email);
156849eb6e38SAndreas Gohr            for($x = 0; $x < $len; $x++) {
156949eb6e38SAndreas Gohr                $encode .= '&#x'.bin2hex($email{$x}).';';
157049eb6e38SAndreas Gohr            }
157100a7b5adSEsther Brunner            return $encode;
157200a7b5adSEsther Brunner
157300a7b5adSEsther Brunner        case 'none' :
157400a7b5adSEsther Brunner        default :
157500a7b5adSEsther Brunner            return $email;
157600a7b5adSEsther Brunner    }
157700a7b5adSEsther Brunner}
157800a7b5adSEsther Brunner
157900a7b5adSEsther Brunner/**
158089541d4bSAndreas Gohr * Removes quoting backslashes
158189541d4bSAndreas Gohr *
158289541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1583140cfbcdSGerrit Uitslag *
1584140cfbcdSGerrit Uitslag * @param string $string
1585140cfbcdSGerrit Uitslag * @param string $char backslashed character
1586140cfbcdSGerrit Uitslag * @return string
158789541d4bSAndreas Gohr */
158889541d4bSAndreas Gohrfunction unslash($string, $char = "'") {
158989541d4bSAndreas Gohr    return str_replace('\\'.$char, $char, $string);
159089541d4bSAndreas Gohr}
159189541d4bSAndreas Gohr
159273038c47SAndreas Gohr/**
159373038c47SAndreas Gohr * Convert php.ini shorthands to byte
159473038c47SAndreas Gohr *
159573038c47SAndreas Gohr * @author <gilthans dot NO dot SPAM at gmail dot com>
159673038c47SAndreas Gohr * @link   http://de3.php.net/manual/en/ini.core.php#79564
1597140cfbcdSGerrit Uitslag *
1598140cfbcdSGerrit Uitslag * @param string $v shorthands
1599140cfbcdSGerrit Uitslag * @return int|string
160073038c47SAndreas Gohr */
160173038c47SAndreas Gohrfunction php_to_byte($v) {
160273038c47SAndreas Gohr    $l   = substr($v, -1);
160373038c47SAndreas Gohr    $ret = substr($v, 0, -1);
160473038c47SAndreas Gohr    switch(strtoupper($l)) {
160574160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
160673038c47SAndreas Gohr        case 'P':
160773038c47SAndreas Gohr            $ret *= 1024;
160874160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
160973038c47SAndreas Gohr        case 'T':
161073038c47SAndreas Gohr            $ret *= 1024;
161174160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
161273038c47SAndreas Gohr        case 'G':
161373038c47SAndreas Gohr            $ret *= 1024;
161474160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
161573038c47SAndreas Gohr        case 'M':
161673038c47SAndreas Gohr            $ret *= 1024;
1617f168548cSGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
161873038c47SAndreas Gohr        case 'K':
161973038c47SAndreas Gohr            $ret *= 1024;
162073038c47SAndreas Gohr            break;
162149cbd23eSOtto Vainio        default;
162249cbd23eSOtto Vainio            $ret *= 10;
162349cbd23eSOtto Vainio            break;
162473038c47SAndreas Gohr    }
162573038c47SAndreas Gohr    return $ret;
162673038c47SAndreas Gohr}
162773038c47SAndreas Gohr
1628546d3a99SAndreas Gohr/**
1629546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1630140cfbcdSGerrit Uitslag *
1631140cfbcdSGerrit Uitslag * @param string $string
1632140cfbcdSGerrit Uitslag * @return string
1633546d3a99SAndreas Gohr */
1634546d3a99SAndreas Gohrfunction preg_quote_cb($string) {
1635546d3a99SAndreas Gohr    return preg_quote($string, '/');
1636546d3a99SAndreas Gohr}
163773038c47SAndreas Gohr
1638bd2f6c2fSAndreas Gohr/**
1639bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1640bd2f6c2fSAndreas Gohr *
1641c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1642bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1643bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1644bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1645bd2f6c2fSAndreas Gohr *
1646bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1647bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1648bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1649bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1650bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
16513272d797SAndreas Gohr * @return string
1652bd2f6c2fSAndreas Gohr */
1653a5d27328SAndreas Gohrfunction shorten($keep, $short, $max, $min = 9, $char = '…') {
1654bd2f6c2fSAndreas Gohr    $max = $max - utf8_strlen($keep);
1655bd2f6c2fSAndreas Gohr    if($max < $min) return $keep;
1656bd2f6c2fSAndreas Gohr    $len = utf8_strlen($short);
1657bd2f6c2fSAndreas Gohr    if($len <= $max) return $keep.$short;
1658bd2f6c2fSAndreas Gohr    $half = floor($max / 2);
1659bd2f6c2fSAndreas Gohr    return $keep.utf8_substr($short, 0, $half - 1).$char.utf8_substr($short, $len - $half);
1660bd2f6c2fSAndreas Gohr}
1661bd2f6c2fSAndreas Gohr
1662dc58b6f4SAndy Webber/**
1663dc58b6f4SAndy Webber * Return the users real name or e-mail address for use
1664dc58b6f4SAndy Webber * in page footer and recent changes pages
1665dc58b6f4SAndy Webber *
1666b4b6c9a1SGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
166715f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1668c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
166915f3bc49SGerrit Uitslag *
1670dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1671dc58b6f4SAndy Webber */
167215f3bc49SGerrit Uitslagfunction editorinfo($username, $textonly = false) {
1673cd4635eeSGerrit Uitslag    return userlink($username, $textonly);
1674dc58b6f4SAndy Webber}
1675dc58b6f4SAndy Webber
167660a396c8SGerrit Uitslag/**
167760a396c8SGerrit Uitslag * Returns users realname w/o link
167860a396c8SGerrit Uitslag *
1679f168548cSGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
168015f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1681c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
168260a396c8SGerrit Uitslag *
168360a396c8SGerrit Uitslag * @triggers COMMON_USER_LINK
168460a396c8SGerrit Uitslag */
1685cd4635eeSGerrit Uitslagfunction userlink($username = null, $textonly = false) {
168660a396c8SGerrit Uitslag    global $conf, $INFO;
168760a396c8SGerrit Uitslag    /** @var DokuWiki_Auth_Plugin $auth */
168860a396c8SGerrit Uitslag    global $auth;
168930f6ec4bSGerrit Uitslag    /** @var Input $INPUT */
169030f6ec4bSGerrit Uitslag    global $INPUT;
169160a396c8SGerrit Uitslag
169260a396c8SGerrit Uitslag    // prepare initial event data
169360a396c8SGerrit Uitslag    $data = array(
169460a396c8SGerrit Uitslag        'username' => $username, // the unique user name
169560a396c8SGerrit Uitslag        'name' => '',
169660a396c8SGerrit Uitslag        'link' => array( //setting 'link' to false disables linking
169760a396c8SGerrit Uitslag                         'target' => '',
169860a396c8SGerrit Uitslag                         'pre' => '',
169960a396c8SGerrit Uitslag                         'suf' => '',
170060a396c8SGerrit Uitslag                         'style' => '',
170160a396c8SGerrit Uitslag                         'more' => '',
170260a396c8SGerrit Uitslag                         'url' => '',
170360a396c8SGerrit Uitslag                         'title' => '',
170460a396c8SGerrit Uitslag                         'class' => ''
170560a396c8SGerrit Uitslag        ),
17064d5fc927SGerrit Uitslag        'userlink' => '', // formatted user name as will be returned
170715f3bc49SGerrit Uitslag        'textonly' => $textonly
170860a396c8SGerrit Uitslag    );
170962c8004eSGerrit Uitslag    if($username === null) {
171030f6ec4bSGerrit Uitslag        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
171115f3bc49SGerrit Uitslag        if($textonly){
171215f3bc49SGerrit Uitslag            $data['name'] = $INFO['userinfo']['name']. ' (' . $INPUT->server->str('REMOTE_USER') . ')';
171315f3bc49SGerrit Uitslag        }else {
171430f6ec4bSGerrit Uitslag            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> (<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
171560a396c8SGerrit Uitslag        }
171615f3bc49SGerrit Uitslag    }
171760a396c8SGerrit Uitslag
171860a396c8SGerrit Uitslag    $evt = new Doku_Event('COMMON_USER_LINK', $data);
171960a396c8SGerrit Uitslag    if($evt->advise_before(true)) {
172060a396c8SGerrit Uitslag        if(empty($data['name'])) {
172160a396c8SGerrit Uitslag            if($auth) $info = $auth->getUserData($username);
172265833968SGerrit Uitslag            if($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1723dc58b6f4SAndy Webber                switch($conf['showuseras']) {
1724dc58b6f4SAndy Webber                    case 'username':
17257f081821SGerrit Uitslag                    case 'username_link':
172615f3bc49SGerrit Uitslag                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
172760a396c8SGerrit Uitslag                        break;
1728dc58b6f4SAndy Webber                    case 'email':
1729dc58b6f4SAndy Webber                    case 'email_link':
173060a396c8SGerrit Uitslag                        $data['name'] = obfuscate($info['mail']);
173160a396c8SGerrit Uitslag                        break;
1732dc58b6f4SAndy Webber                }
173365833968SGerrit Uitslag            } else {
173465833968SGerrit Uitslag                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
173560a396c8SGerrit Uitslag            }
173660a396c8SGerrit Uitslag        }
17377f081821SGerrit Uitslag
17387f081821SGerrit Uitslag        /** @var Doku_Renderer_xhtml $xhtml_renderer */
17397f081821SGerrit Uitslag        static $xhtml_renderer = null;
17407f081821SGerrit Uitslag
174115f3bc49SGerrit Uitslag        if(!$data['textonly'] && empty($data['link']['url'])) {
17427f081821SGerrit Uitslag
17437f081821SGerrit Uitslag            if(in_array($conf['showuseras'], array('email_link', 'username_link'))) {
174460a396c8SGerrit Uitslag                if(!isset($info)) {
174560a396c8SGerrit Uitslag                    if($auth) $info = $auth->getUserData($username);
174660a396c8SGerrit Uitslag                }
174760a396c8SGerrit Uitslag                if(isset($info) && $info) {
17487f081821SGerrit Uitslag                    if($conf['showuseras'] == 'email_link') {
174960a396c8SGerrit Uitslag                        $data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
1750dc58b6f4SAndy Webber                    } else {
17517f081821SGerrit Uitslag                        if(is_null($xhtml_renderer)) {
17527f081821SGerrit Uitslag                            $xhtml_renderer = p_get_renderer('xhtml');
17537f081821SGerrit Uitslag                        }
17547f081821SGerrit Uitslag                        if(empty($xhtml_renderer->interwiki)) {
17557f081821SGerrit Uitslag                            $xhtml_renderer->interwiki = getInterwiki();
17567f081821SGerrit Uitslag                        }
17577f081821SGerrit Uitslag                        $shortcut = 'user';
1758533772e1SGerrit Uitslag                        $exists = null;
17596496c33fSGerrit Uitslag                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
17602a2a43c4SGerrit Uitslag                        $data['link']['class'] .= ' interwiki iw_user';
17616496c33fSGerrit Uitslag                        if($exists !== null) {
17626496c33fSGerrit Uitslag                            if($exists) {
17636496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink1';
17646496c33fSGerrit Uitslag                            } else {
17656496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink2';
17666496c33fSGerrit Uitslag                                $data['link']['rel'] = 'nofollow';
17676496c33fSGerrit Uitslag                            }
17686496c33fSGerrit Uitslag                        }
1769dc58b6f4SAndy Webber                    }
1770dc58b6f4SAndy Webber                } else {
177115f3bc49SGerrit Uitslag                    $data['textonly'] = true;
1772dc58b6f4SAndy Webber                }
177360a396c8SGerrit Uitslag
177460a396c8SGerrit Uitslag            } else {
177515f3bc49SGerrit Uitslag                $data['textonly'] = true;
177660a396c8SGerrit Uitslag            }
177760a396c8SGerrit Uitslag        }
177860a396c8SGerrit Uitslag
177915f3bc49SGerrit Uitslag        if($data['textonly']) {
17804d5fc927SGerrit Uitslag            $data['userlink'] = $data['name'];
178160a396c8SGerrit Uitslag        } else {
178260a396c8SGerrit Uitslag            $data['link']['name'] = $data['name'];
178360a396c8SGerrit Uitslag            if(is_null($xhtml_renderer)) {
178460a396c8SGerrit Uitslag                $xhtml_renderer = p_get_renderer('xhtml');
178560a396c8SGerrit Uitslag            }
17864d5fc927SGerrit Uitslag            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
178760a396c8SGerrit Uitslag        }
178860a396c8SGerrit Uitslag    }
178960a396c8SGerrit Uitslag    $evt->advise_after();
179060a396c8SGerrit Uitslag    unset($evt);
179160a396c8SGerrit Uitslag
17924d5fc927SGerrit Uitslag    return $data['userlink'];
1793066fee30SAndreas Gohr}
1794066fee30SAndreas Gohr
1795066fee30SAndreas Gohr/**
1796066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1797066fee30SAndreas Gohr * When no image exists, returns an empty string
1798066fee30SAndreas Gohr *
1799066fee30SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1800140cfbcdSGerrit Uitslag *
1801066fee30SAndreas Gohr * @param  string $type - type of image 'badge' or 'button'
18023272d797SAndreas Gohr * @return string
1803066fee30SAndreas Gohr */
1804066fee30SAndreas Gohrfunction license_img($type) {
1805066fee30SAndreas Gohr    global $license;
1806066fee30SAndreas Gohr    global $conf;
1807066fee30SAndreas Gohr    if(!$conf['license']) return '';
1808066fee30SAndreas Gohr    if(!is_array($license[$conf['license']])) return '';
1809066fee30SAndreas Gohr    $try   = array();
1810066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1811066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1812066fee30SAndreas Gohr    if(substr($conf['license'], 0, 3) == 'cc-') {
1813066fee30SAndreas Gohr        $try[] = 'lib/images/license/'.$type.'/cc.png';
1814066fee30SAndreas Gohr    }
1815066fee30SAndreas Gohr    foreach($try as $src) {
181679e79377SAndreas Gohr        if(file_exists(DOKU_INC.$src)) return $src;
1817066fee30SAndreas Gohr    }
1818066fee30SAndreas Gohr    return '';
1819dc58b6f4SAndy Webber}
1820dc58b6f4SAndy Webber
182113c08e2fSMichael Klier/**
182213c08e2fSMichael Klier * Checks if the given amount of memory is available
182313c08e2fSMichael Klier *
182413c08e2fSMichael Klier * If the memory_get_usage() function is not available the
182513c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
182613c08e2fSMichael Klier *
182713c08e2fSMichael Klier * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
182813c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
18293272d797SAndreas Gohr *
18303272d797SAndreas Gohr * @param int  $mem    Size of memory you want to allocate in bytes
1831140cfbcdSGerrit Uitslag * @param int  $bytes  already allocated memory (see above)
18323272d797SAndreas Gohr * @return bool
183313c08e2fSMichael Klier */
183413c08e2fSMichael Klierfunction is_mem_available($mem, $bytes = 1048576) {
183513c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
183613c08e2fSMichael Klier    if(empty($limit)) return true; // no limit set!
183713c08e2fSMichael Klier
183813c08e2fSMichael Klier    // parse limit to bytes
183913c08e2fSMichael Klier    $limit = php_to_byte($limit);
184013c08e2fSMichael Klier
184113c08e2fSMichael Klier    // get used memory if possible
184213c08e2fSMichael Klier    if(function_exists('memory_get_usage')) {
184313c08e2fSMichael Klier        $used = memory_get_usage();
184449eb6e38SAndreas Gohr    } else {
184549eb6e38SAndreas Gohr        $used = $bytes;
184613c08e2fSMichael Klier    }
184713c08e2fSMichael Klier
184813c08e2fSMichael Klier    if($used + $mem > $limit) {
184913c08e2fSMichael Klier        return false;
185013c08e2fSMichael Klier    }
185113c08e2fSMichael Klier
185213c08e2fSMichael Klier    return true;
185313c08e2fSMichael Klier}
185413c08e2fSMichael Klier
1855af2408d5SAndreas Gohr/**
1856af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1857af2408d5SAndreas Gohr *
1858af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1859af2408d5SAndreas Gohr *
1860af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1861af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1862140cfbcdSGerrit Uitslag *
1863140cfbcdSGerrit Uitslag * @param string $url url being directed to
1864af2408d5SAndreas Gohr */
1865af2408d5SAndreas Gohrfunction send_redirect($url) {
1866585bf44eSChristopher Smith    /* @var Input $INPUT */
1867585bf44eSChristopher Smith    global $INPUT;
1868585bf44eSChristopher Smith
18690181f021SAndreas Gohr    //are there any undisplayed messages? keep them in session for display
18700181f021SAndreas Gohr    global $MSG;
18710181f021SAndreas Gohr    if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
18720181f021SAndreas Gohr        //reopen session, store data and close session again
18730181f021SAndreas Gohr        @session_start();
18740181f021SAndreas Gohr        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
18750181f021SAndreas Gohr    }
18760181f021SAndreas Gohr
1877d4869846SAndreas Gohr    // always close the session
1878d4869846SAndreas Gohr    session_write_close();
1879d4869846SAndreas Gohr
1880af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
1881585bf44eSChristopher Smith    if($INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1882585bf44eSChristopher Smith        (strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) &&
1883585bf44eSChristopher Smith        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
18843272d797SAndreas Gohr        $matches[1] < 6
18853272d797SAndreas Gohr    ) {
1886af2408d5SAndreas Gohr        header('Refresh: 0;url='.$url);
1887af2408d5SAndreas Gohr    } else {
1888af2408d5SAndreas Gohr        header('Location: '.$url);
1889af2408d5SAndreas Gohr    }
189081781cb6SAndreas Gohr
189181781cb6SAndreas Gohr    if(defined('DOKU_UNITTEST')) return; // no exits during unit tests
1892af2408d5SAndreas Gohr    exit;
1893af2408d5SAndreas Gohr}
1894af2408d5SAndreas Gohr
18955b75cd1fSAdrian Lang/**
18965b75cd1fSAdrian Lang * Validate a value using a set of valid values
18975b75cd1fSAdrian Lang *
18985b75cd1fSAdrian Lang * This function checks whether a specified value is set and in the array
18995b75cd1fSAdrian Lang * $valid_values. If not, the function returns a default value or, if no
19005b75cd1fSAdrian Lang * default is specified, throws an exception.
19015b75cd1fSAdrian Lang *
19025b75cd1fSAdrian Lang * @param string $param        The name of the parameter
19035b75cd1fSAdrian Lang * @param array  $valid_values A set of valid values; Optionally a default may
19045b75cd1fSAdrian Lang *                             be marked by the key “default”.
19055b75cd1fSAdrian Lang * @param array  $array        The array containing the value (typically $_POST
19065b75cd1fSAdrian Lang *                             or $_GET)
19075b75cd1fSAdrian Lang * @param string $exc          The text of the raised exception
19085b75cd1fSAdrian Lang *
19093272d797SAndreas Gohr * @throws Exception
19103272d797SAndreas Gohr * @return mixed
19115b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
19125b75cd1fSAdrian Lang */
19135b75cd1fSAdrian Langfunction valid_input_set($param, $valid_values, $array, $exc = '') {
19145b75cd1fSAdrian Lang    if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
19155b75cd1fSAdrian Lang        return $array[$param];
19165b75cd1fSAdrian Lang    } elseif(isset($valid_values['default'])) {
19175b75cd1fSAdrian Lang        return $valid_values['default'];
19185b75cd1fSAdrian Lang    } else {
19195b75cd1fSAdrian Lang        throw new Exception($exc);
19205b75cd1fSAdrian Lang    }
19215b75cd1fSAdrian Lang}
19225b75cd1fSAdrian Lang
192363703ba5SAndreas Gohr/**
192463703ba5SAndreas Gohr * Read a preference from the DokuWiki cookie
1925646a531aSChristopher Smith * (remembering both keys & values are urlencoded)
1926140cfbcdSGerrit Uitslag *
1927140cfbcdSGerrit Uitslag * @param string $pref     preference key
1928b4b6c9a1SGerrit Uitslag * @param mixed  $default  value returned when preference not found
1929140cfbcdSGerrit Uitslag * @return string preference value
193063703ba5SAndreas Gohr */
1931554a8c9fSAdrian Langfunction get_doku_pref($pref, $default) {
1932646a531aSChristopher Smith    $enc_pref = urlencode($pref);
193306c9ee33SMarius van Witzenburg    if(isset($_COOKIE['DOKU_PREFS']) && strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
1934554a8c9fSAdrian Lang        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
193563703ba5SAndreas Gohr        $cnt   = count($parts);
193663703ba5SAndreas Gohr        for($i = 0; $i < $cnt; $i += 2) {
1937646a531aSChristopher Smith            if($parts[$i] == $enc_pref) {
1938646a531aSChristopher Smith                return urldecode($parts[$i + 1]);
1939554a8c9fSAdrian Lang            }
1940554a8c9fSAdrian Lang        }
1941554a8c9fSAdrian Lang    }
1942554a8c9fSAdrian Lang    return $default;
1943554a8c9fSAdrian Lang}
1944554a8c9fSAdrian Lang
19453c94d07bSAnika Henke/**
19463c94d07bSAnika Henke * Add a preference to the DokuWiki cookie
194736ec377eSChristopher Smith * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
19483a970889SAnika Henke * Remove it by setting $val to false
1949140cfbcdSGerrit Uitslag *
1950140cfbcdSGerrit Uitslag * @param string $pref  preference key
1951140cfbcdSGerrit Uitslag * @param string $val   preference value
19523c94d07bSAnika Henke */
19533c94d07bSAnika Henkefunction set_doku_pref($pref, $val) {
19543c94d07bSAnika Henke    global $conf;
19553c94d07bSAnika Henke    $orig = get_doku_pref($pref, false);
19563c94d07bSAnika Henke    $cookieVal = '';
19573c94d07bSAnika Henke
19583c94d07bSAnika Henke    if($orig && ($orig != $val)) {
19593c94d07bSAnika Henke        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
19603c94d07bSAnika Henke        $cnt   = count($parts);
196136ec377eSChristopher Smith        // urlencode $pref for the comparison
196236ec377eSChristopher Smith        $enc_pref = rawurlencode($pref);
19633c94d07bSAnika Henke        for($i = 0; $i < $cnt; $i += 2) {
196436ec377eSChristopher Smith            if($parts[$i] == $enc_pref) {
19653a970889SAnika Henke                if ($val !== false) {
196636ec377eSChristopher Smith                    $parts[$i + 1] = rawurlencode($val);
19673a970889SAnika Henke                } else {
19683a970889SAnika Henke                    unset($parts[$i]);
19693a970889SAnika Henke                    unset($parts[$i + 1]);
19703a970889SAnika Henke                }
197150f261f7SMichael Hamann                break;
19723c94d07bSAnika Henke            }
19733c94d07bSAnika Henke        }
19743c94d07bSAnika Henke        $cookieVal = implode('#', $parts);
19753a970889SAnika Henke    } else if (!$orig && $val !== false) {
197636ec377eSChristopher Smith        $cookieVal = ($_COOKIE['DOKU_PREFS'] ? $_COOKIE['DOKU_PREFS'].'#' : '').rawurlencode($pref).'#'.rawurlencode($val);
19773c94d07bSAnika Henke    }
19783c94d07bSAnika Henke
19793c94d07bSAnika Henke    if (!empty($cookieVal)) {
198075e4dd8aSGerrit Uitslag        $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
198175e4dd8aSGerrit Uitslag        setcookie('DOKU_PREFS', $cookieVal, time()+365*24*3600, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
19823c94d07bSAnika Henke    }
19833c94d07bSAnika Henke}
19843c94d07bSAnika Henke
1985f8fb2d18SAndreas Gohr/**
1986f8fb2d18SAndreas Gohr * Strips source mapping declarations from given text #601
1987f8fb2d18SAndreas Gohr *
198842ea7f44SGerrit Uitslag * @param string &$text reference to the CSS or JavaScript code to clean
1989f8fb2d18SAndreas Gohr */
1990f8fb2d18SAndreas Gohrfunction stripsourcemaps(&$text){
1991f8fb2d18SAndreas Gohr    $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text);
1992f8fb2d18SAndreas Gohr}
1993f8fb2d18SAndreas Gohr
1994e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1995