xref: /dokuwiki/inc/common.php (revision 0a5f08e56a9411aa26cf692621af9f81de396b0f)
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
90db5771eSMichael Großeuse dokuwiki\Cache\CacheInstructions;
100db5771eSMichael Großeuse dokuwiki\Cache\CacheRenderer;
110c3a5702SAndreas Gohruse dokuwiki\ChangeLog\PageChangeLog;
12704a815fSMichael Großeuse dokuwiki\Subscriptions\PageSubscriptionSender;
1375d66495SMichael Großeuse dokuwiki\Subscriptions\SubscriberManager;
14e1d9dcc8SAndreas Gohruse dokuwiki\Extension\AuthPlugin;
15e1d9dcc8SAndreas Gohruse dokuwiki\Extension\Event;
160c3a5702SAndreas Gohr
17f3f0262cSandi/**
18d5197206Schris * Wrapper around htmlspecialchars()
19d5197206Schris *
20d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
21d5197206Schris * @see    htmlspecialchars()
22140cfbcdSGerrit Uitslag *
23140cfbcdSGerrit Uitslag * @param string $string the string being converted
24140cfbcdSGerrit Uitslag * @return string converted string
25d5197206Schris */
26d5197206Schrisfunction hsc($string) {
27d5197206Schris    return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
28d5197206Schris}
29d5197206Schris
30d5197206Schris/**
315b571377SAndreas Gohr * Checks if the given input is blank
325b571377SAndreas Gohr *
335b571377SAndreas Gohr * This is similar to empty() but will return false for "0".
345b571377SAndreas Gohr *
3567234204SAndreas Gohr * Please note: when you pass uninitialized variables, they will implicitly be created
3667234204SAndreas Gohr * with a NULL value without warning.
3767234204SAndreas Gohr *
3867234204SAndreas Gohr * To avoid this it's recommended to guard the call with isset like this:
3967234204SAndreas Gohr *
4067234204SAndreas Gohr * (isset($foo) && !blank($foo))
4167234204SAndreas Gohr * (!isset($foo) || blank($foo))
4267234204SAndreas Gohr *
435b571377SAndreas Gohr * @param $in
445b571377SAndreas Gohr * @param bool $trim Consider a string of whitespace to be blank
455b571377SAndreas Gohr * @return bool
465b571377SAndreas Gohr */
475b571377SAndreas Gohrfunction blank(&$in, $trim = false) {
485b571377SAndreas Gohr    if(is_null($in)) return true;
495b571377SAndreas Gohr    if(is_array($in)) return empty($in);
505b571377SAndreas Gohr    if($in === "\0") return true;
515b571377SAndreas Gohr    if($trim && trim($in) === '') return true;
525b571377SAndreas Gohr    if(strlen($in) > 0) return false;
535b571377SAndreas Gohr    return empty($in);
545b571377SAndreas Gohr}
555b571377SAndreas Gohr
565b571377SAndreas Gohr/**
57d5197206Schris * print a newline terminated string
58d5197206Schris *
59d5197206Schris * You can give an indention as optional parameter
60d5197206Schris *
61d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
62140cfbcdSGerrit Uitslag *
63140cfbcdSGerrit Uitslag * @param string $string  line of text
64140cfbcdSGerrit Uitslag * @param int    $indent  number of spaces indention
65d5197206Schris */
6625ec097bSChris Smithfunction ptln($string, $indent = 0) {
6725ec097bSChris Smith    echo str_repeat(' ', $indent)."$string\n";
6802b0b681SAndreas Gohr}
6902b0b681SAndreas Gohr
7002b0b681SAndreas Gohr/**
7102b0b681SAndreas Gohr * strips control characters (<32) from the given string
7202b0b681SAndreas Gohr *
7302b0b681SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
74140cfbcdSGerrit Uitslag *
7542ea7f44SGerrit Uitslag * @param string $string being stripped
76140cfbcdSGerrit Uitslag * @return string
7702b0b681SAndreas Gohr */
7802b0b681SAndreas Gohrfunction stripctl($string) {
7902b0b681SAndreas Gohr    return preg_replace('/[\x00-\x1F]+/s', '', $string);
80d5197206Schris}
81d5197206Schris
82d5197206Schris/**
83634d7150SAndreas Gohr * Return a secret token to be used for CSRF attack prevention
84634d7150SAndreas Gohr *
85634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
86634d7150SAndreas Gohr * @link    http://en.wikipedia.org/wiki/Cross-site_request_forgery
87634d7150SAndreas Gohr * @link    http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
8842ea7f44SGerrit Uitslag *
89634d7150SAndreas Gohr * @return  string
90634d7150SAndreas Gohr */
91634d7150SAndreas Gohrfunction getSecurityToken() {
92585bf44eSChristopher Smith    /** @var Input $INPUT */
93585bf44eSChristopher Smith    global $INPUT;
943680e2cdSAndreas Gohr
953680e2cdSAndreas Gohr    $user = $INPUT->server->str('REMOTE_USER');
963680e2cdSAndreas Gohr    $session = session_id();
973680e2cdSAndreas Gohr
983680e2cdSAndreas Gohr    // CSRF checks are only for logged in users - do not generate for anonymous
993680e2cdSAndreas Gohr    if(trim($user) == '' || trim($session) == '') return '';
100c3cc6e05SAndreas Gohr    return \dokuwiki\PassHash::hmac('md5', $session.$user, auth_cookiesalt());
101634d7150SAndreas Gohr}
102634d7150SAndreas Gohr
103634d7150SAndreas Gohr/**
104634d7150SAndreas Gohr * Check the secret CSRF token
105140cfbcdSGerrit Uitslag *
106140cfbcdSGerrit Uitslag * @param null|string $token security token or null to read it from request variable
107140cfbcdSGerrit Uitslag * @return bool success if the token matched
108634d7150SAndreas Gohr */
109634d7150SAndreas Gohrfunction checkSecurityToken($token = null) {
110585bf44eSChristopher Smith    /** @var Input $INPUT */
1117d01a0eaSTom N Harris    global $INPUT;
112585bf44eSChristopher Smith    if(!$INPUT->server->str('REMOTE_USER')) return true; // no logged in user, no need for a check
113df97eaacSAndreas Gohr
1147d01a0eaSTom N Harris    if(is_null($token)) $token = $INPUT->str('sectok');
115634d7150SAndreas Gohr    if(getSecurityToken() != $token) {
116634d7150SAndreas Gohr        msg('Security Token did not match. Possible CSRF attack.', -1);
117634d7150SAndreas Gohr        return false;
118634d7150SAndreas Gohr    }
119634d7150SAndreas Gohr    return true;
120634d7150SAndreas Gohr}
121634d7150SAndreas Gohr
122634d7150SAndreas Gohr/**
123634d7150SAndreas Gohr * Print a hidden form field with a secret CSRF token
124634d7150SAndreas Gohr *
125634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
126140cfbcdSGerrit Uitslag *
127140cfbcdSGerrit Uitslag * @param bool $print  if true print the field, otherwise html of the field is returned
12842ea7f44SGerrit Uitslag * @return string html of hidden form field
129634d7150SAndreas Gohr */
130634d7150SAndreas Gohrfunction formSecurityToken($print = true) {
1312404d0edSAnika Henke    $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
1323272d797SAndreas Gohr    if($print) echo $ret;
133634d7150SAndreas Gohr    return $ret;
134634d7150SAndreas Gohr}
135634d7150SAndreas Gohr
136634d7150SAndreas Gohr/**
1371015a57dSChristopher Smith * Determine basic information for a request of $id
13815fae107Sandi *
13915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1407e87a794SChristopher Smith * @author Chris Smith <chris@jalakai.co.uk>
141140cfbcdSGerrit Uitslag *
142140cfbcdSGerrit Uitslag * @param string $id         pageid
143140cfbcdSGerrit Uitslag * @param bool   $htmlClient add info about whether is mobile browser
144140cfbcdSGerrit Uitslag * @return array with info for a request of $id
145140cfbcdSGerrit Uitslag *
146f3f0262cSandi */
1471015a57dSChristopher Smithfunction basicinfo($id, $htmlClient=true){
148f3f0262cSandi    global $USERINFO;
149585bf44eSChristopher Smith    /* @var Input $INPUT */
150585bf44eSChristopher Smith    global $INPUT;
1516afe8dcaSchris
152c66972f2SAdrian Lang    // set info about manager/admin status.
15359bc3b48SGerrit Uitslag    $info = array();
154c66972f2SAdrian Lang    $info['isadmin']   = false;
155c66972f2SAdrian Lang    $info['ismanager'] = false;
156585bf44eSChristopher Smith    if($INPUT->server->has('REMOTE_USER')) {
157f3f0262cSandi        $info['userinfo']   = $USERINFO;
1581015a57dSChristopher Smith        $info['perm']       = auth_quickaclcheck($id);
159585bf44eSChristopher Smith        $info['client']     = $INPUT->server->str('REMOTE_USER');
16017ee7f66SAndreas Gohr
161f8cc712eSAndreas Gohr        if($info['perm'] == AUTH_ADMIN) {
162f8cc712eSAndreas Gohr            $info['isadmin']   = true;
163f8cc712eSAndreas Gohr            $info['ismanager'] = true;
164f8cc712eSAndreas Gohr        } elseif(auth_ismanager()) {
165f8cc712eSAndreas Gohr            $info['ismanager'] = true;
166f8cc712eSAndreas Gohr        }
167f8cc712eSAndreas Gohr
16817ee7f66SAndreas Gohr        // if some outside auth were used only REMOTE_USER is set
16917ee7f66SAndreas Gohr        if(!$info['userinfo']['name']) {
170585bf44eSChristopher Smith            $info['userinfo']['name'] = $INPUT->server->str('REMOTE_USER');
17117ee7f66SAndreas Gohr        }
172ee4c4a1bSAndreas Gohr
173f3f0262cSandi    } else {
1741015a57dSChristopher Smith        $info['perm']       = auth_aclcheck($id, '', null);
175ee4c4a1bSAndreas Gohr        $info['client']     = clientIP(true);
176f3f0262cSandi    }
177f3f0262cSandi
1781015a57dSChristopher Smith    $info['namespace'] = getNS($id);
1791015a57dSChristopher Smith
1801015a57dSChristopher Smith    // mobile detection
1811015a57dSChristopher Smith    if ($htmlClient) {
1821015a57dSChristopher Smith        $info['ismobile'] = clientismobile();
1831015a57dSChristopher Smith    }
1841015a57dSChristopher Smith
1851015a57dSChristopher Smith    return $info;
1861015a57dSChristopher Smith }
1871015a57dSChristopher Smith
1881015a57dSChristopher Smith/**
1891015a57dSChristopher Smith * Return info about the current document as associative
1901015a57dSChristopher Smith * array.
1911015a57dSChristopher Smith *
1921015a57dSChristopher Smith * @author Andreas Gohr <andi@splitbrain.org>
193140cfbcdSGerrit Uitslag *
194140cfbcdSGerrit Uitslag * @return array with info about current document
1951015a57dSChristopher Smith */
1961015a57dSChristopher Smithfunction pageinfo() {
1971015a57dSChristopher Smith    global $ID;
1981015a57dSChristopher Smith    global $REV;
1991015a57dSChristopher Smith    global $RANGE;
2001015a57dSChristopher Smith    global $lang;
201585bf44eSChristopher Smith    /* @var Input $INPUT */
202585bf44eSChristopher Smith    global $INPUT;
2031015a57dSChristopher Smith
2041015a57dSChristopher Smith    $info = basicinfo($ID);
2051015a57dSChristopher Smith
2061015a57dSChristopher Smith    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
2071015a57dSChristopher Smith    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
2081015a57dSChristopher Smith    $info['id']  = $ID;
2091015a57dSChristopher Smith    $info['rev'] = $REV;
2101015a57dSChristopher Smith
21175d66495SMichael Große    $subManager = new SubscriberManager();
21275d66495SMichael Große    $info['subscribed'] = $subManager->userSubscription();
2137e87a794SChristopher Smith
214f3f0262cSandi    $info['locked']     = checklock($ID);
215317a04c4SSatoshi Sahara    $info['filepath']   = wikiFN($ID);
21679e79377SAndreas Gohr    $info['exists']     = file_exists($info['filepath']);
21701c9a118SAndreas Gohr    $info['currentrev'] = @filemtime($info['filepath']);
2182ca9d91cSBen Coburn    if($REV) {
2192ca9d91cSBen Coburn        //check if current revision was meant
22001c9a118SAndreas Gohr        if($info['exists'] && ($info['currentrev'] == $REV)) {
2212ca9d91cSBen Coburn            $REV = '';
2227b3a6803SAndreas Gohr        } elseif($RANGE) {
2237b3a6803SAndreas Gohr            //section editing does not work with old revisions!
2247b3a6803SAndreas Gohr            $REV   = '';
2257b3a6803SAndreas Gohr            $RANGE = '';
2267b3a6803SAndreas Gohr            msg($lang['nosecedit'], 0);
2272ca9d91cSBen Coburn        } else {
2282ca9d91cSBen Coburn            //really use old revision
229317a04c4SSatoshi Sahara            $info['filepath'] = wikiFN($ID, $REV);
23079e79377SAndreas Gohr            $info['exists']   = file_exists($info['filepath']);
231f3f0262cSandi        }
232f3f0262cSandi    }
233c112d578Sandi    $info['rev'] = $REV;
234f3f0262cSandi    if($info['exists']) {
235f3f0262cSandi        $info['writable'] = (is_writable($info['filepath']) &&
236f3f0262cSandi            ($info['perm'] >= AUTH_EDIT));
237f3f0262cSandi    } else {
238f3f0262cSandi        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
239f3f0262cSandi    }
24050e988b1SAndreas Gohr    $info['editable'] = ($info['writable'] && empty($info['locked']));
241f3f0262cSandi    $info['lastmod']  = @filemtime($info['filepath']);
242f3f0262cSandi
24371726d78SBen Coburn    //load page meta data
24471726d78SBen Coburn    $info['meta'] = p_get_metadata($ID);
24571726d78SBen Coburn
246652610a2Sandi    //who's the editor
247047bad06SGerrit Uitslag    $pagelog = new PageChangeLog($ID, 1024);
248652610a2Sandi    if($REV) {
249f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($REV);
250652610a2Sandi    } else {
2510e80bb5eSChristopher Smith        if(!empty($info['meta']['last_change']) && is_array($info['meta']['last_change'])) {
252aa27cf05SAndreas Gohr            $revinfo = $info['meta']['last_change'];
253aa27cf05SAndreas Gohr        } else {
254f523c971SGerrit Uitslag            $revinfo = $pagelog->getRevisionInfo($info['lastmod']);
255cd00a034SBen Coburn            // cache most recent changelog line in metadata if missing and still valid
256cd00a034SBen Coburn            if($revinfo !== false) {
257cd00a034SBen Coburn                $info['meta']['last_change'] = $revinfo;
258cd00a034SBen Coburn                p_set_metadata($ID, array('last_change' => $revinfo));
259cd00a034SBen Coburn            }
260cd00a034SBen Coburn        }
261cd00a034SBen Coburn    }
262cd00a034SBen Coburn    //and check for an external edit
263cd00a034SBen Coburn    if($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
264cd00a034SBen Coburn        // cached changelog line no longer valid
265cd00a034SBen Coburn        $revinfo                     = false;
266cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
267cd00a034SBen Coburn        p_set_metadata($ID, array('last_change' => $revinfo));
268652610a2Sandi    }
269bb4866bdSchris
2700a444b5aSPhy    if($revinfo !== false){
271652610a2Sandi        $info['ip']   = $revinfo['ip'];
272652610a2Sandi        $info['user'] = $revinfo['user'];
273652610a2Sandi        $info['sum']  = $revinfo['sum'];
27471726d78SBen Coburn        // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
275ebf1501fSBen Coburn        // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
27659f257aeSchris
27788f522e9Sandi        if($revinfo['user']) {
27888f522e9Sandi            $info['editor'] = $revinfo['user'];
27988f522e9Sandi        } else {
28088f522e9Sandi            $info['editor'] = $revinfo['ip'];
28188f522e9Sandi        }
2820a444b5aSPhy    }else{
2830a444b5aSPhy        $info['ip']     = null;
2840a444b5aSPhy        $info['user']   = null;
2850a444b5aSPhy        $info['sum']    = null;
2860a444b5aSPhy        $info['editor'] = null;
2870a444b5aSPhy    }
288652610a2Sandi
289ee4c4a1bSAndreas Gohr    // draft
2900aabe6f8SMichael Große    $draft = new \dokuwiki\Draft($ID, $info['client']);
2910aabe6f8SMichael Große    if ($draft->isDraftAvailable()) {
2920aabe6f8SMichael Große        $info['draft'] = $draft->getDraftFilename();
293ee4c4a1bSAndreas Gohr    }
294ee4c4a1bSAndreas Gohr
2951015a57dSChristopher Smith    return $info;
2961015a57dSChristopher Smith}
2971015a57dSChristopher Smith
2981015a57dSChristopher Smith/**
2990c39d46cSMichael Große * Initialize and/or fill global $JSINFO with some basic info to be given to javascript
3000c39d46cSMichael Große */
3010c39d46cSMichael Großefunction jsinfo() {
3020c39d46cSMichael Große    global $JSINFO, $ID, $INFO, $ACT;
3030c39d46cSMichael Große
3040c39d46cSMichael Große    if (!is_array($JSINFO)) {
3050c39d46cSMichael Große        $JSINFO = [];
3060c39d46cSMichael Große    }
3070c39d46cSMichael Große    //export minimal info to JS, plugins can add more
3080c39d46cSMichael Große    $JSINFO['id']                    = $ID;
30968491db9SPhy    $JSINFO['namespace']             = isset($INFO) ? (string) $INFO['namespace'] : '';
3100c39d46cSMichael Große    $JSINFO['ACT']                   = act_clean($ACT);
3110c39d46cSMichael Große    $JSINFO['useHeadingNavigation']  = (int) useHeading('navigation');
3120c39d46cSMichael Große    $JSINFO['useHeadingContent']     = (int) useHeading('content');
3130c39d46cSMichael Große}
3140c39d46cSMichael Große
3150c39d46cSMichael Große/**
3161015a57dSChristopher Smith * Return information about the current media item as an associative array.
317140cfbcdSGerrit Uitslag *
318140cfbcdSGerrit Uitslag * @return array with info about current media item
3191015a57dSChristopher Smith */
3201015a57dSChristopher Smithfunction mediainfo(){
3211015a57dSChristopher Smith    global $NS;
3221015a57dSChristopher Smith    global $IMG;
3231015a57dSChristopher Smith
3241015a57dSChristopher Smith    $info = basicinfo("$NS:*");
3251015a57dSChristopher Smith    $info['image'] = $IMG;
3261c548ebeSAndreas Gohr
327f3f0262cSandi    return $info;
328f3f0262cSandi}
329f3f0262cSandi
330f3f0262cSandi/**
3312684e50aSAndreas Gohr * Build an string of URL parameters
3322684e50aSAndreas Gohr *
3332684e50aSAndreas Gohr * @author Andreas Gohr
334140cfbcdSGerrit Uitslag *
335140cfbcdSGerrit Uitslag * @param array  $params    array with key-value pairs
336140cfbcdSGerrit Uitslag * @param string $sep       series of pairs are separated by this character
337140cfbcdSGerrit Uitslag * @return string query string
3382684e50aSAndreas Gohr */
339b174aeaeSchrisfunction buildURLparams($params, $sep = '&amp;') {
3402684e50aSAndreas Gohr    $url = '';
3412684e50aSAndreas Gohr    $amp = false;
3422684e50aSAndreas Gohr    foreach($params as $key => $val) {
343b174aeaeSchris        if($amp) $url .= $sep;
3442684e50aSAndreas Gohr
34585e6871fSAdrian Lang        $url .= rawurlencode($key).'=';
3463a50618cSgweissbach        $url .= rawurlencode((string) $val);
3472684e50aSAndreas Gohr        $amp = true;
3482684e50aSAndreas Gohr    }
3492684e50aSAndreas Gohr    return $url;
3502684e50aSAndreas Gohr}
3512684e50aSAndreas Gohr
3522684e50aSAndreas Gohr/**
3532684e50aSAndreas Gohr * Build an string of html tag attributes
3542684e50aSAndreas Gohr *
3557bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
3567bff22c0SAndreas Gohr *
3572684e50aSAndreas Gohr * @author Andreas Gohr
358140cfbcdSGerrit Uitslag *
359140cfbcdSGerrit Uitslag * @param array $params           array with (attribute name-attribute value) pairs
360246d3337SMichael Große * @param bool  $skipEmptyStrings skip empty string values?
361140cfbcdSGerrit Uitslag * @return string
3622684e50aSAndreas Gohr */
363246d3337SMichael Großefunction buildAttributes($params, $skipEmptyStrings = false) {
3642684e50aSAndreas Gohr    $url   = '';
3659063ec14SAdrian Lang    $white = false;
3662684e50aSAndreas Gohr    foreach($params as $key => $val) {
3672401f18dSSyntaxseed        if($key[0] == '_') continue;
368246d3337SMichael Große        if($val === '' && $skipEmptyStrings) continue;
3699063ec14SAdrian Lang        if($white) $url .= ' ';
3707bff22c0SAndreas Gohr
3712684e50aSAndreas Gohr        $url .= $key.'="';
3722684e50aSAndreas Gohr        $url .= htmlspecialchars($val);
3732684e50aSAndreas Gohr        $url .= '"';
3749063ec14SAdrian Lang        $white = true;
3752684e50aSAndreas Gohr    }
3762684e50aSAndreas Gohr    return $url;
3772684e50aSAndreas Gohr}
3782684e50aSAndreas Gohr
3792684e50aSAndreas Gohr/**
38015fae107Sandi * This builds the breadcrumb trail and returns it as array
38115fae107Sandi *
38215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
383140cfbcdSGerrit Uitslag *
384e3710957SGerrit Uitslag * @return string[] with the data: array(pageid=>name, ... )
385f3f0262cSandi */
386f3f0262cSandifunction breadcrumbs() {
3878746e727Sandi    // we prepare the breadcrumbs early for quick session closing
3888746e727Sandi    static $crumbs = null;
3898746e727Sandi    if($crumbs != null) return $crumbs;
3908746e727Sandi
391f3f0262cSandi    global $ID;
392f3f0262cSandi    global $ACT;
393f3f0262cSandi    global $conf;
3940ea5ebb4SB_S666    global $INFO;
395f3f0262cSandi
396f3f0262cSandi    //first visit?
397c66972f2SAdrian Lang    $crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array();
3985603d3c1SHenry Pan    //we only save on show and existing visible readable wiki documents
399a77f5846Sjan    $file = wikiFN($ID);
4005603d3c1SHenry Pan    if($ACT != 'show' || $INFO['perm'] < AUTH_READ || isHiddenPage($ID) || !file_exists($file)) {
401e71ce681SAndreas Gohr        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
402f3f0262cSandi        return $crumbs;
403f3f0262cSandi    }
404a77f5846Sjan
405a77f5846Sjan    // page names
4061a84a0f3SAnika Henke    $name = noNSorNS($ID);
407fe9ec250SChris Smith    if(useHeading('navigation')) {
408a77f5846Sjan        // get page title
40967c15eceSMichael Hamann        $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
410a77f5846Sjan        if($title) {
411a77f5846Sjan            $name = $title;
412a77f5846Sjan        }
413a77f5846Sjan    }
414a77f5846Sjan
415f3f0262cSandi    //remove ID from array
416a77f5846Sjan    if(isset($crumbs[$ID])) {
417a77f5846Sjan        unset($crumbs[$ID]);
418f3f0262cSandi    }
419f3f0262cSandi
420f3f0262cSandi    //add to array
421a77f5846Sjan    $crumbs[$ID] = $name;
422f3f0262cSandi    //reduce size
423f3f0262cSandi    while(count($crumbs) > $conf['breadcrumbs']) {
424f3f0262cSandi        array_shift($crumbs);
425f3f0262cSandi    }
426f3f0262cSandi    //save to session
427e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
428f3f0262cSandi    return $crumbs;
429f3f0262cSandi}
430f3f0262cSandi
431f3f0262cSandi/**
43215fae107Sandi * Filter for page IDs
43315fae107Sandi *
434f3f0262cSandi * This is run on a ID before it is outputted somewhere
435f3f0262cSandi * currently used to replace the colon with something else
436907f24f7SAndreas Gohr * on Windows (non-IIS) systems and to have proper URL encoding
437907f24f7SAndreas Gohr *
438907f24f7SAndreas Gohr * See discussions at https://github.com/splitbrain/dokuwiki/pull/84 and
439907f24f7SAndreas Gohr * https://github.com/splitbrain/dokuwiki/pull/173 why we use a whitelist of
440907f24f7SAndreas Gohr * unaffected servers instead of blacklisting affected servers here.
44115fae107Sandi *
44249c713a3Sandi * Urlencoding is ommitted when the second parameter is false
44349c713a3Sandi *
44415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
445140cfbcdSGerrit Uitslag *
446140cfbcdSGerrit Uitslag * @param string $id pageid being filtered
447140cfbcdSGerrit Uitslag * @param bool   $ue apply urlencoding?
448140cfbcdSGerrit Uitslag * @return string
449f3f0262cSandi */
45049c713a3Sandifunction idfilter($id, $ue = true) {
451f3f0262cSandi    global $conf;
452585bf44eSChristopher Smith    /* @var Input $INPUT */
453585bf44eSChristopher Smith    global $INPUT;
454585bf44eSChristopher Smith
455f3f0262cSandi    if($conf['useslash'] && $conf['userewrite']) {
456f3f0262cSandi        $id = strtr($id, ':', '/');
457f3f0262cSandi    } elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
45858bedc8aSborekb        $conf['userewrite'] &&
459585bf44eSChristopher Smith        strpos($INPUT->server->str('SERVER_SOFTWARE'), 'Microsoft-IIS') === false
4603272d797SAndreas Gohr    ) {
461f3f0262cSandi        $id = strtr($id, ':', ';');
462f3f0262cSandi    }
46349c713a3Sandi    if($ue) {
464b6c6979fSAndreas Gohr        $id = rawurlencode($id);
465f3f0262cSandi        $id = str_replace('%3A', ':', $id); //keep as colon
466edd95259SGerrit Uitslag        $id = str_replace('%3B', ';', $id); //keep as semicolon
467f3f0262cSandi        $id = str_replace('%2F', '/', $id); //keep as slash
46849c713a3Sandi    }
469f3f0262cSandi    return $id;
470f3f0262cSandi}
471f3f0262cSandi
472f3f0262cSandi/**
473ed7b5f09Sandi * This builds a link to a wikipage
47415fae107Sandi *
4754bc480e5SAndreas Gohr * It handles URL rewriting and adds additional parameters
4766c7843b5Sandi *
47715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
4784bc480e5SAndreas Gohr *
4794bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
4804bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
4814bc480e5SAndreas Gohr * @param bool         $absolute       request an absolute URL instead of relative
4824bc480e5SAndreas Gohr * @param string       $separator      parameter separator
4834bc480e5SAndreas Gohr * @return string
484f3f0262cSandi */
48516f15a81SDominik Eckelmannfunction wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;') {
486f3f0262cSandi    global $conf;
48716f15a81SDominik Eckelmann    if(is_array($urlParameters)) {
4884bde2196Slisps        if(isset($urlParameters['rev']) && !$urlParameters['rev']) unset($urlParameters['rev']);
48964159a61SAndreas Gohr        if(isset($urlParameters['at']) && $conf['date_at_format']) {
49064159a61SAndreas Gohr            $urlParameters['at'] = date($conf['date_at_format'], $urlParameters['at']);
49164159a61SAndreas Gohr        }
49216f15a81SDominik Eckelmann        $urlParameters = buildURLparams($urlParameters, $separator);
4936de3759aSAndreas Gohr    } else {
49416f15a81SDominik Eckelmann        $urlParameters = str_replace(',', $separator, $urlParameters);
4956de3759aSAndreas Gohr    }
49616f15a81SDominik Eckelmann    if($id === '') {
49716f15a81SDominik Eckelmann        $id = $conf['start'];
49816f15a81SDominik Eckelmann    }
499f3f0262cSandi    $id = idfilter($id);
50016f15a81SDominik Eckelmann    if($absolute) {
501ed7b5f09Sandi        $xlink = DOKU_URL;
502ed7b5f09Sandi    } else {
503ed7b5f09Sandi        $xlink = DOKU_BASE;
504ed7b5f09Sandi    }
505f3f0262cSandi
5066c7843b5Sandi    if($conf['userewrite'] == 2) {
5076c7843b5Sandi        $xlink .= DOKU_SCRIPT.'/'.$id;
50816f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
5096c7843b5Sandi    } elseif($conf['userewrite']) {
510f3f0262cSandi        $xlink .= $id;
51116f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
51240b5fb5bSPhy    } elseif($id !== '') {
5136c7843b5Sandi        $xlink .= DOKU_SCRIPT.'?id='.$id;
51416f15a81SDominik Eckelmann        if($urlParameters) $xlink .= $separator.$urlParameters;
515bce3726dSAndreas Gohr    } else {
516bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
51716f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
518f3f0262cSandi    }
519f3f0262cSandi
520f3f0262cSandi    return $xlink;
521f3f0262cSandi}
522f3f0262cSandi
523f3f0262cSandi/**
524f5c2808fSBen Coburn * This builds a link to an alternate page format
525f5c2808fSBen Coburn *
526f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
527f5c2808fSBen Coburn *
528f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
5294bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
5304bc480e5SAndreas Gohr * @param string       $format         the export renderer to use
5314bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
5324bc480e5SAndreas Gohr * @param bool         $abs            request an absolute URL instead of relative
5334bc480e5SAndreas Gohr * @param string       $sep            parameter separator
5344bc480e5SAndreas Gohr * @return string
535f5c2808fSBen Coburn */
5364bc480e5SAndreas Gohrfunction exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;') {
537f5c2808fSBen Coburn    global $conf;
5384bc480e5SAndreas Gohr    if(is_array($urlParameters)) {
5394bc480e5SAndreas Gohr        $urlParameters = buildURLparams($urlParameters, $sep);
540f5c2808fSBen Coburn    } else {
5414bc480e5SAndreas Gohr        $urlParameters = str_replace(',', $sep, $urlParameters);
542f5c2808fSBen Coburn    }
543f5c2808fSBen Coburn
544f5c2808fSBen Coburn    $format = rawurlencode($format);
545f5c2808fSBen Coburn    $id     = idfilter($id);
546f5c2808fSBen Coburn    if($abs) {
547f5c2808fSBen Coburn        $xlink = DOKU_URL;
548f5c2808fSBen Coburn    } else {
549f5c2808fSBen Coburn        $xlink = DOKU_BASE;
550f5c2808fSBen Coburn    }
551f5c2808fSBen Coburn
552f5c2808fSBen Coburn    if($conf['userewrite'] == 2) {
553f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
5544bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
555f5c2808fSBen Coburn    } elseif($conf['userewrite'] == 1) {
556f5c2808fSBen Coburn        $xlink .= '_export/'.$format.'/'.$id;
5574bc480e5SAndreas Gohr        if($urlParameters) $xlink .= '?'.$urlParameters;
558f5c2808fSBen Coburn    } else {
559f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
5604bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
561f5c2808fSBen Coburn    }
562f5c2808fSBen Coburn
563f5c2808fSBen Coburn    return $xlink;
564f5c2808fSBen Coburn}
565f5c2808fSBen Coburn
566f5c2808fSBen Coburn/**
5676de3759aSAndreas Gohr * Build a link to a media file
5686de3759aSAndreas Gohr *
5696de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
5708c08db0aSAndreas Gohr *
5718c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
5728c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
5738c08db0aSAndreas Gohr *
5743272d797SAndreas Gohr * @param string  $id     the media file id or URL
5753272d797SAndreas Gohr * @param mixed   $more   string or array with additional parameters
5763272d797SAndreas Gohr * @param bool    $direct link to detail page if false
5773272d797SAndreas Gohr * @param string  $sep    URL parameter separator
5783272d797SAndreas Gohr * @param bool    $abs    Create an absolute URL
5793272d797SAndreas Gohr * @return string
5806de3759aSAndreas Gohr */
58155b2b31bSAndreas Gohrfunction ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false) {
5826de3759aSAndreas Gohr    global $conf;
583b9ee6a44SKlap-in    $isexternalimage = media_isexternal($id);
584826d2766SKlap-in    if(!$isexternalimage) {
585826d2766SKlap-in        $id = cleanID($id);
586826d2766SKlap-in    }
587826d2766SKlap-in
5886de3759aSAndreas Gohr    if(is_array($more)) {
5890f4e0092SChristopher Smith        // add token for resized images
590443e135dSChristopher Smith        if(!empty($more['w']) || !empty($more['h']) || $isexternalimage){
5910f4e0092SChristopher Smith            $more['tok'] = media_get_token($id,$more['w'],$more['h']);
5920f4e0092SChristopher Smith        }
5938c08db0aSAndreas Gohr        // strip defaults for shorter URLs
5948c08db0aSAndreas Gohr        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
595443e135dSChristopher Smith        if(empty($more['w'])) unset($more['w']);
596443e135dSChristopher Smith        if(empty($more['h'])) unset($more['h']);
5978c08db0aSAndreas Gohr        if(isset($more['id']) && $direct) unset($more['id']);
59878b874e6Slisps        if(isset($more['rev']) && !$more['rev']) unset($more['rev']);
599b174aeaeSchris        $more = buildURLparams($more, $sep);
6006de3759aSAndreas Gohr    } else {
6015e7db1e2SChristopher Smith        $matches = array();
602cc036f74SKlap-in        if (preg_match_all('/\b(w|h)=(\d*)\b/',$more,$matches,PREG_SET_ORDER) || $isexternalimage){
6035e7db1e2SChristopher Smith            $resize = array('w'=>0, 'h'=>0);
6045e7db1e2SChristopher Smith            foreach ($matches as $match){
6055e7db1e2SChristopher Smith                $resize[$match[1]] = $match[2];
6065e7db1e2SChristopher Smith            }
607cc036f74SKlap-in            $more .= $more === '' ? '' : $sep;
608cc036f74SKlap-in            $more .= 'tok='.media_get_token($id,$resize['w'],$resize['h']);
6095e7db1e2SChristopher Smith        }
6108c08db0aSAndreas Gohr        $more = str_replace('cache=cache', '', $more); //skip default
6118c08db0aSAndreas Gohr        $more = str_replace(',,', ',', $more);
612b174aeaeSchris        $more = str_replace(',', $sep, $more);
6136de3759aSAndreas Gohr    }
6146de3759aSAndreas Gohr
61555b2b31bSAndreas Gohr    if($abs) {
61655b2b31bSAndreas Gohr        $xlink = DOKU_URL;
61755b2b31bSAndreas Gohr    } else {
6186de3759aSAndreas Gohr        $xlink = DOKU_BASE;
61955b2b31bSAndreas Gohr    }
6206de3759aSAndreas Gohr
6216de3759aSAndreas Gohr    // external URLs are always direct without rewriting
622826d2766SKlap-in    if($isexternalimage) {
6236de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
624cc036f74SKlap-in        $xlink .= '?'.$more;
625b174aeaeSchris        $xlink .= $sep.'media='.rawurlencode($id);
6266de3759aSAndreas Gohr        return $xlink;
6276de3759aSAndreas Gohr    }
6286de3759aSAndreas Gohr
6296de3759aSAndreas Gohr    $id = idfilter($id);
6306de3759aSAndreas Gohr
6316de3759aSAndreas Gohr    // decide on scriptname
6326de3759aSAndreas Gohr    if($direct) {
6336de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
6346de3759aSAndreas Gohr            $script = '_media';
6356de3759aSAndreas Gohr        } else {
6366de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
6376de3759aSAndreas Gohr        }
6386de3759aSAndreas Gohr    } else {
6396de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
6406de3759aSAndreas Gohr            $script = '_detail';
6416de3759aSAndreas Gohr        } else {
6426de3759aSAndreas Gohr            $script = 'lib/exe/detail.php';
6436de3759aSAndreas Gohr        }
6446de3759aSAndreas Gohr    }
6456de3759aSAndreas Gohr
6466de3759aSAndreas Gohr    // build URL based on rewrite mode
6476de3759aSAndreas Gohr    if($conf['userewrite']) {
6486de3759aSAndreas Gohr        $xlink .= $script.'/'.$id;
6496de3759aSAndreas Gohr        if($more) $xlink .= '?'.$more;
6506de3759aSAndreas Gohr    } else {
6516de3759aSAndreas Gohr        if($more) {
652a99d3236SEsther Brunner            $xlink .= $script.'?'.$more;
653b174aeaeSchris            $xlink .= $sep.'media='.$id;
6546de3759aSAndreas Gohr        } else {
655a99d3236SEsther Brunner            $xlink .= $script.'?media='.$id;
6566de3759aSAndreas Gohr        }
6576de3759aSAndreas Gohr    }
6586de3759aSAndreas Gohr
6596de3759aSAndreas Gohr    return $xlink;
6606de3759aSAndreas Gohr}
6616de3759aSAndreas Gohr
6626de3759aSAndreas Gohr/**
66325ca5b17SAndreas Gohr * Returns the URL to the DokuWiki base script
66415fae107Sandi *
66525ca5b17SAndreas Gohr * Consider using wl() instead, unless you absoutely need the doku.php endpoint
66625ca5b17SAndreas Gohr *
66715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
668140cfbcdSGerrit Uitslag *
669140cfbcdSGerrit Uitslag * @return string
670f3f0262cSandi */
67125ca5b17SAndreas Gohrfunction script() {
672ed7b5f09Sandi    return DOKU_BASE.DOKU_SCRIPT;
673f3f0262cSandi}
674f3f0262cSandi
675f3f0262cSandi/**
67615fae107Sandi * Spamcheck against wordlist
67715fae107Sandi *
678f3f0262cSandi * Checks the wikitext against a list of blocked expressions
679f3f0262cSandi * returns true if the text contains any bad words
68015fae107Sandi *
681e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
682e403cc58SMichael Klier *
683e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
684e403cc58SMichael Klier *  and gain information about the user who was blocked.
685e403cc58SMichael Klier *
686e403cc58SMichael Klier *  Event data:
687e403cc58SMichael Klier *    data['matches']  - array of matches
688e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
689e403cc58SMichael Klier *      [ip]           - ip address
690e403cc58SMichael Klier *      [user]         - username (if logged in)
691e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
692e403cc58SMichael Klier *      [name]         - real name (if logged in)
693e403cc58SMichael Klier *
69415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
6956dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
696140cfbcdSGerrit Uitslag *
6976dffa0e0SAndreas Gohr * @param  string $text - optional text to check, if not given the globals are used
6986dffa0e0SAndreas Gohr * @return bool         - true if a spam word was found
699f3f0262cSandi */
7006dffa0e0SAndreas Gohrfunction checkwordblock($text = '') {
701f3f0262cSandi    global $TEXT;
7026dffa0e0SAndreas Gohr    global $PRE;
7036dffa0e0SAndreas Gohr    global $SUF;
704e0086ca2SAndreas Gohr    global $SUM;
705f3f0262cSandi    global $conf;
706e403cc58SMichael Klier    global $INFO;
707585bf44eSChristopher Smith    /* @var Input $INPUT */
708585bf44eSChristopher Smith    global $INPUT;
709f3f0262cSandi
710f3f0262cSandi    if(!$conf['usewordblock']) return false;
711f3f0262cSandi
712e0086ca2SAndreas Gohr    if(!$text) $text = "$PRE $TEXT $SUF $SUM";
7136dffa0e0SAndreas Gohr
714041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
71564159a61SAndreas Gohr    // phpcs:disable Generic.Files.LineLength.TooLong
71664159a61SAndreas Gohr    $text = preg_replace(
71764159a61SAndreas Gohr        '!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i',
71864159a61SAndreas Gohr        '\1http://\2 \2\3',
71964159a61SAndreas Gohr        $text
72064159a61SAndreas Gohr    );
72164159a61SAndreas Gohr    // phpcs:enable
722041d1964SAndreas Gohr
723b9ac8716Schris    $wordblocks = getWordblocks();
7243e2965d7Sandi    // how many lines to read at once (to work around some PCRE limits)
7253e2965d7Sandi    if(version_compare(phpversion(), '4.3.0', '<')) {
7263e2965d7Sandi        // old versions of PCRE define a maximum of parenthesises even if no
7273e2965d7Sandi        // backreferences are used - the maximum is 99
7283e2965d7Sandi        // this is very bad performancewise and may even be too high still
7293e2965d7Sandi        $chunksize = 40;
7303e2965d7Sandi    } else {
731a51d08efSAndreas Gohr        // read file in chunks of 200 - this should work around the
7323e2965d7Sandi        // MAX_PATTERN_SIZE in modern PCRE
733a51d08efSAndreas Gohr        $chunksize = 200;
7343e2965d7Sandi    }
735b9ac8716Schris    while($blocks = array_splice($wordblocks, 0, $chunksize)) {
736f3f0262cSandi        $re = array();
73749eb6e38SAndreas Gohr        // build regexp from blocks
738f3f0262cSandi        foreach($blocks as $block) {
739f3f0262cSandi            $block = preg_replace('/#.*$/', '', $block);
740f3f0262cSandi            $block = trim($block);
741f3f0262cSandi            if(empty($block)) continue;
742f3f0262cSandi            $re[] = $block;
743f3f0262cSandi        }
744e403cc58SMichael Klier        if(count($re) && preg_match('#('.join('|', $re).')#si', $text, $matches)) {
745e403cc58SMichael Klier            // prepare event data
74659bc3b48SGerrit Uitslag            $data = array();
747e403cc58SMichael Klier            $data['matches']        = $matches;
748585bf44eSChristopher Smith            $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
749585bf44eSChristopher Smith            if($INPUT->server->str('REMOTE_USER')) {
750585bf44eSChristopher Smith                $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
751e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
752e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
753e403cc58SMichael Klier            }
754bad6fc0dSAndreas Gohr            $callback = function () {
755bad6fc0dSAndreas Gohr                return true;
756bad6fc0dSAndreas Gohr            };
757cbb44eabSAndreas Gohr            return Event::createAndTrigger('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
758b9ac8716Schris        }
759703f6fdeSandi    }
760f3f0262cSandi    return false;
761f3f0262cSandi}
762f3f0262cSandi
763f3f0262cSandi/**
76415fae107Sandi * Return the IP of the client
76515fae107Sandi *
7666d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
76715fae107Sandi *
7686d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
7696d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
7706d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
7716d8affe6SAndreas Gohr * headers
7726d8affe6SAndreas Gohr *
77315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
774140cfbcdSGerrit Uitslag *
7753272d797SAndreas Gohr * @param  boolean $single If set only a single IP is returned
7763272d797SAndreas Gohr * @return string
777f3f0262cSandi */
7786d8affe6SAndreas Gohrfunction clientIP($single = false) {
779585bf44eSChristopher Smith    /* @var Input $INPUT */
780925105e8SPhy    global $INPUT, $conf;
781585bf44eSChristopher Smith
7826d8affe6SAndreas Gohr    $ip   = array();
783585bf44eSChristopher Smith    $ip[] = $INPUT->server->str('REMOTE_ADDR');
784585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_FORWARDED_FOR')) {
785585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_FORWARDED_FOR'))));
786585bf44eSChristopher Smith    }
787585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_REAL_IP')) {
788585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_REAL_IP'))));
789585bf44eSChristopher Smith    }
7906d8affe6SAndreas Gohr
7916d8affe6SAndreas Gohr    // remove any non-IP stuff
7926d8affe6SAndreas Gohr    $cnt   = count($ip);
7936d8affe6SAndreas Gohr    for($i = 0; $i < $cnt; $i++) {
794*0a5f08e5SAdaKaleh        if(filter_var($ip[$i], FILTER_VALIDATE_IP) === false) {
795*0a5f08e5SAdaKaleh            unset($ip[$i]);
796*0a5f08e5SAdaKaleh        }
797f3f0262cSandi    }
7986d8affe6SAndreas Gohr    $ip = array_values(array_unique($ip));
7996d8affe6SAndreas Gohr    if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
8006d8affe6SAndreas Gohr
8016d8affe6SAndreas Gohr    if(!$single) return join(',', $ip);
8026d8affe6SAndreas Gohr
803925105e8SPhy    // skip trusted local addresses
8046d8affe6SAndreas Gohr    foreach($ip as $i) {
805925105e8SPhy        if(!empty($conf['trustedproxy']) && preg_match('/'.$conf['trustedproxy'].'/', $i)) {
8066d8affe6SAndreas Gohr            continue;
8076d8affe6SAndreas Gohr        } else {
8086d8affe6SAndreas Gohr            return $i;
8096d8affe6SAndreas Gohr        }
8106d8affe6SAndreas Gohr    }
811925105e8SPhy
812925105e8SPhy    // still here? just use the last address
813925105e8SPhy    // this case all ips in the list are trusted
814925105e8SPhy    return $ip[count($ip)-1];
815f3f0262cSandi}
816f3f0262cSandi
817f3f0262cSandi/**
8181c548ebeSAndreas Gohr * Check if the browser is on a mobile device
8191c548ebeSAndreas Gohr *
8201c548ebeSAndreas Gohr * Adapted from the example code at url below
8211c548ebeSAndreas Gohr *
8221c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
823140cfbcdSGerrit Uitslag *
82464159a61SAndreas Gohr * @deprecated 2018-04-27 you probably want media queries instead anyway
825140cfbcdSGerrit Uitslag * @return bool if true, client is mobile browser; otherwise false
8261c548ebeSAndreas Gohr */
8271c548ebeSAndreas Gohrfunction clientismobile() {
828585bf44eSChristopher Smith    /* @var Input $INPUT */
829585bf44eSChristopher Smith    global $INPUT;
8301c548ebeSAndreas Gohr
831585bf44eSChristopher Smith    if($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
8321c548ebeSAndreas Gohr
833585bf44eSChristopher Smith    if(preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
8341c548ebeSAndreas Gohr
835585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_USER_AGENT')) return false;
8361c548ebeSAndreas Gohr
83764159a61SAndreas Gohr    $uamatches = join(
83864159a61SAndreas Gohr        '|',
83964159a61SAndreas Gohr        [
84064159a61SAndreas Gohr            'midp', 'j2me', 'avantg', 'docomo', 'novarra', 'palmos', 'palmsource', '240x320', 'opwv',
84164159a61SAndreas Gohr            'chtml', 'pda', 'windows ce', 'mmp\/', 'blackberry', 'mib\/', 'symbian', 'wireless', 'nokia',
84264159a61SAndreas Gohr            'hand', 'mobi', 'phone', 'cdm', 'up\.b', 'audio', 'SIE\-', 'SEC\-', 'samsung', 'HTC', 'mot\-',
84364159a61SAndreas Gohr            'mitsu', 'sagem', 'sony', 'alcatel', 'lg', 'erics', 'vx', 'NEC', 'philips', 'mmm', 'xx',
84464159a61SAndreas Gohr            'panasonic', 'sharp', 'wap', 'sch', 'rover', 'pocket', 'benq', 'java', 'pt', 'pg', 'vox',
84564159a61SAndreas Gohr            'amoi', 'bird', 'compal', 'kg', 'voda', 'sany', 'kdd', 'dbt', 'sendo', 'sgh', 'gradi', 'jb',
84664159a61SAndreas Gohr            '\d\d\di', 'moto'
84764159a61SAndreas Gohr        ]
84864159a61SAndreas Gohr    );
8491c548ebeSAndreas Gohr
850585bf44eSChristopher Smith    if(preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
8511c548ebeSAndreas Gohr
8521c548ebeSAndreas Gohr    return false;
8531c548ebeSAndreas Gohr}
8541c548ebeSAndreas Gohr
8551c548ebeSAndreas Gohr/**
8566efc45a2SDmitry Katsubo * check if a given link is interwiki link
8576efc45a2SDmitry Katsubo *
8586efc45a2SDmitry Katsubo * @param string $link the link, e.g. "wiki>page"
8596efc45a2SDmitry Katsubo * @return bool
8606efc45a2SDmitry Katsubo */
8616efc45a2SDmitry Katsubofunction link_isinterwiki($link){
8626efc45a2SDmitry Katsubo    if (preg_match('/^[a-zA-Z0-9\.]+>/u',$link)) return true;
8636efc45a2SDmitry Katsubo    return false;
8646efc45a2SDmitry Katsubo}
8656efc45a2SDmitry Katsubo
8666efc45a2SDmitry Katsubo/**
86763211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
86863211f61SGlen Harris *
86922ef1e32SAndreas Gohr * If $conf['dnslookups'] is disabled it simply returns the input string
87022ef1e32SAndreas Gohr *
87163211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
872140cfbcdSGerrit Uitslag *
8733272d797SAndreas Gohr * @param  string $ips comma separated list of IP addresses
8743272d797SAndreas Gohr * @return string a comma separated list of hostnames
87563211f61SGlen Harris */
87663211f61SGlen Harrisfunction gethostsbyaddrs($ips) {
87722ef1e32SAndreas Gohr    global $conf;
87822ef1e32SAndreas Gohr    if(!$conf['dnslookups']) return $ips;
87922ef1e32SAndreas Gohr
88063211f61SGlen Harris    $hosts = array();
88163211f61SGlen Harris    $ips   = explode(',', $ips);
882551a720fSMichael Klier
883551a720fSMichael Klier    if(is_array($ips)) {
8843886270dSAndreas Gohr        foreach($ips as $ip) {
885551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
88663211f61SGlen Harris        }
887551a720fSMichael Klier        return join(',', $hosts);
888551a720fSMichael Klier    } else {
889551a720fSMichael Klier        return gethostbyaddr(trim($ips));
890551a720fSMichael Klier    }
89163211f61SGlen Harris}
89263211f61SGlen Harris
89363211f61SGlen Harris/**
89415fae107Sandi * Checks if a given page is currently locked.
89515fae107Sandi *
896f3f0262cSandi * removes stale lockfiles
89715fae107Sandi *
89815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
899140cfbcdSGerrit Uitslag *
900140cfbcdSGerrit Uitslag * @param string $id page id
901140cfbcdSGerrit Uitslag * @return bool page is locked?
902f3f0262cSandi */
903f3f0262cSandifunction checklock($id) {
904f3f0262cSandi    global $conf;
905585bf44eSChristopher Smith    /* @var Input $INPUT */
906585bf44eSChristopher Smith    global $INPUT;
907585bf44eSChristopher Smith
908c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
909f3f0262cSandi
910f3f0262cSandi    //no lockfile
91179e79377SAndreas Gohr    if(!file_exists($lock)) return false;
912f3f0262cSandi
913f3f0262cSandi    //lockfile expired
914f3f0262cSandi    if((time() - filemtime($lock)) > $conf['locktime']) {
915d8186216SBen Coburn        @unlink($lock);
916f3f0262cSandi        return false;
917f3f0262cSandi    }
918f3f0262cSandi
919f3f0262cSandi    //my own lock
9206d2af55dSChristopher Smith    @list($ip, $session) = explode("\n", io_readFile($lock));
9210712fefaSAndreas Gohr    if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || (session_id() && $session == session_id())) {
922f3f0262cSandi        return false;
923f3f0262cSandi    }
924f3f0262cSandi
925f3f0262cSandi    return $ip;
926f3f0262cSandi}
927f3f0262cSandi
928f3f0262cSandi/**
92915fae107Sandi * Lock a page for editing
93015fae107Sandi *
93115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
932140cfbcdSGerrit Uitslag *
933140cfbcdSGerrit Uitslag * @param string $id page id to lock
934f3f0262cSandi */
935f3f0262cSandifunction lock($id) {
936544ed901SDaniel Calviño Sánchez    global $conf;
937585bf44eSChristopher Smith    /* @var Input $INPUT */
938585bf44eSChristopher Smith    global $INPUT;
939544ed901SDaniel Calviño Sánchez
940544ed901SDaniel Calviño Sánchez    if($conf['locktime'] == 0) {
941544ed901SDaniel Calviño Sánchez        return;
942544ed901SDaniel Calviño Sánchez    }
943544ed901SDaniel Calviño Sánchez
944c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
945585bf44eSChristopher Smith    if($INPUT->server->str('REMOTE_USER')) {
946585bf44eSChristopher Smith        io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
947f3f0262cSandi    } else {
94885fef7e2SAndreas Gohr        io_saveFile($lock, clientIP()."\n".session_id());
949f3f0262cSandi    }
950f3f0262cSandi}
951f3f0262cSandi
952f3f0262cSandi/**
95315fae107Sandi * Unlock a page if it was locked by the user
954f3f0262cSandi *
95515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
956140cfbcdSGerrit Uitslag *
9573272d797SAndreas Gohr * @param string $id page id to unlock
95815fae107Sandi * @return bool true if a lock was removed
959f3f0262cSandi */
960f3f0262cSandifunction unlock($id) {
961585bf44eSChristopher Smith    /* @var Input $INPUT */
962585bf44eSChristopher Smith    global $INPUT;
963585bf44eSChristopher Smith
964c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
96579e79377SAndreas Gohr    if(file_exists($lock)) {
9666d2af55dSChristopher Smith        @list($ip, $session) = explode("\n", io_readFile($lock));
967585bf44eSChristopher Smith        if($ip == $INPUT->server->str('REMOTE_USER') || $ip == clientIP() || $session == session_id()) {
968f3f0262cSandi            @unlink($lock);
969f3f0262cSandi            return true;
970f3f0262cSandi        }
971f3f0262cSandi    }
972f3f0262cSandi    return false;
973f3f0262cSandi}
974f3f0262cSandi
975f3f0262cSandi/**
976f3f0262cSandi * convert line ending to unix format
977f3f0262cSandi *
9786db7468bSAndreas Gohr * also makes sure the given text is valid UTF-8
9796db7468bSAndreas Gohr *
98015fae107Sandi * @see    formText() for 2crlf conversion
98115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
982140cfbcdSGerrit Uitslag *
983140cfbcdSGerrit Uitslag * @param string $text
984140cfbcdSGerrit Uitslag * @return string
985f3f0262cSandi */
986f3f0262cSandifunction cleanText($text) {
987f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
9886db7468bSAndreas Gohr
9896db7468bSAndreas Gohr    // if the text is not valid UTF-8 we simply assume latin1
9906db7468bSAndreas Gohr    // this won't break any worse than it breaks with the wrong encoding
9916db7468bSAndreas Gohr    // but might actually fix the problem in many cases
9928cbc5ee8SAndreas Gohr    if(!\dokuwiki\Utf8\Clean::isUtf8($text)) $text = utf8_encode($text);
9936db7468bSAndreas Gohr
994f3f0262cSandi    return $text;
995f3f0262cSandi}
996f3f0262cSandi
997f3f0262cSandi/**
998f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
999f3f0262cSandi * It also converts line endings to Windows format which is
1000f3f0262cSandi * pseudo standard for webforms.
1001f3f0262cSandi *
100215fae107Sandi * @see    cleanText() for 2unix conversion
100315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1004140cfbcdSGerrit Uitslag *
1005140cfbcdSGerrit Uitslag * @param string $text
1006140cfbcdSGerrit Uitslag * @return string
1007f3f0262cSandi */
1008f3f0262cSandifunction formText($text) {
10095b7d45a5SAndreas Gohr    $text = str_replace("\012", "\015\012", $text);
1010f3f0262cSandi    return htmlspecialchars($text);
1011f3f0262cSandi}
1012f3f0262cSandi
1013f3f0262cSandi/**
101415fae107Sandi * Returns the specified local text in raw format
101515fae107Sandi *
101615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1017140cfbcdSGerrit Uitslag *
1018140cfbcdSGerrit Uitslag * @param string $id   page id
1019140cfbcdSGerrit Uitslag * @param string $ext  extension of file being read, default 'txt'
1020140cfbcdSGerrit Uitslag * @return string
1021f3f0262cSandi */
10222adaf2b8SAndreas Gohrfunction rawLocale($id, $ext = 'txt') {
10232adaf2b8SAndreas Gohr    return io_readFile(localeFN($id, $ext));
1024f3f0262cSandi}
1025f3f0262cSandi
1026f3f0262cSandi/**
1027f3f0262cSandi * Returns the raw WikiText
102815fae107Sandi *
102915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1030140cfbcdSGerrit Uitslag *
1031140cfbcdSGerrit Uitslag * @param string $id   page id
1032e0c26282SGerrit Uitslag * @param string|int $rev  timestamp when a revision of wikitext is desired
1033140cfbcdSGerrit Uitslag * @return string
1034f3f0262cSandi */
1035f3f0262cSandifunction rawWiki($id, $rev = '') {
1036cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1037f3f0262cSandi}
1038f3f0262cSandi
1039f3f0262cSandi/**
10407146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
10417146cee2SAndreas Gohr *
10427b84afa2SAndreas Gohr * @triggers COMMON_PAGETPL_LOAD
10437146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1044140cfbcdSGerrit Uitslag *
1045140cfbcdSGerrit Uitslag * @param string $id the id of the page to be created
1046140cfbcdSGerrit Uitslag * @return string parsed pagetemplate content
10477146cee2SAndreas Gohr */
1048fe17917eSAdrian Langfunction pageTemplate($id) {
1049a15ce62dSEsther Brunner    global $conf;
1050e29549feSAndreas Gohr
1051fe17917eSAdrian Lang    if(is_array($id)) $id = $id[0];
1052e29549feSAndreas Gohr
10537b84afa2SAndreas Gohr    // prepare initial event data
10547b84afa2SAndreas Gohr    $data = array(
10557b84afa2SAndreas Gohr        'id'        => $id, // the id of the page to be created
10567b84afa2SAndreas Gohr        'tpl'       => '', // the text used as template
10577b84afa2SAndreas Gohr        'tplfile'   => '', // the file above text was/should be loaded from
10587b84afa2SAndreas Gohr        'doreplace' => true // should wildcard replacements be done on the text?
10597b84afa2SAndreas Gohr    );
10607b84afa2SAndreas Gohr
1061e1d9dcc8SAndreas Gohr    $evt = new Event('COMMON_PAGETPL_LOAD', $data);
10627b84afa2SAndreas Gohr    if($evt->advise_before(true)) {
10637b84afa2SAndreas Gohr        // the before event might have loaded the content already
10647b84afa2SAndreas Gohr        if(empty($data['tpl'])) {
10657b84afa2SAndreas Gohr            // if the before event did not set a template file, try to find one
10667b84afa2SAndreas Gohr            if(empty($data['tplfile'])) {
1067fe17917eSAdrian Lang                $path = dirname(wikiFN($id));
106879e79377SAndreas Gohr                if(file_exists($path.'/_template.txt')) {
10697b84afa2SAndreas Gohr                    $data['tplfile'] = $path.'/_template.txt';
1070e29549feSAndreas Gohr                } else {
1071e29549feSAndreas Gohr                    // search upper namespaces for templates
1072e29549feSAndreas Gohr                    $len = strlen(rtrim($conf['datadir'], '/'));
1073e29549feSAndreas Gohr                    while(strlen($path) >= $len) {
107479e79377SAndreas Gohr                        if(file_exists($path.'/__template.txt')) {
10757b84afa2SAndreas Gohr                            $data['tplfile'] = $path.'/__template.txt';
1076e29549feSAndreas Gohr                            break;
1077e29549feSAndreas Gohr                        }
1078e29549feSAndreas Gohr                        $path = substr($path, 0, strrpos($path, '/'));
1079e29549feSAndreas Gohr                    }
1080e29549feSAndreas Gohr                }
10817b84afa2SAndreas Gohr            }
10827b84afa2SAndreas Gohr            // load the content
10833d7ac595SMichael Hamann            $data['tpl'] = io_readFile($data['tplfile']);
10847b84afa2SAndreas Gohr        }
1085a1bbd05bSMichael Hamann        if($data['doreplace']) parsePageTemplate($data);
10867b84afa2SAndreas Gohr    }
10877b84afa2SAndreas Gohr    $evt->advise_after();
10887b84afa2SAndreas Gohr    unset($evt);
10897b84afa2SAndreas Gohr
1090fe17917eSAdrian Lang    return $data['tpl'];
10912b1223ecSAdrian Lang}
10922b1223ecSAdrian Lang
10932b1223ecSAdrian Lang/**
10942b1223ecSAdrian Lang * Performs common page template replacements
10957b84afa2SAndreas Gohr * This works on data from COMMON_PAGETPL_LOAD
10962b1223ecSAdrian Lang *
10972b1223ecSAdrian Lang * @author Andreas Gohr <andi@splitbrain.org>
1098140cfbcdSGerrit Uitslag *
1099140cfbcdSGerrit Uitslag * @param array $data array with event data
1100140cfbcdSGerrit Uitslag * @return string
11012b1223ecSAdrian Lang */
1102d535a2e9Sstretchyboyfunction parsePageTemplate(&$data) {
11033272d797SAndreas Gohr    /**
11043272d797SAndreas Gohr     * @var string $id        the id of the page to be created
11053272d797SAndreas Gohr     * @var string $tpl       the text used as template
11063272d797SAndreas Gohr     * @var string $tplfile   the file above text was/should be loaded from
11073272d797SAndreas Gohr     * @var bool   $doreplace should wildcard replacements be done on the text?
11083272d797SAndreas Gohr     */
1109fe17917eSAdrian Lang    extract($data);
1110fe17917eSAdrian Lang
1111b856f7dfSAdrian Lang    global $USERINFO;
1112bce53b1fSAdrian Lang    global $conf;
1113585bf44eSChristopher Smith    /* @var Input $INPUT */
1114585bf44eSChristopher Smith    global $INPUT;
1115e29549feSAndreas Gohr
1116e29549feSAndreas Gohr    // replace placeholders
111726ece5a7SAndreas Gohr    $file = noNS($id);
111837c1acbdSAdrian Lang    $page = strtr($file, $conf['sepchar'], ' ');
111926ece5a7SAndreas Gohr
11203272d797SAndreas Gohr    $tpl = str_replace(
11213272d797SAndreas Gohr        array(
112226ece5a7SAndreas Gohr             '@ID@',
112326ece5a7SAndreas Gohr             '@NS@',
11248a7bcf66SShota Miyazaki             '@CURNS@',
1125a3db0ab0SSimon Lees             '@!CURNS@',
1126a3db0ab0SSimon Lees             '@!!CURNS@',
1127a3db0ab0SSimon Lees             '@!CURNS!@',
112826ece5a7SAndreas Gohr             '@FILE@',
112926ece5a7SAndreas Gohr             '@!FILE@',
113026ece5a7SAndreas Gohr             '@!FILE!@',
113126ece5a7SAndreas Gohr             '@PAGE@',
113226ece5a7SAndreas Gohr             '@!PAGE@',
113326ece5a7SAndreas Gohr             '@!!PAGE@',
113426ece5a7SAndreas Gohr             '@!PAGE!@',
113526ece5a7SAndreas Gohr             '@USER@',
113626ece5a7SAndreas Gohr             '@NAME@',
113726ece5a7SAndreas Gohr             '@MAIL@',
113826ece5a7SAndreas Gohr             '@DATE@',
113926ece5a7SAndreas Gohr        ),
114026ece5a7SAndreas Gohr        array(
114126ece5a7SAndreas Gohr             $id,
114226ece5a7SAndreas Gohr             getNS($id),
11438a7bcf66SShota Miyazaki             curNS($id),
1144c1ec88ceSAndreas Gohr             \dokuwiki\Utf8\PhpString::ucfirst(curNS($id)),
1145c1ec88ceSAndreas Gohr             \dokuwiki\Utf8\PhpString::ucwords(curNS($id)),
1146c1ec88ceSAndreas Gohr             \dokuwiki\Utf8\PhpString::strtoupper(curNS($id)),
114726ece5a7SAndreas Gohr             $file,
11488cbc5ee8SAndreas Gohr             \dokuwiki\Utf8\PhpString::ucfirst($file),
11498cbc5ee8SAndreas Gohr             \dokuwiki\Utf8\PhpString::strtoupper($file),
115026ece5a7SAndreas Gohr             $page,
11518cbc5ee8SAndreas Gohr             \dokuwiki\Utf8\PhpString::ucfirst($page),
11528cbc5ee8SAndreas Gohr             \dokuwiki\Utf8\PhpString::ucwords($page),
11538cbc5ee8SAndreas Gohr             \dokuwiki\Utf8\PhpString::strtoupper($page),
1154585bf44eSChristopher Smith             $INPUT->server->str('REMOTE_USER'),
11553e9ae63dSPhy             $USERINFO ? $USERINFO['name'] : '',
11563e9ae63dSPhy             $USERINFO ? $USERINFO['mail'] : '',
115726ece5a7SAndreas Gohr             $conf['dformat'],
11583272d797SAndreas Gohr        ), $tpl
11593272d797SAndreas Gohr    );
116026ece5a7SAndreas Gohr
11617d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
1162bad6fc0dSAndreas Gohr    $tpl = preg_replace_callback(
1163bad6fc0dSAndreas Gohr        '/%./',
1164bad6fc0dSAndreas Gohr        function ($m) {
1165bad6fc0dSAndreas Gohr            return strftime($m[0]);
1166bad6fc0dSAndreas Gohr        },
1167bad6fc0dSAndreas Gohr        $tpl
1168bad6fc0dSAndreas Gohr    );
1169d535a2e9Sstretchyboy    $data['tpl'] = $tpl;
1170a15ce62dSEsther Brunner    return $tpl;
11717146cee2SAndreas Gohr}
11727146cee2SAndreas Gohr
11737146cee2SAndreas Gohr/**
117415fae107Sandi * Returns the raw Wiki Text in three slices.
117515fae107Sandi *
117615fae107Sandi * The range parameter needs to have the form "from-to"
117715cfe303Sandi * and gives the range of the section in bytes - no
117815cfe303Sandi * UTF-8 awareness is needed.
1179f3f0262cSandi * The returned order is prefix, section and suffix.
118015fae107Sandi *
118115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1182140cfbcdSGerrit Uitslag *
1183140cfbcdSGerrit Uitslag * @param string $range in form "from-to"
1184140cfbcdSGerrit Uitslag * @param string $id    page id
1185140cfbcdSGerrit Uitslag * @param string $rev   optional, the revision timestamp
118642ea7f44SGerrit Uitslag * @return string[] with three slices
1187f3f0262cSandi */
1188f3f0262cSandifunction rawWikiSlices($range, $id, $rev = '') {
1189cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1190f3f0262cSandi
119180fcb268SAdrian Lang    // Parse range
119280fcb268SAdrian Lang    list($from, $to) = explode('-', $range, 2);
119380fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
119480fcb268SAdrian Lang    $from = !$from ? 0 : ($from - 1);
119580fcb268SAdrian Lang    $to   = !$to ? strlen($text) : ($to - 1);
119680fcb268SAdrian Lang
119759bc3b48SGerrit Uitslag    $slices = array();
119880fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
119980fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to - $from);
120015cfe303Sandi    $slices[2] = substr($text, $to);
1201f3f0262cSandi    return $slices;
1202f3f0262cSandi}
1203f3f0262cSandi
1204f3f0262cSandi/**
120515fae107Sandi * Joins wiki text slices
120615fae107Sandi *
120780fcb268SAdrian Lang * function to join the text slices.
1208f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
1209f3f0262cSandi * lines between sections if needed (used on saving).
121015fae107Sandi *
121115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1212140cfbcdSGerrit Uitslag *
1213140cfbcdSGerrit Uitslag * @param string $pre   prefix
1214140cfbcdSGerrit Uitslag * @param string $text  text in the middle
1215140cfbcdSGerrit Uitslag * @param string $suf   suffix
1216140cfbcdSGerrit Uitslag * @param bool $pretty add additional empty lines between sections
1217140cfbcdSGerrit Uitslag * @return string
1218f3f0262cSandi */
1219f3f0262cSandifunction con($pre, $text, $suf, $pretty = false) {
1220f3f0262cSandi    if($pretty) {
122180fcb268SAdrian Lang        if($pre !== '' && substr($pre, -1) !== "\n" &&
12223272d797SAndreas Gohr            substr($text, 0, 1) !== "\n"
12233272d797SAndreas Gohr        ) {
122480fcb268SAdrian Lang            $pre .= "\n";
122580fcb268SAdrian Lang        }
122680fcb268SAdrian Lang        if($suf !== '' && substr($text, -1) !== "\n" &&
12273272d797SAndreas Gohr            substr($suf, 0, 1) !== "\n"
12283272d797SAndreas Gohr        ) {
122980fcb268SAdrian Lang            $text .= "\n";
123080fcb268SAdrian Lang        }
1231f3f0262cSandi    }
1232f3f0262cSandi
1233f3f0262cSandi    return $pre.$text.$suf;
1234f3f0262cSandi}
1235f3f0262cSandi
1236f3f0262cSandi/**
1237b24d9195SAndreas Gohr * Checks if the current page version is newer than the last entry in the page's
1238b24d9195SAndreas Gohr * changelog. If so, we assume it has been an external edit and we create an
1239b24d9195SAndreas Gohr * attic copy and add a proper changelog line.
1240b24d9195SAndreas Gohr *
1241b24d9195SAndreas Gohr * This check is only executed when the page is about to be saved again from the
1242b24d9195SAndreas Gohr * wiki, triggered in @see saveWikiText()
1243b24d9195SAndreas Gohr *
1244b24d9195SAndreas Gohr * @param string $id the page ID
1245b24d9195SAndreas Gohr */
1246b24d9195SAndreas Gohrfunction detectExternalEdit($id) {
1247b24d9195SAndreas Gohr    global $lang;
1248b24d9195SAndreas Gohr
12498c7319beSGerrit Uitslag    $fileLastMod = wikiFN($id);
12508c7319beSGerrit Uitslag    $lastMod     = @filemtime($fileLastMod); // from page
1251b24d9195SAndreas Gohr    $pagelog     = new PageChangeLog($id, 1024);
12528c7319beSGerrit Uitslag    $lastRev     = $pagelog->getRevisions(-1, 1); // from changelog
12538c7319beSGerrit Uitslag    $lastRev     = (int) (empty($lastRev) ? 0 : $lastRev[0]);
1254b24d9195SAndreas Gohr
12558c7319beSGerrit Uitslag    if(!file_exists(wikiFN($id, $lastMod)) && file_exists($fileLastMod) && $lastMod >= $lastRev) {
1256b24d9195SAndreas Gohr        // add old revision to the attic if missing
1257b24d9195SAndreas Gohr        saveOldRevision($id);
1258b24d9195SAndreas Gohr        // add a changelog entry if this edit came from outside dokuwiki
12598c7319beSGerrit Uitslag        if($lastMod > $lastRev) {
12608c7319beSGerrit Uitslag            $fileLastRev = wikiFN($id, $lastRev);
12618c7319beSGerrit Uitslag            $revinfo = $pagelog->getRevisionInfo($lastRev);
12623c48b1d0SGerrit Uitslag            if(empty($lastRev) || !file_exists($fileLastRev) || $revinfo['type'] == DOKU_CHANGE_TYPE_DELETE) {
12634b5aebc1SGerrit Uitslag                $filesize_old = 0;
12644b5aebc1SGerrit Uitslag            } else {
12658c7319beSGerrit Uitslag                $filesize_old = io_getSizeFile($fileLastRev);
12664b5aebc1SGerrit Uitslag            }
12678c7319beSGerrit Uitslag            $filesize_new = filesize($fileLastMod);
12682966355bSGerrit Uitslag            $sizechange = $filesize_new - $filesize_old;
12692966355bSGerrit Uitslag
127064159a61SAndreas Gohr            addLogEntry(
127164159a61SAndreas Gohr                $lastMod,
127264159a61SAndreas Gohr                $id,
127364159a61SAndreas Gohr                DOKU_CHANGE_TYPE_EDIT,
127464159a61SAndreas Gohr                $lang['external_edit'],
127564159a61SAndreas Gohr                '',
127664159a61SAndreas Gohr                array('ExternalEdit' => true),
127764159a61SAndreas Gohr                $sizechange
127864159a61SAndreas Gohr            );
1279b24d9195SAndreas Gohr            // remove soon to be stale instructions
12800db5771eSMichael Große            $cache = new CacheInstructions($id, $fileLastMod);
1281b24d9195SAndreas Gohr            $cache->removeCache();
1282b24d9195SAndreas Gohr        }
1283b24d9195SAndreas Gohr    }
1284b24d9195SAndreas Gohr}
1285b24d9195SAndreas Gohr
1286b24d9195SAndreas Gohr/**
1287a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
1288a701424fSBen Coburn * Also directs changelog and attic updates.
128915fae107Sandi *
129015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
129171726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
1292140cfbcdSGerrit Uitslag *
1293140cfbcdSGerrit Uitslag * @param string $id       page id
1294140cfbcdSGerrit Uitslag * @param string $text     wikitext being saved
1295140cfbcdSGerrit Uitslag * @param string $summary  summary of text update
1296140cfbcdSGerrit Uitslag * @param bool   $minor    mark this saved version as minor update
1297f3f0262cSandi */
1298b6912aeaSAndreas Gohrfunction saveWikiText($id, $text, $summary, $minor = false) {
1299a701424fSBen Coburn    /* Note to developers:
1300a701424fSBen Coburn       This code is subtle and delicate. Test the behavior of
1301a701424fSBen Coburn       the attic and changelog with dokuwiki and external edits
1302a701424fSBen Coburn       after any changes. External edits change the wiki page
1303a701424fSBen Coburn       directly without using php or dokuwiki.
1304a701424fSBen Coburn     */
1305f3f0262cSandi    global $conf;
1306f3f0262cSandi    global $lang;
130771726d78SBen Coburn    global $REV;
1308585bf44eSChristopher Smith    /* @var Input $INPUT */
1309585bf44eSChristopher Smith    global $INPUT;
1310585bf44eSChristopher Smith
1311b24d9195SAndreas Gohr    // prepare data for event
1312b24d9195SAndreas Gohr    $svdta = array();
1313b24d9195SAndreas Gohr    $svdta['id']             = $id;
1314b24d9195SAndreas Gohr    $svdta['file']           = wikiFN($id);
1315b24d9195SAndreas Gohr    $svdta['revertFrom']     = $REV;
1316b24d9195SAndreas Gohr    $svdta['oldRevision']    = @filemtime($svdta['file']);
1317b24d9195SAndreas Gohr    $svdta['newRevision']    = 0;
1318b24d9195SAndreas Gohr    $svdta['newContent']     = $text;
1319b24d9195SAndreas Gohr    $svdta['oldContent']     = rawWiki($id);
1320b24d9195SAndreas Gohr    $svdta['summary']        = $summary;
1321b24d9195SAndreas Gohr    $svdta['contentChanged'] = ($svdta['newContent'] != $svdta['oldContent']);
1322b24d9195SAndreas Gohr    $svdta['changeInfo']     = '';
1323b24d9195SAndreas Gohr    $svdta['changeType']     = DOKU_CHANGE_TYPE_EDIT;
13242966355bSGerrit Uitslag    $svdta['sizechange']     = null;
1325b24d9195SAndreas Gohr
1326b24d9195SAndreas Gohr    // select changelog line type
1327b24d9195SAndreas Gohr    if($REV) {
1328b24d9195SAndreas Gohr        $svdta['changeType']  = DOKU_CHANGE_TYPE_REVERT;
1329b24d9195SAndreas Gohr        $svdta['changeInfo'] = $REV;
1330b24d9195SAndreas Gohr    } else if(!file_exists($svdta['file'])) {
1331b24d9195SAndreas Gohr        $svdta['changeType'] = DOKU_CHANGE_TYPE_CREATE;
1332b24d9195SAndreas Gohr    } else if(trim($text) == '') {
1333b24d9195SAndreas Gohr        // empty or whitespace only content deletes
1334b24d9195SAndreas Gohr        $svdta['changeType'] = DOKU_CHANGE_TYPE_DELETE;
1335b24d9195SAndreas Gohr        // autoset summary on deletion
1336655ddc1dSGerrit Uitslag        if(blank($svdta['summary'])) {
1337655ddc1dSGerrit Uitslag            $svdta['summary'] = $lang['deleted'];
1338655ddc1dSGerrit Uitslag        }
1339b24d9195SAndreas Gohr    } else if($minor && $conf['useacl'] && $INPUT->server->str('REMOTE_USER')) {
1340b24d9195SAndreas Gohr        //minor edits only for logged in users
1341b24d9195SAndreas Gohr        $svdta['changeType'] = DOKU_CHANGE_TYPE_MINOR_EDIT;
1342f3f0262cSandi    }
1343f3f0262cSandi
1344e1d9dcc8SAndreas Gohr    $event = new Event('COMMON_WIKIPAGE_SAVE', $svdta);
1345b24d9195SAndreas Gohr    if(!$event->advise_before()) return;
1346f3f0262cSandi
1347b24d9195SAndreas Gohr    // if the content has not been changed, no save happens (plugins may override this)
1348b24d9195SAndreas Gohr    if(!$svdta['contentChanged']) return;
1349b24d9195SAndreas Gohr
1350b24d9195SAndreas Gohr    detectExternalEdit($id);
1351f3f0262cSandi
13524b5aebc1SGerrit Uitslag    if(
13534b5aebc1SGerrit Uitslag        $svdta['changeType'] == DOKU_CHANGE_TYPE_CREATE ||
13544b5aebc1SGerrit Uitslag        ($svdta['changeType'] == DOKU_CHANGE_TYPE_REVERT && !file_exists($svdta['file']))
13554b5aebc1SGerrit Uitslag    ) {
1356ac3ed4afSGerrit Uitslag        $filesize_old = 0;
1357ac3ed4afSGerrit Uitslag    } else {
13582966355bSGerrit Uitslag        $filesize_old = filesize($svdta['file']);
1359ac3ed4afSGerrit Uitslag    }
1360b24d9195SAndreas Gohr    if($svdta['changeType'] == DOKU_CHANGE_TYPE_DELETE) {
136130725328SGabriel Birke        // Send "update" event with empty data, so plugins can react to page deletion
1362b24d9195SAndreas Gohr        $data = array(array($svdta['file'], '', false), getNS($id), noNS($id), false);
1363cbb44eabSAndreas Gohr        Event::createAndTrigger('IO_WIKIPAGE_WRITE', $data);
1364e45b34cdSBen Coburn        // pre-save deleted revision
1365b24d9195SAndreas Gohr        @touch($svdta['file']);
136646844156SBen Coburn        clearstatcache();
13672d69eb44SMichael Hamann        $svdta['newRevision'] = saveOldRevision($id);
1368e1f3d9e1SEsther Brunner        // remove empty file
1369b24d9195SAndreas Gohr        @unlink($svdta['file']);
1370ac3ed4afSGerrit Uitslag        $filesize_new = 0;
137164159a61SAndreas Gohr        // don't remove old meta info as it should be saved, plugins can use
137264159a61SAndreas Gohr        // IO_WIKIPAGE_WRITE for removing their metadata...
1373c5f92742SMichael Hamann        // purge non-persistant meta data
13743d1f9ec3SMichael Klier        p_purge_metadata($id);
137553d6ccfeSandi        // remove empty namespaces
1376cc7d0c94SBen Coburn        io_sweepNS($id, 'datadir');
1377cc7d0c94SBen Coburn        io_sweepNS($id, 'mediadir');
1378f3f0262cSandi    } else {
1379cc7d0c94SBen Coburn        // save file (namespace dir is created in io_writeWikiPage)
138033d979e7SMichael Große        io_writeWikiPage($svdta['file'], $svdta['newContent'], $id);
138146844156SBen Coburn        // pre-save the revision, to keep the attic in sync
1382b24d9195SAndreas Gohr        $svdta['newRevision'] = saveOldRevision($id);
13832966355bSGerrit Uitslag        $filesize_new = filesize($svdta['file']);
1384f3f0262cSandi    }
13852966355bSGerrit Uitslag    $svdta['sizechange'] = $filesize_new - $filesize_old;
1386f3f0262cSandi
1387b24d9195SAndreas Gohr    $event->advise_after();
138871726d78SBen Coburn
138964159a61SAndreas Gohr    addLogEntry(
139064159a61SAndreas Gohr        $svdta['newRevision'],
139164159a61SAndreas Gohr        $svdta['id'],
139264159a61SAndreas Gohr        $svdta['changeType'],
139364159a61SAndreas Gohr        $svdta['summary'],
139464159a61SAndreas Gohr        $svdta['changeInfo'],
139564159a61SAndreas Gohr        null,
139664159a61SAndreas Gohr        $svdta['sizechange']
139764159a61SAndreas Gohr    );
1398ac3ed4afSGerrit Uitslag
139926a0801fSAndreas Gohr    // send notify mails
140083734cddSPhy    notify($svdta['id'], 'admin', $svdta['oldRevision'], $svdta['summary'], $minor, $svdta['newRevision']);
140183734cddSPhy    notify($svdta['id'], 'subscribers', $svdta['oldRevision'], $svdta['summary'], $minor, $svdta['newRevision']);
1402f3f0262cSandi
1403ce6b63d9Schris    // update the purgefile (timestamp of the last time anything within the wiki was changed)
140498407a7aSandi    io_saveFile($conf['cachedir'].'/purgefile', time());
14052eccbdaaSGina Haeussge
14062eccbdaaSGina Haeussge    // if useheading is enabled, purge the cache of all linking pages
1407fe9ec250SChris Smith    if(useHeading('content')) {
140807ff0babSMichael Hamann        $pages = ft_backlinks($id, true);
14092eccbdaaSGina Haeussge        foreach($pages as $page) {
14100db5771eSMichael Große            $cache = new CacheRenderer($page, wikiFN($page), 'xhtml');
14112eccbdaaSGina Haeussge            $cache->removeCache();
14122eccbdaaSGina Haeussge        }
14132eccbdaaSGina Haeussge    }
1414f3f0262cSandi}
1415f3f0262cSandi
1416f3f0262cSandi/**
1417f3f0262cSandi * moves the current version to the attic and returns its
1418f3f0262cSandi * revision date
141915fae107Sandi *
142015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1421140cfbcdSGerrit Uitslag *
1422140cfbcdSGerrit Uitslag * @param string $id page id
1423140cfbcdSGerrit Uitslag * @return int|string revision timestamp
1424f3f0262cSandi */
1425f3f0262cSandifunction saveOldRevision($id) {
1426f3f0262cSandi    $oldf = wikiFN($id);
142779e79377SAndreas Gohr    if(!file_exists($oldf)) return '';
1428f3f0262cSandi    $date = filemtime($oldf);
1429f3f0262cSandi    $newf = wikiFN($id, $date);
1430cc7d0c94SBen Coburn    io_writeWikiPage($newf, rawWiki($id), $id, $date);
1431f3f0262cSandi    return $date;
1432f3f0262cSandi}
1433f3f0262cSandi
1434f3f0262cSandi/**
1435fde10de4SAdrian Lang * Sends a notify mail on page change or registration
143626a0801fSAndreas Gohr *
143726a0801fSAndreas Gohr * @param string     $id       The changed page
1438fde10de4SAdrian Lang * @param string     $who      Who to notify (admin|subscribers|register)
14393272d797SAndreas Gohr * @param int|string $rev Old page revision
144026a0801fSAndreas Gohr * @param string     $summary  What changed
144190033e9dSAndreas Gohr * @param boolean    $minor    Is this a minor edit?
144242ea7f44SGerrit Uitslag * @param string[]   $replace  Additional string substitutions, @KEY@ to be replaced by value
144383734cddSPhy * @param int|string $current_rev  New page revision
14443272d797SAndreas Gohr * @return bool
1445140cfbcdSGerrit Uitslag *
144615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1447f3f0262cSandi */
144883734cddSPhyfunction notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array(), $current_rev = false) {
1449f3f0262cSandi    global $conf;
1450585bf44eSChristopher Smith    /* @var Input $INPUT */
1451585bf44eSChristopher Smith    global $INPUT;
1452b158d625SSteven Danz
14536df843eeSAndreas Gohr    // decide if there is something to do, eg. whom to mail
145426a0801fSAndreas Gohr    if($who == 'admin') {
14553272d797SAndreas Gohr        if(empty($conf['notify'])) return false; //notify enabled?
14562ed38036SAndreas Gohr        $tpl = 'mailtext';
145726a0801fSAndreas Gohr        $to  = $conf['notify'];
145826a0801fSAndreas Gohr    } elseif($who == 'subscribers') {
145984c1127cSAndreas Gohr        if(!actionOK('subscribe')) return false; //subscribers enabled?
1460585bf44eSChristopher Smith        if($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
14610bb37868SGerrit Uitslag        $data = array('id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace);
1462cbb44eabSAndreas Gohr        Event::createAndTrigger(
14633272d797SAndreas Gohr            'COMMON_NOTIFY_ADDRESSLIST', $data,
1464c8cc4053SAndreas Gohr            array(new SubscriberManager(), 'notifyAddresses')
14653272d797SAndreas Gohr        );
14662ed38036SAndreas Gohr        $to = $data['addresslist'];
14672ed38036SAndreas Gohr        if(empty($to)) return false;
14682ed38036SAndreas Gohr        $tpl = 'subscr_single';
146926a0801fSAndreas Gohr    } else {
14703272d797SAndreas Gohr        return false; //just to be safe
147126a0801fSAndreas Gohr    }
147226a0801fSAndreas Gohr
14736df843eeSAndreas Gohr    // prepare content
1474704a815fSMichael Große    $subscription = new PageSubscriptionSender();
147583734cddSPhy    return $subscription->sendPageDiff($to, $tpl, $id, $rev, $summary, $current_rev);
1476f3f0262cSandi}
14772ed38036SAndreas Gohr
147815fae107Sandi/**
147971f7bde7SAndreas Gohr * extracts the query from a search engine referrer
148015fae107Sandi *
148115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
148271f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1483140cfbcdSGerrit Uitslag *
1484140cfbcdSGerrit Uitslag * @return array|string
1485f3f0262cSandi */
1486f3f0262cSandifunction getGoogleQuery() {
1487585bf44eSChristopher Smith    /* @var Input $INPUT */
1488585bf44eSChristopher Smith    global $INPUT;
1489585bf44eSChristopher Smith
1490585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_REFERER')) {
1491c66972f2SAdrian Lang        return '';
1492c66972f2SAdrian Lang    }
1493585bf44eSChristopher Smith    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1494f3f0262cSandi
1495079b3ac1SAndreas Gohr    // only handle common SEs
1496079b3ac1SAndreas Gohr    if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/',$url['host'])) return '';
1497e4d8a516SKazutaka Miyasaka
1498079b3ac1SAndreas Gohr    $query = array();
1499f3f0262cSandi    parse_str($url['query'], $query);
1500e4d8a516SKazutaka Miyasaka
1501c66972f2SAdrian Lang    $q = '';
1502079b3ac1SAndreas Gohr    if(isset($query['q'])){
1503079b3ac1SAndreas Gohr        $q = $query['q'];
1504079b3ac1SAndreas Gohr    }elseif(isset($query['p'])){
1505079b3ac1SAndreas Gohr        $q = $query['p'];
1506079b3ac1SAndreas Gohr    }elseif(isset($query['query'])){
1507079b3ac1SAndreas Gohr        $q = $query['query'];
1508079b3ac1SAndreas Gohr    }
1509079b3ac1SAndreas Gohr    $q = trim($q);
1510f3f0262cSandi
1511079b3ac1SAndreas Gohr    if(!$q) return '';
1512c7dc833bSPhy    // ignore if query includes a full URL
1513c7dc833bSPhy    if(strpos($q, '//') !== false) return '';
15146531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1515f93b3b50SAndreas Gohr    return $q;
1516f3f0262cSandi}
1517f3f0262cSandi
1518f3f0262cSandi/**
1519f3f0262cSandi * Return the human readable size of a file
1520f3f0262cSandi *
1521f3f0262cSandi * @param int $size A file size
1522f3f0262cSandi * @param int $dec A number of decimal places
152374160ca1SGerrit Uitslag * @return string human readable size
1524140cfbcdSGerrit Uitslag *
1525f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1526f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1527f3f0262cSandi * @version     1.0.0
1528f3f0262cSandi */
1529f31d5b73Sandifunction filesize_h($size, $dec = 1) {
1530f3f0262cSandi    $sizes = array('B', 'KB', 'MB', 'GB');
1531f3f0262cSandi    $count = count($sizes);
1532f3f0262cSandi    $i     = 0;
1533f3f0262cSandi
1534f3f0262cSandi    while($size >= 1024 && ($i < $count - 1)) {
1535f3f0262cSandi        $size /= 1024;
1536f3f0262cSandi        $i++;
1537f3f0262cSandi    }
1538f3f0262cSandi
1539ef08383eSAndreas Gohr    return round($size, $dec)."\xC2\xA0".$sizes[$i]; //non-breaking space
1540f3f0262cSandi}
1541f3f0262cSandi
154215fae107Sandi/**
1543c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1544c57e365eSAndreas Gohr *
1545c57e365eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1546140cfbcdSGerrit Uitslag *
1547140cfbcdSGerrit Uitslag * @param int $dt timestamp
1548140cfbcdSGerrit Uitslag * @return string
1549c57e365eSAndreas Gohr */
1550c57e365eSAndreas Gohrfunction datetime_h($dt) {
1551c57e365eSAndreas Gohr    global $lang;
1552c57e365eSAndreas Gohr
1553c57e365eSAndreas Gohr    $ago = time() - $dt;
1554c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1555c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1556c57e365eSAndreas Gohr    }
1557c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 2) {
1558c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1559c57e365eSAndreas Gohr    }
1560c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 7 * 2) {
1561c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1562c57e365eSAndreas Gohr    }
1563c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 2) {
1564c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1565c57e365eSAndreas Gohr    }
1566c57e365eSAndreas Gohr    if($ago > 60 * 60 * 2) {
1567c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago / (60 * 60)));
1568c57e365eSAndreas Gohr    }
1569c57e365eSAndreas Gohr    if($ago > 60 * 2) {
1570c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago / (60)));
1571c57e365eSAndreas Gohr    }
1572c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1573c57e365eSAndreas Gohr}
1574c57e365eSAndreas Gohr
1575c57e365eSAndreas Gohr/**
1576f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1577f2263577SAndreas Gohr *
1578f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1579f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1580f2263577SAndreas Gohr *
1581f2263577SAndreas Gohr * @see datetime_h
1582f2263577SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1583140cfbcdSGerrit Uitslag *
1584140cfbcdSGerrit Uitslag * @param int|null $dt      timestamp when given, null will take current timestamp
1585140cfbcdSGerrit Uitslag * @param string   $format  empty default to $conf['dformat'], or provide format as recognized by strftime()
1586140cfbcdSGerrit Uitslag * @return string
1587f2263577SAndreas Gohr */
1588f2263577SAndreas Gohrfunction dformat($dt = null, $format = '') {
1589f2263577SAndreas Gohr    global $conf;
1590f2263577SAndreas Gohr
1591f2263577SAndreas Gohr    if(is_null($dt)) $dt = time();
1592f2263577SAndreas Gohr    $dt = (int) $dt;
1593f2263577SAndreas Gohr    if(!$format) $format = $conf['dformat'];
1594f2263577SAndreas Gohr
1595f2263577SAndreas Gohr    $format = str_replace('%f', datetime_h($dt), $format);
1596f2263577SAndreas Gohr    return strftime($format, $dt);
1597f2263577SAndreas Gohr}
1598f2263577SAndreas Gohr
1599f2263577SAndreas Gohr/**
1600c4f79b71SMichael Hamann * Formats a timestamp as ISO 8601 date
1601c4f79b71SMichael Hamann *
1602c4f79b71SMichael Hamann * @author <ungu at terong dot com>
160359752844SAnders Sandblad * @link http://php.net/manual/en/function.date.php#54072
1604140cfbcdSGerrit Uitslag *
16057e8500eeSGerrit Uitslag * @param int $int_date current date in UNIX timestamp
16063272d797SAndreas Gohr * @return string
1607c4f79b71SMichael Hamann */
1608c4f79b71SMichael Hamannfunction date_iso8601($int_date) {
1609c4f79b71SMichael Hamann    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1610c4f79b71SMichael Hamann    $pre_timezone = date('O', $int_date);
1611c4f79b71SMichael Hamann    $time_zone    = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1612c4f79b71SMichael Hamann    $date_mod .= $time_zone;
1613c4f79b71SMichael Hamann    return $date_mod;
1614c4f79b71SMichael Hamann}
1615c4f79b71SMichael Hamann
1616c4f79b71SMichael Hamann/**
161700a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
161800a7b5adSEsther Brunner *
161900a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
162000a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
1621140cfbcdSGerrit Uitslag *
1622140cfbcdSGerrit Uitslag * @param string $email email address
1623140cfbcdSGerrit Uitslag * @return string
162400a7b5adSEsther Brunner */
162500a7b5adSEsther Brunnerfunction obfuscate($email) {
162600a7b5adSEsther Brunner    global $conf;
162700a7b5adSEsther Brunner
162800a7b5adSEsther Brunner    switch($conf['mailguard']) {
162900a7b5adSEsther Brunner        case 'visible' :
163000a7b5adSEsther Brunner            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
163100a7b5adSEsther Brunner            return strtr($email, $obfuscate);
163200a7b5adSEsther Brunner
163300a7b5adSEsther Brunner        case 'hex' :
1634c1ec88ceSAndreas Gohr            return \dokuwiki\Utf8\Conversion::toHtml($email, true);
163500a7b5adSEsther Brunner
163600a7b5adSEsther Brunner        case 'none' :
163700a7b5adSEsther Brunner        default :
163800a7b5adSEsther Brunner            return $email;
163900a7b5adSEsther Brunner    }
164000a7b5adSEsther Brunner}
164100a7b5adSEsther Brunner
164200a7b5adSEsther Brunner/**
164389541d4bSAndreas Gohr * Removes quoting backslashes
164489541d4bSAndreas Gohr *
164589541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1646140cfbcdSGerrit Uitslag *
1647140cfbcdSGerrit Uitslag * @param string $string
1648140cfbcdSGerrit Uitslag * @param string $char backslashed character
1649140cfbcdSGerrit Uitslag * @return string
165089541d4bSAndreas Gohr */
165189541d4bSAndreas Gohrfunction unslash($string, $char = "'") {
165289541d4bSAndreas Gohr    return str_replace('\\'.$char, $char, $string);
165389541d4bSAndreas Gohr}
165489541d4bSAndreas Gohr
165573038c47SAndreas Gohr/**
165673038c47SAndreas Gohr * Convert php.ini shorthands to byte
165773038c47SAndreas Gohr *
1658a81f3d99SAndreas Gohr * On 32 bit systems values >= 2GB will fail!
1659140cfbcdSGerrit Uitslag *
1660a81f3d99SAndreas Gohr * -1 (infinite size) will be reported as -1
1661a81f3d99SAndreas Gohr *
1662a81f3d99SAndreas Gohr * @link   https://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
1663a81f3d99SAndreas Gohr * @param string $value PHP size shorthand
1664a81f3d99SAndreas Gohr * @return int
166573038c47SAndreas Gohr */
1666a81f3d99SAndreas Gohrfunction php_to_byte($value) {
1667f5c0c80bSAndreas Gohr    switch (strtoupper(substr($value,-1))) {
166873038c47SAndreas Gohr        case 'G':
1669a81f3d99SAndreas Gohr            $ret = intval(substr($value, 0, -1)) * 1024 * 1024 * 1024;
167073038c47SAndreas Gohr            break;
167173038c47SAndreas Gohr        case 'M':
1672a81f3d99SAndreas Gohr            $ret = intval(substr($value, 0, -1)) * 1024 * 1024;
1673a81f3d99SAndreas Gohr            break;
167473038c47SAndreas Gohr        case 'K':
1675a81f3d99SAndreas Gohr            $ret = intval(substr($value, 0, -1)) * 1024;
167673038c47SAndreas Gohr            break;
16779eeeb775SAndreas Gohr        default:
1678a81f3d99SAndreas Gohr            $ret = intval($value);
167949cbd23eSOtto Vainio            break;
168073038c47SAndreas Gohr    }
168173038c47SAndreas Gohr    return $ret;
168273038c47SAndreas Gohr}
168373038c47SAndreas Gohr
1684546d3a99SAndreas Gohr/**
1685546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1686140cfbcdSGerrit Uitslag *
1687140cfbcdSGerrit Uitslag * @param string $string
1688140cfbcdSGerrit Uitslag * @return string
1689546d3a99SAndreas Gohr */
1690546d3a99SAndreas Gohrfunction preg_quote_cb($string) {
1691546d3a99SAndreas Gohr    return preg_quote($string, '/');
1692546d3a99SAndreas Gohr}
169373038c47SAndreas Gohr
1694bd2f6c2fSAndreas Gohr/**
1695bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1696bd2f6c2fSAndreas Gohr *
1697c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1698bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1699bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1700bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1701bd2f6c2fSAndreas Gohr *
1702bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1703bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1704bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1705bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1706bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
17073272d797SAndreas Gohr * @return string
1708bd2f6c2fSAndreas Gohr */
1709a5d27328SAndreas Gohrfunction shorten($keep, $short, $max, $min = 9, $char = '…') {
17108cbc5ee8SAndreas Gohr    $max = $max - \dokuwiki\Utf8\PhpString::strlen($keep);
1711bd2f6c2fSAndreas Gohr    if($max < $min) return $keep;
17128cbc5ee8SAndreas Gohr    $len = \dokuwiki\Utf8\PhpString::strlen($short);
1713bd2f6c2fSAndreas Gohr    if($len <= $max) return $keep.$short;
1714bd2f6c2fSAndreas Gohr    $half = floor($max / 2);
17156ce3e5f8SAndreas Gohr    return $keep .
17166ce3e5f8SAndreas Gohr        \dokuwiki\Utf8\PhpString::substr($short, 0, $half - 1) .
17176ce3e5f8SAndreas Gohr        $char .
17186ce3e5f8SAndreas Gohr        \dokuwiki\Utf8\PhpString::substr($short, $len - $half);
1719bd2f6c2fSAndreas Gohr}
1720bd2f6c2fSAndreas Gohr
1721dc58b6f4SAndy Webber/**
1722dc58b6f4SAndy Webber * Return the users real name or e-mail address for use
1723dc58b6f4SAndy Webber * in page footer and recent changes pages
1724dc58b6f4SAndy Webber *
1725b4b6c9a1SGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
172615f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1727c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
172815f3bc49SGerrit Uitslag *
1729dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1730dc58b6f4SAndy Webber */
173115f3bc49SGerrit Uitslagfunction editorinfo($username, $textonly = false) {
1732cd4635eeSGerrit Uitslag    return userlink($username, $textonly);
1733dc58b6f4SAndy Webber}
1734dc58b6f4SAndy Webber
173560a396c8SGerrit Uitslag/**
173660a396c8SGerrit Uitslag * Returns users realname w/o link
173760a396c8SGerrit Uitslag *
1738f168548cSGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
173915f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1740c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
174160a396c8SGerrit Uitslag *
174260a396c8SGerrit Uitslag * @triggers COMMON_USER_LINK
174360a396c8SGerrit Uitslag */
1744cd4635eeSGerrit Uitslagfunction userlink($username = null, $textonly = false) {
174560a396c8SGerrit Uitslag    global $conf, $INFO;
1746e1d9dcc8SAndreas Gohr    /** @var AuthPlugin $auth */
174760a396c8SGerrit Uitslag    global $auth;
174830f6ec4bSGerrit Uitslag    /** @var Input $INPUT */
174930f6ec4bSGerrit Uitslag    global $INPUT;
175060a396c8SGerrit Uitslag
175160a396c8SGerrit Uitslag    // prepare initial event data
175260a396c8SGerrit Uitslag    $data = array(
175360a396c8SGerrit Uitslag        'username' => $username, // the unique user name
175460a396c8SGerrit Uitslag        'name' => '',
175560a396c8SGerrit Uitslag        'link' => array( //setting 'link' to false disables linking
175660a396c8SGerrit Uitslag                         'target' => '',
175760a396c8SGerrit Uitslag                         'pre' => '',
175860a396c8SGerrit Uitslag                         'suf' => '',
175960a396c8SGerrit Uitslag                         'style' => '',
176060a396c8SGerrit Uitslag                         'more' => '',
176160a396c8SGerrit Uitslag                         'url' => '',
176260a396c8SGerrit Uitslag                         'title' => '',
176360a396c8SGerrit Uitslag                         'class' => ''
176460a396c8SGerrit Uitslag        ),
17654d5fc927SGerrit Uitslag        'userlink' => '', // formatted user name as will be returned
176615f3bc49SGerrit Uitslag        'textonly' => $textonly
176760a396c8SGerrit Uitslag    );
176862c8004eSGerrit Uitslag    if($username === null) {
176930f6ec4bSGerrit Uitslag        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
177015f3bc49SGerrit Uitslag        if($textonly){
177115f3bc49SGerrit Uitslag            $data['name'] = $INFO['userinfo']['name']. ' (' . $INPUT->server->str('REMOTE_USER') . ')';
177215f3bc49SGerrit Uitslag        }else {
177364159a61SAndreas Gohr            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> '.
177464159a61SAndreas Gohr                '(<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
177560a396c8SGerrit Uitslag        }
177615f3bc49SGerrit Uitslag    }
177760a396c8SGerrit Uitslag
1778e1d9dcc8SAndreas Gohr    $evt = new Event('COMMON_USER_LINK', $data);
177960a396c8SGerrit Uitslag    if($evt->advise_before(true)) {
178060a396c8SGerrit Uitslag        if(empty($data['name'])) {
178160a396c8SGerrit Uitslag            if($auth) $info = $auth->getUserData($username);
178265833968SGerrit Uitslag            if($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1783dc58b6f4SAndy Webber                switch($conf['showuseras']) {
1784dc58b6f4SAndy Webber                    case 'username':
17857f081821SGerrit Uitslag                    case 'username_link':
178615f3bc49SGerrit Uitslag                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
178760a396c8SGerrit Uitslag                        break;
1788dc58b6f4SAndy Webber                    case 'email':
1789dc58b6f4SAndy Webber                    case 'email_link':
179060a396c8SGerrit Uitslag                        $data['name'] = obfuscate($info['mail']);
179160a396c8SGerrit Uitslag                        break;
1792dc58b6f4SAndy Webber                }
179365833968SGerrit Uitslag            } else {
179465833968SGerrit Uitslag                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
179560a396c8SGerrit Uitslag            }
179660a396c8SGerrit Uitslag        }
17977f081821SGerrit Uitslag
17987f081821SGerrit Uitslag        /** @var Doku_Renderer_xhtml $xhtml_renderer */
17997f081821SGerrit Uitslag        static $xhtml_renderer = null;
18007f081821SGerrit Uitslag
180115f3bc49SGerrit Uitslag        if(!$data['textonly'] && empty($data['link']['url'])) {
18027f081821SGerrit Uitslag
18037f081821SGerrit Uitslag            if(in_array($conf['showuseras'], array('email_link', 'username_link'))) {
180460a396c8SGerrit Uitslag                if(!isset($info)) {
180560a396c8SGerrit Uitslag                    if($auth) $info = $auth->getUserData($username);
180660a396c8SGerrit Uitslag                }
180760a396c8SGerrit Uitslag                if(isset($info) && $info) {
18087f081821SGerrit Uitslag                    if($conf['showuseras'] == 'email_link') {
180960a396c8SGerrit Uitslag                        $data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
1810dc58b6f4SAndy Webber                    } else {
18117f081821SGerrit Uitslag                        if(is_null($xhtml_renderer)) {
18127f081821SGerrit Uitslag                            $xhtml_renderer = p_get_renderer('xhtml');
18137f081821SGerrit Uitslag                        }
18147f081821SGerrit Uitslag                        if(empty($xhtml_renderer->interwiki)) {
18157f081821SGerrit Uitslag                            $xhtml_renderer->interwiki = getInterwiki();
18167f081821SGerrit Uitslag                        }
18177f081821SGerrit Uitslag                        $shortcut = 'user';
1818533772e1SGerrit Uitslag                        $exists = null;
18196496c33fSGerrit Uitslag                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
18202a2a43c4SGerrit Uitslag                        $data['link']['class'] .= ' interwiki iw_user';
18216496c33fSGerrit Uitslag                        if($exists !== null) {
18226496c33fSGerrit Uitslag                            if($exists) {
18236496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink1';
18246496c33fSGerrit Uitslag                            } else {
18256496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink2';
18266496c33fSGerrit Uitslag                                $data['link']['rel'] = 'nofollow';
18276496c33fSGerrit Uitslag                            }
18286496c33fSGerrit Uitslag                        }
1829dc58b6f4SAndy Webber                    }
1830dc58b6f4SAndy Webber                } else {
183115f3bc49SGerrit Uitslag                    $data['textonly'] = true;
1832dc58b6f4SAndy Webber                }
183360a396c8SGerrit Uitslag
183460a396c8SGerrit Uitslag            } else {
183515f3bc49SGerrit Uitslag                $data['textonly'] = true;
183660a396c8SGerrit Uitslag            }
183760a396c8SGerrit Uitslag        }
183860a396c8SGerrit Uitslag
183915f3bc49SGerrit Uitslag        if($data['textonly']) {
18404d5fc927SGerrit Uitslag            $data['userlink'] = $data['name'];
184160a396c8SGerrit Uitslag        } else {
184260a396c8SGerrit Uitslag            $data['link']['name'] = $data['name'];
184360a396c8SGerrit Uitslag            if(is_null($xhtml_renderer)) {
184460a396c8SGerrit Uitslag                $xhtml_renderer = p_get_renderer('xhtml');
184560a396c8SGerrit Uitslag            }
18464d5fc927SGerrit Uitslag            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
184760a396c8SGerrit Uitslag        }
184860a396c8SGerrit Uitslag    }
184960a396c8SGerrit Uitslag    $evt->advise_after();
185060a396c8SGerrit Uitslag    unset($evt);
185160a396c8SGerrit Uitslag
18524d5fc927SGerrit Uitslag    return $data['userlink'];
1853066fee30SAndreas Gohr}
1854066fee30SAndreas Gohr
1855066fee30SAndreas Gohr/**
1856066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1857066fee30SAndreas Gohr * When no image exists, returns an empty string
1858066fee30SAndreas Gohr *
1859066fee30SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1860140cfbcdSGerrit Uitslag *
1861066fee30SAndreas Gohr * @param  string $type - type of image 'badge' or 'button'
18623272d797SAndreas Gohr * @return string
1863066fee30SAndreas Gohr */
1864066fee30SAndreas Gohrfunction license_img($type) {
1865066fee30SAndreas Gohr    global $license;
1866066fee30SAndreas Gohr    global $conf;
1867066fee30SAndreas Gohr    if(!$conf['license']) return '';
1868066fee30SAndreas Gohr    if(!is_array($license[$conf['license']])) return '';
1869066fee30SAndreas Gohr    $try   = array();
1870066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1871066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1872066fee30SAndreas Gohr    if(substr($conf['license'], 0, 3) == 'cc-') {
1873066fee30SAndreas Gohr        $try[] = 'lib/images/license/'.$type.'/cc.png';
1874066fee30SAndreas Gohr    }
1875066fee30SAndreas Gohr    foreach($try as $src) {
187679e79377SAndreas Gohr        if(file_exists(DOKU_INC.$src)) return $src;
1877066fee30SAndreas Gohr    }
1878066fee30SAndreas Gohr    return '';
1879dc58b6f4SAndy Webber}
1880dc58b6f4SAndy Webber
188113c08e2fSMichael Klier/**
188213c08e2fSMichael Klier * Checks if the given amount of memory is available
188313c08e2fSMichael Klier *
188413c08e2fSMichael Klier * If the memory_get_usage() function is not available the
188513c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
188613c08e2fSMichael Klier *
188713c08e2fSMichael Klier * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
188813c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
18893272d797SAndreas Gohr *
18903272d797SAndreas Gohr * @param int  $mem    Size of memory you want to allocate in bytes
1891140cfbcdSGerrit Uitslag * @param int  $bytes  already allocated memory (see above)
18923272d797SAndreas Gohr * @return bool
189313c08e2fSMichael Klier */
189413c08e2fSMichael Klierfunction is_mem_available($mem, $bytes = 1048576) {
189513c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
189613c08e2fSMichael Klier    if(empty($limit)) return true; // no limit set!
1897985d6187SElenchus    if($limit == -1) return true; // unlimited
189813c08e2fSMichael Klier
189913c08e2fSMichael Klier    // parse limit to bytes
190013c08e2fSMichael Klier    $limit = php_to_byte($limit);
190113c08e2fSMichael Klier
190213c08e2fSMichael Klier    // get used memory if possible
190313c08e2fSMichael Klier    if(function_exists('memory_get_usage')) {
190413c08e2fSMichael Klier        $used = memory_get_usage();
190549eb6e38SAndreas Gohr    } else {
190649eb6e38SAndreas Gohr        $used = $bytes;
190713c08e2fSMichael Klier    }
190813c08e2fSMichael Klier
190913c08e2fSMichael Klier    if($used + $mem > $limit) {
191013c08e2fSMichael Klier        return false;
191113c08e2fSMichael Klier    }
191213c08e2fSMichael Klier
191313c08e2fSMichael Klier    return true;
191413c08e2fSMichael Klier}
191513c08e2fSMichael Klier
1916af2408d5SAndreas Gohr/**
1917af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1918af2408d5SAndreas Gohr *
1919af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1920af2408d5SAndreas Gohr *
1921af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1922af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1923140cfbcdSGerrit Uitslag *
1924140cfbcdSGerrit Uitslag * @param string $url url being directed to
1925af2408d5SAndreas Gohr */
1926af2408d5SAndreas Gohrfunction send_redirect($url) {
192798ca30d2SAndreas Gohr    $url = stripctl($url); // defend against HTTP Response Splitting
192898ca30d2SAndreas Gohr
1929585bf44eSChristopher Smith    /* @var Input $INPUT */
1930585bf44eSChristopher Smith    global $INPUT;
1931585bf44eSChristopher Smith
19320181f021SAndreas Gohr    //are there any undisplayed messages? keep them in session for display
19330181f021SAndreas Gohr    global $MSG;
19340181f021SAndreas Gohr    if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
19350181f021SAndreas Gohr        //reopen session, store data and close session again
19360181f021SAndreas Gohr        @session_start();
19370181f021SAndreas Gohr        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
19380181f021SAndreas Gohr    }
19390181f021SAndreas Gohr
1940d4869846SAndreas Gohr    // always close the session
1941d4869846SAndreas Gohr    session_write_close();
1942d4869846SAndreas Gohr
1943af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
1944585bf44eSChristopher Smith    if($INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1945585bf44eSChristopher Smith        (strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) &&
1946585bf44eSChristopher Smith        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
19473272d797SAndreas Gohr        $matches[1] < 6
19483272d797SAndreas Gohr    ) {
1949af2408d5SAndreas Gohr        header('Refresh: 0;url='.$url);
1950af2408d5SAndreas Gohr    } else {
1951af2408d5SAndreas Gohr        header('Location: '.$url);
1952af2408d5SAndreas Gohr    }
195381781cb6SAndreas Gohr
1954572dc222SLarsDW223    // no exits during unit tests
195527c0c399SAndreas Gohr    if(defined('DOKU_UNITTEST')) {
195627c0c399SAndreas Gohr        // pass info about the redirect back to the test suite
195727c0c399SAndreas Gohr        $testRequest = TestRequest::getRunning();
195827c0c399SAndreas Gohr        if($testRequest !== null) {
195927c0c399SAndreas Gohr            $testRequest->addData('send_redirect', $url);
196027c0c399SAndreas Gohr        }
1961572dc222SLarsDW223        return;
1962572dc222SLarsDW223    }
196327c0c399SAndreas Gohr
1964af2408d5SAndreas Gohr    exit;
1965af2408d5SAndreas Gohr}
1966af2408d5SAndreas Gohr
19675b75cd1fSAdrian Lang/**
19685b75cd1fSAdrian Lang * Validate a value using a set of valid values
19695b75cd1fSAdrian Lang *
19705b75cd1fSAdrian Lang * This function checks whether a specified value is set and in the array
19715b75cd1fSAdrian Lang * $valid_values. If not, the function returns a default value or, if no
19725b75cd1fSAdrian Lang * default is specified, throws an exception.
19735b75cd1fSAdrian Lang *
19745b75cd1fSAdrian Lang * @param string $param        The name of the parameter
19755b75cd1fSAdrian Lang * @param array  $valid_values A set of valid values; Optionally a default may
19765b75cd1fSAdrian Lang *                             be marked by the key “default”.
19775b75cd1fSAdrian Lang * @param array  $array        The array containing the value (typically $_POST
19785b75cd1fSAdrian Lang *                             or $_GET)
19795b75cd1fSAdrian Lang * @param string $exc          The text of the raised exception
19805b75cd1fSAdrian Lang *
19813272d797SAndreas Gohr * @throws Exception
19823272d797SAndreas Gohr * @return mixed
19835b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
19845b75cd1fSAdrian Lang */
19855b75cd1fSAdrian Langfunction valid_input_set($param, $valid_values, $array, $exc = '') {
19865b75cd1fSAdrian Lang    if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
19875b75cd1fSAdrian Lang        return $array[$param];
19885b75cd1fSAdrian Lang    } elseif(isset($valid_values['default'])) {
19895b75cd1fSAdrian Lang        return $valid_values['default'];
19905b75cd1fSAdrian Lang    } else {
19915b75cd1fSAdrian Lang        throw new Exception($exc);
19925b75cd1fSAdrian Lang    }
19935b75cd1fSAdrian Lang}
19945b75cd1fSAdrian Lang
199563703ba5SAndreas Gohr/**
199663703ba5SAndreas Gohr * Read a preference from the DokuWiki cookie
1997646a531aSChristopher Smith * (remembering both keys & values are urlencoded)
1998140cfbcdSGerrit Uitslag *
1999140cfbcdSGerrit Uitslag * @param string $pref     preference key
2000b4b6c9a1SGerrit Uitslag * @param mixed  $default  value returned when preference not found
2001140cfbcdSGerrit Uitslag * @return string preference value
200263703ba5SAndreas Gohr */
2003554a8c9fSAdrian Langfunction get_doku_pref($pref, $default) {
2004646a531aSChristopher Smith    $enc_pref = urlencode($pref);
200506c9ee33SMarius van Witzenburg    if(isset($_COOKIE['DOKU_PREFS']) && strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
2006554a8c9fSAdrian Lang        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
200763703ba5SAndreas Gohr        $cnt   = count($parts);
20081c3eca7dSPhy
20091c3eca7dSPhy        // due to #2721 there might be duplicate entries,
20101c3eca7dSPhy        // so we read from the end
20111c3eca7dSPhy        for($i = $cnt-2; $i >= 0; $i -= 2) {
2012646a531aSChristopher Smith            if($parts[$i] == $enc_pref) {
2013646a531aSChristopher Smith                return urldecode($parts[$i + 1]);
2014554a8c9fSAdrian Lang            }
2015554a8c9fSAdrian Lang        }
2016554a8c9fSAdrian Lang    }
2017554a8c9fSAdrian Lang    return $default;
2018554a8c9fSAdrian Lang}
2019554a8c9fSAdrian Lang
20203c94d07bSAnika Henke/**
20213c94d07bSAnika Henke * Add a preference to the DokuWiki cookie
202236ec377eSChristopher Smith * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
20233a970889SAnika Henke * Remove it by setting $val to false
2024140cfbcdSGerrit Uitslag *
2025140cfbcdSGerrit Uitslag * @param string $pref  preference key
2026140cfbcdSGerrit Uitslag * @param string $val   preference value
20273c94d07bSAnika Henke */
20283c94d07bSAnika Henkefunction set_doku_pref($pref, $val) {
20293c94d07bSAnika Henke    global $conf;
20303c94d07bSAnika Henke    $orig = get_doku_pref($pref, false);
20313c94d07bSAnika Henke    $cookieVal = '';
20323c94d07bSAnika Henke
20331c3eca7dSPhy    if($orig !== false && ($orig !== $val)) {
20343c94d07bSAnika Henke        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
20353c94d07bSAnika Henke        $cnt   = count($parts);
203636ec377eSChristopher Smith        // urlencode $pref for the comparison
203736ec377eSChristopher Smith        $enc_pref = rawurlencode($pref);
20381c3eca7dSPhy        $seen = false;
20393c94d07bSAnika Henke        for ($i = 0; $i < $cnt; $i += 2) {
204036ec377eSChristopher Smith            if ($parts[$i] == $enc_pref) {
20411c3eca7dSPhy                if (!$seen){
20423a970889SAnika Henke                    if ($val !== false) {
204336ec377eSChristopher Smith                        $parts[$i + 1] = rawurlencode($val);
20443a970889SAnika Henke                    } else {
20453a970889SAnika Henke                        unset($parts[$i]);
20463a970889SAnika Henke                        unset($parts[$i + 1]);
20473a970889SAnika Henke                    }
20481c3eca7dSPhy                    $seen = true;
20491c3eca7dSPhy                } else {
20501c3eca7dSPhy                    // no break because we want to remove duplicate entries
20511c3eca7dSPhy                    unset($parts[$i]);
20521c3eca7dSPhy                    unset($parts[$i + 1]);
20531c3eca7dSPhy                }
20543c94d07bSAnika Henke            }
20553c94d07bSAnika Henke        }
20563c94d07bSAnika Henke        $cookieVal = implode('#', $parts);
20571c3eca7dSPhy    } else if ($orig === false && $val !== false) {
205864159a61SAndreas Gohr        $cookieVal = ($_COOKIE['DOKU_PREFS'] ? $_COOKIE['DOKU_PREFS'] . '#' : '') .
205964159a61SAndreas Gohr            rawurlencode($pref) . '#' . rawurlencode($val);
20603c94d07bSAnika Henke    }
20613c94d07bSAnika Henke
206275e4dd8aSGerrit Uitslag    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
20635833995aSPhy    if(defined('DOKU_UNITTEST')) {
20645833995aSPhy        $_COOKIE['DOKU_PREFS'] = $cookieVal;
20655833995aSPhy    }else{
206675e4dd8aSGerrit Uitslag        setcookie('DOKU_PREFS', $cookieVal, time()+365*24*3600, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
20673c94d07bSAnika Henke    }
20683c94d07bSAnika Henke}
20693c94d07bSAnika Henke
2070f8fb2d18SAndreas Gohr/**
2071f8fb2d18SAndreas Gohr * Strips source mapping declarations from given text #601
2072f8fb2d18SAndreas Gohr *
207342ea7f44SGerrit Uitslag * @param string &$text reference to the CSS or JavaScript code to clean
2074f8fb2d18SAndreas Gohr */
2075f8fb2d18SAndreas Gohrfunction stripsourcemaps(&$text){
2076f8fb2d18SAndreas Gohr    $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text);
2077f8fb2d18SAndreas Gohr}
2078f8fb2d18SAndreas Gohr
20793c27983bSAndreas Gohr/**
208071de5572SAndreas Gohr * Returns the contents of a given SVG file for embedding
20813c27983bSAndreas Gohr *
20823c27983bSAndreas Gohr * Inlining SVGs saves on HTTP requests and more importantly allows for styling them through
20833c27983bSAndreas Gohr * CSS. However it should used with small SVGs only. The $maxsize setting ensures only small
20843c27983bSAndreas Gohr * files are embedded.
20853c27983bSAndreas Gohr *
208671de5572SAndreas Gohr * This strips unneeded headers, comments and newline. The result is not a vaild standalone SVG!
208771de5572SAndreas Gohr *
20883c27983bSAndreas Gohr * @param string $file full path to the SVG file
20893c27983bSAndreas Gohr * @param int $maxsize maximum allowed size for the SVG to be embedded
209071de5572SAndreas Gohr * @return string|false the SVG content, false if the file couldn't be loaded
20913c27983bSAndreas Gohr */
20924cd2074fSAndreas Gohrfunction inlineSVG($file, $maxsize = 2048) {
20933c27983bSAndreas Gohr    $file = trim($file);
20943c27983bSAndreas Gohr    if($file === '') return false;
20953c27983bSAndreas Gohr    if(!file_exists($file)) return false;
20963c27983bSAndreas Gohr    if(filesize($file) > $maxsize) return false;
20973c27983bSAndreas Gohr    if(!is_readable($file)) return false;
20983c27983bSAndreas Gohr    $content = file_get_contents($file);
20990849fa88SAndreas Gohr    $content = preg_replace('/<!--.*?(-->)/s','', $content); // comments
21000849fa88SAndreas Gohr    $content = preg_replace('/<\?xml .*?\?>/i', '', $content); // xml header
21010849fa88SAndreas Gohr    $content = preg_replace('/<!DOCTYPE .*?>/i', '', $content); // doc type
21020849fa88SAndreas Gohr    $content = preg_replace('/>\s+</s', '><', $content); // newlines between tags
21033c27983bSAndreas Gohr    $content = trim($content);
21043c27983bSAndreas Gohr    if(substr($content, 0, 5) !== '<svg ') return false;
210571de5572SAndreas Gohr    return $content;
21063c27983bSAndreas Gohr}
21073c27983bSAndreas Gohr
2108e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
2109