xref: /dokuwiki/inc/common.php (revision 985d6187472ee1df57d7a569fa13bad7f6941c91)
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;
973680e2cdSAndreas Gohr
983680e2cdSAndreas Gohr    $user = $INPUT->server->str('REMOTE_USER');
993680e2cdSAndreas Gohr    $session = session_id();
1003680e2cdSAndreas Gohr
1013680e2cdSAndreas Gohr    // CSRF checks are only for logged in users - do not generate for anonymous
1023680e2cdSAndreas Gohr    if(trim($user) == '' || trim($session) == '') return '';
1033680e2cdSAndreas Gohr    return PassHash::hmac('md5', $session.$user, auth_cookiesalt());
104634d7150SAndreas Gohr}
105634d7150SAndreas Gohr
106634d7150SAndreas Gohr/**
107634d7150SAndreas Gohr * Check the secret CSRF token
108140cfbcdSGerrit Uitslag *
109140cfbcdSGerrit Uitslag * @param null|string $token security token or null to read it from request variable
110140cfbcdSGerrit Uitslag * @return bool success if the token matched
111634d7150SAndreas Gohr */
112634d7150SAndreas Gohrfunction checkSecurityToken($token = null) {
113585bf44eSChristopher Smith    /** @var Input $INPUT */
1147d01a0eaSTom N Harris    global $INPUT;
115585bf44eSChristopher Smith    if(!$INPUT->server->str('REMOTE_USER')) return true; // no logged in user, no need for a check
116df97eaacSAndreas Gohr
1177d01a0eaSTom N Harris    if(is_null($token)) $token = $INPUT->str('sectok');
118634d7150SAndreas Gohr    if(getSecurityToken() != $token) {
119634d7150SAndreas Gohr        msg('Security Token did not match. Possible CSRF attack.', -1);
120634d7150SAndreas Gohr        return false;
121634d7150SAndreas Gohr    }
122634d7150SAndreas Gohr    return true;
123634d7150SAndreas Gohr}
124634d7150SAndreas Gohr
125634d7150SAndreas Gohr/**
126634d7150SAndreas Gohr * Print a hidden form field with a secret CSRF token
127634d7150SAndreas Gohr *
128634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
129140cfbcdSGerrit Uitslag *
130140cfbcdSGerrit Uitslag * @param bool $print  if true print the field, otherwise html of the field is returned
13142ea7f44SGerrit Uitslag * @return string html of hidden form field
132634d7150SAndreas Gohr */
133634d7150SAndreas Gohrfunction formSecurityToken($print = true) {
1342404d0edSAnika Henke    $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
1353272d797SAndreas Gohr    if($print) echo $ret;
136634d7150SAndreas Gohr    return $ret;
137634d7150SAndreas Gohr}
138634d7150SAndreas Gohr
139634d7150SAndreas Gohr/**
1401015a57dSChristopher Smith * Determine basic information for a request of $id
14115fae107Sandi *
14215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1437e87a794SChristopher Smith * @author Chris Smith <chris@jalakai.co.uk>
144140cfbcdSGerrit Uitslag *
145140cfbcdSGerrit Uitslag * @param string $id         pageid
146140cfbcdSGerrit Uitslag * @param bool   $htmlClient add info about whether is mobile browser
147140cfbcdSGerrit Uitslag * @return array with info for a request of $id
148140cfbcdSGerrit Uitslag *
149f3f0262cSandi */
1501015a57dSChristopher Smithfunction basicinfo($id, $htmlClient=true){
151f3f0262cSandi    global $USERINFO;
152585bf44eSChristopher Smith    /* @var Input $INPUT */
153585bf44eSChristopher Smith    global $INPUT;
1546afe8dcaSchris
155c66972f2SAdrian Lang    // set info about manager/admin status.
15659bc3b48SGerrit Uitslag    $info = array();
157c66972f2SAdrian Lang    $info['isadmin']   = false;
158c66972f2SAdrian Lang    $info['ismanager'] = false;
159585bf44eSChristopher Smith    if($INPUT->server->has('REMOTE_USER')) {
160f3f0262cSandi        $info['userinfo']   = $USERINFO;
1611015a57dSChristopher Smith        $info['perm']       = auth_quickaclcheck($id);
162585bf44eSChristopher Smith        $info['client']     = $INPUT->server->str('REMOTE_USER');
16317ee7f66SAndreas Gohr
164f8cc712eSAndreas Gohr        if($info['perm'] == AUTH_ADMIN) {
165f8cc712eSAndreas Gohr            $info['isadmin']   = true;
166f8cc712eSAndreas Gohr            $info['ismanager'] = true;
167f8cc712eSAndreas Gohr        } elseif(auth_ismanager()) {
168f8cc712eSAndreas Gohr            $info['ismanager'] = true;
169f8cc712eSAndreas Gohr        }
170f8cc712eSAndreas Gohr
17117ee7f66SAndreas Gohr        // if some outside auth were used only REMOTE_USER is set
17217ee7f66SAndreas Gohr        if(!$info['userinfo']['name']) {
173585bf44eSChristopher Smith            $info['userinfo']['name'] = $INPUT->server->str('REMOTE_USER');
17417ee7f66SAndreas Gohr        }
175ee4c4a1bSAndreas Gohr
176f3f0262cSandi    } else {
1771015a57dSChristopher Smith        $info['perm']       = auth_aclcheck($id, '', null);
178ee4c4a1bSAndreas Gohr        $info['client']     = clientIP(true);
179f3f0262cSandi    }
180f3f0262cSandi
1811015a57dSChristopher Smith    $info['namespace'] = getNS($id);
1821015a57dSChristopher Smith
1831015a57dSChristopher Smith    // mobile detection
1841015a57dSChristopher Smith    if ($htmlClient) {
1851015a57dSChristopher Smith        $info['ismobile'] = clientismobile();
1861015a57dSChristopher Smith    }
1871015a57dSChristopher Smith
1881015a57dSChristopher Smith    return $info;
1891015a57dSChristopher Smith }
1901015a57dSChristopher Smith
1911015a57dSChristopher Smith/**
1921015a57dSChristopher Smith * Return info about the current document as associative
1931015a57dSChristopher Smith * array.
1941015a57dSChristopher Smith *
1951015a57dSChristopher Smith * @author Andreas Gohr <andi@splitbrain.org>
196140cfbcdSGerrit Uitslag *
197140cfbcdSGerrit Uitslag * @return array with info about current document
1981015a57dSChristopher Smith */
1991015a57dSChristopher Smithfunction pageinfo() {
2001015a57dSChristopher Smith    global $ID;
2011015a57dSChristopher Smith    global $REV;
2021015a57dSChristopher Smith    global $RANGE;
2031015a57dSChristopher Smith    global $lang;
204585bf44eSChristopher Smith    /* @var Input $INPUT */
205585bf44eSChristopher Smith    global $INPUT;
2061015a57dSChristopher Smith
2071015a57dSChristopher Smith    $info = basicinfo($ID);
2081015a57dSChristopher Smith
2091015a57dSChristopher Smith    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
2101015a57dSChristopher Smith    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
2111015a57dSChristopher Smith    $info['id']  = $ID;
2121015a57dSChristopher Smith    $info['rev'] = $REV;
2131015a57dSChristopher Smith
214585bf44eSChristopher Smith    if($INPUT->server->has('REMOTE_USER')) {
2157e87a794SChristopher Smith        $sub = new Subscription();
2167e87a794SChristopher Smith        $info['subscribed'] = $sub->user_subscription();
2177e87a794SChristopher Smith    } else {
2187e87a794SChristopher Smith        $info['subscribed'] = false;
2197e87a794SChristopher Smith    }
2207e87a794SChristopher Smith
221f3f0262cSandi    $info['locked']     = checklock($ID);
222317a04c4SSatoshi Sahara    $info['filepath']   = wikiFN($ID);
22379e79377SAndreas Gohr    $info['exists']     = file_exists($info['filepath']);
22401c9a118SAndreas Gohr    $info['currentrev'] = @filemtime($info['filepath']);
2252ca9d91cSBen Coburn    if($REV) {
2262ca9d91cSBen Coburn        //check if current revision was meant
22701c9a118SAndreas Gohr        if($info['exists'] && ($info['currentrev'] == $REV)) {
2282ca9d91cSBen Coburn            $REV = '';
2297b3a6803SAndreas Gohr        } elseif($RANGE) {
2307b3a6803SAndreas Gohr            //section editing does not work with old revisions!
2317b3a6803SAndreas Gohr            $REV   = '';
2327b3a6803SAndreas Gohr            $RANGE = '';
2337b3a6803SAndreas Gohr            msg($lang['nosecedit'], 0);
2342ca9d91cSBen Coburn        } else {
2352ca9d91cSBen Coburn            //really use old revision
236317a04c4SSatoshi Sahara            $info['filepath'] = wikiFN($ID, $REV);
23779e79377SAndreas Gohr            $info['exists']   = file_exists($info['filepath']);
238f3f0262cSandi        }
239f3f0262cSandi    }
240c112d578Sandi    $info['rev'] = $REV;
241f3f0262cSandi    if($info['exists']) {
242f3f0262cSandi        $info['writable'] = (is_writable($info['filepath']) &&
243f3f0262cSandi            ($info['perm'] >= AUTH_EDIT));
244f3f0262cSandi    } else {
245f3f0262cSandi        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
246f3f0262cSandi    }
24750e988b1SAndreas Gohr    $info['editable'] = ($info['writable'] && empty($info['locked']));
248f3f0262cSandi    $info['lastmod']  = @filemtime($info['filepath']);
249f3f0262cSandi
25071726d78SBen Coburn    //load page meta data
25171726d78SBen Coburn    $info['meta'] = p_get_metadata($ID);
25271726d78SBen Coburn
253652610a2Sandi    //who's the editor
254047bad06SGerrit Uitslag    $pagelog = new PageChangeLog($ID, 1024);
255652610a2Sandi    if($REV) {
256f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($REV);
257652610a2Sandi    } else {
2580e80bb5eSChristopher Smith        if(!empty($info['meta']['last_change']) && is_array($info['meta']['last_change'])) {
259aa27cf05SAndreas Gohr            $revinfo = $info['meta']['last_change'];
260aa27cf05SAndreas Gohr        } else {
261f523c971SGerrit Uitslag            $revinfo = $pagelog->getRevisionInfo($info['lastmod']);
262cd00a034SBen Coburn            // cache most recent changelog line in metadata if missing and still valid
263cd00a034SBen Coburn            if($revinfo !== false) {
264cd00a034SBen Coburn                $info['meta']['last_change'] = $revinfo;
265cd00a034SBen Coburn                p_set_metadata($ID, array('last_change' => $revinfo));
266cd00a034SBen Coburn            }
267cd00a034SBen Coburn        }
268cd00a034SBen Coburn    }
269cd00a034SBen Coburn    //and check for an external edit
270cd00a034SBen Coburn    if($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
271cd00a034SBen Coburn        // cached changelog line no longer valid
272cd00a034SBen Coburn        $revinfo                     = false;
273cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
274cd00a034SBen Coburn        p_set_metadata($ID, array('last_change' => $revinfo));
275652610a2Sandi    }
276bb4866bdSchris
277652610a2Sandi    $info['ip']   = $revinfo['ip'];
278652610a2Sandi    $info['user'] = $revinfo['user'];
279652610a2Sandi    $info['sum']  = $revinfo['sum'];
28071726d78SBen Coburn    // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
281ebf1501fSBen Coburn    // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
28259f257aeSchris
28388f522e9Sandi    if($revinfo['user']) {
28488f522e9Sandi        $info['editor'] = $revinfo['user'];
28588f522e9Sandi    } else {
28688f522e9Sandi        $info['editor'] = $revinfo['ip'];
28788f522e9Sandi    }
288652610a2Sandi
289ee4c4a1bSAndreas Gohr    // draft
290ee4c4a1bSAndreas Gohr    $draft = getCacheName($info['client'].$ID, '.draft');
29179e79377SAndreas Gohr    if(file_exists($draft)) {
292ee4c4a1bSAndreas Gohr        if(@filemtime($draft) < @filemtime(wikiFN($ID))) {
293ee4c4a1bSAndreas Gohr            // remove stale draft
294ee4c4a1bSAndreas Gohr            @unlink($draft);
295ee4c4a1bSAndreas Gohr        } else {
296ee4c4a1bSAndreas Gohr            $info['draft'] = $draft;
297ee4c4a1bSAndreas Gohr        }
298ee4c4a1bSAndreas Gohr    }
299ee4c4a1bSAndreas Gohr
3001015a57dSChristopher Smith    return $info;
3011015a57dSChristopher Smith}
3021015a57dSChristopher Smith
3031015a57dSChristopher Smith/**
3040c39d46cSMichael Große * Initialize and/or fill global $JSINFO with some basic info to be given to javascript
3050c39d46cSMichael Große */
3060c39d46cSMichael Großefunction jsinfo() {
3070c39d46cSMichael Große    global $JSINFO, $ID, $INFO, $ACT;
3080c39d46cSMichael Große
3090c39d46cSMichael Große    if (!is_array($JSINFO)) {
3100c39d46cSMichael Große        $JSINFO = [];
3110c39d46cSMichael Große    }
3120c39d46cSMichael Große    //export minimal info to JS, plugins can add more
3130c39d46cSMichael Große    $JSINFO['id']                    = $ID;
3140c39d46cSMichael Große    $JSINFO['namespace']             = (string) $INFO['namespace'];
3150c39d46cSMichael Große    $JSINFO['ACT']                   = act_clean($ACT);
3160c39d46cSMichael Große    $JSINFO['useHeadingNavigation']  = (int) useHeading('navigation');
3170c39d46cSMichael Große    $JSINFO['useHeadingContent']     = (int) useHeading('content');
3180c39d46cSMichael Große}
3190c39d46cSMichael Große
3200c39d46cSMichael Große/**
3211015a57dSChristopher Smith * Return information about the current media item as an associative array.
322140cfbcdSGerrit Uitslag *
323140cfbcdSGerrit Uitslag * @return array with info about current media item
3241015a57dSChristopher Smith */
3251015a57dSChristopher Smithfunction mediainfo(){
3261015a57dSChristopher Smith    global $NS;
3271015a57dSChristopher Smith    global $IMG;
3281015a57dSChristopher Smith
3291015a57dSChristopher Smith    $info = basicinfo("$NS:*");
3301015a57dSChristopher Smith    $info['image'] = $IMG;
3311c548ebeSAndreas Gohr
332f3f0262cSandi    return $info;
333f3f0262cSandi}
334f3f0262cSandi
335f3f0262cSandi/**
3362684e50aSAndreas Gohr * Build an string of URL parameters
3372684e50aSAndreas Gohr *
3382684e50aSAndreas Gohr * @author Andreas Gohr
339140cfbcdSGerrit Uitslag *
340140cfbcdSGerrit Uitslag * @param array  $params    array with key-value pairs
341140cfbcdSGerrit Uitslag * @param string $sep       series of pairs are separated by this character
342140cfbcdSGerrit Uitslag * @return string query string
3432684e50aSAndreas Gohr */
344b174aeaeSchrisfunction buildURLparams($params, $sep = '&amp;') {
3452684e50aSAndreas Gohr    $url = '';
3462684e50aSAndreas Gohr    $amp = false;
3472684e50aSAndreas Gohr    foreach($params as $key => $val) {
348b174aeaeSchris        if($amp) $url .= $sep;
3492684e50aSAndreas Gohr
35085e6871fSAdrian Lang        $url .= rawurlencode($key).'=';
3513a50618cSgweissbach        $url .= rawurlencode((string) $val);
3522684e50aSAndreas Gohr        $amp = true;
3532684e50aSAndreas Gohr    }
3542684e50aSAndreas Gohr    return $url;
3552684e50aSAndreas Gohr}
3562684e50aSAndreas Gohr
3572684e50aSAndreas Gohr/**
3582684e50aSAndreas Gohr * Build an string of html tag attributes
3592684e50aSAndreas Gohr *
3607bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
3617bff22c0SAndreas Gohr *
3622684e50aSAndreas Gohr * @author Andreas Gohr
363140cfbcdSGerrit Uitslag *
364140cfbcdSGerrit Uitslag * @param array $params    array with (attribute name-attribute value) pairs
365140cfbcdSGerrit Uitslag * @param bool  $skipempty skip empty string values?
366140cfbcdSGerrit Uitslag * @return string
3672684e50aSAndreas Gohr */
3684b030ce7SAndreas Gohrfunction buildAttributes($params, $skipempty = false) {
3692684e50aSAndreas Gohr    $url   = '';
3709063ec14SAdrian Lang    $white = false;
3712684e50aSAndreas Gohr    foreach($params as $key => $val) {
3727bff22c0SAndreas Gohr        if($key{0} == '_') continue;
373b1c94f1dSAndreas Gohr        if($val === '' && $skipempty) continue;
3749063ec14SAdrian Lang        if($white) $url .= ' ';
3757bff22c0SAndreas Gohr
3762684e50aSAndreas Gohr        $url .= $key.'="';
3772684e50aSAndreas Gohr        $url .= htmlspecialchars($val);
3782684e50aSAndreas Gohr        $url .= '"';
3799063ec14SAdrian Lang        $white = true;
3802684e50aSAndreas Gohr    }
3812684e50aSAndreas Gohr    return $url;
3822684e50aSAndreas Gohr}
3832684e50aSAndreas Gohr
3842684e50aSAndreas Gohr/**
38515fae107Sandi * This builds the breadcrumb trail and returns it as array
38615fae107Sandi *
38715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
388140cfbcdSGerrit Uitslag *
389e3710957SGerrit Uitslag * @return string[] with the data: array(pageid=>name, ... )
390f3f0262cSandi */
391f3f0262cSandifunction breadcrumbs() {
3928746e727Sandi    // we prepare the breadcrumbs early for quick session closing
3938746e727Sandi    static $crumbs = null;
3948746e727Sandi    if($crumbs != null) return $crumbs;
3958746e727Sandi
396f3f0262cSandi    global $ID;
397f3f0262cSandi    global $ACT;
398f3f0262cSandi    global $conf;
399f3f0262cSandi
400f3f0262cSandi    //first visit?
401c66972f2SAdrian Lang    $crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array();
4024d1fee4cSB_S666    //we only save on show and existing visible wiki documents
403a77f5846Sjan    $file = wikiFN($ID);
4044d1fee4cSB_S666    if($ACT != 'show' || isHiddenPage($ID) || !file_exists($file)) {
405e71ce681SAndreas Gohr        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
406f3f0262cSandi        return $crumbs;
407f3f0262cSandi    }
408a77f5846Sjan
409a77f5846Sjan    // page names
4101a84a0f3SAnika Henke    $name = noNSorNS($ID);
411fe9ec250SChris Smith    if(useHeading('navigation')) {
412a77f5846Sjan        // get page title
41367c15eceSMichael Hamann        $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
414a77f5846Sjan        if($title) {
415a77f5846Sjan            $name = $title;
416a77f5846Sjan        }
417a77f5846Sjan    }
418a77f5846Sjan
419f3f0262cSandi    //remove ID from array
420a77f5846Sjan    if(isset($crumbs[$ID])) {
421a77f5846Sjan        unset($crumbs[$ID]);
422f3f0262cSandi    }
423f3f0262cSandi
424f3f0262cSandi    //add to array
425a77f5846Sjan    $crumbs[$ID] = $name;
426f3f0262cSandi    //reduce size
427f3f0262cSandi    while(count($crumbs) > $conf['breadcrumbs']) {
428f3f0262cSandi        array_shift($crumbs);
429f3f0262cSandi    }
430f3f0262cSandi    //save to session
431e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
432f3f0262cSandi    return $crumbs;
433f3f0262cSandi}
434f3f0262cSandi
435f3f0262cSandi/**
43615fae107Sandi * Filter for page IDs
43715fae107Sandi *
438f3f0262cSandi * This is run on a ID before it is outputted somewhere
439f3f0262cSandi * currently used to replace the colon with something else
440907f24f7SAndreas Gohr * on Windows (non-IIS) systems and to have proper URL encoding
441907f24f7SAndreas Gohr *
442907f24f7SAndreas Gohr * See discussions at https://github.com/splitbrain/dokuwiki/pull/84 and
443907f24f7SAndreas Gohr * https://github.com/splitbrain/dokuwiki/pull/173 why we use a whitelist of
444907f24f7SAndreas Gohr * unaffected servers instead of blacklisting affected servers here.
44515fae107Sandi *
44649c713a3Sandi * Urlencoding is ommitted when the second parameter is false
44749c713a3Sandi *
44815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
449140cfbcdSGerrit Uitslag *
450140cfbcdSGerrit Uitslag * @param string $id pageid being filtered
451140cfbcdSGerrit Uitslag * @param bool   $ue apply urlencoding?
452140cfbcdSGerrit Uitslag * @return string
453f3f0262cSandi */
45449c713a3Sandifunction idfilter($id, $ue = true) {
455f3f0262cSandi    global $conf;
456585bf44eSChristopher Smith    /* @var Input $INPUT */
457585bf44eSChristopher Smith    global $INPUT;
458585bf44eSChristopher Smith
459f3f0262cSandi    if($conf['useslash'] && $conf['userewrite']) {
460f3f0262cSandi        $id = strtr($id, ':', '/');
461f3f0262cSandi    } elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
46258bedc8aSborekb        $conf['userewrite'] &&
463585bf44eSChristopher Smith        strpos($INPUT->server->str('SERVER_SOFTWARE'), 'Microsoft-IIS') === false
4643272d797SAndreas Gohr    ) {
465f3f0262cSandi        $id = strtr($id, ':', ';');
466f3f0262cSandi    }
46749c713a3Sandi    if($ue) {
468b6c6979fSAndreas Gohr        $id = rawurlencode($id);
469f3f0262cSandi        $id = str_replace('%3A', ':', $id); //keep as colon
470edd95259SGerrit Uitslag        $id = str_replace('%3B', ';', $id); //keep as semicolon
471f3f0262cSandi        $id = str_replace('%2F', '/', $id); //keep as slash
47249c713a3Sandi    }
473f3f0262cSandi    return $id;
474f3f0262cSandi}
475f3f0262cSandi
476f3f0262cSandi/**
477ed7b5f09Sandi * This builds a link to a wikipage
47815fae107Sandi *
4794bc480e5SAndreas Gohr * It handles URL rewriting and adds additional parameters
4806c7843b5Sandi *
48115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
4824bc480e5SAndreas Gohr *
4834bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
4844bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
4854bc480e5SAndreas Gohr * @param bool         $absolute       request an absolute URL instead of relative
4864bc480e5SAndreas Gohr * @param string       $separator      parameter separator
4874bc480e5SAndreas Gohr * @return string
488f3f0262cSandi */
48916f15a81SDominik Eckelmannfunction wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;') {
490f3f0262cSandi    global $conf;
49116f15a81SDominik Eckelmann    if(is_array($urlParameters)) {
4924bde2196Slisps        if(isset($urlParameters['rev']) && !$urlParameters['rev']) unset($urlParameters['rev']);
4937b62b42dSlisps        if(isset($urlParameters['at']) && $conf['date_at_format']) $urlParameters['at'] = date($conf['date_at_format'],$urlParameters['at']);
49416f15a81SDominik Eckelmann        $urlParameters = buildURLparams($urlParameters, $separator);
4956de3759aSAndreas Gohr    } else {
49616f15a81SDominik Eckelmann        $urlParameters = str_replace(',', $separator, $urlParameters);
4976de3759aSAndreas Gohr    }
49816f15a81SDominik Eckelmann    if($id === '') {
49916f15a81SDominik Eckelmann        $id = $conf['start'];
50016f15a81SDominik Eckelmann    }
501f3f0262cSandi    $id = idfilter($id);
50216f15a81SDominik Eckelmann    if($absolute) {
503ed7b5f09Sandi        $xlink = DOKU_URL;
504ed7b5f09Sandi    } else {
505ed7b5f09Sandi        $xlink = DOKU_BASE;
506ed7b5f09Sandi    }
507f3f0262cSandi
5086c7843b5Sandi    if($conf['userewrite'] == 2) {
5096c7843b5Sandi        $xlink .= DOKU_SCRIPT.'/'.$id;
51016f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
5116c7843b5Sandi    } elseif($conf['userewrite']) {
512f3f0262cSandi        $xlink .= $id;
51316f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
514bce3726dSAndreas Gohr    } elseif($id) {
5156c7843b5Sandi        $xlink .= DOKU_SCRIPT.'?id='.$id;
51616f15a81SDominik Eckelmann        if($urlParameters) $xlink .= $separator.$urlParameters;
517bce3726dSAndreas Gohr    } else {
518bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
51916f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
520f3f0262cSandi    }
521f3f0262cSandi
522f3f0262cSandi    return $xlink;
523f3f0262cSandi}
524f3f0262cSandi
525f3f0262cSandi/**
526f5c2808fSBen Coburn * This builds a link to an alternate page format
527f5c2808fSBen Coburn *
528f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
529f5c2808fSBen Coburn *
530f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
5314bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
5324bc480e5SAndreas Gohr * @param string       $format         the export renderer to use
5334bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
5344bc480e5SAndreas Gohr * @param bool         $abs            request an absolute URL instead of relative
5354bc480e5SAndreas Gohr * @param string       $sep            parameter separator
5364bc480e5SAndreas Gohr * @return string
537f5c2808fSBen Coburn */
5384bc480e5SAndreas Gohrfunction exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;') {
539f5c2808fSBen Coburn    global $conf;
5404bc480e5SAndreas Gohr    if(is_array($urlParameters)) {
5414bc480e5SAndreas Gohr        $urlParameters = buildURLparams($urlParameters, $sep);
542f5c2808fSBen Coburn    } else {
5434bc480e5SAndreas Gohr        $urlParameters = str_replace(',', $sep, $urlParameters);
544f5c2808fSBen Coburn    }
545f5c2808fSBen Coburn
546f5c2808fSBen Coburn    $format = rawurlencode($format);
547f5c2808fSBen Coburn    $id     = idfilter($id);
548f5c2808fSBen Coburn    if($abs) {
549f5c2808fSBen Coburn        $xlink = DOKU_URL;
550f5c2808fSBen Coburn    } else {
551f5c2808fSBen Coburn        $xlink = DOKU_BASE;
552f5c2808fSBen Coburn    }
553f5c2808fSBen Coburn
554f5c2808fSBen Coburn    if($conf['userewrite'] == 2) {
555f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
5564bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
557f5c2808fSBen Coburn    } elseif($conf['userewrite'] == 1) {
558f5c2808fSBen Coburn        $xlink .= '_export/'.$format.'/'.$id;
5594bc480e5SAndreas Gohr        if($urlParameters) $xlink .= '?'.$urlParameters;
560f5c2808fSBen Coburn    } else {
561f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
5624bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
563f5c2808fSBen Coburn    }
564f5c2808fSBen Coburn
565f5c2808fSBen Coburn    return $xlink;
566f5c2808fSBen Coburn}
567f5c2808fSBen Coburn
568f5c2808fSBen Coburn/**
5696de3759aSAndreas Gohr * Build a link to a media file
5706de3759aSAndreas Gohr *
5716de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
5728c08db0aSAndreas Gohr *
5738c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
5748c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
5758c08db0aSAndreas Gohr *
5763272d797SAndreas Gohr * @param string  $id     the media file id or URL
5773272d797SAndreas Gohr * @param mixed   $more   string or array with additional parameters
5783272d797SAndreas Gohr * @param bool    $direct link to detail page if false
5793272d797SAndreas Gohr * @param string  $sep    URL parameter separator
5803272d797SAndreas Gohr * @param bool    $abs    Create an absolute URL
5813272d797SAndreas Gohr * @return string
5826de3759aSAndreas Gohr */
58355b2b31bSAndreas Gohrfunction ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false) {
5846de3759aSAndreas Gohr    global $conf;
585b9ee6a44SKlap-in    $isexternalimage = media_isexternal($id);
586826d2766SKlap-in    if(!$isexternalimage) {
587826d2766SKlap-in        $id = cleanID($id);
588826d2766SKlap-in    }
589826d2766SKlap-in
5906de3759aSAndreas Gohr    if(is_array($more)) {
5910f4e0092SChristopher Smith        // add token for resized images
592443e135dSChristopher Smith        if(!empty($more['w']) || !empty($more['h']) || $isexternalimage){
5930f4e0092SChristopher Smith            $more['tok'] = media_get_token($id,$more['w'],$more['h']);
5940f4e0092SChristopher Smith        }
5958c08db0aSAndreas Gohr        // strip defaults for shorter URLs
5968c08db0aSAndreas Gohr        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
597443e135dSChristopher Smith        if(empty($more['w'])) unset($more['w']);
598443e135dSChristopher Smith        if(empty($more['h'])) unset($more['h']);
5998c08db0aSAndreas Gohr        if(isset($more['id']) && $direct) unset($more['id']);
60078b874e6Slisps        if(isset($more['rev']) && !$more['rev']) unset($more['rev']);
601b174aeaeSchris        $more = buildURLparams($more, $sep);
6026de3759aSAndreas Gohr    } else {
6035e7db1e2SChristopher Smith        $matches = array();
604cc036f74SKlap-in        if (preg_match_all('/\b(w|h)=(\d*)\b/',$more,$matches,PREG_SET_ORDER) || $isexternalimage){
6055e7db1e2SChristopher Smith            $resize = array('w'=>0, 'h'=>0);
6065e7db1e2SChristopher Smith            foreach ($matches as $match){
6075e7db1e2SChristopher Smith                $resize[$match[1]] = $match[2];
6085e7db1e2SChristopher Smith            }
609cc036f74SKlap-in            $more .= $more === '' ? '' : $sep;
610cc036f74SKlap-in            $more .= 'tok='.media_get_token($id,$resize['w'],$resize['h']);
6115e7db1e2SChristopher Smith        }
6128c08db0aSAndreas Gohr        $more = str_replace('cache=cache', '', $more); //skip default
6138c08db0aSAndreas Gohr        $more = str_replace(',,', ',', $more);
614b174aeaeSchris        $more = str_replace(',', $sep, $more);
6156de3759aSAndreas Gohr    }
6166de3759aSAndreas Gohr
61755b2b31bSAndreas Gohr    if($abs) {
61855b2b31bSAndreas Gohr        $xlink = DOKU_URL;
61955b2b31bSAndreas Gohr    } else {
6206de3759aSAndreas Gohr        $xlink = DOKU_BASE;
62155b2b31bSAndreas Gohr    }
6226de3759aSAndreas Gohr
6236de3759aSAndreas Gohr    // external URLs are always direct without rewriting
624826d2766SKlap-in    if($isexternalimage) {
6256de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
626cc036f74SKlap-in        $xlink .= '?'.$more;
627b174aeaeSchris        $xlink .= $sep.'media='.rawurlencode($id);
6286de3759aSAndreas Gohr        return $xlink;
6296de3759aSAndreas Gohr    }
6306de3759aSAndreas Gohr
6316de3759aSAndreas Gohr    $id = idfilter($id);
6326de3759aSAndreas Gohr
6336de3759aSAndreas Gohr    // decide on scriptname
6346de3759aSAndreas Gohr    if($direct) {
6356de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
6366de3759aSAndreas Gohr            $script = '_media';
6376de3759aSAndreas Gohr        } else {
6386de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
6396de3759aSAndreas Gohr        }
6406de3759aSAndreas Gohr    } else {
6416de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
6426de3759aSAndreas Gohr            $script = '_detail';
6436de3759aSAndreas Gohr        } else {
6446de3759aSAndreas Gohr            $script = 'lib/exe/detail.php';
6456de3759aSAndreas Gohr        }
6466de3759aSAndreas Gohr    }
6476de3759aSAndreas Gohr
6486de3759aSAndreas Gohr    // build URL based on rewrite mode
6496de3759aSAndreas Gohr    if($conf['userewrite']) {
6506de3759aSAndreas Gohr        $xlink .= $script.'/'.$id;
6516de3759aSAndreas Gohr        if($more) $xlink .= '?'.$more;
6526de3759aSAndreas Gohr    } else {
6536de3759aSAndreas Gohr        if($more) {
654a99d3236SEsther Brunner            $xlink .= $script.'?'.$more;
655b174aeaeSchris            $xlink .= $sep.'media='.$id;
6566de3759aSAndreas Gohr        } else {
657a99d3236SEsther Brunner            $xlink .= $script.'?media='.$id;
6586de3759aSAndreas Gohr        }
6596de3759aSAndreas Gohr    }
6606de3759aSAndreas Gohr
6616de3759aSAndreas Gohr    return $xlink;
6626de3759aSAndreas Gohr}
6636de3759aSAndreas Gohr
6646de3759aSAndreas Gohr/**
66525ca5b17SAndreas Gohr * Returns the URL to the DokuWiki base script
66615fae107Sandi *
66725ca5b17SAndreas Gohr * Consider using wl() instead, unless you absoutely need the doku.php endpoint
66825ca5b17SAndreas Gohr *
66915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
670140cfbcdSGerrit Uitslag *
671140cfbcdSGerrit Uitslag * @return string
672f3f0262cSandi */
67325ca5b17SAndreas Gohrfunction script() {
674ed7b5f09Sandi    return DOKU_BASE.DOKU_SCRIPT;
675f3f0262cSandi}
676f3f0262cSandi
677f3f0262cSandi/**
67815fae107Sandi * Spamcheck against wordlist
67915fae107Sandi *
680f3f0262cSandi * Checks the wikitext against a list of blocked expressions
681f3f0262cSandi * returns true if the text contains any bad words
68215fae107Sandi *
683e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
684e403cc58SMichael Klier *
685e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
686e403cc58SMichael Klier *  and gain information about the user who was blocked.
687e403cc58SMichael Klier *
688e403cc58SMichael Klier *  Event data:
689e403cc58SMichael Klier *    data['matches']  - array of matches
690e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
691e403cc58SMichael Klier *      [ip]           - ip address
692e403cc58SMichael Klier *      [user]         - username (if logged in)
693e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
694e403cc58SMichael Klier *      [name]         - real name (if logged in)
695e403cc58SMichael Klier *
69615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
6976dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
698140cfbcdSGerrit Uitslag *
6996dffa0e0SAndreas Gohr * @param  string $text - optional text to check, if not given the globals are used
7006dffa0e0SAndreas Gohr * @return bool         - true if a spam word was found
701f3f0262cSandi */
7026dffa0e0SAndreas Gohrfunction checkwordblock($text = '') {
703f3f0262cSandi    global $TEXT;
7046dffa0e0SAndreas Gohr    global $PRE;
7056dffa0e0SAndreas Gohr    global $SUF;
706e0086ca2SAndreas Gohr    global $SUM;
707f3f0262cSandi    global $conf;
708e403cc58SMichael Klier    global $INFO;
709585bf44eSChristopher Smith    /* @var Input $INPUT */
710585bf44eSChristopher Smith    global $INPUT;
711f3f0262cSandi
712f3f0262cSandi    if(!$conf['usewordblock']) return false;
713f3f0262cSandi
714e0086ca2SAndreas Gohr    if(!$text) $text = "$PRE $TEXT $SUF $SUM";
7156dffa0e0SAndreas Gohr
716041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
7176dffa0e0SAndreas Gohr    $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i', '\1http://\2 \2\3', $text);
718041d1964SAndreas Gohr
719b9ac8716Schris    $wordblocks = getWordblocks();
7203e2965d7Sandi    // how many lines to read at once (to work around some PCRE limits)
7213e2965d7Sandi    if(version_compare(phpversion(), '4.3.0', '<')) {
7223e2965d7Sandi        // old versions of PCRE define a maximum of parenthesises even if no
7233e2965d7Sandi        // backreferences are used - the maximum is 99
7243e2965d7Sandi        // this is very bad performancewise and may even be too high still
7253e2965d7Sandi        $chunksize = 40;
7263e2965d7Sandi    } else {
727a51d08efSAndreas Gohr        // read file in chunks of 200 - this should work around the
7283e2965d7Sandi        // MAX_PATTERN_SIZE in modern PCRE
729a51d08efSAndreas Gohr        $chunksize = 200;
7303e2965d7Sandi    }
731b9ac8716Schris    while($blocks = array_splice($wordblocks, 0, $chunksize)) {
732f3f0262cSandi        $re = array();
73349eb6e38SAndreas Gohr        // build regexp from blocks
734f3f0262cSandi        foreach($blocks as $block) {
735f3f0262cSandi            $block = preg_replace('/#.*$/', '', $block);
736f3f0262cSandi            $block = trim($block);
737f3f0262cSandi            if(empty($block)) continue;
738f3f0262cSandi            $re[] = $block;
739f3f0262cSandi        }
740e403cc58SMichael Klier        if(count($re) && preg_match('#('.join('|', $re).')#si', $text, $matches)) {
741e403cc58SMichael Klier            // prepare event data
74259bc3b48SGerrit Uitslag            $data = array();
743e403cc58SMichael Klier            $data['matches']        = $matches;
744585bf44eSChristopher Smith            $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
745585bf44eSChristopher Smith            if($INPUT->server->str('REMOTE_USER')) {
746585bf44eSChristopher Smith                $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
747e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
748e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
749e403cc58SMichael Klier            }
750bad6fc0dSAndreas Gohr            $callback = function () {
751bad6fc0dSAndreas Gohr                return true;
752bad6fc0dSAndreas Gohr            };
753e403cc58SMichael Klier            return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
754b9ac8716Schris        }
755703f6fdeSandi    }
756f3f0262cSandi    return false;
757f3f0262cSandi}
758f3f0262cSandi
759f3f0262cSandi/**
76015fae107Sandi * Return the IP of the client
76115fae107Sandi *
7626d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
76315fae107Sandi *
7646d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
7656d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
7666d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
7676d8affe6SAndreas Gohr * headers
7686d8affe6SAndreas Gohr *
76915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
770140cfbcdSGerrit Uitslag *
7713272d797SAndreas Gohr * @param  boolean $single If set only a single IP is returned
7723272d797SAndreas Gohr * @return string
773f3f0262cSandi */
7746d8affe6SAndreas Gohrfunction clientIP($single = false) {
775585bf44eSChristopher Smith    /* @var Input $INPUT */
776585bf44eSChristopher Smith    global $INPUT;
777585bf44eSChristopher Smith
7786d8affe6SAndreas Gohr    $ip   = array();
779585bf44eSChristopher Smith    $ip[] = $INPUT->server->str('REMOTE_ADDR');
780585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_FORWARDED_FOR')) {
781585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_FORWARDED_FOR'))));
782585bf44eSChristopher Smith    }
783585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_REAL_IP')) {
784585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_REAL_IP'))));
785585bf44eSChristopher Smith    }
7866d8affe6SAndreas Gohr
787dc14c6d1SGuy Brand    // some IPv4/v6 regexps borrowed from Feyd
788dc14c6d1SGuy Brand    // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
789dc14c6d1SGuy Brand    $dec_octet   = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
790dc14c6d1SGuy Brand    $hex_digit   = '[A-Fa-f0-9]';
791dc14c6d1SGuy Brand    $h16         = "{$hex_digit}{1,4}";
792dc14c6d1SGuy Brand    $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
793dc14c6d1SGuy Brand    $ls32        = "(?:$h16:$h16|$IPv4Address)";
794dc14c6d1SGuy Brand    $IPv6Address =
795dc14c6d1SGuy Brand        "(?:(?:{$IPv4Address})|(?:".
796dc14c6d1SGuy Brand            "(?:$h16:){6}$ls32".
797dc14c6d1SGuy Brand            "|::(?:$h16:){5}$ls32".
798dc14c6d1SGuy Brand            "|(?:$h16)?::(?:$h16:){4}$ls32".
799dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32".
800dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32".
801dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32".
802dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,4}$h16)?::$ls32".
803dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,5}$h16)?::$h16".
804dc14c6d1SGuy Brand            "|(?:(?:$h16:){0,6}$h16)?::".
805dc14c6d1SGuy Brand            ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
806dc14c6d1SGuy Brand
8076d8affe6SAndreas Gohr    // remove any non-IP stuff
8086d8affe6SAndreas Gohr    $cnt   = count($ip);
8094ff28443Schris    $match = array();
8106d8affe6SAndreas Gohr    for($i = 0; $i < $cnt; $i++) {
811dc14c6d1SGuy Brand        if(preg_match("/^$IPv4Address$/", $ip[$i], $match) || preg_match("/^$IPv6Address$/", $ip[$i], $match)) {
8124ff28443Schris            $ip[$i] = $match[0];
8134ff28443Schris        } else {
8144ff28443Schris            $ip[$i] = '';
8154ff28443Schris        }
8166d8affe6SAndreas Gohr        if(empty($ip[$i])) unset($ip[$i]);
817f3f0262cSandi    }
8186d8affe6SAndreas Gohr    $ip = array_values(array_unique($ip));
8196d8affe6SAndreas Gohr    if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
8206d8affe6SAndreas Gohr
8216d8affe6SAndreas Gohr    if(!$single) return join(',', $ip);
8226d8affe6SAndreas Gohr
8236d8affe6SAndreas Gohr    // decide which IP to use, trying to avoid local addresses
8246d8affe6SAndreas Gohr    $ip = array_reverse($ip);
8256d8affe6SAndreas Gohr    foreach($ip as $i) {
8262343a762SAndreas Gohr        if(preg_match('/^(::1|[fF][eE]80:|127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/', $i)) {
8276d8affe6SAndreas Gohr            continue;
8286d8affe6SAndreas Gohr        } else {
8296d8affe6SAndreas Gohr            return $i;
8306d8affe6SAndreas Gohr        }
8316d8affe6SAndreas Gohr    }
8326d8affe6SAndreas Gohr    // still here? just use the first (last) address
8336d8affe6SAndreas Gohr    return $ip[0];
834f3f0262cSandi}
835f3f0262cSandi
836f3f0262cSandi/**
8371c548ebeSAndreas Gohr * Check if the browser is on a mobile device
8381c548ebeSAndreas Gohr *
8391c548ebeSAndreas Gohr * Adapted from the example code at url below
8401c548ebeSAndreas Gohr *
8411c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
842140cfbcdSGerrit Uitslag *
843140cfbcdSGerrit Uitslag * @return bool if true, client is mobile browser; otherwise false
8441c548ebeSAndreas Gohr */
8451c548ebeSAndreas Gohrfunction clientismobile() {
846585bf44eSChristopher Smith    /* @var Input $INPUT */
847585bf44eSChristopher Smith    global $INPUT;
8481c548ebeSAndreas Gohr
849585bf44eSChristopher Smith    if($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
8501c548ebeSAndreas Gohr
851585bf44eSChristopher Smith    if(preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
8521c548ebeSAndreas Gohr
853585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_USER_AGENT')) return false;
8541c548ebeSAndreas Gohr
8551c548ebeSAndreas 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';
8561c548ebeSAndreas Gohr
857585bf44eSChristopher Smith    if(preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
8581c548ebeSAndreas Gohr
8591c548ebeSAndreas Gohr    return false;
8601c548ebeSAndreas Gohr}
8611c548ebeSAndreas Gohr
8621c548ebeSAndreas Gohr/**
8636efc45a2SDmitry Katsubo * check if a given link is interwiki link
8646efc45a2SDmitry Katsubo *
8656efc45a2SDmitry Katsubo * @param string $link the link, e.g. "wiki>page"
8666efc45a2SDmitry Katsubo * @return bool
8676efc45a2SDmitry Katsubo */
8686efc45a2SDmitry Katsubofunction link_isinterwiki($link){
8696efc45a2SDmitry Katsubo    if (preg_match('/^[a-zA-Z0-9\.]+>/u',$link)) return true;
8706efc45a2SDmitry Katsubo    return false;
8716efc45a2SDmitry Katsubo}
8726efc45a2SDmitry Katsubo
8736efc45a2SDmitry Katsubo/**
87463211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
87563211f61SGlen Harris *
87622ef1e32SAndreas Gohr * If $conf['dnslookups'] is disabled it simply returns the input string
87722ef1e32SAndreas Gohr *
87863211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
879140cfbcdSGerrit Uitslag *
8803272d797SAndreas Gohr * @param  string $ips comma separated list of IP addresses
8813272d797SAndreas Gohr * @return string a comma separated list of hostnames
88263211f61SGlen Harris */
88363211f61SGlen Harrisfunction gethostsbyaddrs($ips) {
88422ef1e32SAndreas Gohr    global $conf;
88522ef1e32SAndreas Gohr    if(!$conf['dnslookups']) return $ips;
88622ef1e32SAndreas Gohr
88763211f61SGlen Harris    $hosts = array();
88863211f61SGlen Harris    $ips   = explode(',', $ips);
889551a720fSMichael Klier
890551a720fSMichael Klier    if(is_array($ips)) {
8913886270dSAndreas Gohr        foreach($ips as $ip) {
892551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
89363211f61SGlen Harris        }
894551a720fSMichael Klier        return join(',', $hosts);
895551a720fSMichael Klier    } else {
896551a720fSMichael Klier        return gethostbyaddr(trim($ips));
897551a720fSMichael Klier    }
89863211f61SGlen Harris}
89963211f61SGlen Harris
90063211f61SGlen Harris/**
90115fae107Sandi * Checks if a given page is currently locked.
90215fae107Sandi *
903f3f0262cSandi * removes stale lockfiles
90415fae107Sandi *
90515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
906140cfbcdSGerrit Uitslag *
907140cfbcdSGerrit Uitslag * @param string $id page id
908140cfbcdSGerrit Uitslag * @return bool page is locked?
909f3f0262cSandi */
910f3f0262cSandifunction checklock($id) {
911f3f0262cSandi    global $conf;
912585bf44eSChristopher Smith    /* @var Input $INPUT */
913585bf44eSChristopher Smith    global $INPUT;
914585bf44eSChristopher Smith
915c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
916f3f0262cSandi
917f3f0262cSandi    //no lockfile
91879e79377SAndreas Gohr    if(!file_exists($lock)) return false;
919f3f0262cSandi
920f3f0262cSandi    //lockfile expired
921f3f0262cSandi    if((time() - filemtime($lock)) > $conf['locktime']) {
922d8186216SBen Coburn        @unlink($lock);
923f3f0262cSandi        return false;
924f3f0262cSandi    }
925f3f0262cSandi
926f3f0262cSandi    //my own lock
9276d2af55dSChristopher Smith    @list($ip, $session) = explode("\n", io_readFile($lock));
9280712fefaSAndreas Gohr    if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || (session_id() && $session == session_id())) {
929f3f0262cSandi        return false;
930f3f0262cSandi    }
931f3f0262cSandi
932f3f0262cSandi    return $ip;
933f3f0262cSandi}
934f3f0262cSandi
935f3f0262cSandi/**
93615fae107Sandi * Lock a page for editing
93715fae107Sandi *
93815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
939140cfbcdSGerrit Uitslag *
940140cfbcdSGerrit Uitslag * @param string $id page id to lock
941f3f0262cSandi */
942f3f0262cSandifunction lock($id) {
943544ed901SDaniel Calviño Sánchez    global $conf;
944585bf44eSChristopher Smith    /* @var Input $INPUT */
945585bf44eSChristopher Smith    global $INPUT;
946544ed901SDaniel Calviño Sánchez
947544ed901SDaniel Calviño Sánchez    if($conf['locktime'] == 0) {
948544ed901SDaniel Calviño Sánchez        return;
949544ed901SDaniel Calviño Sánchez    }
950544ed901SDaniel Calviño Sánchez
951c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
952585bf44eSChristopher Smith    if($INPUT->server->str('REMOTE_USER')) {
953585bf44eSChristopher Smith        io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
954f3f0262cSandi    } else {
95585fef7e2SAndreas Gohr        io_saveFile($lock, clientIP()."\n".session_id());
956f3f0262cSandi    }
957f3f0262cSandi}
958f3f0262cSandi
959f3f0262cSandi/**
96015fae107Sandi * Unlock a page if it was locked by the user
961f3f0262cSandi *
96215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
963140cfbcdSGerrit Uitslag *
9643272d797SAndreas Gohr * @param string $id page id to unlock
96515fae107Sandi * @return bool true if a lock was removed
966f3f0262cSandi */
967f3f0262cSandifunction unlock($id) {
968585bf44eSChristopher Smith    /* @var Input $INPUT */
969585bf44eSChristopher Smith    global $INPUT;
970585bf44eSChristopher Smith
971c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
97279e79377SAndreas Gohr    if(file_exists($lock)) {
9736d2af55dSChristopher Smith        @list($ip, $session) = explode("\n", io_readFile($lock));
974585bf44eSChristopher Smith        if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || $session == session_id()) {
975f3f0262cSandi            @unlink($lock);
976f3f0262cSandi            return true;
977f3f0262cSandi        }
978f3f0262cSandi    }
979f3f0262cSandi    return false;
980f3f0262cSandi}
981f3f0262cSandi
982f3f0262cSandi/**
983f3f0262cSandi * convert line ending to unix format
984f3f0262cSandi *
9856db7468bSAndreas Gohr * also makes sure the given text is valid UTF-8
9866db7468bSAndreas Gohr *
98715fae107Sandi * @see    formText() for 2crlf conversion
98815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
989140cfbcdSGerrit Uitslag *
990140cfbcdSGerrit Uitslag * @param string $text
991140cfbcdSGerrit Uitslag * @return string
992f3f0262cSandi */
993f3f0262cSandifunction cleanText($text) {
994f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
9956db7468bSAndreas Gohr
9966db7468bSAndreas Gohr    // if the text is not valid UTF-8 we simply assume latin1
9976db7468bSAndreas Gohr    // this won't break any worse than it breaks with the wrong encoding
9986db7468bSAndreas Gohr    // but might actually fix the problem in many cases
9996db7468bSAndreas Gohr    if(!utf8_check($text)) $text = utf8_encode($text);
10006db7468bSAndreas Gohr
1001f3f0262cSandi    return $text;
1002f3f0262cSandi}
1003f3f0262cSandi
1004f3f0262cSandi/**
1005f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
1006f3f0262cSandi * It also converts line endings to Windows format which is
1007f3f0262cSandi * pseudo standard for webforms.
1008f3f0262cSandi *
100915fae107Sandi * @see    cleanText() for 2unix conversion
101015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1011140cfbcdSGerrit Uitslag *
1012140cfbcdSGerrit Uitslag * @param string $text
1013140cfbcdSGerrit Uitslag * @return string
1014f3f0262cSandi */
1015f3f0262cSandifunction formText($text) {
10165b7d45a5SAndreas Gohr    $text = str_replace("\012", "\015\012", $text);
1017f3f0262cSandi    return htmlspecialchars($text);
1018f3f0262cSandi}
1019f3f0262cSandi
1020f3f0262cSandi/**
102115fae107Sandi * Returns the specified local text in raw format
102215fae107Sandi *
102315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1024140cfbcdSGerrit Uitslag *
1025140cfbcdSGerrit Uitslag * @param string $id   page id
1026140cfbcdSGerrit Uitslag * @param string $ext  extension of file being read, default 'txt'
1027140cfbcdSGerrit Uitslag * @return string
1028f3f0262cSandi */
10292adaf2b8SAndreas Gohrfunction rawLocale($id, $ext = 'txt') {
10302adaf2b8SAndreas Gohr    return io_readFile(localeFN($id, $ext));
1031f3f0262cSandi}
1032f3f0262cSandi
1033f3f0262cSandi/**
1034f3f0262cSandi * Returns the raw WikiText
103515fae107Sandi *
103615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1037140cfbcdSGerrit Uitslag *
1038140cfbcdSGerrit Uitslag * @param string $id   page id
1039e0c26282SGerrit Uitslag * @param string|int $rev  timestamp when a revision of wikitext is desired
1040140cfbcdSGerrit Uitslag * @return string
1041f3f0262cSandi */
1042f3f0262cSandifunction rawWiki($id, $rev = '') {
1043cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1044f3f0262cSandi}
1045f3f0262cSandi
1046f3f0262cSandi/**
10477146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
10487146cee2SAndreas Gohr *
10497b84afa2SAndreas Gohr * @triggers COMMON_PAGETPL_LOAD
10507146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1051140cfbcdSGerrit Uitslag *
1052140cfbcdSGerrit Uitslag * @param string $id the id of the page to be created
1053140cfbcdSGerrit Uitslag * @return string parsed pagetemplate content
10547146cee2SAndreas Gohr */
1055fe17917eSAdrian Langfunction pageTemplate($id) {
1056a15ce62dSEsther Brunner    global $conf;
1057e29549feSAndreas Gohr
1058fe17917eSAdrian Lang    if(is_array($id)) $id = $id[0];
1059e29549feSAndreas Gohr
10607b84afa2SAndreas Gohr    // prepare initial event data
10617b84afa2SAndreas Gohr    $data = array(
10627b84afa2SAndreas Gohr        'id'        => $id, // the id of the page to be created
10637b84afa2SAndreas Gohr        'tpl'       => '', // the text used as template
10647b84afa2SAndreas Gohr        'tplfile'   => '', // the file above text was/should be loaded from
10657b84afa2SAndreas Gohr        'doreplace' => true // should wildcard replacements be done on the text?
10667b84afa2SAndreas Gohr    );
10677b84afa2SAndreas Gohr
10687b84afa2SAndreas Gohr    $evt = new Doku_Event('COMMON_PAGETPL_LOAD', $data);
10697b84afa2SAndreas Gohr    if($evt->advise_before(true)) {
10707b84afa2SAndreas Gohr        // the before event might have loaded the content already
10717b84afa2SAndreas Gohr        if(empty($data['tpl'])) {
10727b84afa2SAndreas Gohr            // if the before event did not set a template file, try to find one
10737b84afa2SAndreas Gohr            if(empty($data['tplfile'])) {
1074fe17917eSAdrian Lang                $path = dirname(wikiFN($id));
107579e79377SAndreas Gohr                if(file_exists($path.'/_template.txt')) {
10767b84afa2SAndreas Gohr                    $data['tplfile'] = $path.'/_template.txt';
1077e29549feSAndreas Gohr                } else {
1078e29549feSAndreas Gohr                    // search upper namespaces for templates
1079e29549feSAndreas Gohr                    $len = strlen(rtrim($conf['datadir'], '/'));
1080e29549feSAndreas Gohr                    while(strlen($path) >= $len) {
108179e79377SAndreas Gohr                        if(file_exists($path.'/__template.txt')) {
10827b84afa2SAndreas Gohr                            $data['tplfile'] = $path.'/__template.txt';
1083e29549feSAndreas Gohr                            break;
1084e29549feSAndreas Gohr                        }
1085e29549feSAndreas Gohr                        $path = substr($path, 0, strrpos($path, '/'));
1086e29549feSAndreas Gohr                    }
1087e29549feSAndreas Gohr                }
10887b84afa2SAndreas Gohr            }
10897b84afa2SAndreas Gohr            // load the content
10903d7ac595SMichael Hamann            $data['tpl'] = io_readFile($data['tplfile']);
10917b84afa2SAndreas Gohr        }
1092a1bbd05bSMichael Hamann        if($data['doreplace']) parsePageTemplate($data);
10937b84afa2SAndreas Gohr    }
10947b84afa2SAndreas Gohr    $evt->advise_after();
10957b84afa2SAndreas Gohr    unset($evt);
10967b84afa2SAndreas Gohr
1097fe17917eSAdrian Lang    return $data['tpl'];
10982b1223ecSAdrian Lang}
10992b1223ecSAdrian Lang
11002b1223ecSAdrian Lang/**
11012b1223ecSAdrian Lang * Performs common page template replacements
11027b84afa2SAndreas Gohr * This works on data from COMMON_PAGETPL_LOAD
11032b1223ecSAdrian Lang *
11042b1223ecSAdrian Lang * @author Andreas Gohr <andi@splitbrain.org>
1105140cfbcdSGerrit Uitslag *
1106140cfbcdSGerrit Uitslag * @param array $data array with event data
1107140cfbcdSGerrit Uitslag * @return string
11082b1223ecSAdrian Lang */
1109d535a2e9Sstretchyboyfunction parsePageTemplate(&$data) {
11103272d797SAndreas Gohr    /**
11113272d797SAndreas Gohr     * @var string $id        the id of the page to be created
11123272d797SAndreas Gohr     * @var string $tpl       the text used as template
11133272d797SAndreas Gohr     * @var string $tplfile   the file above text was/should be loaded from
11143272d797SAndreas Gohr     * @var bool   $doreplace should wildcard replacements be done on the text?
11153272d797SAndreas Gohr     */
1116fe17917eSAdrian Lang    extract($data);
1117fe17917eSAdrian Lang
1118b856f7dfSAdrian Lang    global $USERINFO;
1119bce53b1fSAdrian Lang    global $conf;
1120585bf44eSChristopher Smith    /* @var Input $INPUT */
1121585bf44eSChristopher Smith    global $INPUT;
1122e29549feSAndreas Gohr
1123e29549feSAndreas Gohr    // replace placeholders
112426ece5a7SAndreas Gohr    $file = noNS($id);
112537c1acbdSAdrian Lang    $page = strtr($file, $conf['sepchar'], ' ');
112626ece5a7SAndreas Gohr
11273272d797SAndreas Gohr    $tpl = str_replace(
11283272d797SAndreas Gohr        array(
112926ece5a7SAndreas Gohr             '@ID@',
113026ece5a7SAndreas Gohr             '@NS@',
11318a7bcf66SShota Miyazaki             '@CURNS@',
113226ece5a7SAndreas Gohr             '@FILE@',
113326ece5a7SAndreas Gohr             '@!FILE@',
113426ece5a7SAndreas Gohr             '@!FILE!@',
113526ece5a7SAndreas Gohr             '@PAGE@',
113626ece5a7SAndreas Gohr             '@!PAGE@',
113726ece5a7SAndreas Gohr             '@!!PAGE@',
113826ece5a7SAndreas Gohr             '@!PAGE!@',
113926ece5a7SAndreas Gohr             '@USER@',
114026ece5a7SAndreas Gohr             '@NAME@',
114126ece5a7SAndreas Gohr             '@MAIL@',
114226ece5a7SAndreas Gohr             '@DATE@',
114326ece5a7SAndreas Gohr        ),
114426ece5a7SAndreas Gohr        array(
114526ece5a7SAndreas Gohr             $id,
114626ece5a7SAndreas Gohr             getNS($id),
11478a7bcf66SShota Miyazaki             curNS($id),
114826ece5a7SAndreas Gohr             $file,
114926ece5a7SAndreas Gohr             utf8_ucfirst($file),
115026ece5a7SAndreas Gohr             utf8_strtoupper($file),
115126ece5a7SAndreas Gohr             $page,
115226ece5a7SAndreas Gohr             utf8_ucfirst($page),
115326ece5a7SAndreas Gohr             utf8_ucwords($page),
115426ece5a7SAndreas Gohr             utf8_strtoupper($page),
1155585bf44eSChristopher Smith             $INPUT->server->str('REMOTE_USER'),
1156b856f7dfSAdrian Lang             $USERINFO['name'],
1157b856f7dfSAdrian Lang             $USERINFO['mail'],
115826ece5a7SAndreas Gohr             $conf['dformat'],
11593272d797SAndreas Gohr        ), $tpl
11603272d797SAndreas Gohr    );
116126ece5a7SAndreas Gohr
11627d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
1163bad6fc0dSAndreas Gohr    $tpl = preg_replace_callback(
1164bad6fc0dSAndreas Gohr        '/%./',
1165bad6fc0dSAndreas Gohr        function ($m) {
1166bad6fc0dSAndreas Gohr            return strftime($m[0]);
1167bad6fc0dSAndreas Gohr        },
1168bad6fc0dSAndreas Gohr        $tpl
1169bad6fc0dSAndreas Gohr    );
1170d535a2e9Sstretchyboy    $data['tpl'] = $tpl;
1171a15ce62dSEsther Brunner    return $tpl;
11727146cee2SAndreas Gohr}
11737146cee2SAndreas Gohr
11747146cee2SAndreas Gohr/**
117515fae107Sandi * Returns the raw Wiki Text in three slices.
117615fae107Sandi *
117715fae107Sandi * The range parameter needs to have the form "from-to"
117815cfe303Sandi * and gives the range of the section in bytes - no
117915cfe303Sandi * UTF-8 awareness is needed.
1180f3f0262cSandi * The returned order is prefix, section and suffix.
118115fae107Sandi *
118215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1183140cfbcdSGerrit Uitslag *
1184140cfbcdSGerrit Uitslag * @param string $range in form "from-to"
1185140cfbcdSGerrit Uitslag * @param string $id    page id
1186140cfbcdSGerrit Uitslag * @param string $rev   optional, the revision timestamp
118742ea7f44SGerrit Uitslag * @return string[] with three slices
1188f3f0262cSandi */
1189f3f0262cSandifunction rawWikiSlices($range, $id, $rev = '') {
1190cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1191f3f0262cSandi
119280fcb268SAdrian Lang    // Parse range
119380fcb268SAdrian Lang    list($from, $to) = explode('-', $range, 2);
119480fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
119580fcb268SAdrian Lang    $from = !$from ? 0 : ($from - 1);
119680fcb268SAdrian Lang    $to   = !$to ? strlen($text) : ($to - 1);
119780fcb268SAdrian Lang
119859bc3b48SGerrit Uitslag    $slices = array();
119980fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
120080fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to - $from);
120115cfe303Sandi    $slices[2] = substr($text, $to);
1202f3f0262cSandi    return $slices;
1203f3f0262cSandi}
1204f3f0262cSandi
1205f3f0262cSandi/**
120615fae107Sandi * Joins wiki text slices
120715fae107Sandi *
120880fcb268SAdrian Lang * function to join the text slices.
1209f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
1210f3f0262cSandi * lines between sections if needed (used on saving).
121115fae107Sandi *
121215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1213140cfbcdSGerrit Uitslag *
1214140cfbcdSGerrit Uitslag * @param string $pre   prefix
1215140cfbcdSGerrit Uitslag * @param string $text  text in the middle
1216140cfbcdSGerrit Uitslag * @param string $suf   suffix
1217140cfbcdSGerrit Uitslag * @param bool $pretty add additional empty lines between sections
1218140cfbcdSGerrit Uitslag * @return string
1219f3f0262cSandi */
1220f3f0262cSandifunction con($pre, $text, $suf, $pretty = false) {
1221f3f0262cSandi    if($pretty) {
122280fcb268SAdrian Lang        if($pre !== '' && substr($pre, -1) !== "\n" &&
12233272d797SAndreas Gohr            substr($text, 0, 1) !== "\n"
12243272d797SAndreas Gohr        ) {
122580fcb268SAdrian Lang            $pre .= "\n";
122680fcb268SAdrian Lang        }
122780fcb268SAdrian Lang        if($suf !== '' && substr($text, -1) !== "\n" &&
12283272d797SAndreas Gohr            substr($suf, 0, 1) !== "\n"
12293272d797SAndreas Gohr        ) {
123080fcb268SAdrian Lang            $text .= "\n";
123180fcb268SAdrian Lang        }
1232f3f0262cSandi    }
1233f3f0262cSandi
1234f3f0262cSandi    return $pre.$text.$suf;
1235f3f0262cSandi}
1236f3f0262cSandi
1237f3f0262cSandi/**
1238b24d9195SAndreas Gohr * Checks if the current page version is newer than the last entry in the page's
1239b24d9195SAndreas Gohr * changelog. If so, we assume it has been an external edit and we create an
1240b24d9195SAndreas Gohr * attic copy and add a proper changelog line.
1241b24d9195SAndreas Gohr *
1242b24d9195SAndreas Gohr * This check is only executed when the page is about to be saved again from the
1243b24d9195SAndreas Gohr * wiki, triggered in @see saveWikiText()
1244b24d9195SAndreas Gohr *
1245b24d9195SAndreas Gohr * @param string $id the page ID
1246b24d9195SAndreas Gohr */
1247b24d9195SAndreas Gohrfunction detectExternalEdit($id) {
1248b24d9195SAndreas Gohr    global $lang;
1249b24d9195SAndreas Gohr
12508c7319beSGerrit Uitslag    $fileLastMod = wikiFN($id);
12518c7319beSGerrit Uitslag    $lastMod     = @filemtime($fileLastMod); // from page
1252b24d9195SAndreas Gohr    $pagelog     = new PageChangeLog($id, 1024);
12538c7319beSGerrit Uitslag    $lastRev     = $pagelog->getRevisions(-1, 1); // from changelog
12548c7319beSGerrit Uitslag    $lastRev     = (int) (empty($lastRev) ? 0 : $lastRev[0]);
1255b24d9195SAndreas Gohr
12568c7319beSGerrit Uitslag    if(!file_exists(wikiFN($id, $lastMod)) && file_exists($fileLastMod) && $lastMod >= $lastRev) {
1257b24d9195SAndreas Gohr        // add old revision to the attic if missing
1258b24d9195SAndreas Gohr        saveOldRevision($id);
1259b24d9195SAndreas Gohr        // add a changelog entry if this edit came from outside dokuwiki
12608c7319beSGerrit Uitslag        if($lastMod > $lastRev) {
12618c7319beSGerrit Uitslag            $fileLastRev = wikiFN($id, $lastRev);
12628c7319beSGerrit Uitslag            $revinfo = $pagelog->getRevisionInfo($lastRev);
12633c48b1d0SGerrit Uitslag            if(empty($lastRev) || !file_exists($fileLastRev) || $revinfo['type'] == DOKU_CHANGE_TYPE_DELETE) {
12644b5aebc1SGerrit Uitslag                $filesize_old = 0;
12654b5aebc1SGerrit Uitslag            } else {
12668c7319beSGerrit Uitslag                $filesize_old = io_getSizeFile($fileLastRev);
12674b5aebc1SGerrit Uitslag            }
12688c7319beSGerrit Uitslag            $filesize_new = filesize($fileLastMod);
12692966355bSGerrit Uitslag            $sizechange = $filesize_new - $filesize_old;
12702966355bSGerrit Uitslag
12718c7319beSGerrit Uitslag            addLogEntry($lastMod, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=> true), $sizechange);
1272b24d9195SAndreas Gohr            // remove soon to be stale instructions
12738c7319beSGerrit Uitslag            $cache = new cache_instructions($id, $fileLastMod);
1274b24d9195SAndreas Gohr            $cache->removeCache();
1275b24d9195SAndreas Gohr        }
1276b24d9195SAndreas Gohr    }
1277b24d9195SAndreas Gohr}
1278b24d9195SAndreas Gohr
1279b24d9195SAndreas Gohr/**
1280a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
1281a701424fSBen Coburn * Also directs changelog and attic updates.
128215fae107Sandi *
128315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
128471726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
1285140cfbcdSGerrit Uitslag *
1286140cfbcdSGerrit Uitslag * @param string $id       page id
1287140cfbcdSGerrit Uitslag * @param string $text     wikitext being saved
1288140cfbcdSGerrit Uitslag * @param string $summary  summary of text update
1289140cfbcdSGerrit Uitslag * @param bool   $minor    mark this saved version as minor update
1290f3f0262cSandi */
1291b6912aeaSAndreas Gohrfunction saveWikiText($id, $text, $summary, $minor = false) {
1292a701424fSBen Coburn    /* Note to developers:
1293a701424fSBen Coburn       This code is subtle and delicate. Test the behavior of
1294a701424fSBen Coburn       the attic and changelog with dokuwiki and external edits
1295a701424fSBen Coburn       after any changes. External edits change the wiki page
1296a701424fSBen Coburn       directly without using php or dokuwiki.
1297a701424fSBen Coburn     */
1298f3f0262cSandi    global $conf;
1299f3f0262cSandi    global $lang;
130071726d78SBen Coburn    global $REV;
1301585bf44eSChristopher Smith    /* @var Input $INPUT */
1302585bf44eSChristopher Smith    global $INPUT;
1303585bf44eSChristopher Smith
1304b24d9195SAndreas Gohr    // prepare data for event
1305b24d9195SAndreas Gohr    $svdta = array();
1306b24d9195SAndreas Gohr    $svdta['id']             = $id;
1307b24d9195SAndreas Gohr    $svdta['file']           = wikiFN($id);
1308b24d9195SAndreas Gohr    $svdta['revertFrom']     = $REV;
1309b24d9195SAndreas Gohr    $svdta['oldRevision']    = @filemtime($svdta['file']);
1310b24d9195SAndreas Gohr    $svdta['newRevision']    = 0;
1311b24d9195SAndreas Gohr    $svdta['newContent']     = $text;
1312b24d9195SAndreas Gohr    $svdta['oldContent']     = rawWiki($id);
1313b24d9195SAndreas Gohr    $svdta['summary']        = $summary;
1314b24d9195SAndreas Gohr    $svdta['contentChanged'] = ($svdta['newContent'] != $svdta['oldContent']);
1315b24d9195SAndreas Gohr    $svdta['changeInfo']     = '';
1316b24d9195SAndreas Gohr    $svdta['changeType']     = DOKU_CHANGE_TYPE_EDIT;
13172966355bSGerrit Uitslag    $svdta['sizechange']     = null;
1318b24d9195SAndreas Gohr
1319b24d9195SAndreas Gohr    // select changelog line type
1320b24d9195SAndreas Gohr    if($REV) {
1321b24d9195SAndreas Gohr        $svdta['changeType']  = DOKU_CHANGE_TYPE_REVERT;
1322b24d9195SAndreas Gohr        $svdta['changeInfo'] = $REV;
1323b24d9195SAndreas Gohr    } else if(!file_exists($svdta['file'])) {
1324b24d9195SAndreas Gohr        $svdta['changeType'] = DOKU_CHANGE_TYPE_CREATE;
1325b24d9195SAndreas Gohr    } else if(trim($text) == '') {
1326b24d9195SAndreas Gohr        // empty or whitespace only content deletes
1327b24d9195SAndreas Gohr        $svdta['changeType'] = DOKU_CHANGE_TYPE_DELETE;
1328b24d9195SAndreas Gohr        // autoset summary on deletion
1329655ddc1dSGerrit Uitslag        if(blank($svdta['summary'])) {
1330655ddc1dSGerrit Uitslag            $svdta['summary'] = $lang['deleted'];
1331655ddc1dSGerrit Uitslag        }
1332b24d9195SAndreas Gohr    } else if($minor && $conf['useacl'] && $INPUT->server->str('REMOTE_USER')) {
1333b24d9195SAndreas Gohr        //minor edits only for logged in users
1334b24d9195SAndreas Gohr        $svdta['changeType'] = DOKU_CHANGE_TYPE_MINOR_EDIT;
1335f3f0262cSandi    }
1336f3f0262cSandi
1337b24d9195SAndreas Gohr    $event = new Doku_Event('COMMON_WIKIPAGE_SAVE', $svdta);
1338b24d9195SAndreas Gohr    if(!$event->advise_before()) return;
1339f3f0262cSandi
1340b24d9195SAndreas Gohr    // if the content has not been changed, no save happens (plugins may override this)
1341b24d9195SAndreas Gohr    if(!$svdta['contentChanged']) return;
1342b24d9195SAndreas Gohr
1343b24d9195SAndreas Gohr    detectExternalEdit($id);
1344f3f0262cSandi
13454b5aebc1SGerrit Uitslag    if(
13464b5aebc1SGerrit Uitslag        $svdta['changeType'] == DOKU_CHANGE_TYPE_CREATE ||
13474b5aebc1SGerrit Uitslag        ($svdta['changeType'] == DOKU_CHANGE_TYPE_REVERT && !file_exists($svdta['file']))
13484b5aebc1SGerrit Uitslag    ) {
1349ac3ed4afSGerrit Uitslag        $filesize_old = 0;
1350ac3ed4afSGerrit Uitslag    } else {
13512966355bSGerrit Uitslag        $filesize_old = filesize($svdta['file']);
1352ac3ed4afSGerrit Uitslag    }
1353b24d9195SAndreas Gohr    if($svdta['changeType'] == DOKU_CHANGE_TYPE_DELETE) {
135430725328SGabriel Birke        // Send "update" event with empty data, so plugins can react to page deletion
1355b24d9195SAndreas Gohr        $data = array(array($svdta['file'], '', false), getNS($id), noNS($id), false);
135630725328SGabriel Birke        trigger_event('IO_WIKIPAGE_WRITE', $data);
1357e45b34cdSBen Coburn        // pre-save deleted revision
1358b24d9195SAndreas Gohr        @touch($svdta['file']);
135946844156SBen Coburn        clearstatcache();
13602d69eb44SMichael Hamann        $svdta['newRevision'] = saveOldRevision($id);
1361e1f3d9e1SEsther Brunner        // remove empty file
1362b24d9195SAndreas Gohr        @unlink($svdta['file']);
1363ac3ed4afSGerrit Uitslag        $filesize_new = 0;
1364c5f92742SMichael Hamann        // don't remove old meta info as it should be saved, plugins can use IO_WIKIPAGE_WRITE for removing their metadata...
1365c5f92742SMichael Hamann        // purge non-persistant meta data
13663d1f9ec3SMichael Klier        p_purge_metadata($id);
136753d6ccfeSandi        // remove empty namespaces
1368cc7d0c94SBen Coburn        io_sweepNS($id, 'datadir');
1369cc7d0c94SBen Coburn        io_sweepNS($id, 'mediadir');
1370f3f0262cSandi    } else {
1371cc7d0c94SBen Coburn        // save file (namespace dir is created in io_writeWikiPage)
137233d979e7SMichael Große        io_writeWikiPage($svdta['file'], $svdta['newContent'], $id);
137346844156SBen Coburn        // pre-save the revision, to keep the attic in sync
1374b24d9195SAndreas Gohr        $svdta['newRevision'] = saveOldRevision($id);
13752966355bSGerrit Uitslag        $filesize_new = filesize($svdta['file']);
1376f3f0262cSandi    }
13772966355bSGerrit Uitslag    $svdta['sizechange'] = $filesize_new - $filesize_old;
1378f3f0262cSandi
1379b24d9195SAndreas Gohr    $event->advise_after();
138071726d78SBen Coburn
13812966355bSGerrit Uitslag    addLogEntry($svdta['newRevision'], $svdta['id'], $svdta['changeType'], $svdta['summary'], $svdta['changeInfo'], null, $svdta['sizechange']);
1382ac3ed4afSGerrit Uitslag
138326a0801fSAndreas Gohr    // send notify mails
1384b24d9195SAndreas Gohr    notify($svdta['id'], 'admin', $svdta['oldRevision'], $svdta['summary'], $minor);
1385b24d9195SAndreas Gohr    notify($svdta['id'], 'subscribers', $svdta['oldRevision'], $svdta['summary'], $minor);
1386f3f0262cSandi
1387ce6b63d9Schris    // update the purgefile (timestamp of the last time anything within the wiki was changed)
138898407a7aSandi    io_saveFile($conf['cachedir'].'/purgefile', time());
13892eccbdaaSGina Haeussge
13902eccbdaaSGina Haeussge    // if useheading is enabled, purge the cache of all linking pages
1391fe9ec250SChris Smith    if(useHeading('content')) {
139207ff0babSMichael Hamann        $pages = ft_backlinks($id, true);
13932eccbdaaSGina Haeussge        foreach($pages as $page) {
13942eccbdaaSGina Haeussge            $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
13952eccbdaaSGina Haeussge            $cache->removeCache();
13962eccbdaaSGina Haeussge        }
13972eccbdaaSGina Haeussge    }
1398f3f0262cSandi}
1399f3f0262cSandi
1400f3f0262cSandi/**
1401f3f0262cSandi * moves the current version to the attic and returns its
1402f3f0262cSandi * revision date
140315fae107Sandi *
140415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1405140cfbcdSGerrit Uitslag *
1406140cfbcdSGerrit Uitslag * @param string $id page id
1407140cfbcdSGerrit Uitslag * @return int|string revision timestamp
1408f3f0262cSandi */
1409f3f0262cSandifunction saveOldRevision($id) {
1410f3f0262cSandi    $oldf = wikiFN($id);
141179e79377SAndreas Gohr    if(!file_exists($oldf)) return '';
1412f3f0262cSandi    $date = filemtime($oldf);
1413f3f0262cSandi    $newf = wikiFN($id, $date);
1414cc7d0c94SBen Coburn    io_writeWikiPage($newf, rawWiki($id), $id, $date);
1415f3f0262cSandi    return $date;
1416f3f0262cSandi}
1417f3f0262cSandi
1418f3f0262cSandi/**
1419fde10de4SAdrian Lang * Sends a notify mail on page change or registration
142026a0801fSAndreas Gohr *
142126a0801fSAndreas Gohr * @param string     $id       The changed page
1422fde10de4SAdrian Lang * @param string     $who      Who to notify (admin|subscribers|register)
14233272d797SAndreas Gohr * @param int|string $rev Old page revision
142426a0801fSAndreas Gohr * @param string     $summary  What changed
142590033e9dSAndreas Gohr * @param boolean    $minor    Is this a minor edit?
142642ea7f44SGerrit Uitslag * @param string[]   $replace  Additional string substitutions, @KEY@ to be replaced by value
14273272d797SAndreas Gohr * @return bool
1428140cfbcdSGerrit Uitslag *
142915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1430f3f0262cSandi */
143102a498e7Schrisfunction notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array()) {
1432f3f0262cSandi    global $conf;
1433585bf44eSChristopher Smith    /* @var Input $INPUT */
1434585bf44eSChristopher Smith    global $INPUT;
1435b158d625SSteven Danz
14366df843eeSAndreas Gohr    // decide if there is something to do, eg. whom to mail
143726a0801fSAndreas Gohr    if($who == 'admin') {
14383272d797SAndreas Gohr        if(empty($conf['notify'])) return false; //notify enabled?
14392ed38036SAndreas Gohr        $tpl = 'mailtext';
144026a0801fSAndreas Gohr        $to  = $conf['notify'];
144126a0801fSAndreas Gohr    } elseif($who == 'subscribers') {
144284c1127cSAndreas Gohr        if(!actionOK('subscribe')) return false; //subscribers enabled?
1443585bf44eSChristopher Smith        if($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
14440bb37868SGerrit Uitslag        $data = array('id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace);
14453272d797SAndreas Gohr        trigger_event(
14463272d797SAndreas Gohr            'COMMON_NOTIFY_ADDRESSLIST', $data,
1447835242b0SAndreas Gohr            array(new Subscription(), 'notifyaddresses')
14483272d797SAndreas Gohr        );
14492ed38036SAndreas Gohr        $to = $data['addresslist'];
14502ed38036SAndreas Gohr        if(empty($to)) return false;
14512ed38036SAndreas Gohr        $tpl = 'subscr_single';
145226a0801fSAndreas Gohr    } else {
14533272d797SAndreas Gohr        return false; //just to be safe
145426a0801fSAndreas Gohr    }
145526a0801fSAndreas Gohr
14566df843eeSAndreas Gohr    // prepare content
14572ed38036SAndreas Gohr    $subscription = new Subscription();
14582ed38036SAndreas Gohr    return $subscription->send_diff($to, $tpl, $id, $rev, $summary);
1459f3f0262cSandi}
14602ed38036SAndreas Gohr
146115fae107Sandi/**
146271f7bde7SAndreas Gohr * extracts the query from a search engine referrer
146315fae107Sandi *
146415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
146571f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1466140cfbcdSGerrit Uitslag *
1467140cfbcdSGerrit Uitslag * @return array|string
1468f3f0262cSandi */
1469f3f0262cSandifunction getGoogleQuery() {
1470585bf44eSChristopher Smith    /* @var Input $INPUT */
1471585bf44eSChristopher Smith    global $INPUT;
1472585bf44eSChristopher Smith
1473585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_REFERER')) {
1474c66972f2SAdrian Lang        return '';
1475c66972f2SAdrian Lang    }
1476585bf44eSChristopher Smith    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1477f3f0262cSandi
1478079b3ac1SAndreas Gohr    // only handle common SEs
1479079b3ac1SAndreas Gohr    if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/',$url['host'])) return '';
1480e4d8a516SKazutaka Miyasaka
1481079b3ac1SAndreas Gohr    $query = array();
1482e4d8a516SKazutaka Miyasaka    // temporary workaround against PHP bug #49733
1483e4d8a516SKazutaka Miyasaka    // see http://bugs.php.net/bug.php?id=49733
1484e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) $enc = mb_internal_encoding();
1485f3f0262cSandi    parse_str($url['query'], $query);
1486e4d8a516SKazutaka Miyasaka    if(UTF8_MBSTRING) mb_internal_encoding($enc);
1487e4d8a516SKazutaka Miyasaka
1488c66972f2SAdrian Lang    $q = '';
1489079b3ac1SAndreas Gohr    if(isset($query['q'])){
1490079b3ac1SAndreas Gohr        $q = $query['q'];
1491079b3ac1SAndreas Gohr    }elseif(isset($query['p'])){
1492079b3ac1SAndreas Gohr        $q = $query['p'];
1493079b3ac1SAndreas Gohr    }elseif(isset($query['query'])){
1494079b3ac1SAndreas Gohr        $q = $query['query'];
1495079b3ac1SAndreas Gohr    }
1496079b3ac1SAndreas Gohr    $q = trim($q);
1497f3f0262cSandi
1498079b3ac1SAndreas Gohr    if(!$q) return '';
14996531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1500f93b3b50SAndreas Gohr    return $q;
1501f3f0262cSandi}
1502f3f0262cSandi
1503f3f0262cSandi/**
1504f3f0262cSandi * Return the human readable size of a file
1505f3f0262cSandi *
1506f3f0262cSandi * @param int $size A file size
1507f3f0262cSandi * @param int $dec A number of decimal places
150874160ca1SGerrit Uitslag * @return string human readable size
1509140cfbcdSGerrit Uitslag *
1510f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1511f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1512f3f0262cSandi * @version     1.0.0
1513f3f0262cSandi */
1514f31d5b73Sandifunction filesize_h($size, $dec = 1) {
1515f3f0262cSandi    $sizes = array('B', 'KB', 'MB', 'GB');
1516f3f0262cSandi    $count = count($sizes);
1517f3f0262cSandi    $i     = 0;
1518f3f0262cSandi
1519f3f0262cSandi    while($size >= 1024 && ($i < $count - 1)) {
1520f3f0262cSandi        $size /= 1024;
1521f3f0262cSandi        $i++;
1522f3f0262cSandi    }
1523f3f0262cSandi
1524ef08383eSAndreas Gohr    return round($size, $dec)."\xC2\xA0".$sizes[$i]; //non-breaking space
1525f3f0262cSandi}
1526f3f0262cSandi
152715fae107Sandi/**
1528c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1529c57e365eSAndreas Gohr *
1530c57e365eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1531140cfbcdSGerrit Uitslag *
1532140cfbcdSGerrit Uitslag * @param int $dt timestamp
1533140cfbcdSGerrit Uitslag * @return string
1534c57e365eSAndreas Gohr */
1535c57e365eSAndreas Gohrfunction datetime_h($dt) {
1536c57e365eSAndreas Gohr    global $lang;
1537c57e365eSAndreas Gohr
1538c57e365eSAndreas Gohr    $ago = time() - $dt;
1539c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1540c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1541c57e365eSAndreas Gohr    }
1542c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 2) {
1543c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1544c57e365eSAndreas Gohr    }
1545c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 7 * 2) {
1546c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1547c57e365eSAndreas Gohr    }
1548c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 2) {
1549c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1550c57e365eSAndreas Gohr    }
1551c57e365eSAndreas Gohr    if($ago > 60 * 60 * 2) {
1552c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago / (60 * 60)));
1553c57e365eSAndreas Gohr    }
1554c57e365eSAndreas Gohr    if($ago > 60 * 2) {
1555c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago / (60)));
1556c57e365eSAndreas Gohr    }
1557c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1558c57e365eSAndreas Gohr}
1559c57e365eSAndreas Gohr
1560c57e365eSAndreas Gohr/**
1561f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1562f2263577SAndreas Gohr *
1563f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1564f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1565f2263577SAndreas Gohr *
1566f2263577SAndreas Gohr * @see datetime_h
1567f2263577SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1568140cfbcdSGerrit Uitslag *
1569140cfbcdSGerrit Uitslag * @param int|null $dt      timestamp when given, null will take current timestamp
1570140cfbcdSGerrit Uitslag * @param string   $format  empty default to $conf['dformat'], or provide format as recognized by strftime()
1571140cfbcdSGerrit Uitslag * @return string
1572f2263577SAndreas Gohr */
1573f2263577SAndreas Gohrfunction dformat($dt = null, $format = '') {
1574f2263577SAndreas Gohr    global $conf;
1575f2263577SAndreas Gohr
1576f2263577SAndreas Gohr    if(is_null($dt)) $dt = time();
1577f2263577SAndreas Gohr    $dt = (int) $dt;
1578f2263577SAndreas Gohr    if(!$format) $format = $conf['dformat'];
1579f2263577SAndreas Gohr
1580f2263577SAndreas Gohr    $format = str_replace('%f', datetime_h($dt), $format);
1581f2263577SAndreas Gohr    return strftime($format, $dt);
1582f2263577SAndreas Gohr}
1583f2263577SAndreas Gohr
1584f2263577SAndreas Gohr/**
1585c4f79b71SMichael Hamann * Formats a timestamp as ISO 8601 date
1586c4f79b71SMichael Hamann *
1587c4f79b71SMichael Hamann * @author <ungu at terong dot com>
158859752844SAnders Sandblad * @link http://php.net/manual/en/function.date.php#54072
1589140cfbcdSGerrit Uitslag *
15907e8500eeSGerrit Uitslag * @param int $int_date current date in UNIX timestamp
15913272d797SAndreas Gohr * @return string
1592c4f79b71SMichael Hamann */
1593c4f79b71SMichael Hamannfunction date_iso8601($int_date) {
1594c4f79b71SMichael Hamann    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1595c4f79b71SMichael Hamann    $pre_timezone = date('O', $int_date);
1596c4f79b71SMichael Hamann    $time_zone    = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1597c4f79b71SMichael Hamann    $date_mod .= $time_zone;
1598c4f79b71SMichael Hamann    return $date_mod;
1599c4f79b71SMichael Hamann}
1600c4f79b71SMichael Hamann
1601c4f79b71SMichael Hamann/**
160200a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
160300a7b5adSEsther Brunner *
160400a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
160500a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
1606140cfbcdSGerrit Uitslag *
1607140cfbcdSGerrit Uitslag * @param string $email email address
1608140cfbcdSGerrit Uitslag * @return string
160900a7b5adSEsther Brunner */
161000a7b5adSEsther Brunnerfunction obfuscate($email) {
161100a7b5adSEsther Brunner    global $conf;
161200a7b5adSEsther Brunner
161300a7b5adSEsther Brunner    switch($conf['mailguard']) {
161400a7b5adSEsther Brunner        case 'visible' :
161500a7b5adSEsther Brunner            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
161600a7b5adSEsther Brunner            return strtr($email, $obfuscate);
161700a7b5adSEsther Brunner
161800a7b5adSEsther Brunner        case 'hex' :
161900a7b5adSEsther Brunner            $encode = '';
162049eb6e38SAndreas Gohr            $len    = strlen($email);
162149eb6e38SAndreas Gohr            for($x = 0; $x < $len; $x++) {
162249eb6e38SAndreas Gohr                $encode .= '&#x'.bin2hex($email{$x}).';';
162349eb6e38SAndreas Gohr            }
162400a7b5adSEsther Brunner            return $encode;
162500a7b5adSEsther Brunner
162600a7b5adSEsther Brunner        case 'none' :
162700a7b5adSEsther Brunner        default :
162800a7b5adSEsther Brunner            return $email;
162900a7b5adSEsther Brunner    }
163000a7b5adSEsther Brunner}
163100a7b5adSEsther Brunner
163200a7b5adSEsther Brunner/**
163389541d4bSAndreas Gohr * Removes quoting backslashes
163489541d4bSAndreas Gohr *
163589541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1636140cfbcdSGerrit Uitslag *
1637140cfbcdSGerrit Uitslag * @param string $string
1638140cfbcdSGerrit Uitslag * @param string $char backslashed character
1639140cfbcdSGerrit Uitslag * @return string
164089541d4bSAndreas Gohr */
164189541d4bSAndreas Gohrfunction unslash($string, $char = "'") {
164289541d4bSAndreas Gohr    return str_replace('\\'.$char, $char, $string);
164389541d4bSAndreas Gohr}
164489541d4bSAndreas Gohr
164573038c47SAndreas Gohr/**
164673038c47SAndreas Gohr * Convert php.ini shorthands to byte
164773038c47SAndreas Gohr *
164873038c47SAndreas Gohr * @author <gilthans dot NO dot SPAM at gmail dot com>
164959752844SAnders Sandblad * @link   http://php.net/manual/en/ini.core.php#79564
1650140cfbcdSGerrit Uitslag *
1651140cfbcdSGerrit Uitslag * @param string $v shorthands
1652140cfbcdSGerrit Uitslag * @return int|string
165373038c47SAndreas Gohr */
165473038c47SAndreas Gohrfunction php_to_byte($v) {
165573038c47SAndreas Gohr    $l   = substr($v, -1);
165673038c47SAndreas Gohr    $ret = substr($v, 0, -1);
165773038c47SAndreas Gohr    switch(strtoupper($l)) {
165874160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
165973038c47SAndreas Gohr        case 'P':
166073038c47SAndreas Gohr            $ret *= 1024;
166174160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
166273038c47SAndreas Gohr        case 'T':
166373038c47SAndreas Gohr            $ret *= 1024;
166474160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
166573038c47SAndreas Gohr        case 'G':
166673038c47SAndreas Gohr            $ret *= 1024;
166774160ca1SGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
166873038c47SAndreas Gohr        case 'M':
166973038c47SAndreas Gohr            $ret *= 1024;
1670f168548cSGerrit Uitslag        /** @noinspection PhpMissingBreakStatementInspection */
167173038c47SAndreas Gohr        case 'K':
167273038c47SAndreas Gohr            $ret *= 1024;
167373038c47SAndreas Gohr            break;
167449cbd23eSOtto Vainio        default;
167549cbd23eSOtto Vainio            $ret *= 10;
167649cbd23eSOtto Vainio            break;
167773038c47SAndreas Gohr    }
167873038c47SAndreas Gohr    return $ret;
167973038c47SAndreas Gohr}
168073038c47SAndreas Gohr
1681546d3a99SAndreas Gohr/**
1682546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1683140cfbcdSGerrit Uitslag *
1684140cfbcdSGerrit Uitslag * @param string $string
1685140cfbcdSGerrit Uitslag * @return string
1686546d3a99SAndreas Gohr */
1687546d3a99SAndreas Gohrfunction preg_quote_cb($string) {
1688546d3a99SAndreas Gohr    return preg_quote($string, '/');
1689546d3a99SAndreas Gohr}
169073038c47SAndreas Gohr
1691bd2f6c2fSAndreas Gohr/**
1692bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1693bd2f6c2fSAndreas Gohr *
1694c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1695bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1696bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1697bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1698bd2f6c2fSAndreas Gohr *
1699bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1700bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1701bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1702bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1703bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
17043272d797SAndreas Gohr * @return string
1705bd2f6c2fSAndreas Gohr */
1706a5d27328SAndreas Gohrfunction shorten($keep, $short, $max, $min = 9, $char = '…') {
1707bd2f6c2fSAndreas Gohr    $max = $max - utf8_strlen($keep);
1708bd2f6c2fSAndreas Gohr    if($max < $min) return $keep;
1709bd2f6c2fSAndreas Gohr    $len = utf8_strlen($short);
1710bd2f6c2fSAndreas Gohr    if($len <= $max) return $keep.$short;
1711bd2f6c2fSAndreas Gohr    $half = floor($max / 2);
1712bd2f6c2fSAndreas Gohr    return $keep.utf8_substr($short, 0, $half - 1).$char.utf8_substr($short, $len - $half);
1713bd2f6c2fSAndreas Gohr}
1714bd2f6c2fSAndreas Gohr
1715dc58b6f4SAndy Webber/**
1716dc58b6f4SAndy Webber * Return the users real name or e-mail address for use
1717dc58b6f4SAndy Webber * in page footer and recent changes pages
1718dc58b6f4SAndy Webber *
1719b4b6c9a1SGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
172015f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1721c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
172215f3bc49SGerrit Uitslag *
1723dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1724dc58b6f4SAndy Webber */
172515f3bc49SGerrit Uitslagfunction editorinfo($username, $textonly = false) {
1726cd4635eeSGerrit Uitslag    return userlink($username, $textonly);
1727dc58b6f4SAndy Webber}
1728dc58b6f4SAndy Webber
172960a396c8SGerrit Uitslag/**
173060a396c8SGerrit Uitslag * Returns users realname w/o link
173160a396c8SGerrit Uitslag *
1732f168548cSGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
173315f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1734c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
173560a396c8SGerrit Uitslag *
173660a396c8SGerrit Uitslag * @triggers COMMON_USER_LINK
173760a396c8SGerrit Uitslag */
1738cd4635eeSGerrit Uitslagfunction userlink($username = null, $textonly = false) {
173960a396c8SGerrit Uitslag    global $conf, $INFO;
174060a396c8SGerrit Uitslag    /** @var DokuWiki_Auth_Plugin $auth */
174160a396c8SGerrit Uitslag    global $auth;
174230f6ec4bSGerrit Uitslag    /** @var Input $INPUT */
174330f6ec4bSGerrit Uitslag    global $INPUT;
174460a396c8SGerrit Uitslag
174560a396c8SGerrit Uitslag    // prepare initial event data
174660a396c8SGerrit Uitslag    $data = array(
174760a396c8SGerrit Uitslag        'username' => $username, // the unique user name
174860a396c8SGerrit Uitslag        'name' => '',
174960a396c8SGerrit Uitslag        'link' => array( //setting 'link' to false disables linking
175060a396c8SGerrit Uitslag                         'target' => '',
175160a396c8SGerrit Uitslag                         'pre' => '',
175260a396c8SGerrit Uitslag                         'suf' => '',
175360a396c8SGerrit Uitslag                         'style' => '',
175460a396c8SGerrit Uitslag                         'more' => '',
175560a396c8SGerrit Uitslag                         'url' => '',
175660a396c8SGerrit Uitslag                         'title' => '',
175760a396c8SGerrit Uitslag                         'class' => ''
175860a396c8SGerrit Uitslag        ),
17594d5fc927SGerrit Uitslag        'userlink' => '', // formatted user name as will be returned
176015f3bc49SGerrit Uitslag        'textonly' => $textonly
176160a396c8SGerrit Uitslag    );
176262c8004eSGerrit Uitslag    if($username === null) {
176330f6ec4bSGerrit Uitslag        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
176415f3bc49SGerrit Uitslag        if($textonly){
176515f3bc49SGerrit Uitslag            $data['name'] = $INFO['userinfo']['name']. ' (' . $INPUT->server->str('REMOTE_USER') . ')';
176615f3bc49SGerrit Uitslag        }else {
176730f6ec4bSGerrit Uitslag            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> (<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
176860a396c8SGerrit Uitslag        }
176915f3bc49SGerrit Uitslag    }
177060a396c8SGerrit Uitslag
177160a396c8SGerrit Uitslag    $evt = new Doku_Event('COMMON_USER_LINK', $data);
177260a396c8SGerrit Uitslag    if($evt->advise_before(true)) {
177360a396c8SGerrit Uitslag        if(empty($data['name'])) {
177460a396c8SGerrit Uitslag            if($auth) $info = $auth->getUserData($username);
177565833968SGerrit Uitslag            if($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1776dc58b6f4SAndy Webber                switch($conf['showuseras']) {
1777dc58b6f4SAndy Webber                    case 'username':
17787f081821SGerrit Uitslag                    case 'username_link':
177915f3bc49SGerrit Uitslag                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
178060a396c8SGerrit Uitslag                        break;
1781dc58b6f4SAndy Webber                    case 'email':
1782dc58b6f4SAndy Webber                    case 'email_link':
178360a396c8SGerrit Uitslag                        $data['name'] = obfuscate($info['mail']);
178460a396c8SGerrit Uitslag                        break;
1785dc58b6f4SAndy Webber                }
178665833968SGerrit Uitslag            } else {
178765833968SGerrit Uitslag                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
178860a396c8SGerrit Uitslag            }
178960a396c8SGerrit Uitslag        }
17907f081821SGerrit Uitslag
17917f081821SGerrit Uitslag        /** @var Doku_Renderer_xhtml $xhtml_renderer */
17927f081821SGerrit Uitslag        static $xhtml_renderer = null;
17937f081821SGerrit Uitslag
179415f3bc49SGerrit Uitslag        if(!$data['textonly'] && empty($data['link']['url'])) {
17957f081821SGerrit Uitslag
17967f081821SGerrit Uitslag            if(in_array($conf['showuseras'], array('email_link', 'username_link'))) {
179760a396c8SGerrit Uitslag                if(!isset($info)) {
179860a396c8SGerrit Uitslag                    if($auth) $info = $auth->getUserData($username);
179960a396c8SGerrit Uitslag                }
180060a396c8SGerrit Uitslag                if(isset($info) && $info) {
18017f081821SGerrit Uitslag                    if($conf['showuseras'] == 'email_link') {
180260a396c8SGerrit Uitslag                        $data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
1803dc58b6f4SAndy Webber                    } else {
18047f081821SGerrit Uitslag                        if(is_null($xhtml_renderer)) {
18057f081821SGerrit Uitslag                            $xhtml_renderer = p_get_renderer('xhtml');
18067f081821SGerrit Uitslag                        }
18077f081821SGerrit Uitslag                        if(empty($xhtml_renderer->interwiki)) {
18087f081821SGerrit Uitslag                            $xhtml_renderer->interwiki = getInterwiki();
18097f081821SGerrit Uitslag                        }
18107f081821SGerrit Uitslag                        $shortcut = 'user';
1811533772e1SGerrit Uitslag                        $exists = null;
18126496c33fSGerrit Uitslag                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
18132a2a43c4SGerrit Uitslag                        $data['link']['class'] .= ' interwiki iw_user';
18146496c33fSGerrit Uitslag                        if($exists !== null) {
18156496c33fSGerrit Uitslag                            if($exists) {
18166496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink1';
18176496c33fSGerrit Uitslag                            } else {
18186496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink2';
18196496c33fSGerrit Uitslag                                $data['link']['rel'] = 'nofollow';
18206496c33fSGerrit Uitslag                            }
18216496c33fSGerrit Uitslag                        }
1822dc58b6f4SAndy Webber                    }
1823dc58b6f4SAndy Webber                } else {
182415f3bc49SGerrit Uitslag                    $data['textonly'] = true;
1825dc58b6f4SAndy Webber                }
182660a396c8SGerrit Uitslag
182760a396c8SGerrit Uitslag            } else {
182815f3bc49SGerrit Uitslag                $data['textonly'] = true;
182960a396c8SGerrit Uitslag            }
183060a396c8SGerrit Uitslag        }
183160a396c8SGerrit Uitslag
183215f3bc49SGerrit Uitslag        if($data['textonly']) {
18334d5fc927SGerrit Uitslag            $data['userlink'] = $data['name'];
183460a396c8SGerrit Uitslag        } else {
183560a396c8SGerrit Uitslag            $data['link']['name'] = $data['name'];
183660a396c8SGerrit Uitslag            if(is_null($xhtml_renderer)) {
183760a396c8SGerrit Uitslag                $xhtml_renderer = p_get_renderer('xhtml');
183860a396c8SGerrit Uitslag            }
18394d5fc927SGerrit Uitslag            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
184060a396c8SGerrit Uitslag        }
184160a396c8SGerrit Uitslag    }
184260a396c8SGerrit Uitslag    $evt->advise_after();
184360a396c8SGerrit Uitslag    unset($evt);
184460a396c8SGerrit Uitslag
18454d5fc927SGerrit Uitslag    return $data['userlink'];
1846066fee30SAndreas Gohr}
1847066fee30SAndreas Gohr
1848066fee30SAndreas Gohr/**
1849066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1850066fee30SAndreas Gohr * When no image exists, returns an empty string
1851066fee30SAndreas Gohr *
1852066fee30SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1853140cfbcdSGerrit Uitslag *
1854066fee30SAndreas Gohr * @param  string $type - type of image 'badge' or 'button'
18553272d797SAndreas Gohr * @return string
1856066fee30SAndreas Gohr */
1857066fee30SAndreas Gohrfunction license_img($type) {
1858066fee30SAndreas Gohr    global $license;
1859066fee30SAndreas Gohr    global $conf;
1860066fee30SAndreas Gohr    if(!$conf['license']) return '';
1861066fee30SAndreas Gohr    if(!is_array($license[$conf['license']])) return '';
1862066fee30SAndreas Gohr    $try   = array();
1863066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1864066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1865066fee30SAndreas Gohr    if(substr($conf['license'], 0, 3) == 'cc-') {
1866066fee30SAndreas Gohr        $try[] = 'lib/images/license/'.$type.'/cc.png';
1867066fee30SAndreas Gohr    }
1868066fee30SAndreas Gohr    foreach($try as $src) {
186979e79377SAndreas Gohr        if(file_exists(DOKU_INC.$src)) return $src;
1870066fee30SAndreas Gohr    }
1871066fee30SAndreas Gohr    return '';
1872dc58b6f4SAndy Webber}
1873dc58b6f4SAndy Webber
187413c08e2fSMichael Klier/**
187513c08e2fSMichael Klier * Checks if the given amount of memory is available
187613c08e2fSMichael Klier *
187713c08e2fSMichael Klier * If the memory_get_usage() function is not available the
187813c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
187913c08e2fSMichael Klier *
188013c08e2fSMichael Klier * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
188113c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
18823272d797SAndreas Gohr *
18833272d797SAndreas Gohr * @param int  $mem    Size of memory you want to allocate in bytes
1884140cfbcdSGerrit Uitslag * @param int  $bytes  already allocated memory (see above)
18853272d797SAndreas Gohr * @return bool
188613c08e2fSMichael Klier */
188713c08e2fSMichael Klierfunction is_mem_available($mem, $bytes = 1048576) {
188813c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
188913c08e2fSMichael Klier    if(empty($limit)) return true; // no limit set!
1890*985d6187SElenchus    if($limit == -1) return true; // unlimited
189113c08e2fSMichael Klier
189213c08e2fSMichael Klier    // parse limit to bytes
189313c08e2fSMichael Klier    $limit = php_to_byte($limit);
189413c08e2fSMichael Klier
189513c08e2fSMichael Klier    // get used memory if possible
189613c08e2fSMichael Klier    if(function_exists('memory_get_usage')) {
189713c08e2fSMichael Klier        $used = memory_get_usage();
189849eb6e38SAndreas Gohr    } else {
189949eb6e38SAndreas Gohr        $used = $bytes;
190013c08e2fSMichael Klier    }
190113c08e2fSMichael Klier
190213c08e2fSMichael Klier    if($used + $mem > $limit) {
190313c08e2fSMichael Klier        return false;
190413c08e2fSMichael Klier    }
190513c08e2fSMichael Klier
190613c08e2fSMichael Klier    return true;
190713c08e2fSMichael Klier}
190813c08e2fSMichael Klier
1909af2408d5SAndreas Gohr/**
1910af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1911af2408d5SAndreas Gohr *
1912af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1913af2408d5SAndreas Gohr *
1914af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1915af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1916140cfbcdSGerrit Uitslag *
1917140cfbcdSGerrit Uitslag * @param string $url url being directed to
1918af2408d5SAndreas Gohr */
1919af2408d5SAndreas Gohrfunction send_redirect($url) {
192098ca30d2SAndreas Gohr    $url = stripctl($url); // defend against HTTP Response Splitting
192198ca30d2SAndreas Gohr
1922585bf44eSChristopher Smith    /* @var Input $INPUT */
1923585bf44eSChristopher Smith    global $INPUT;
1924585bf44eSChristopher Smith
19250181f021SAndreas Gohr    //are there any undisplayed messages? keep them in session for display
19260181f021SAndreas Gohr    global $MSG;
19270181f021SAndreas Gohr    if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
19280181f021SAndreas Gohr        //reopen session, store data and close session again
19290181f021SAndreas Gohr        @session_start();
19300181f021SAndreas Gohr        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
19310181f021SAndreas Gohr    }
19320181f021SAndreas Gohr
1933d4869846SAndreas Gohr    // always close the session
1934d4869846SAndreas Gohr    session_write_close();
1935d4869846SAndreas Gohr
1936af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
1937585bf44eSChristopher Smith    if($INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1938585bf44eSChristopher Smith        (strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) &&
1939585bf44eSChristopher Smith        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
19403272d797SAndreas Gohr        $matches[1] < 6
19413272d797SAndreas Gohr    ) {
1942af2408d5SAndreas Gohr        header('Refresh: 0;url='.$url);
1943af2408d5SAndreas Gohr    } else {
1944af2408d5SAndreas Gohr        header('Location: '.$url);
1945af2408d5SAndreas Gohr    }
194681781cb6SAndreas Gohr
1947572dc222SLarsDW223    // no exits during unit tests
194827c0c399SAndreas Gohr    if(defined('DOKU_UNITTEST')) {
194927c0c399SAndreas Gohr        // pass info about the redirect back to the test suite
195027c0c399SAndreas Gohr        $testRequest = TestRequest::getRunning();
195127c0c399SAndreas Gohr        if($testRequest !== null) {
195227c0c399SAndreas Gohr            $testRequest->addData('send_redirect', $url);
195327c0c399SAndreas Gohr        }
1954572dc222SLarsDW223        return;
1955572dc222SLarsDW223    }
195627c0c399SAndreas Gohr
1957af2408d5SAndreas Gohr    exit;
1958af2408d5SAndreas Gohr}
1959af2408d5SAndreas Gohr
19605b75cd1fSAdrian Lang/**
19615b75cd1fSAdrian Lang * Validate a value using a set of valid values
19625b75cd1fSAdrian Lang *
19635b75cd1fSAdrian Lang * This function checks whether a specified value is set and in the array
19645b75cd1fSAdrian Lang * $valid_values. If not, the function returns a default value or, if no
19655b75cd1fSAdrian Lang * default is specified, throws an exception.
19665b75cd1fSAdrian Lang *
19675b75cd1fSAdrian Lang * @param string $param        The name of the parameter
19685b75cd1fSAdrian Lang * @param array  $valid_values A set of valid values; Optionally a default may
19695b75cd1fSAdrian Lang *                             be marked by the key “default”.
19705b75cd1fSAdrian Lang * @param array  $array        The array containing the value (typically $_POST
19715b75cd1fSAdrian Lang *                             or $_GET)
19725b75cd1fSAdrian Lang * @param string $exc          The text of the raised exception
19735b75cd1fSAdrian Lang *
19743272d797SAndreas Gohr * @throws Exception
19753272d797SAndreas Gohr * @return mixed
19765b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
19775b75cd1fSAdrian Lang */
19785b75cd1fSAdrian Langfunction valid_input_set($param, $valid_values, $array, $exc = '') {
19795b75cd1fSAdrian Lang    if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
19805b75cd1fSAdrian Lang        return $array[$param];
19815b75cd1fSAdrian Lang    } elseif(isset($valid_values['default'])) {
19825b75cd1fSAdrian Lang        return $valid_values['default'];
19835b75cd1fSAdrian Lang    } else {
19845b75cd1fSAdrian Lang        throw new Exception($exc);
19855b75cd1fSAdrian Lang    }
19865b75cd1fSAdrian Lang}
19875b75cd1fSAdrian Lang
198863703ba5SAndreas Gohr/**
198963703ba5SAndreas Gohr * Read a preference from the DokuWiki cookie
1990646a531aSChristopher Smith * (remembering both keys & values are urlencoded)
1991140cfbcdSGerrit Uitslag *
1992140cfbcdSGerrit Uitslag * @param string $pref     preference key
1993b4b6c9a1SGerrit Uitslag * @param mixed  $default  value returned when preference not found
1994140cfbcdSGerrit Uitslag * @return string preference value
199563703ba5SAndreas Gohr */
1996554a8c9fSAdrian Langfunction get_doku_pref($pref, $default) {
1997646a531aSChristopher Smith    $enc_pref = urlencode($pref);
199806c9ee33SMarius van Witzenburg    if(isset($_COOKIE['DOKU_PREFS']) && strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
1999554a8c9fSAdrian Lang        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
200063703ba5SAndreas Gohr        $cnt   = count($parts);
200163703ba5SAndreas Gohr        for($i = 0; $i < $cnt; $i += 2) {
2002646a531aSChristopher Smith            if($parts[$i] == $enc_pref) {
2003646a531aSChristopher Smith                return urldecode($parts[$i + 1]);
2004554a8c9fSAdrian Lang            }
2005554a8c9fSAdrian Lang        }
2006554a8c9fSAdrian Lang    }
2007554a8c9fSAdrian Lang    return $default;
2008554a8c9fSAdrian Lang}
2009554a8c9fSAdrian Lang
20103c94d07bSAnika Henke/**
20113c94d07bSAnika Henke * Add a preference to the DokuWiki cookie
201236ec377eSChristopher Smith * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
20133a970889SAnika Henke * Remove it by setting $val to false
2014140cfbcdSGerrit Uitslag *
2015140cfbcdSGerrit Uitslag * @param string $pref  preference key
2016140cfbcdSGerrit Uitslag * @param string $val   preference value
20173c94d07bSAnika Henke */
20183c94d07bSAnika Henkefunction set_doku_pref($pref, $val) {
20193c94d07bSAnika Henke    global $conf;
20203c94d07bSAnika Henke    $orig = get_doku_pref($pref, false);
20213c94d07bSAnika Henke    $cookieVal = '';
20223c94d07bSAnika Henke
20233c94d07bSAnika Henke    if($orig && ($orig != $val)) {
20243c94d07bSAnika Henke        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
20253c94d07bSAnika Henke        $cnt   = count($parts);
202636ec377eSChristopher Smith        // urlencode $pref for the comparison
202736ec377eSChristopher Smith        $enc_pref = rawurlencode($pref);
20283c94d07bSAnika Henke        for($i = 0; $i < $cnt; $i += 2) {
202936ec377eSChristopher Smith            if($parts[$i] == $enc_pref) {
20303a970889SAnika Henke                if ($val !== false) {
203136ec377eSChristopher Smith                    $parts[$i + 1] = rawurlencode($val);
20323a970889SAnika Henke                } else {
20333a970889SAnika Henke                    unset($parts[$i]);
20343a970889SAnika Henke                    unset($parts[$i + 1]);
20353a970889SAnika Henke                }
203650f261f7SMichael Hamann                break;
20373c94d07bSAnika Henke            }
20383c94d07bSAnika Henke        }
20393c94d07bSAnika Henke        $cookieVal = implode('#', $parts);
20403a970889SAnika Henke    } else if (!$orig && $val !== false) {
204136ec377eSChristopher Smith        $cookieVal = ($_COOKIE['DOKU_PREFS'] ? $_COOKIE['DOKU_PREFS'].'#' : '').rawurlencode($pref).'#'.rawurlencode($val);
20423c94d07bSAnika Henke    }
20433c94d07bSAnika Henke
20443c94d07bSAnika Henke    if (!empty($cookieVal)) {
204575e4dd8aSGerrit Uitslag        $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
204675e4dd8aSGerrit Uitslag        setcookie('DOKU_PREFS', $cookieVal, time()+365*24*3600, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
20473c94d07bSAnika Henke    }
20483c94d07bSAnika Henke}
20493c94d07bSAnika Henke
2050f8fb2d18SAndreas Gohr/**
2051f8fb2d18SAndreas Gohr * Strips source mapping declarations from given text #601
2052f8fb2d18SAndreas Gohr *
205342ea7f44SGerrit Uitslag * @param string &$text reference to the CSS or JavaScript code to clean
2054f8fb2d18SAndreas Gohr */
2055f8fb2d18SAndreas Gohrfunction stripsourcemaps(&$text){
2056f8fb2d18SAndreas Gohr    $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text);
2057f8fb2d18SAndreas Gohr}
2058f8fb2d18SAndreas Gohr
20593c27983bSAndreas Gohr/**
206071de5572SAndreas Gohr * Returns the contents of a given SVG file for embedding
20613c27983bSAndreas Gohr *
20623c27983bSAndreas Gohr * Inlining SVGs saves on HTTP requests and more importantly allows for styling them through
20633c27983bSAndreas Gohr * CSS. However it should used with small SVGs only. The $maxsize setting ensures only small
20643c27983bSAndreas Gohr * files are embedded.
20653c27983bSAndreas Gohr *
206671de5572SAndreas Gohr * This strips unneeded headers, comments and newline. The result is not a vaild standalone SVG!
206771de5572SAndreas Gohr *
20683c27983bSAndreas Gohr * @param string $file full path to the SVG file
20693c27983bSAndreas Gohr * @param int $maxsize maximum allowed size for the SVG to be embedded
207071de5572SAndreas Gohr * @return string|false the SVG content, false if the file couldn't be loaded
20713c27983bSAndreas Gohr */
20724cd2074fSAndreas Gohrfunction inlineSVG($file, $maxsize = 2048) {
20733c27983bSAndreas Gohr    $file = trim($file);
20743c27983bSAndreas Gohr    if($file === '') return false;
20753c27983bSAndreas Gohr    if(!file_exists($file)) return false;
20763c27983bSAndreas Gohr    if(filesize($file) > $maxsize) return false;
20773c27983bSAndreas Gohr    if(!is_readable($file)) return false;
20783c27983bSAndreas Gohr    $content = file_get_contents($file);
20790849fa88SAndreas Gohr    $content = preg_replace('/<!--.*?(-->)/s','', $content); // comments
20800849fa88SAndreas Gohr    $content = preg_replace('/<\?xml .*?\?>/i', '', $content); // xml header
20810849fa88SAndreas Gohr    $content = preg_replace('/<!DOCTYPE .*?>/i', '', $content); // doc type
20820849fa88SAndreas Gohr    $content = preg_replace('/>\s+</s', '><', $content); // newlines between tags
20833c27983bSAndreas Gohr    $content = trim($content);
20843c27983bSAndreas Gohr    if(substr($content, 0, 5) !== '<svg ') return false;
208571de5572SAndreas Gohr    return $content;
20863c27983bSAndreas Gohr}
20873c27983bSAndreas Gohr
2088e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
2089