xref: /dokuwiki/inc/common.php (revision c7f6b7b7a4e54be385b5ea54ae0fe82abf57997b)
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;
12b24e9c4aSSatoshi Saharause dokuwiki\File\PageFile;
13*c7f6b7b7SZebra Northuse dokuwiki\Ip;
1466f4cdd4SSatoshi Saharause dokuwiki\Logger;
15704a815fSMichael Großeuse dokuwiki\Subscriptions\PageSubscriptionSender;
1675d66495SMichael Großeuse dokuwiki\Subscriptions\SubscriberManager;
17e1d9dcc8SAndreas Gohruse dokuwiki\Extension\AuthPlugin;
18e1d9dcc8SAndreas Gohruse dokuwiki\Extension\Event;
190c3a5702SAndreas Gohr
20f3f0262cSandi/**
21d5197206Schris * Wrapper around htmlspecialchars()
22d5197206Schris *
23d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
24d5197206Schris * @see    htmlspecialchars()
25140cfbcdSGerrit Uitslag *
26140cfbcdSGerrit Uitslag * @param string $string the string being converted
27140cfbcdSGerrit Uitslag * @return string converted string
28d5197206Schris */
29d5197206Schrisfunction hsc($string) {
30f7711f2bSAndreas Gohr    return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, 'UTF-8');
31d5197206Schris}
32d5197206Schris
33d5197206Schris/**
3412dd3cbcSAndreas Gohr * A safer explode for fixed length lists
3512dd3cbcSAndreas Gohr *
3612dd3cbcSAndreas Gohr * This works just like explode(), but will always return the wanted number of elements.
3712dd3cbcSAndreas Gohr * If the $input string does not contain enough elements, the missing elements will be
3812dd3cbcSAndreas Gohr * filled up with the $default value. If the input string contains more elements, the last
3912dd3cbcSAndreas Gohr * one will NOT be split up and will still contain $separator
4012dd3cbcSAndreas Gohr *
4112dd3cbcSAndreas Gohr * @param string $separator The boundary string
4212dd3cbcSAndreas Gohr * @param string $string The input string
4312dd3cbcSAndreas Gohr * @param int $limit The number of expected elements
4412dd3cbcSAndreas Gohr * @param mixed $default The value to use when filling up missing elements
4512dd3cbcSAndreas Gohr * @see explode
4612dd3cbcSAndreas Gohr * @return array
4712dd3cbcSAndreas Gohr */
4812dd3cbcSAndreas Gohrfunction sexplode($separator, $string, $limit, $default = null)
4912dd3cbcSAndreas Gohr{
5012dd3cbcSAndreas Gohr    return array_pad(explode($separator, $string, $limit), $limit, $default);
5112dd3cbcSAndreas Gohr}
5212dd3cbcSAndreas Gohr
5312dd3cbcSAndreas Gohr/**
545b571377SAndreas Gohr * Checks if the given input is blank
555b571377SAndreas Gohr *
565b571377SAndreas Gohr * This is similar to empty() but will return false for "0".
575b571377SAndreas Gohr *
5867234204SAndreas Gohr * Please note: when you pass uninitialized variables, they will implicitly be created
5967234204SAndreas Gohr * with a NULL value without warning.
6067234204SAndreas Gohr *
6167234204SAndreas Gohr * To avoid this it's recommended to guard the call with isset like this:
6267234204SAndreas Gohr *
6367234204SAndreas Gohr * (isset($foo) && !blank($foo))
6467234204SAndreas Gohr * (!isset($foo) || blank($foo))
6567234204SAndreas Gohr *
665b571377SAndreas Gohr * @param $in
675b571377SAndreas Gohr * @param bool $trim Consider a string of whitespace to be blank
685b571377SAndreas Gohr * @return bool
695b571377SAndreas Gohr */
705b571377SAndreas Gohrfunction blank(&$in, $trim = false) {
715b571377SAndreas Gohr    if(is_null($in)) return true;
725b571377SAndreas Gohr    if(is_array($in)) return empty($in);
735b571377SAndreas Gohr    if($in === "\0") return true;
745b571377SAndreas Gohr    if($trim && trim($in) === '') return true;
755b571377SAndreas Gohr    if(strlen($in) > 0) return false;
765b571377SAndreas Gohr    return empty($in);
775b571377SAndreas Gohr}
785b571377SAndreas Gohr
795b571377SAndreas Gohr/**
80d5197206Schris * print a newline terminated string
81d5197206Schris *
82d5197206Schris * You can give an indention as optional parameter
83d5197206Schris *
84d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
85140cfbcdSGerrit Uitslag *
86140cfbcdSGerrit Uitslag * @param string $string  line of text
87140cfbcdSGerrit Uitslag * @param int    $indent  number of spaces indention
88d5197206Schris */
8925ec097bSChris Smithfunction ptln($string, $indent = 0) {
9025ec097bSChris Smith    echo str_repeat(' ', $indent)."$string\n";
9102b0b681SAndreas Gohr}
9202b0b681SAndreas Gohr
9302b0b681SAndreas Gohr/**
9402b0b681SAndreas Gohr * strips control characters (<32) from the given string
9502b0b681SAndreas Gohr *
9602b0b681SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
97140cfbcdSGerrit Uitslag *
9842ea7f44SGerrit Uitslag * @param string $string being stripped
99140cfbcdSGerrit Uitslag * @return string
10002b0b681SAndreas Gohr */
10102b0b681SAndreas Gohrfunction stripctl($string) {
10202b0b681SAndreas Gohr    return preg_replace('/[\x00-\x1F]+/s', '', $string);
103d5197206Schris}
104d5197206Schris
105d5197206Schris/**
106634d7150SAndreas Gohr * Return a secret token to be used for CSRF attack prevention
107634d7150SAndreas Gohr *
108634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
109634d7150SAndreas Gohr * @link    http://en.wikipedia.org/wiki/Cross-site_request_forgery
110634d7150SAndreas Gohr * @link    http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
11142ea7f44SGerrit Uitslag *
112634d7150SAndreas Gohr * @return  string
113634d7150SAndreas Gohr */
114634d7150SAndreas Gohrfunction getSecurityToken() {
115585bf44eSChristopher Smith    /** @var Input $INPUT */
116585bf44eSChristopher Smith    global $INPUT;
1173680e2cdSAndreas Gohr
1183680e2cdSAndreas Gohr    $user = $INPUT->server->str('REMOTE_USER');
1193680e2cdSAndreas Gohr    $session = session_id();
1203680e2cdSAndreas Gohr
1213680e2cdSAndreas Gohr    // CSRF checks are only for logged in users - do not generate for anonymous
1223680e2cdSAndreas Gohr    if(trim($user) == '' || trim($session) == '') return '';
123c3cc6e05SAndreas Gohr    return \dokuwiki\PassHash::hmac('md5', $session.$user, auth_cookiesalt());
124634d7150SAndreas Gohr}
125634d7150SAndreas Gohr
126634d7150SAndreas Gohr/**
127634d7150SAndreas Gohr * Check the secret CSRF token
128140cfbcdSGerrit Uitslag *
129140cfbcdSGerrit Uitslag * @param null|string $token security token or null to read it from request variable
130140cfbcdSGerrit Uitslag * @return bool success if the token matched
131634d7150SAndreas Gohr */
132634d7150SAndreas Gohrfunction checkSecurityToken($token = null) {
133585bf44eSChristopher Smith    /** @var Input $INPUT */
1347d01a0eaSTom N Harris    global $INPUT;
135585bf44eSChristopher Smith    if(!$INPUT->server->str('REMOTE_USER')) return true; // no logged in user, no need for a check
136df97eaacSAndreas Gohr
1377d01a0eaSTom N Harris    if(is_null($token)) $token = $INPUT->str('sectok');
138634d7150SAndreas Gohr    if(getSecurityToken() != $token) {
139634d7150SAndreas Gohr        msg('Security Token did not match. Possible CSRF attack.', -1);
140634d7150SAndreas Gohr        return false;
141634d7150SAndreas Gohr    }
142634d7150SAndreas Gohr    return true;
143634d7150SAndreas Gohr}
144634d7150SAndreas Gohr
145634d7150SAndreas Gohr/**
146634d7150SAndreas Gohr * Print a hidden form field with a secret CSRF token
147634d7150SAndreas Gohr *
148634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
149140cfbcdSGerrit Uitslag *
150140cfbcdSGerrit Uitslag * @param bool $print  if true print the field, otherwise html of the field is returned
15142ea7f44SGerrit Uitslag * @return string html of hidden form field
152634d7150SAndreas Gohr */
153634d7150SAndreas Gohrfunction formSecurityToken($print = true) {
1542404d0edSAnika Henke    $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
1553272d797SAndreas Gohr    if($print) echo $ret;
156634d7150SAndreas Gohr    return $ret;
157634d7150SAndreas Gohr}
158634d7150SAndreas Gohr
159634d7150SAndreas Gohr/**
1601015a57dSChristopher Smith * Determine basic information for a request of $id
16115fae107Sandi *
16215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1637e87a794SChristopher Smith * @author Chris Smith <chris@jalakai.co.uk>
164140cfbcdSGerrit Uitslag *
165140cfbcdSGerrit Uitslag * @param string $id         pageid
166140cfbcdSGerrit Uitslag * @param bool   $htmlClient add info about whether is mobile browser
167140cfbcdSGerrit Uitslag * @return array with info for a request of $id
168140cfbcdSGerrit Uitslag *
169f3f0262cSandi */
1701015a57dSChristopher Smithfunction basicinfo($id, $htmlClient=true){
171f3f0262cSandi    global $USERINFO;
172585bf44eSChristopher Smith    /* @var Input $INPUT */
173585bf44eSChristopher Smith    global $INPUT;
1746afe8dcaSchris
175c66972f2SAdrian Lang    // set info about manager/admin status.
17659bc3b48SGerrit Uitslag    $info = array();
177c66972f2SAdrian Lang    $info['isadmin']   = false;
178c66972f2SAdrian Lang    $info['ismanager'] = false;
179585bf44eSChristopher Smith    if($INPUT->server->has('REMOTE_USER')) {
180f3f0262cSandi        $info['userinfo']   = $USERINFO;
1811015a57dSChristopher Smith        $info['perm']       = auth_quickaclcheck($id);
182585bf44eSChristopher Smith        $info['client']     = $INPUT->server->str('REMOTE_USER');
18317ee7f66SAndreas Gohr
184f8cc712eSAndreas Gohr        if($info['perm'] == AUTH_ADMIN) {
185f8cc712eSAndreas Gohr            $info['isadmin']   = true;
186f8cc712eSAndreas Gohr            $info['ismanager'] = true;
187f8cc712eSAndreas Gohr        } elseif(auth_ismanager()) {
188f8cc712eSAndreas Gohr            $info['ismanager'] = true;
189f8cc712eSAndreas Gohr        }
190f8cc712eSAndreas Gohr
19117ee7f66SAndreas Gohr        // if some outside auth were used only REMOTE_USER is set
192a58fcbbcSAndreas Gohr        if(empty($info['userinfo']['name'])) {
193585bf44eSChristopher Smith            $info['userinfo']['name'] = $INPUT->server->str('REMOTE_USER');
19417ee7f66SAndreas Gohr        }
195ee4c4a1bSAndreas Gohr
196f3f0262cSandi    } else {
1971015a57dSChristopher Smith        $info['perm']       = auth_aclcheck($id, '', null);
198ee4c4a1bSAndreas Gohr        $info['client']     = clientIP(true);
199f3f0262cSandi    }
200f3f0262cSandi
2011015a57dSChristopher Smith    $info['namespace'] = getNS($id);
2021015a57dSChristopher Smith
2031015a57dSChristopher Smith    // mobile detection
2041015a57dSChristopher Smith    if ($htmlClient) {
2051015a57dSChristopher Smith        $info['ismobile'] = clientismobile();
2061015a57dSChristopher Smith    }
2071015a57dSChristopher Smith
2081015a57dSChristopher Smith    return $info;
2091015a57dSChristopher Smith }
2101015a57dSChristopher Smith
2111015a57dSChristopher Smith/**
2121015a57dSChristopher Smith * Return info about the current document as associative
2131015a57dSChristopher Smith * array.
2141015a57dSChristopher Smith *
2151015a57dSChristopher Smith * @author Andreas Gohr <andi@splitbrain.org>
216140cfbcdSGerrit Uitslag *
217140cfbcdSGerrit Uitslag * @return array with info about current document
2181015a57dSChristopher Smith */
2191015a57dSChristopher Smithfunction pageinfo() {
2201015a57dSChristopher Smith    global $ID;
2211015a57dSChristopher Smith    global $REV;
2221015a57dSChristopher Smith    global $RANGE;
2231015a57dSChristopher Smith    global $lang;
224585bf44eSChristopher Smith    /* @var Input $INPUT */
225585bf44eSChristopher Smith    global $INPUT;
2261015a57dSChristopher Smith
2271015a57dSChristopher Smith    $info = basicinfo($ID);
2281015a57dSChristopher Smith
2291015a57dSChristopher Smith    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
2301015a57dSChristopher Smith    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
2311015a57dSChristopher Smith    $info['id']  = $ID;
2321015a57dSChristopher Smith    $info['rev'] = $REV;
2331015a57dSChristopher Smith
23475d66495SMichael Große    $subManager = new SubscriberManager();
23575d66495SMichael Große    $info['subscribed'] = $subManager->userSubscription();
2367e87a794SChristopher Smith
237f3f0262cSandi    $info['locked']     = checklock($ID);
238317a04c4SSatoshi Sahara    $info['filepath']   = wikiFN($ID);
23979e79377SAndreas Gohr    $info['exists']     = file_exists($info['filepath']);
24001c9a118SAndreas Gohr    $info['currentrev'] = @filemtime($info['filepath']);
2415ec96136SSatoshi Sahara
2422ca9d91cSBen Coburn    if ($REV) {
2432ca9d91cSBen Coburn        //check if current revision was meant
24401c9a118SAndreas Gohr        if ($info['exists'] && ($info['currentrev'] == $REV)) {
2452ca9d91cSBen Coburn            $REV = '';
2467b3a6803SAndreas Gohr        } elseif ($RANGE) {
2477b3a6803SAndreas Gohr            //section editing does not work with old revisions!
2487b3a6803SAndreas Gohr            $REV   = '';
2497b3a6803SAndreas Gohr            $RANGE = '';
2507b3a6803SAndreas Gohr            msg($lang['nosecedit'], 0);
2512ca9d91cSBen Coburn        } else {
2522ca9d91cSBen Coburn            //really use old revision
253317a04c4SSatoshi Sahara            $info['filepath'] = wikiFN($ID, $REV);
25479e79377SAndreas Gohr            $info['exists']   = file_exists($info['filepath']);
255f3f0262cSandi        }
256f3f0262cSandi    }
257c112d578Sandi    $info['rev'] = $REV;
258f3f0262cSandi    if ($info['exists']) {
259252acce3SSatoshi Sahara        $info['writable'] = (is_writable($info['filepath']) && $info['perm'] >= AUTH_EDIT);
260f3f0262cSandi    } else {
261f3f0262cSandi        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
262f3f0262cSandi    }
26350e988b1SAndreas Gohr    $info['editable'] = ($info['writable'] && empty($info['locked']));
264f3f0262cSandi    $info['lastmod']  = @filemtime($info['filepath']);
265f3f0262cSandi
26671726d78SBen Coburn    //load page meta data
26771726d78SBen Coburn    $info['meta'] = p_get_metadata($ID);
26871726d78SBen Coburn
269652610a2Sandi    //who's the editor
270047bad06SGerrit Uitslag    $pagelog = new PageChangeLog($ID, 1024);
271652610a2Sandi    if ($REV) {
272f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($REV);
273652610a2Sandi    } else {
2740e80bb5eSChristopher Smith        if (!empty($info['meta']['last_change']) && is_array($info['meta']['last_change'])) {
275aa27cf05SAndreas Gohr            $revinfo = $info['meta']['last_change'];
276aa27cf05SAndreas Gohr        } else {
277f523c971SGerrit Uitslag            $revinfo = $pagelog->getRevisionInfo($info['lastmod']);
278cd00a034SBen Coburn            // cache most recent changelog line in metadata if missing and still valid
279cd00a034SBen Coburn            if ($revinfo !== false) {
280cd00a034SBen Coburn                $info['meta']['last_change'] = $revinfo;
281cd00a034SBen Coburn                p_set_metadata($ID, array('last_change' => $revinfo));
282cd00a034SBen Coburn            }
283cd00a034SBen Coburn        }
284cd00a034SBen Coburn    }
285cd00a034SBen Coburn    //and check for an external edit
286cd00a034SBen Coburn    if ($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
287cd00a034SBen Coburn        // cached changelog line no longer valid
288cd00a034SBen Coburn        $revinfo                     = false;
289cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
290cd00a034SBen Coburn        p_set_metadata($ID, array('last_change' => $revinfo));
291652610a2Sandi    }
292bb4866bdSchris
2930a444b5aSPhy    if ($revinfo !== false) {
294652610a2Sandi        $info['ip']   = $revinfo['ip'];
295652610a2Sandi        $info['user'] = $revinfo['user'];
296652610a2Sandi        $info['sum']  = $revinfo['sum'];
29771726d78SBen Coburn        // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
298ebf1501fSBen Coburn        // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
29959f257aeSchris
300252acce3SSatoshi Sahara        $info['editor'] = $revinfo['user'] ?: $revinfo['ip'];
3010a444b5aSPhy    } else {
3020a444b5aSPhy        $info['ip']     = null;
3030a444b5aSPhy        $info['user']   = null;
3040a444b5aSPhy        $info['sum']    = null;
3050a444b5aSPhy        $info['editor'] = null;
3060a444b5aSPhy    }
307652610a2Sandi
308ee4c4a1bSAndreas Gohr    // draft
3090aabe6f8SMichael Große    $draft = new \dokuwiki\Draft($ID, $info['client']);
3100aabe6f8SMichael Große    if ($draft->isDraftAvailable()) {
3110aabe6f8SMichael Große        $info['draft'] = $draft->getDraftFilename();
312ee4c4a1bSAndreas Gohr    }
313ee4c4a1bSAndreas Gohr
3141015a57dSChristopher Smith    return $info;
3151015a57dSChristopher Smith}
3161015a57dSChristopher Smith
3171015a57dSChristopher Smith/**
3180c39d46cSMichael Große * Initialize and/or fill global $JSINFO with some basic info to be given to javascript
3190c39d46cSMichael Große */
3200c39d46cSMichael Großefunction jsinfo() {
3210c39d46cSMichael Große    global $JSINFO, $ID, $INFO, $ACT;
3220c39d46cSMichael Große
3230c39d46cSMichael Große    if (!is_array($JSINFO)) {
3240c39d46cSMichael Große        $JSINFO = [];
3250c39d46cSMichael Große    }
3260c39d46cSMichael Große    //export minimal info to JS, plugins can add more
3270c39d46cSMichael Große    $JSINFO['id']                    = $ID;
32868491db9SPhy    $JSINFO['namespace']             = isset($INFO) ? (string) $INFO['namespace'] : '';
3290c39d46cSMichael Große    $JSINFO['ACT']                   = act_clean($ACT);
3300c39d46cSMichael Große    $JSINFO['useHeadingNavigation']  = (int) useHeading('navigation');
3310c39d46cSMichael Große    $JSINFO['useHeadingContent']     = (int) useHeading('content');
3320c39d46cSMichael Große}
3330c39d46cSMichael Große
3340c39d46cSMichael Große/**
3351015a57dSChristopher Smith * Return information about the current media item as an associative array.
336140cfbcdSGerrit Uitslag *
337140cfbcdSGerrit Uitslag * @return array with info about current media item
3381015a57dSChristopher Smith */
3391015a57dSChristopher Smithfunction mediainfo() {
3401015a57dSChristopher Smith    global $NS;
3411015a57dSChristopher Smith    global $IMG;
3421015a57dSChristopher Smith
3431015a57dSChristopher Smith    $info = basicinfo("$NS:*");
3441015a57dSChristopher Smith    $info['image'] = $IMG;
3451c548ebeSAndreas Gohr
346f3f0262cSandi    return $info;
347f3f0262cSandi}
348f3f0262cSandi
349f3f0262cSandi/**
3502684e50aSAndreas Gohr * Build an string of URL parameters
3512684e50aSAndreas Gohr *
3522684e50aSAndreas Gohr * @author Andreas Gohr
353140cfbcdSGerrit Uitslag *
354140cfbcdSGerrit Uitslag * @param array  $params    array with key-value pairs
355140cfbcdSGerrit Uitslag * @param string $sep       series of pairs are separated by this character
356140cfbcdSGerrit Uitslag * @return string query string
3572684e50aSAndreas Gohr */
358b174aeaeSchrisfunction buildURLparams($params, $sep = '&amp;') {
3592684e50aSAndreas Gohr    $url = '';
3602684e50aSAndreas Gohr    $amp = false;
3612684e50aSAndreas Gohr    foreach($params as $key => $val) {
362b174aeaeSchris        if($amp) $url .= $sep;
3632684e50aSAndreas Gohr
36485e6871fSAdrian Lang        $url .= rawurlencode($key).'=';
3653a50618cSgweissbach        $url .= rawurlencode((string) $val);
3662684e50aSAndreas Gohr        $amp = true;
3672684e50aSAndreas Gohr    }
3682684e50aSAndreas Gohr    return $url;
3692684e50aSAndreas Gohr}
3702684e50aSAndreas Gohr
3712684e50aSAndreas Gohr/**
3722684e50aSAndreas Gohr * Build an string of html tag attributes
3732684e50aSAndreas Gohr *
3747bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
3757bff22c0SAndreas Gohr *
3762684e50aSAndreas Gohr * @author Andreas Gohr
377140cfbcdSGerrit Uitslag *
378140cfbcdSGerrit Uitslag * @param array $params           array with (attribute name-attribute value) pairs
379246d3337SMichael Große * @param bool  $skipEmptyStrings skip empty string values?
380140cfbcdSGerrit Uitslag * @return string
3812684e50aSAndreas Gohr */
382246d3337SMichael Großefunction buildAttributes($params, $skipEmptyStrings = false) {
3832684e50aSAndreas Gohr    $url   = '';
3849063ec14SAdrian Lang    $white = false;
3852684e50aSAndreas Gohr    foreach($params as $key => $val) {
3862401f18dSSyntaxseed        if($key[0] == '_') continue;
387246d3337SMichael Große        if($val === '' && $skipEmptyStrings) continue;
3889063ec14SAdrian Lang        if($white) $url .= ' ';
3897bff22c0SAndreas Gohr
3902684e50aSAndreas Gohr        $url .= $key.'="';
391f7711f2bSAndreas Gohr        $url .= hsc($val);
3922684e50aSAndreas Gohr        $url .= '"';
3939063ec14SAdrian Lang        $white = true;
3942684e50aSAndreas Gohr    }
3952684e50aSAndreas Gohr    return $url;
3962684e50aSAndreas Gohr}
3972684e50aSAndreas Gohr
3982684e50aSAndreas Gohr/**
39915fae107Sandi * This builds the breadcrumb trail and returns it as array
40015fae107Sandi *
40115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
402140cfbcdSGerrit Uitslag *
403e3710957SGerrit Uitslag * @return string[] with the data: array(pageid=>name, ... )
404f3f0262cSandi */
405f3f0262cSandifunction breadcrumbs() {
4068746e727Sandi    // we prepare the breadcrumbs early for quick session closing
4078746e727Sandi    static $crumbs = null;
4088746e727Sandi    if($crumbs != null) return $crumbs;
4098746e727Sandi
410f3f0262cSandi    global $ID;
411f3f0262cSandi    global $ACT;
412f3f0262cSandi    global $conf;
4130ea5ebb4SB_S666    global $INFO;
414f3f0262cSandi
415f3f0262cSandi    //first visit?
416c66972f2SAdrian Lang    $crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array();
4175603d3c1SHenry Pan    //we only save on show and existing visible readable wiki documents
418a77f5846Sjan    $file = wikiFN($ID);
4195603d3c1SHenry Pan    if($ACT != 'show' || $INFO['perm'] < AUTH_READ || isHiddenPage($ID) || !file_exists($file)) {
420e71ce681SAndreas Gohr        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
421f3f0262cSandi        return $crumbs;
422f3f0262cSandi    }
423a77f5846Sjan
424a77f5846Sjan    // page names
4251a84a0f3SAnika Henke    $name = noNSorNS($ID);
426fe9ec250SChris Smith    if(useHeading('navigation')) {
427a77f5846Sjan        // get page title
42867c15eceSMichael Hamann        $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
429a77f5846Sjan        if($title) {
430a77f5846Sjan            $name = $title;
431a77f5846Sjan        }
432a77f5846Sjan    }
433a77f5846Sjan
434f3f0262cSandi    //remove ID from array
435a77f5846Sjan    if(isset($crumbs[$ID])) {
436a77f5846Sjan        unset($crumbs[$ID]);
437f3f0262cSandi    }
438f3f0262cSandi
439f3f0262cSandi    //add to array
440a77f5846Sjan    $crumbs[$ID] = $name;
441f3f0262cSandi    //reduce size
442f3f0262cSandi    while(count($crumbs) > $conf['breadcrumbs']) {
443f3f0262cSandi        array_shift($crumbs);
444f3f0262cSandi    }
445f3f0262cSandi    //save to session
446e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
447f3f0262cSandi    return $crumbs;
448f3f0262cSandi}
449f3f0262cSandi
450f3f0262cSandi/**
45115fae107Sandi * Filter for page IDs
45215fae107Sandi *
453f3f0262cSandi * This is run on a ID before it is outputted somewhere
454f3f0262cSandi * currently used to replace the colon with something else
455907f24f7SAndreas Gohr * on Windows (non-IIS) systems and to have proper URL encoding
456907f24f7SAndreas Gohr *
457907f24f7SAndreas Gohr * See discussions at https://github.com/splitbrain/dokuwiki/pull/84 and
458907f24f7SAndreas Gohr * https://github.com/splitbrain/dokuwiki/pull/173 why we use a whitelist of
459907f24f7SAndreas Gohr * unaffected servers instead of blacklisting affected servers here.
46015fae107Sandi *
46149c713a3Sandi * Urlencoding is ommitted when the second parameter is false
46249c713a3Sandi *
46315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
464140cfbcdSGerrit Uitslag *
465140cfbcdSGerrit Uitslag * @param string $id pageid being filtered
466140cfbcdSGerrit Uitslag * @param bool   $ue apply urlencoding?
467140cfbcdSGerrit Uitslag * @return string
468f3f0262cSandi */
46949c713a3Sandifunction idfilter($id, $ue = true) {
470f3f0262cSandi    global $conf;
471585bf44eSChristopher Smith    /* @var Input $INPUT */
472585bf44eSChristopher Smith    global $INPUT;
473585bf44eSChristopher Smith
474bf8f8509SAndreas Gohr    $id = (string) $id;
475bf8f8509SAndreas Gohr
476f3f0262cSandi    if($conf['useslash'] && $conf['userewrite']) {
477f3f0262cSandi        $id = strtr($id, ':', '/');
478f3f0262cSandi    } elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
47958bedc8aSborekb        $conf['userewrite'] &&
480585bf44eSChristopher Smith        strpos($INPUT->server->str('SERVER_SOFTWARE'), 'Microsoft-IIS') === false
4813272d797SAndreas Gohr    ) {
482f3f0262cSandi        $id = strtr($id, ':', ';');
483f3f0262cSandi    }
48449c713a3Sandi    if($ue) {
485b6c6979fSAndreas Gohr        $id = rawurlencode($id);
486f3f0262cSandi        $id = str_replace('%3A', ':', $id); //keep as colon
487edd95259SGerrit Uitslag        $id = str_replace('%3B', ';', $id); //keep as semicolon
488f3f0262cSandi        $id = str_replace('%2F', '/', $id); //keep as slash
48949c713a3Sandi    }
490f3f0262cSandi    return $id;
491f3f0262cSandi}
492f3f0262cSandi
493f3f0262cSandi/**
494ed7b5f09Sandi * This builds a link to a wikipage
49515fae107Sandi *
4964bc480e5SAndreas Gohr * It handles URL rewriting and adds additional parameters
4976c7843b5Sandi *
49815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
4994bc480e5SAndreas Gohr *
5004bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
5014bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
5024bc480e5SAndreas Gohr * @param bool         $absolute       request an absolute URL instead of relative
5034bc480e5SAndreas Gohr * @param string       $separator      parameter separator
5044bc480e5SAndreas Gohr * @return string
505f3f0262cSandi */
50616f15a81SDominik Eckelmannfunction wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;') {
507f3f0262cSandi    global $conf;
50816f15a81SDominik Eckelmann    if(is_array($urlParameters)) {
5094bde2196Slisps        if(isset($urlParameters['rev']) && !$urlParameters['rev']) unset($urlParameters['rev']);
51064159a61SAndreas Gohr        if(isset($urlParameters['at']) && $conf['date_at_format']) {
51164159a61SAndreas Gohr            $urlParameters['at'] = date($conf['date_at_format'], $urlParameters['at']);
51264159a61SAndreas Gohr        }
51316f15a81SDominik Eckelmann        $urlParameters = buildURLparams($urlParameters, $separator);
5146de3759aSAndreas Gohr    } else {
51516f15a81SDominik Eckelmann        $urlParameters = str_replace(',', $separator, $urlParameters);
5166de3759aSAndreas Gohr    }
51716f15a81SDominik Eckelmann    if($id === '') {
51816f15a81SDominik Eckelmann        $id = $conf['start'];
51916f15a81SDominik Eckelmann    }
520f3f0262cSandi    $id = idfilter($id);
52116f15a81SDominik Eckelmann    if($absolute) {
522ed7b5f09Sandi        $xlink = DOKU_URL;
523ed7b5f09Sandi    } else {
524ed7b5f09Sandi        $xlink = DOKU_BASE;
525ed7b5f09Sandi    }
526f3f0262cSandi
5276c7843b5Sandi    if($conf['userewrite'] == 2) {
5286c7843b5Sandi        $xlink .= DOKU_SCRIPT.'/'.$id;
52916f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
5306c7843b5Sandi    } elseif($conf['userewrite']) {
531f3f0262cSandi        $xlink .= $id;
53216f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
53340b5fb5bSPhy    } elseif($id !== '') {
5346c7843b5Sandi        $xlink .= DOKU_SCRIPT.'?id='.$id;
53516f15a81SDominik Eckelmann        if($urlParameters) $xlink .= $separator.$urlParameters;
536bce3726dSAndreas Gohr    } else {
537bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
53816f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
539f3f0262cSandi    }
540f3f0262cSandi
541f3f0262cSandi    return $xlink;
542f3f0262cSandi}
543f3f0262cSandi
544f3f0262cSandi/**
545f5c2808fSBen Coburn * This builds a link to an alternate page format
546f5c2808fSBen Coburn *
547f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
548f5c2808fSBen Coburn *
549f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
5504bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
5514bc480e5SAndreas Gohr * @param string       $format         the export renderer to use
5524bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
5534bc480e5SAndreas Gohr * @param bool         $abs            request an absolute URL instead of relative
5544bc480e5SAndreas Gohr * @param string       $sep            parameter separator
5554bc480e5SAndreas Gohr * @return string
556f5c2808fSBen Coburn */
5574bc480e5SAndreas Gohrfunction exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;') {
558f5c2808fSBen Coburn    global $conf;
5594bc480e5SAndreas Gohr    if(is_array($urlParameters)) {
5604bc480e5SAndreas Gohr        $urlParameters = buildURLparams($urlParameters, $sep);
561f5c2808fSBen Coburn    } else {
5624bc480e5SAndreas Gohr        $urlParameters = str_replace(',', $sep, $urlParameters);
563f5c2808fSBen Coburn    }
564f5c2808fSBen Coburn
565f5c2808fSBen Coburn    $format = rawurlencode($format);
566f5c2808fSBen Coburn    $id     = idfilter($id);
567f5c2808fSBen Coburn    if($abs) {
568f5c2808fSBen Coburn        $xlink = DOKU_URL;
569f5c2808fSBen Coburn    } else {
570f5c2808fSBen Coburn        $xlink = DOKU_BASE;
571f5c2808fSBen Coburn    }
572f5c2808fSBen Coburn
573f5c2808fSBen Coburn    if($conf['userewrite'] == 2) {
574f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
5754bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
576f5c2808fSBen Coburn    } elseif($conf['userewrite'] == 1) {
577f5c2808fSBen Coburn        $xlink .= '_export/'.$format.'/'.$id;
5784bc480e5SAndreas Gohr        if($urlParameters) $xlink .= '?'.$urlParameters;
579f5c2808fSBen Coburn    } else {
580f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
5814bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
582f5c2808fSBen Coburn    }
583f5c2808fSBen Coburn
584f5c2808fSBen Coburn    return $xlink;
585f5c2808fSBen Coburn}
586f5c2808fSBen Coburn
587f5c2808fSBen Coburn/**
5886de3759aSAndreas Gohr * Build a link to a media file
5896de3759aSAndreas Gohr *
5906de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
5918c08db0aSAndreas Gohr *
5928c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
5938c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
5948c08db0aSAndreas Gohr *
5953272d797SAndreas Gohr * @param string  $id     the media file id or URL
5963272d797SAndreas Gohr * @param mixed   $more   string or array with additional parameters
5973272d797SAndreas Gohr * @param bool    $direct link to detail page if false
5983272d797SAndreas Gohr * @param string  $sep    URL parameter separator
5993272d797SAndreas Gohr * @param bool    $abs    Create an absolute URL
6003272d797SAndreas Gohr * @return string
6016de3759aSAndreas Gohr */
60255b2b31bSAndreas Gohrfunction ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false) {
6036de3759aSAndreas Gohr    global $conf;
604b9ee6a44SKlap-in    $isexternalimage = media_isexternal($id);
605826d2766SKlap-in    if(!$isexternalimage) {
606826d2766SKlap-in        $id = cleanID($id);
607826d2766SKlap-in    }
608826d2766SKlap-in
6096de3759aSAndreas Gohr    if(is_array($more)) {
6100f4e0092SChristopher Smith        // add token for resized images
611357c9a39SDamien Regad        $w = isset($more['w']) ? $more['w'] : null;
612357c9a39SDamien Regad        $h = isset($more['h']) ? $more['h'] : null;
61398fe1ac9SDamien Regad        if($w || $h || $isexternalimage){
614357c9a39SDamien Regad            $more['tok'] = media_get_token($id, $w, $h);
6150f4e0092SChristopher Smith        }
6168c08db0aSAndreas Gohr        // strip defaults for shorter URLs
6178c08db0aSAndreas Gohr        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
618443e135dSChristopher Smith        if(empty($more['w'])) unset($more['w']);
619443e135dSChristopher Smith        if(empty($more['h'])) unset($more['h']);
6208c08db0aSAndreas Gohr        if(isset($more['id']) && $direct) unset($more['id']);
62178b874e6Slisps        if(isset($more['rev']) && !$more['rev']) unset($more['rev']);
622b174aeaeSchris        $more = buildURLparams($more, $sep);
6236de3759aSAndreas Gohr    } else {
6245e7db1e2SChristopher Smith        $matches = array();
625cc036f74SKlap-in        if (preg_match_all('/\b(w|h)=(\d*)\b/',$more,$matches,PREG_SET_ORDER) || $isexternalimage){
6265e7db1e2SChristopher Smith            $resize = array('w'=>0, 'h'=>0);
6275e7db1e2SChristopher Smith            foreach ($matches as $match){
6285e7db1e2SChristopher Smith                $resize[$match[1]] = $match[2];
6295e7db1e2SChristopher Smith            }
630cc036f74SKlap-in            $more .= $more === '' ? '' : $sep;
631cc036f74SKlap-in            $more .= 'tok='.media_get_token($id,$resize['w'],$resize['h']);
6325e7db1e2SChristopher Smith        }
6338c08db0aSAndreas Gohr        $more = str_replace('cache=cache', '', $more); //skip default
6348c08db0aSAndreas Gohr        $more = str_replace(',,', ',', $more);
635b174aeaeSchris        $more = str_replace(',', $sep, $more);
6366de3759aSAndreas Gohr    }
6376de3759aSAndreas Gohr
63855b2b31bSAndreas Gohr    if($abs) {
63955b2b31bSAndreas Gohr        $xlink = DOKU_URL;
64055b2b31bSAndreas Gohr    } else {
6416de3759aSAndreas Gohr        $xlink = DOKU_BASE;
64255b2b31bSAndreas Gohr    }
6436de3759aSAndreas Gohr
6446de3759aSAndreas Gohr    // external URLs are always direct without rewriting
645826d2766SKlap-in    if($isexternalimage) {
6466de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
647cc036f74SKlap-in        $xlink .= '?'.$more;
648b174aeaeSchris        $xlink .= $sep.'media='.rawurlencode($id);
6496de3759aSAndreas Gohr        return $xlink;
6506de3759aSAndreas Gohr    }
6516de3759aSAndreas Gohr
6526de3759aSAndreas Gohr    $id = idfilter($id);
6536de3759aSAndreas Gohr
6546de3759aSAndreas Gohr    // decide on scriptname
6556de3759aSAndreas Gohr    if($direct) {
6566de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
6576de3759aSAndreas Gohr            $script = '_media';
6586de3759aSAndreas Gohr        } else {
6596de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
6606de3759aSAndreas Gohr        }
6616de3759aSAndreas Gohr    } else {
6626de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
6636de3759aSAndreas Gohr            $script = '_detail';
6646de3759aSAndreas Gohr        } else {
6656de3759aSAndreas Gohr            $script = 'lib/exe/detail.php';
6666de3759aSAndreas Gohr        }
6676de3759aSAndreas Gohr    }
6686de3759aSAndreas Gohr
6696de3759aSAndreas Gohr    // build URL based on rewrite mode
6706de3759aSAndreas Gohr    if($conf['userewrite']) {
6716de3759aSAndreas Gohr        $xlink .= $script.'/'.$id;
6726de3759aSAndreas Gohr        if($more) $xlink .= '?'.$more;
6736de3759aSAndreas Gohr    } else {
6746de3759aSAndreas Gohr        if($more) {
675a99d3236SEsther Brunner            $xlink .= $script.'?'.$more;
676b174aeaeSchris            $xlink .= $sep.'media='.$id;
6776de3759aSAndreas Gohr        } else {
678a99d3236SEsther Brunner            $xlink .= $script.'?media='.$id;
6796de3759aSAndreas Gohr        }
6806de3759aSAndreas Gohr    }
6816de3759aSAndreas Gohr
6826de3759aSAndreas Gohr    return $xlink;
6836de3759aSAndreas Gohr}
6846de3759aSAndreas Gohr
6856de3759aSAndreas Gohr/**
68625ca5b17SAndreas Gohr * Returns the URL to the DokuWiki base script
68715fae107Sandi *
68825ca5b17SAndreas Gohr * Consider using wl() instead, unless you absoutely need the doku.php endpoint
68925ca5b17SAndreas Gohr *
69015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
691140cfbcdSGerrit Uitslag *
692140cfbcdSGerrit Uitslag * @return string
693f3f0262cSandi */
69425ca5b17SAndreas Gohrfunction script() {
695ed7b5f09Sandi    return DOKU_BASE.DOKU_SCRIPT;
696f3f0262cSandi}
697f3f0262cSandi
698f3f0262cSandi/**
69915fae107Sandi * Spamcheck against wordlist
70015fae107Sandi *
701f3f0262cSandi * Checks the wikitext against a list of blocked expressions
702f3f0262cSandi * returns true if the text contains any bad words
70315fae107Sandi *
704e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
705e403cc58SMichael Klier *
706e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
707e403cc58SMichael Klier *  and gain information about the user who was blocked.
708e403cc58SMichael Klier *
709e403cc58SMichael Klier *  Event data:
710e403cc58SMichael Klier *    data['matches']  - array of matches
711e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
712e403cc58SMichael Klier *      [ip]           - ip address
713e403cc58SMichael Klier *      [user]         - username (if logged in)
714e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
715e403cc58SMichael Klier *      [name]         - real name (if logged in)
716e403cc58SMichael Klier *
71715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
7186dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
719140cfbcdSGerrit Uitslag *
7206dffa0e0SAndreas Gohr * @param  string $text - optional text to check, if not given the globals are used
7216dffa0e0SAndreas Gohr * @return bool         - true if a spam word was found
722f3f0262cSandi */
7236dffa0e0SAndreas Gohrfunction checkwordblock($text = '') {
724f3f0262cSandi    global $TEXT;
7256dffa0e0SAndreas Gohr    global $PRE;
7266dffa0e0SAndreas Gohr    global $SUF;
727e0086ca2SAndreas Gohr    global $SUM;
728f3f0262cSandi    global $conf;
729e403cc58SMichael Klier    global $INFO;
730585bf44eSChristopher Smith    /* @var Input $INPUT */
731585bf44eSChristopher Smith    global $INPUT;
732f3f0262cSandi
733f3f0262cSandi    if(!$conf['usewordblock']) return false;
734f3f0262cSandi
735e0086ca2SAndreas Gohr    if(!$text) $text = "$PRE $TEXT $SUF $SUM";
7366dffa0e0SAndreas Gohr
737041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
73864159a61SAndreas Gohr    // phpcs:disable Generic.Files.LineLength.TooLong
73964159a61SAndreas Gohr    $text = preg_replace(
74064159a61SAndreas Gohr        '!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i',
74164159a61SAndreas Gohr        '\1http://\2 \2\3',
74264159a61SAndreas Gohr        $text
74364159a61SAndreas Gohr    );
74464159a61SAndreas Gohr    // phpcs:enable
745041d1964SAndreas Gohr
746b9ac8716Schris    $wordblocks = getWordblocks();
7473e2965d7Sandi    // how many lines to read at once (to work around some PCRE limits)
7483e2965d7Sandi    if(version_compare(phpversion(), '4.3.0', '<')) {
7493e2965d7Sandi        // old versions of PCRE define a maximum of parenthesises even if no
7503e2965d7Sandi        // backreferences are used - the maximum is 99
7513e2965d7Sandi        // this is very bad performancewise and may even be too high still
7523e2965d7Sandi        $chunksize = 40;
7533e2965d7Sandi    } else {
754a51d08efSAndreas Gohr        // read file in chunks of 200 - this should work around the
7553e2965d7Sandi        // MAX_PATTERN_SIZE in modern PCRE
756a51d08efSAndreas Gohr        $chunksize = 200;
7573e2965d7Sandi    }
758b9ac8716Schris    while($blocks = array_splice($wordblocks, 0, $chunksize)) {
759f3f0262cSandi        $re = array();
76049eb6e38SAndreas Gohr        // build regexp from blocks
761f3f0262cSandi        foreach($blocks as $block) {
762f3f0262cSandi            $block = preg_replace('/#.*$/', '', $block);
763f3f0262cSandi            $block = trim($block);
764f3f0262cSandi            if(empty($block)) continue;
765f3f0262cSandi            $re[] = $block;
766f3f0262cSandi        }
767e403cc58SMichael Klier        if(count($re) && preg_match('#('.join('|', $re).')#si', $text, $matches)) {
768e403cc58SMichael Klier            // prepare event data
76959bc3b48SGerrit Uitslag            $data = array();
770e403cc58SMichael Klier            $data['matches']        = $matches;
771585bf44eSChristopher Smith            $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
772585bf44eSChristopher Smith            if($INPUT->server->str('REMOTE_USER')) {
773585bf44eSChristopher Smith                $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
774e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
775e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
776e403cc58SMichael Klier            }
777bad6fc0dSAndreas Gohr            $callback = function () {
778bad6fc0dSAndreas Gohr                return true;
779bad6fc0dSAndreas Gohr            };
780cbb44eabSAndreas Gohr            return Event::createAndTrigger('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
781b9ac8716Schris        }
782703f6fdeSandi    }
783f3f0262cSandi    return false;
784f3f0262cSandi}
785f3f0262cSandi
786f3f0262cSandi/**
787a7580321SZebra North * Return the IP of the client.
78815fae107Sandi *
789a7580321SZebra North * The IP is sourced from, in order of preference:
79015fae107Sandi *
791a7580321SZebra North *   - The X-Real-IP header if $conf[realip] is true.
792a7580321SZebra North *   - The X-Forwarded-For header if all the proxies are trusted by $conf[trustedproxy].
793a7580321SZebra North *   - The TCP/IP connection remote address.
794a7580321SZebra North *   - 0.0.0.0 if all else fails.
7956d8affe6SAndreas Gohr *
796a7580321SZebra North * The 'realip' config value should only be set to true if the X-Real-IP header
797a7580321SZebra North * is being added by the web server, otherwise it may be spoofed by the client.
798a7580321SZebra North *
799a7580321SZebra North * The 'trustedproxy' setting must not allow any IP, otherwise the X-Forwarded-For
800a7580321SZebra North * may be spoofed by the client.
801a7580321SZebra North *
802a7580321SZebra North * @author Zebra North <mrzebra@mrzebra.co.uk>
803140cfbcdSGerrit Uitslag *
804608cdefcSZebra North * @param  bool $single If set only a single IP is returned.
805608cdefcSZebra North *
806a7580321SZebra North * @return string Returns an IP address if 'single' is true, or a comma-separated list
807a7580321SZebra North *                of IP addresses otherwise.
808f3f0262cSandi */
8096d8affe6SAndreas Gohrfunction clientIP($single = false) {
810a7580321SZebra North    // Return the first IP in single mode, or all the IPs.
811*c7f6b7b7SZebra North    return $single ? Ip::clientIp() : join(',', Ip::clientIps());
812f3f0262cSandi}
813f3f0262cSandi
814f3f0262cSandi/**
8151c548ebeSAndreas Gohr * Check if the browser is on a mobile device
8161c548ebeSAndreas Gohr *
8171c548ebeSAndreas Gohr * Adapted from the example code at url below
8181c548ebeSAndreas Gohr *
8191c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
820140cfbcdSGerrit Uitslag *
82164159a61SAndreas Gohr * @deprecated 2018-04-27 you probably want media queries instead anyway
822140cfbcdSGerrit Uitslag * @return bool if true, client is mobile browser; otherwise false
8231c548ebeSAndreas Gohr */
8241c548ebeSAndreas Gohrfunction clientismobile() {
825585bf44eSChristopher Smith    /* @var Input $INPUT */
826585bf44eSChristopher Smith    global $INPUT;
8271c548ebeSAndreas Gohr
828585bf44eSChristopher Smith    if($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
8291c548ebeSAndreas Gohr
830585bf44eSChristopher Smith    if(preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
8311c548ebeSAndreas Gohr
832585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_USER_AGENT')) return false;
8331c548ebeSAndreas Gohr
83464159a61SAndreas Gohr    $uamatches = join(
83564159a61SAndreas Gohr        '|',
83664159a61SAndreas Gohr        [
83764159a61SAndreas Gohr            'midp', 'j2me', 'avantg', 'docomo', 'novarra', 'palmos', 'palmsource', '240x320', 'opwv',
83864159a61SAndreas Gohr            'chtml', 'pda', 'windows ce', 'mmp\/', 'blackberry', 'mib\/', 'symbian', 'wireless', 'nokia',
83964159a61SAndreas Gohr            'hand', 'mobi', 'phone', 'cdm', 'up\.b', 'audio', 'SIE\-', 'SEC\-', 'samsung', 'HTC', 'mot\-',
84064159a61SAndreas Gohr            'mitsu', 'sagem', 'sony', 'alcatel', 'lg', 'erics', 'vx', 'NEC', 'philips', 'mmm', 'xx',
84164159a61SAndreas Gohr            'panasonic', 'sharp', 'wap', 'sch', 'rover', 'pocket', 'benq', 'java', 'pt', 'pg', 'vox',
84264159a61SAndreas Gohr            'amoi', 'bird', 'compal', 'kg', 'voda', 'sany', 'kdd', 'dbt', 'sendo', 'sgh', 'gradi', 'jb',
84364159a61SAndreas Gohr            '\d\d\di', 'moto'
84464159a61SAndreas Gohr        ]
84564159a61SAndreas Gohr    );
8461c548ebeSAndreas Gohr
847585bf44eSChristopher Smith    if(preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
8481c548ebeSAndreas Gohr
8491c548ebeSAndreas Gohr    return false;
8501c548ebeSAndreas Gohr}
8511c548ebeSAndreas Gohr
8521c548ebeSAndreas Gohr/**
8536efc45a2SDmitry Katsubo * check if a given link is interwiki link
8546efc45a2SDmitry Katsubo *
8556efc45a2SDmitry Katsubo * @param string $link the link, e.g. "wiki>page"
8566efc45a2SDmitry Katsubo * @return bool
8576efc45a2SDmitry Katsubo */
8586efc45a2SDmitry Katsubofunction link_isinterwiki($link){
8596efc45a2SDmitry Katsubo    if (preg_match('/^[a-zA-Z0-9\.]+>/u',$link)) return true;
8606efc45a2SDmitry Katsubo    return false;
8616efc45a2SDmitry Katsubo}
8626efc45a2SDmitry Katsubo
8636efc45a2SDmitry Katsubo/**
86463211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
86563211f61SGlen Harris *
86622ef1e32SAndreas Gohr * If $conf['dnslookups'] is disabled it simply returns the input string
86722ef1e32SAndreas Gohr *
86863211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
869140cfbcdSGerrit Uitslag *
8703272d797SAndreas Gohr * @param  string $ips comma separated list of IP addresses
8713272d797SAndreas Gohr * @return string a comma separated list of hostnames
87263211f61SGlen Harris */
87363211f61SGlen Harrisfunction gethostsbyaddrs($ips) {
87422ef1e32SAndreas Gohr    global $conf;
87522ef1e32SAndreas Gohr    if(!$conf['dnslookups']) return $ips;
87622ef1e32SAndreas Gohr
87763211f61SGlen Harris    $hosts = array();
87863211f61SGlen Harris    $ips   = explode(',', $ips);
879551a720fSMichael Klier
880551a720fSMichael Klier    if(is_array($ips)) {
8813886270dSAndreas Gohr        foreach($ips as $ip) {
882551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
88363211f61SGlen Harris        }
884551a720fSMichael Klier        return join(',', $hosts);
885551a720fSMichael Klier    } else {
886551a720fSMichael Klier        return gethostbyaddr(trim($ips));
887551a720fSMichael Klier    }
88863211f61SGlen Harris}
88963211f61SGlen Harris
89063211f61SGlen Harris/**
89115fae107Sandi * Checks if a given page is currently locked.
89215fae107Sandi *
893f3f0262cSandi * removes stale lockfiles
89415fae107Sandi *
89515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
896140cfbcdSGerrit Uitslag *
897140cfbcdSGerrit Uitslag * @param string $id page id
898140cfbcdSGerrit Uitslag * @return bool page is locked?
899f3f0262cSandi */
900f3f0262cSandifunction checklock($id) {
901f3f0262cSandi    global $conf;
902585bf44eSChristopher Smith    /* @var Input $INPUT */
903585bf44eSChristopher Smith    global $INPUT;
904585bf44eSChristopher Smith
905c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
906f3f0262cSandi
907f3f0262cSandi    //no lockfile
90879e79377SAndreas Gohr    if(!file_exists($lock)) return false;
909f3f0262cSandi
910f3f0262cSandi    //lockfile expired
911f3f0262cSandi    if((time() - filemtime($lock)) > $conf['locktime']) {
912d8186216SBen Coburn        @unlink($lock);
913f3f0262cSandi        return false;
914f3f0262cSandi    }
915f3f0262cSandi
916f3f0262cSandi    //my own lock
9176d2af55dSChristopher Smith    @list($ip, $session) = explode("\n", io_readFile($lock));
918c0dd3914SAdaKaleh    if($ip == $INPUT->server->str('REMOTE_USER') || (session_id() && $session == session_id())) {
919f3f0262cSandi        return false;
920f3f0262cSandi    }
921f3f0262cSandi
922f3f0262cSandi    return $ip;
923f3f0262cSandi}
924f3f0262cSandi
925f3f0262cSandi/**
92615fae107Sandi * Lock a page for editing
92715fae107Sandi *
92815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
929140cfbcdSGerrit Uitslag *
930140cfbcdSGerrit Uitslag * @param string $id page id to lock
931f3f0262cSandi */
932f3f0262cSandifunction lock($id) {
933544ed901SDaniel Calviño Sánchez    global $conf;
934585bf44eSChristopher Smith    /* @var Input $INPUT */
935585bf44eSChristopher Smith    global $INPUT;
936544ed901SDaniel Calviño Sánchez
937544ed901SDaniel Calviño Sánchez    if($conf['locktime'] == 0) {
938544ed901SDaniel Calviño Sánchez        return;
939544ed901SDaniel Calviño Sánchez    }
940544ed901SDaniel Calviño Sánchez
941c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
942585bf44eSChristopher Smith    if($INPUT->server->str('REMOTE_USER')) {
943585bf44eSChristopher Smith        io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
944f3f0262cSandi    } else {
94585fef7e2SAndreas Gohr        io_saveFile($lock, clientIP()."\n".session_id());
946f3f0262cSandi    }
947f3f0262cSandi}
948f3f0262cSandi
949f3f0262cSandi/**
95015fae107Sandi * Unlock a page if it was locked by the user
951f3f0262cSandi *
95215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
953140cfbcdSGerrit Uitslag *
9543272d797SAndreas Gohr * @param string $id page id to unlock
95515fae107Sandi * @return bool true if a lock was removed
956f3f0262cSandi */
957f3f0262cSandifunction unlock($id) {
958585bf44eSChristopher Smith    /* @var Input $INPUT */
959585bf44eSChristopher Smith    global $INPUT;
960585bf44eSChristopher Smith
961c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
96279e79377SAndreas Gohr    if(file_exists($lock)) {
9636d2af55dSChristopher Smith        @list($ip, $session) = explode("\n", io_readFile($lock));
964c0dd3914SAdaKaleh        if($ip == $INPUT->server->str('REMOTE_USER') || $session == session_id()) {
965f3f0262cSandi            @unlink($lock);
966f3f0262cSandi            return true;
967f3f0262cSandi        }
968f3f0262cSandi    }
969f3f0262cSandi    return false;
970f3f0262cSandi}
971f3f0262cSandi
972f3f0262cSandi/**
973f3f0262cSandi * convert line ending to unix format
974f3f0262cSandi *
9756db7468bSAndreas Gohr * also makes sure the given text is valid UTF-8
9766db7468bSAndreas Gohr *
97715fae107Sandi * @see    formText() for 2crlf conversion
97815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
979140cfbcdSGerrit Uitslag *
980140cfbcdSGerrit Uitslag * @param string $text
981140cfbcdSGerrit Uitslag * @return string
982f3f0262cSandi */
983f3f0262cSandifunction cleanText($text) {
984f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
9856db7468bSAndreas Gohr
9866db7468bSAndreas Gohr    // if the text is not valid UTF-8 we simply assume latin1
9876db7468bSAndreas Gohr    // this won't break any worse than it breaks with the wrong encoding
9886db7468bSAndreas Gohr    // but might actually fix the problem in many cases
9898cbc5ee8SAndreas Gohr    if(!\dokuwiki\Utf8\Clean::isUtf8($text)) $text = utf8_encode($text);
9906db7468bSAndreas Gohr
991f3f0262cSandi    return $text;
992f3f0262cSandi}
993f3f0262cSandi
994f3f0262cSandi/**
995f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
996f3f0262cSandi * It also converts line endings to Windows format which is
997f3f0262cSandi * pseudo standard for webforms.
998f3f0262cSandi *
99915fae107Sandi * @see    cleanText() for 2unix conversion
100015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1001140cfbcdSGerrit Uitslag *
1002140cfbcdSGerrit Uitslag * @param string $text
1003140cfbcdSGerrit Uitslag * @return string
1004f3f0262cSandi */
1005f3f0262cSandifunction formText($text) {
10065b7d45a5SAndreas Gohr    $text = str_replace("\012", "\015\012", $text);
1007f3f0262cSandi    return htmlspecialchars($text);
1008f3f0262cSandi}
1009f3f0262cSandi
1010f3f0262cSandi/**
101115fae107Sandi * Returns the specified local text in raw format
101215fae107Sandi *
101315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1014140cfbcdSGerrit Uitslag *
1015140cfbcdSGerrit Uitslag * @param string $id   page id
1016140cfbcdSGerrit Uitslag * @param string $ext  extension of file being read, default 'txt'
1017140cfbcdSGerrit Uitslag * @return string
1018f3f0262cSandi */
10192adaf2b8SAndreas Gohrfunction rawLocale($id, $ext = 'txt') {
10202adaf2b8SAndreas Gohr    return io_readFile(localeFN($id, $ext));
1021f3f0262cSandi}
1022f3f0262cSandi
1023f3f0262cSandi/**
1024f3f0262cSandi * Returns the raw WikiText
102515fae107Sandi *
102615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1027140cfbcdSGerrit Uitslag *
1028140cfbcdSGerrit Uitslag * @param string $id   page id
1029e0c26282SGerrit Uitslag * @param string|int $rev  timestamp when a revision of wikitext is desired
1030140cfbcdSGerrit Uitslag * @return string
1031f3f0262cSandi */
1032f3f0262cSandifunction rawWiki($id, $rev = '') {
1033cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1034f3f0262cSandi}
1035f3f0262cSandi
1036f3f0262cSandi/**
10377146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
10387146cee2SAndreas Gohr *
10397b84afa2SAndreas Gohr * @triggers COMMON_PAGETPL_LOAD
10407146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1041140cfbcdSGerrit Uitslag *
1042140cfbcdSGerrit Uitslag * @param string $id the id of the page to be created
1043140cfbcdSGerrit Uitslag * @return string parsed pagetemplate content
10447146cee2SAndreas Gohr */
1045fe17917eSAdrian Langfunction pageTemplate($id) {
1046a15ce62dSEsther Brunner    global $conf;
1047e29549feSAndreas Gohr
1048fe17917eSAdrian Lang    if(is_array($id)) $id = $id[0];
1049e29549feSAndreas Gohr
10507b84afa2SAndreas Gohr    // prepare initial event data
10517b84afa2SAndreas Gohr    $data = array(
10527b84afa2SAndreas Gohr        'id'        => $id, // the id of the page to be created
10537b84afa2SAndreas Gohr        'tpl'       => '', // the text used as template
10547b84afa2SAndreas Gohr        'tplfile'   => '', // the file above text was/should be loaded from
10557b84afa2SAndreas Gohr        'doreplace' => true // should wildcard replacements be done on the text?
10567b84afa2SAndreas Gohr    );
10577b84afa2SAndreas Gohr
1058e1d9dcc8SAndreas Gohr    $evt = new Event('COMMON_PAGETPL_LOAD', $data);
10597b84afa2SAndreas Gohr    if($evt->advise_before(true)) {
10607b84afa2SAndreas Gohr        // the before event might have loaded the content already
10617b84afa2SAndreas Gohr        if(empty($data['tpl'])) {
10627b84afa2SAndreas Gohr            // if the before event did not set a template file, try to find one
10637b84afa2SAndreas Gohr            if(empty($data['tplfile'])) {
1064fe17917eSAdrian Lang                $path = dirname(wikiFN($id));
106579e79377SAndreas Gohr                if(file_exists($path.'/_template.txt')) {
10667b84afa2SAndreas Gohr                    $data['tplfile'] = $path.'/_template.txt';
1067e29549feSAndreas Gohr                } else {
1068e29549feSAndreas Gohr                    // search upper namespaces for templates
1069e29549feSAndreas Gohr                    $len = strlen(rtrim($conf['datadir'], '/'));
1070e29549feSAndreas Gohr                    while(strlen($path) >= $len) {
107179e79377SAndreas Gohr                        if(file_exists($path.'/__template.txt')) {
10727b84afa2SAndreas Gohr                            $data['tplfile'] = $path.'/__template.txt';
1073e29549feSAndreas Gohr                            break;
1074e29549feSAndreas Gohr                        }
1075e29549feSAndreas Gohr                        $path = substr($path, 0, strrpos($path, '/'));
1076e29549feSAndreas Gohr                    }
1077e29549feSAndreas Gohr                }
10787b84afa2SAndreas Gohr            }
10797b84afa2SAndreas Gohr            // load the content
10803d7ac595SMichael Hamann            $data['tpl'] = io_readFile($data['tplfile']);
10817b84afa2SAndreas Gohr        }
1082a1bbd05bSMichael Hamann        if($data['doreplace']) parsePageTemplate($data);
10837b84afa2SAndreas Gohr    }
10847b84afa2SAndreas Gohr    $evt->advise_after();
10857b84afa2SAndreas Gohr    unset($evt);
10867b84afa2SAndreas Gohr
1087fe17917eSAdrian Lang    return $data['tpl'];
10882b1223ecSAdrian Lang}
10892b1223ecSAdrian Lang
10902b1223ecSAdrian Lang/**
10912b1223ecSAdrian Lang * Performs common page template replacements
10927b84afa2SAndreas Gohr * This works on data from COMMON_PAGETPL_LOAD
10932b1223ecSAdrian Lang *
10942b1223ecSAdrian Lang * @author Andreas Gohr <andi@splitbrain.org>
1095140cfbcdSGerrit Uitslag *
1096140cfbcdSGerrit Uitslag * @param array $data array with event data
1097140cfbcdSGerrit Uitslag * @return string
10982b1223ecSAdrian Lang */
1099d535a2e9Sstretchyboyfunction parsePageTemplate(&$data) {
11003272d797SAndreas Gohr    /**
11013272d797SAndreas Gohr     * @var string $id        the id of the page to be created
11023272d797SAndreas Gohr     * @var string $tpl       the text used as template
11033272d797SAndreas Gohr     * @var string $tplfile   the file above text was/should be loaded from
11043272d797SAndreas Gohr     * @var bool   $doreplace should wildcard replacements be done on the text?
11053272d797SAndreas Gohr     */
1106fe17917eSAdrian Lang    extract($data);
1107fe17917eSAdrian Lang
1108b856f7dfSAdrian Lang    global $USERINFO;
1109bce53b1fSAdrian Lang    global $conf;
1110585bf44eSChristopher Smith    /* @var Input $INPUT */
1111585bf44eSChristopher Smith    global $INPUT;
1112e29549feSAndreas Gohr
1113e29549feSAndreas Gohr    // replace placeholders
111426ece5a7SAndreas Gohr    $file = noNS($id);
111537c1acbdSAdrian Lang    $page = strtr($file, $conf['sepchar'], ' ');
111626ece5a7SAndreas Gohr
11173272d797SAndreas Gohr    $tpl = str_replace(
11183272d797SAndreas Gohr        array(
111926ece5a7SAndreas Gohr             '@ID@',
112026ece5a7SAndreas Gohr             '@NS@',
11218a7bcf66SShota Miyazaki             '@CURNS@',
1122a3db0ab0SSimon Lees             '@!CURNS@',
1123a3db0ab0SSimon Lees             '@!!CURNS@',
1124a3db0ab0SSimon Lees             '@!CURNS!@',
112526ece5a7SAndreas Gohr             '@FILE@',
112626ece5a7SAndreas Gohr             '@!FILE@',
112726ece5a7SAndreas Gohr             '@!FILE!@',
112826ece5a7SAndreas Gohr             '@PAGE@',
112926ece5a7SAndreas Gohr             '@!PAGE@',
113026ece5a7SAndreas Gohr             '@!!PAGE@',
113126ece5a7SAndreas Gohr             '@!PAGE!@',
113226ece5a7SAndreas Gohr             '@USER@',
113326ece5a7SAndreas Gohr             '@NAME@',
113426ece5a7SAndreas Gohr             '@MAIL@',
113526ece5a7SAndreas Gohr             '@DATE@',
113626ece5a7SAndreas Gohr        ),
113726ece5a7SAndreas Gohr        array(
113826ece5a7SAndreas Gohr             $id,
113926ece5a7SAndreas Gohr             getNS($id),
11408a7bcf66SShota Miyazaki             curNS($id),
1141c1ec88ceSAndreas Gohr             \dokuwiki\Utf8\PhpString::ucfirst(curNS($id)),
1142c1ec88ceSAndreas Gohr             \dokuwiki\Utf8\PhpString::ucwords(curNS($id)),
1143c1ec88ceSAndreas Gohr             \dokuwiki\Utf8\PhpString::strtoupper(curNS($id)),
114426ece5a7SAndreas Gohr             $file,
11458cbc5ee8SAndreas Gohr             \dokuwiki\Utf8\PhpString::ucfirst($file),
11468cbc5ee8SAndreas Gohr             \dokuwiki\Utf8\PhpString::strtoupper($file),
114726ece5a7SAndreas Gohr             $page,
11488cbc5ee8SAndreas Gohr             \dokuwiki\Utf8\PhpString::ucfirst($page),
11498cbc5ee8SAndreas Gohr             \dokuwiki\Utf8\PhpString::ucwords($page),
11508cbc5ee8SAndreas Gohr             \dokuwiki\Utf8\PhpString::strtoupper($page),
1151585bf44eSChristopher Smith             $INPUT->server->str('REMOTE_USER'),
11523e9ae63dSPhy             $USERINFO ? $USERINFO['name'] : '',
11533e9ae63dSPhy             $USERINFO ? $USERINFO['mail'] : '',
115426ece5a7SAndreas Gohr             $conf['dformat'],
11553272d797SAndreas Gohr        ), $tpl
11563272d797SAndreas Gohr    );
115726ece5a7SAndreas Gohr
11587d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
1159bad6fc0dSAndreas Gohr    $tpl = preg_replace_callback(
1160bad6fc0dSAndreas Gohr        '/%./',
1161bad6fc0dSAndreas Gohr        function ($m) {
116210f359adSAndreas Gohr            return dformat(null, $m[0]);
1163bad6fc0dSAndreas Gohr        },
1164bad6fc0dSAndreas Gohr        $tpl
1165bad6fc0dSAndreas Gohr    );
1166d535a2e9Sstretchyboy    $data['tpl'] = $tpl;
1167a15ce62dSEsther Brunner    return $tpl;
11687146cee2SAndreas Gohr}
11697146cee2SAndreas Gohr
11707146cee2SAndreas Gohr/**
117115fae107Sandi * Returns the raw Wiki Text in three slices.
117215fae107Sandi *
117315fae107Sandi * The range parameter needs to have the form "from-to"
117415cfe303Sandi * and gives the range of the section in bytes - no
117515cfe303Sandi * UTF-8 awareness is needed.
1176f3f0262cSandi * The returned order is prefix, section and suffix.
117715fae107Sandi *
117815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1179140cfbcdSGerrit Uitslag *
1180140cfbcdSGerrit Uitslag * @param string $range in form "from-to"
1181140cfbcdSGerrit Uitslag * @param string $id    page id
1182140cfbcdSGerrit Uitslag * @param string $rev   optional, the revision timestamp
118342ea7f44SGerrit Uitslag * @return string[] with three slices
1184f3f0262cSandi */
1185f3f0262cSandifunction rawWikiSlices($range, $id, $rev = '') {
1186cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1187f3f0262cSandi
118880fcb268SAdrian Lang    // Parse range
1189ec34bb30SAndreas Gohr    list($from, $to) = sexplode('-', $range, 2);
119080fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
119180fcb268SAdrian Lang    $from = !$from ? 0 : ($from - 1);
119280fcb268SAdrian Lang    $to   = !$to ? strlen($text) : ($to - 1);
119380fcb268SAdrian Lang
119459bc3b48SGerrit Uitslag    $slices = array();
119580fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
119680fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to - $from);
119715cfe303Sandi    $slices[2] = substr($text, $to);
1198f3f0262cSandi    return $slices;
1199f3f0262cSandi}
1200f3f0262cSandi
1201f3f0262cSandi/**
120215fae107Sandi * Joins wiki text slices
120315fae107Sandi *
120480fcb268SAdrian Lang * function to join the text slices.
1205f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
1206f3f0262cSandi * lines between sections if needed (used on saving).
120715fae107Sandi *
120815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1209140cfbcdSGerrit Uitslag *
1210140cfbcdSGerrit Uitslag * @param string $pre   prefix
1211140cfbcdSGerrit Uitslag * @param string $text  text in the middle
1212140cfbcdSGerrit Uitslag * @param string $suf   suffix
1213140cfbcdSGerrit Uitslag * @param bool $pretty add additional empty lines between sections
1214140cfbcdSGerrit Uitslag * @return string
1215f3f0262cSandi */
1216f3f0262cSandifunction con($pre, $text, $suf, $pretty = false) {
1217f3f0262cSandi    if($pretty) {
121880fcb268SAdrian Lang        if($pre !== '' && substr($pre, -1) !== "\n" &&
12193272d797SAndreas Gohr            substr($text, 0, 1) !== "\n"
12203272d797SAndreas Gohr        ) {
122180fcb268SAdrian Lang            $pre .= "\n";
122280fcb268SAdrian Lang        }
122380fcb268SAdrian Lang        if($suf !== '' && substr($text, -1) !== "\n" &&
12243272d797SAndreas Gohr            substr($suf, 0, 1) !== "\n"
12253272d797SAndreas Gohr        ) {
122680fcb268SAdrian Lang            $text .= "\n";
122780fcb268SAdrian Lang        }
1228f3f0262cSandi    }
1229f3f0262cSandi
1230f3f0262cSandi    return $pre.$text.$suf;
1231f3f0262cSandi}
1232f3f0262cSandi
1233f3f0262cSandi/**
1234b24d9195SAndreas Gohr * Checks if the current page version is newer than the last entry in the page's
1235b24d9195SAndreas Gohr * changelog. If so, we assume it has been an external edit and we create an
1236b24d9195SAndreas Gohr * attic copy and add a proper changelog line.
1237b24d9195SAndreas Gohr *
1238b24d9195SAndreas Gohr * This check is only executed when the page is about to be saved again from the
1239b24d9195SAndreas Gohr * wiki, triggered in @see saveWikiText()
1240b24d9195SAndreas Gohr *
1241b24d9195SAndreas Gohr * @param string $id the page ID
124269f9b481SSatoshi Sahara * @deprecated 2021-11-28
1243b24d9195SAndreas Gohr */
1244b24d9195SAndreas Gohrfunction detectExternalEdit($id) {
124579a2d784SGerrit Uitslag    dbg_deprecated(PageFile::class .'::detectExternalEdit()');
1246b24e9c4aSSatoshi Sahara    (new PageFile($id))->detectExternalEdit();
1247b24d9195SAndreas Gohr}
1248b24d9195SAndreas Gohr
1249b24d9195SAndreas Gohr/**
1250a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
1251a701424fSBen Coburn * Also directs changelog and attic updates.
125215fae107Sandi *
125315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
125471726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
1255140cfbcdSGerrit Uitslag *
1256140cfbcdSGerrit Uitslag * @param string $id       page id
1257140cfbcdSGerrit Uitslag * @param string $text     wikitext being saved
1258140cfbcdSGerrit Uitslag * @param string $summary  summary of text update
1259140cfbcdSGerrit Uitslag * @param bool   $minor    mark this saved version as minor update
1260f3f0262cSandi */
1261b6912aeaSAndreas Gohrfunction saveWikiText($id, $text, $summary, $minor = false) {
1262585bf44eSChristopher Smith
1263b24e9c4aSSatoshi Sahara    // get COMMON_WIKIPAGE_SAVE event data
1264b24e9c4aSSatoshi Sahara    $data = (new PageFile($id))->saveWikiText($text, $summary, $minor);
1265ac3ed4afSGerrit Uitslag
126626a0801fSAndreas Gohr    // send notify mails
12673b813d43SSatoshi Sahara    list('oldRevision' => $rev, 'newRevision' => $new_rev, 'summary' => $summary) = $data;
12683b813d43SSatoshi Sahara    notify($id, 'admin', $rev, $summary, $minor, $new_rev);
12693b813d43SSatoshi Sahara    notify($id, 'subscribers', $rev, $summary, $minor, $new_rev);
1270f3f0262cSandi
12712eccbdaaSGina Haeussge    // if useheading is enabled, purge the cache of all linking pages
1272fe9ec250SChris Smith    if (useHeading('content')) {
127307ff0babSMichael Hamann        $pages = ft_backlinks($id, true);
12742eccbdaaSGina Haeussge        foreach ($pages as $page) {
12750db5771eSMichael Große            $cache = new CacheRenderer($page, wikiFN($page), 'xhtml');
12762eccbdaaSGina Haeussge            $cache->removeCache();
12772eccbdaaSGina Haeussge        }
12782eccbdaaSGina Haeussge    }
1279f3f0262cSandi}
1280f3f0262cSandi
1281f3f0262cSandi/**
1282d5824ab9SSatoshi Sahara * moves the current version to the attic and returns its revision date
128315fae107Sandi *
128415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1285140cfbcdSGerrit Uitslag *
1286140cfbcdSGerrit Uitslag * @param string $id page id
1287140cfbcdSGerrit Uitslag * @return int|string revision timestamp
128869f9b481SSatoshi Sahara * @deprecated 2021-11-28
1289f3f0262cSandi */
1290f3f0262cSandifunction saveOldRevision($id) {
129179a2d784SGerrit Uitslag    dbg_deprecated(PageFile::class .'::saveOldRevision()');
1292b24e9c4aSSatoshi Sahara    return (new PageFile($id))->saveOldRevision();
1293f3f0262cSandi}
1294f3f0262cSandi
1295f3f0262cSandi/**
1296fde10de4SAdrian Lang * Sends a notify mail on page change or registration
129726a0801fSAndreas Gohr *
129826a0801fSAndreas Gohr * @param string     $id       The changed page
1299fde10de4SAdrian Lang * @param string     $who      Who to notify (admin|subscribers|register)
13003272d797SAndreas Gohr * @param int|string $rev      Old page revision
130126a0801fSAndreas Gohr * @param string     $summary  What changed
130290033e9dSAndreas Gohr * @param boolean    $minor    Is this a minor edit?
130342ea7f44SGerrit Uitslag * @param string[]   $replace  Additional string substitutions, @KEY@ to be replaced by value
130483734cddSPhy * @param int|string $current_rev  New page revision
13053272d797SAndreas Gohr * @return bool
1306140cfbcdSGerrit Uitslag *
130715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1308f3f0262cSandi */
130983734cddSPhyfunction notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array(), $current_rev = false) {
1310f3f0262cSandi    global $conf;
1311585bf44eSChristopher Smith    /* @var Input $INPUT */
1312585bf44eSChristopher Smith    global $INPUT;
1313b158d625SSteven Danz
13146df843eeSAndreas Gohr    // decide if there is something to do, eg. whom to mail
131526a0801fSAndreas Gohr    if ($who == 'admin') {
13163272d797SAndreas Gohr        if (empty($conf['notify'])) return false; //notify enabled?
13172ed38036SAndreas Gohr        $tpl = 'mailtext';
131826a0801fSAndreas Gohr        $to  = $conf['notify'];
131926a0801fSAndreas Gohr    } elseif ($who == 'subscribers') {
132084c1127cSAndreas Gohr        if (!actionOK('subscribe')) return false; //subscribers enabled?
1321585bf44eSChristopher Smith        if ($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
13220bb37868SGerrit Uitslag        $data = array('id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace);
1323cbb44eabSAndreas Gohr        Event::createAndTrigger(
13243272d797SAndreas Gohr            'COMMON_NOTIFY_ADDRESSLIST', $data,
1325c8cc4053SAndreas Gohr            array(new SubscriberManager(), 'notifyAddresses')
13263272d797SAndreas Gohr        );
13272ed38036SAndreas Gohr        $to = $data['addresslist'];
13282ed38036SAndreas Gohr        if (empty($to)) return false;
13292ed38036SAndreas Gohr        $tpl = 'subscr_single';
133026a0801fSAndreas Gohr    } else {
13313272d797SAndreas Gohr        return false; //just to be safe
133226a0801fSAndreas Gohr    }
133326a0801fSAndreas Gohr
13346df843eeSAndreas Gohr    // prepare content
1335704a815fSMichael Große    $subscription = new PageSubscriptionSender();
133683734cddSPhy    return $subscription->sendPageDiff($to, $tpl, $id, $rev, $summary, $current_rev);
1337f3f0262cSandi}
13382ed38036SAndreas Gohr
133915fae107Sandi/**
134071f7bde7SAndreas Gohr * extracts the query from a search engine referrer
134115fae107Sandi *
134215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
134371f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1344140cfbcdSGerrit Uitslag *
1345140cfbcdSGerrit Uitslag * @return array|string
1346f3f0262cSandi */
1347f3f0262cSandifunction getGoogleQuery() {
1348585bf44eSChristopher Smith    /* @var Input $INPUT */
1349585bf44eSChristopher Smith    global $INPUT;
1350585bf44eSChristopher Smith
1351585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_REFERER')) {
1352c66972f2SAdrian Lang        return '';
1353c66972f2SAdrian Lang    }
1354585bf44eSChristopher Smith    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1355f3f0262cSandi
1356079b3ac1SAndreas Gohr    // only handle common SEs
1357079b3ac1SAndreas Gohr    if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/',$url['host'])) return '';
1358e4d8a516SKazutaka Miyasaka
1359079b3ac1SAndreas Gohr    $query = array();
1360f3f0262cSandi    parse_str($url['query'], $query);
1361e4d8a516SKazutaka Miyasaka
1362c66972f2SAdrian Lang    $q = '';
1363079b3ac1SAndreas Gohr    if(isset($query['q'])){
1364079b3ac1SAndreas Gohr        $q = $query['q'];
1365079b3ac1SAndreas Gohr    }elseif(isset($query['p'])){
1366079b3ac1SAndreas Gohr        $q = $query['p'];
1367079b3ac1SAndreas Gohr    }elseif(isset($query['query'])){
1368079b3ac1SAndreas Gohr        $q = $query['query'];
1369079b3ac1SAndreas Gohr    }
1370079b3ac1SAndreas Gohr    $q = trim($q);
1371f3f0262cSandi
1372079b3ac1SAndreas Gohr    if(!$q) return '';
1373c7dc833bSPhy    // ignore if query includes a full URL
1374c7dc833bSPhy    if(strpos($q, '//') !== false) return '';
13756531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1376f93b3b50SAndreas Gohr    return $q;
1377f3f0262cSandi}
1378f3f0262cSandi
1379f3f0262cSandi/**
1380f3f0262cSandi * Return the human readable size of a file
1381f3f0262cSandi *
1382f3f0262cSandi * @param int $size A file size
1383f3f0262cSandi * @param int $dec A number of decimal places
138474160ca1SGerrit Uitslag * @return string human readable size
1385140cfbcdSGerrit Uitslag *
1386f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1387f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1388f3f0262cSandi * @version     1.0.0
1389f3f0262cSandi */
1390f31d5b73Sandifunction filesize_h($size, $dec = 1) {
1391f3f0262cSandi    $sizes = array('B', 'KB', 'MB', 'GB');
1392f3f0262cSandi    $count = count($sizes);
1393f3f0262cSandi    $i     = 0;
1394f3f0262cSandi
1395f3f0262cSandi    while($size >= 1024 && ($i < $count - 1)) {
1396f3f0262cSandi        $size /= 1024;
1397f3f0262cSandi        $i++;
1398f3f0262cSandi    }
1399f3f0262cSandi
1400ef08383eSAndreas Gohr    return round($size, $dec)."\xC2\xA0".$sizes[$i]; //non-breaking space
1401f3f0262cSandi}
1402f3f0262cSandi
140315fae107Sandi/**
1404c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1405c57e365eSAndreas Gohr *
1406c57e365eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1407140cfbcdSGerrit Uitslag *
1408140cfbcdSGerrit Uitslag * @param int $dt timestamp
1409140cfbcdSGerrit Uitslag * @return string
1410c57e365eSAndreas Gohr */
1411c57e365eSAndreas Gohrfunction datetime_h($dt) {
1412c57e365eSAndreas Gohr    global $lang;
1413c57e365eSAndreas Gohr
1414c57e365eSAndreas Gohr    $ago = time() - $dt;
1415c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1416c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1417c57e365eSAndreas Gohr    }
1418c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 2) {
1419c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1420c57e365eSAndreas Gohr    }
1421c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 7 * 2) {
1422c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1423c57e365eSAndreas Gohr    }
1424c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 2) {
1425c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1426c57e365eSAndreas Gohr    }
1427c57e365eSAndreas Gohr    if($ago > 60 * 60 * 2) {
1428c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago / (60 * 60)));
1429c57e365eSAndreas Gohr    }
1430c57e365eSAndreas Gohr    if($ago > 60 * 2) {
1431c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago / (60)));
1432c57e365eSAndreas Gohr    }
1433c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1434c57e365eSAndreas Gohr}
1435c57e365eSAndreas Gohr
1436c57e365eSAndreas Gohr/**
1437f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1438f2263577SAndreas Gohr *
1439f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1440f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1441f2263577SAndreas Gohr *
1442f2263577SAndreas Gohr * @see datetime_h
1443f2263577SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1444140cfbcdSGerrit Uitslag *
1445140cfbcdSGerrit Uitslag * @param int|null $dt      timestamp when given, null will take current timestamp
1446140cfbcdSGerrit Uitslag * @param string   $format  empty default to $conf['dformat'], or provide format as recognized by strftime()
1447140cfbcdSGerrit Uitslag * @return string
1448f2263577SAndreas Gohr */
1449f2263577SAndreas Gohrfunction dformat($dt = null, $format = '') {
1450f2263577SAndreas Gohr    global $conf;
1451f2263577SAndreas Gohr
1452f2263577SAndreas Gohr    if(is_null($dt)) $dt = time();
1453f2263577SAndreas Gohr    $dt = (int) $dt;
1454f2263577SAndreas Gohr    if(!$format) $format = $conf['dformat'];
1455f2263577SAndreas Gohr
1456f2263577SAndreas Gohr    $format = str_replace('%f', datetime_h($dt), $format);
1457f2263577SAndreas Gohr    return strftime($format, $dt);
1458f2263577SAndreas Gohr}
1459f2263577SAndreas Gohr
1460f2263577SAndreas Gohr/**
1461c4f79b71SMichael Hamann * Formats a timestamp as ISO 8601 date
1462c4f79b71SMichael Hamann *
1463c4f79b71SMichael Hamann * @author <ungu at terong dot com>
146459752844SAnders Sandblad * @link http://php.net/manual/en/function.date.php#54072
1465140cfbcdSGerrit Uitslag *
14667e8500eeSGerrit Uitslag * @param int $int_date current date in UNIX timestamp
14673272d797SAndreas Gohr * @return string
1468c4f79b71SMichael Hamann */
1469c4f79b71SMichael Hamannfunction date_iso8601($int_date) {
1470c4f79b71SMichael Hamann    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1471c4f79b71SMichael Hamann    $pre_timezone = date('O', $int_date);
1472c4f79b71SMichael Hamann    $time_zone    = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1473c4f79b71SMichael Hamann    $date_mod .= $time_zone;
1474c4f79b71SMichael Hamann    return $date_mod;
1475c4f79b71SMichael Hamann}
1476c4f79b71SMichael Hamann
1477c4f79b71SMichael Hamann/**
147800a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
147900a7b5adSEsther Brunner *
148000a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
148100a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
1482140cfbcdSGerrit Uitslag *
1483140cfbcdSGerrit Uitslag * @param string $email email address
1484140cfbcdSGerrit Uitslag * @return string
148500a7b5adSEsther Brunner */
148600a7b5adSEsther Brunnerfunction obfuscate($email) {
148700a7b5adSEsther Brunner    global $conf;
148800a7b5adSEsther Brunner
148900a7b5adSEsther Brunner    switch($conf['mailguard']) {
149000a7b5adSEsther Brunner        case 'visible' :
149100a7b5adSEsther Brunner            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
149200a7b5adSEsther Brunner            return strtr($email, $obfuscate);
149300a7b5adSEsther Brunner
149400a7b5adSEsther Brunner        case 'hex' :
1495c1ec88ceSAndreas Gohr            return \dokuwiki\Utf8\Conversion::toHtml($email, true);
149600a7b5adSEsther Brunner
149700a7b5adSEsther Brunner        case 'none' :
149800a7b5adSEsther Brunner        default :
149900a7b5adSEsther Brunner            return $email;
150000a7b5adSEsther Brunner    }
150100a7b5adSEsther Brunner}
150200a7b5adSEsther Brunner
150300a7b5adSEsther Brunner/**
150489541d4bSAndreas Gohr * Removes quoting backslashes
150589541d4bSAndreas Gohr *
150689541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1507140cfbcdSGerrit Uitslag *
1508140cfbcdSGerrit Uitslag * @param string $string
1509140cfbcdSGerrit Uitslag * @param string $char backslashed character
1510140cfbcdSGerrit Uitslag * @return string
151189541d4bSAndreas Gohr */
151289541d4bSAndreas Gohrfunction unslash($string, $char = "'") {
151389541d4bSAndreas Gohr    return str_replace('\\'.$char, $char, $string);
151489541d4bSAndreas Gohr}
151589541d4bSAndreas Gohr
151673038c47SAndreas Gohr/**
151773038c47SAndreas Gohr * Convert php.ini shorthands to byte
151873038c47SAndreas Gohr *
1519a81f3d99SAndreas Gohr * On 32 bit systems values >= 2GB will fail!
1520140cfbcdSGerrit Uitslag *
1521a81f3d99SAndreas Gohr * -1 (infinite size) will be reported as -1
1522a81f3d99SAndreas Gohr *
1523a81f3d99SAndreas Gohr * @link   https://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
1524a81f3d99SAndreas Gohr * @param string $value PHP size shorthand
1525a81f3d99SAndreas Gohr * @return int
152673038c47SAndreas Gohr */
1527a81f3d99SAndreas Gohrfunction php_to_byte($value) {
1528f5c0c80bSAndreas Gohr    switch (strtoupper(substr($value,-1))) {
152973038c47SAndreas Gohr        case 'G':
1530a81f3d99SAndreas Gohr            $ret = intval(substr($value, 0, -1)) * 1024 * 1024 * 1024;
153173038c47SAndreas Gohr            break;
153273038c47SAndreas Gohr        case 'M':
1533a81f3d99SAndreas Gohr            $ret = intval(substr($value, 0, -1)) * 1024 * 1024;
1534a81f3d99SAndreas Gohr            break;
153573038c47SAndreas Gohr        case 'K':
1536a81f3d99SAndreas Gohr            $ret = intval(substr($value, 0, -1)) * 1024;
153773038c47SAndreas Gohr            break;
15389eeeb775SAndreas Gohr        default:
1539a81f3d99SAndreas Gohr            $ret = intval($value);
154049cbd23eSOtto Vainio            break;
154173038c47SAndreas Gohr    }
154273038c47SAndreas Gohr    return $ret;
154373038c47SAndreas Gohr}
154473038c47SAndreas Gohr
1545546d3a99SAndreas Gohr/**
1546546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1547140cfbcdSGerrit Uitslag *
1548140cfbcdSGerrit Uitslag * @param string $string
1549140cfbcdSGerrit Uitslag * @return string
1550546d3a99SAndreas Gohr */
1551546d3a99SAndreas Gohrfunction preg_quote_cb($string) {
1552546d3a99SAndreas Gohr    return preg_quote($string, '/');
1553546d3a99SAndreas Gohr}
155473038c47SAndreas Gohr
1555bd2f6c2fSAndreas Gohr/**
1556bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1557bd2f6c2fSAndreas Gohr *
1558c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1559bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1560bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1561bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1562bd2f6c2fSAndreas Gohr *
1563bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1564bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1565bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1566bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1567bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
15683272d797SAndreas Gohr * @return string
1569bd2f6c2fSAndreas Gohr */
1570a5d27328SAndreas Gohrfunction shorten($keep, $short, $max, $min = 9, $char = '…') {
15718cbc5ee8SAndreas Gohr    $max = $max - \dokuwiki\Utf8\PhpString::strlen($keep);
1572bd2f6c2fSAndreas Gohr    if($max < $min) return $keep;
15738cbc5ee8SAndreas Gohr    $len = \dokuwiki\Utf8\PhpString::strlen($short);
1574bd2f6c2fSAndreas Gohr    if($len <= $max) return $keep.$short;
1575bd2f6c2fSAndreas Gohr    $half = floor($max / 2);
15766ce3e5f8SAndreas Gohr    return $keep .
15776ce3e5f8SAndreas Gohr        \dokuwiki\Utf8\PhpString::substr($short, 0, $half - 1) .
15786ce3e5f8SAndreas Gohr        $char .
15796ce3e5f8SAndreas Gohr        \dokuwiki\Utf8\PhpString::substr($short, $len - $half);
1580bd2f6c2fSAndreas Gohr}
1581bd2f6c2fSAndreas Gohr
1582dc58b6f4SAndy Webber/**
1583dc58b6f4SAndy Webber * Return the users real name or e-mail address for use
1584dc58b6f4SAndy Webber * in page footer and recent changes pages
1585dc58b6f4SAndy Webber *
1586b4b6c9a1SGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
158715f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1588c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
158915f3bc49SGerrit Uitslag *
1590dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1591dc58b6f4SAndy Webber */
159215f3bc49SGerrit Uitslagfunction editorinfo($username, $textonly = false) {
1593cd4635eeSGerrit Uitslag    return userlink($username, $textonly);
1594dc58b6f4SAndy Webber}
1595dc58b6f4SAndy Webber
159660a396c8SGerrit Uitslag/**
159760a396c8SGerrit Uitslag * Returns users realname w/o link
159860a396c8SGerrit Uitslag *
1599f168548cSGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
160015f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1601c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
160260a396c8SGerrit Uitslag *
160360a396c8SGerrit Uitslag * @triggers COMMON_USER_LINK
160460a396c8SGerrit Uitslag */
1605cd4635eeSGerrit Uitslagfunction userlink($username = null, $textonly = false) {
160660a396c8SGerrit Uitslag    global $conf, $INFO;
1607e1d9dcc8SAndreas Gohr    /** @var AuthPlugin $auth */
160860a396c8SGerrit Uitslag    global $auth;
160930f6ec4bSGerrit Uitslag    /** @var Input $INPUT */
161030f6ec4bSGerrit Uitslag    global $INPUT;
161160a396c8SGerrit Uitslag
161260a396c8SGerrit Uitslag    // prepare initial event data
161360a396c8SGerrit Uitslag    $data = array(
161460a396c8SGerrit Uitslag        'username' => $username, // the unique user name
161560a396c8SGerrit Uitslag        'name' => '',
161660a396c8SGerrit Uitslag        'link' => array( //setting 'link' to false disables linking
161760a396c8SGerrit Uitslag                         'target' => '',
161860a396c8SGerrit Uitslag                         'pre' => '',
161960a396c8SGerrit Uitslag                         'suf' => '',
162060a396c8SGerrit Uitslag                         'style' => '',
162160a396c8SGerrit Uitslag                         'more' => '',
162260a396c8SGerrit Uitslag                         'url' => '',
162360a396c8SGerrit Uitslag                         'title' => '',
162460a396c8SGerrit Uitslag                         'class' => ''
162560a396c8SGerrit Uitslag        ),
16264d5fc927SGerrit Uitslag        'userlink' => '', // formatted user name as will be returned
162715f3bc49SGerrit Uitslag        'textonly' => $textonly
162860a396c8SGerrit Uitslag    );
162962c8004eSGerrit Uitslag    if($username === null) {
163030f6ec4bSGerrit Uitslag        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
163115f3bc49SGerrit Uitslag        if($textonly){
163215f3bc49SGerrit Uitslag            $data['name'] = $INFO['userinfo']['name']. ' (' . $INPUT->server->str('REMOTE_USER') . ')';
163315f3bc49SGerrit Uitslag        }else {
163464159a61SAndreas Gohr            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> '.
163564159a61SAndreas Gohr                '(<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
163660a396c8SGerrit Uitslag        }
163715f3bc49SGerrit Uitslag    }
163860a396c8SGerrit Uitslag
1639e1d9dcc8SAndreas Gohr    $evt = new Event('COMMON_USER_LINK', $data);
164060a396c8SGerrit Uitslag    if($evt->advise_before(true)) {
164160a396c8SGerrit Uitslag        if(empty($data['name'])) {
164260a396c8SGerrit Uitslag            if($auth) $info = $auth->getUserData($username);
164365833968SGerrit Uitslag            if($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1644dc58b6f4SAndy Webber                switch($conf['showuseras']) {
1645dc58b6f4SAndy Webber                    case 'username':
16467f081821SGerrit Uitslag                    case 'username_link':
164715f3bc49SGerrit Uitslag                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
164860a396c8SGerrit Uitslag                        break;
1649dc58b6f4SAndy Webber                    case 'email':
1650dc58b6f4SAndy Webber                    case 'email_link':
165160a396c8SGerrit Uitslag                        $data['name'] = obfuscate($info['mail']);
165260a396c8SGerrit Uitslag                        break;
1653dc58b6f4SAndy Webber                }
165465833968SGerrit Uitslag            } else {
165565833968SGerrit Uitslag                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
165660a396c8SGerrit Uitslag            }
165760a396c8SGerrit Uitslag        }
16587f081821SGerrit Uitslag
16597f081821SGerrit Uitslag        /** @var Doku_Renderer_xhtml $xhtml_renderer */
16607f081821SGerrit Uitslag        static $xhtml_renderer = null;
16617f081821SGerrit Uitslag
166215f3bc49SGerrit Uitslag        if(!$data['textonly'] && empty($data['link']['url'])) {
16637f081821SGerrit Uitslag
16647f081821SGerrit Uitslag            if(in_array($conf['showuseras'], array('email_link', 'username_link'))) {
166560a396c8SGerrit Uitslag                if(!isset($info)) {
166660a396c8SGerrit Uitslag                    if($auth) $info = $auth->getUserData($username);
166760a396c8SGerrit Uitslag                }
166860a396c8SGerrit Uitslag                if(isset($info) && $info) {
16697f081821SGerrit Uitslag                    if($conf['showuseras'] == 'email_link') {
167060a396c8SGerrit Uitslag                        $data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
1671dc58b6f4SAndy Webber                    } else {
16727f081821SGerrit Uitslag                        if(is_null($xhtml_renderer)) {
16737f081821SGerrit Uitslag                            $xhtml_renderer = p_get_renderer('xhtml');
16747f081821SGerrit Uitslag                        }
16757f081821SGerrit Uitslag                        if(empty($xhtml_renderer->interwiki)) {
16767f081821SGerrit Uitslag                            $xhtml_renderer->interwiki = getInterwiki();
16777f081821SGerrit Uitslag                        }
16787f081821SGerrit Uitslag                        $shortcut = 'user';
1679533772e1SGerrit Uitslag                        $exists = null;
16806496c33fSGerrit Uitslag                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
16812a2a43c4SGerrit Uitslag                        $data['link']['class'] .= ' interwiki iw_user';
16826496c33fSGerrit Uitslag                        if($exists !== null) {
16836496c33fSGerrit Uitslag                            if($exists) {
16846496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink1';
16856496c33fSGerrit Uitslag                            } else {
16866496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink2';
16876496c33fSGerrit Uitslag                                $data['link']['rel'] = 'nofollow';
16886496c33fSGerrit Uitslag                            }
16896496c33fSGerrit Uitslag                        }
1690dc58b6f4SAndy Webber                    }
1691dc58b6f4SAndy Webber                } else {
169215f3bc49SGerrit Uitslag                    $data['textonly'] = true;
1693dc58b6f4SAndy Webber                }
169460a396c8SGerrit Uitslag
169560a396c8SGerrit Uitslag            } else {
169615f3bc49SGerrit Uitslag                $data['textonly'] = true;
169760a396c8SGerrit Uitslag            }
169860a396c8SGerrit Uitslag        }
169960a396c8SGerrit Uitslag
170015f3bc49SGerrit Uitslag        if($data['textonly']) {
17014d5fc927SGerrit Uitslag            $data['userlink'] = $data['name'];
170260a396c8SGerrit Uitslag        } else {
170360a396c8SGerrit Uitslag            $data['link']['name'] = $data['name'];
170460a396c8SGerrit Uitslag            if(is_null($xhtml_renderer)) {
170560a396c8SGerrit Uitslag                $xhtml_renderer = p_get_renderer('xhtml');
170660a396c8SGerrit Uitslag            }
17074d5fc927SGerrit Uitslag            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
170860a396c8SGerrit Uitslag        }
170960a396c8SGerrit Uitslag    }
171060a396c8SGerrit Uitslag    $evt->advise_after();
171160a396c8SGerrit Uitslag    unset($evt);
171260a396c8SGerrit Uitslag
17134d5fc927SGerrit Uitslag    return $data['userlink'];
1714066fee30SAndreas Gohr}
1715066fee30SAndreas Gohr
1716066fee30SAndreas Gohr/**
1717066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1718066fee30SAndreas Gohr * When no image exists, returns an empty string
1719066fee30SAndreas Gohr *
1720066fee30SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1721140cfbcdSGerrit Uitslag *
1722066fee30SAndreas Gohr * @param  string $type - type of image 'badge' or 'button'
17233272d797SAndreas Gohr * @return string
1724066fee30SAndreas Gohr */
1725066fee30SAndreas Gohrfunction license_img($type) {
1726066fee30SAndreas Gohr    global $license;
1727066fee30SAndreas Gohr    global $conf;
1728066fee30SAndreas Gohr    if(!$conf['license']) return '';
1729066fee30SAndreas Gohr    if(!is_array($license[$conf['license']])) return '';
1730066fee30SAndreas Gohr    $try   = array();
1731066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1732066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1733066fee30SAndreas Gohr    if(substr($conf['license'], 0, 3) == 'cc-') {
1734066fee30SAndreas Gohr        $try[] = 'lib/images/license/'.$type.'/cc.png';
1735066fee30SAndreas Gohr    }
1736066fee30SAndreas Gohr    foreach($try as $src) {
173779e79377SAndreas Gohr        if(file_exists(DOKU_INC.$src)) return $src;
1738066fee30SAndreas Gohr    }
1739066fee30SAndreas Gohr    return '';
1740dc58b6f4SAndy Webber}
1741dc58b6f4SAndy Webber
174213c08e2fSMichael Klier/**
174313c08e2fSMichael Klier * Checks if the given amount of memory is available
174413c08e2fSMichael Klier *
174513c08e2fSMichael Klier * If the memory_get_usage() function is not available the
174613c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
174713c08e2fSMichael Klier *
174813c08e2fSMichael Klier * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
174913c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
17503272d797SAndreas Gohr *
17513272d797SAndreas Gohr * @param int  $mem    Size of memory you want to allocate in bytes
1752140cfbcdSGerrit Uitslag * @param int  $bytes  already allocated memory (see above)
17533272d797SAndreas Gohr * @return bool
175413c08e2fSMichael Klier */
175513c08e2fSMichael Klierfunction is_mem_available($mem, $bytes = 1048576) {
175613c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
175713c08e2fSMichael Klier    if(empty($limit)) return true; // no limit set!
1758985d6187SElenchus    if($limit == -1) return true; // unlimited
175913c08e2fSMichael Klier
176013c08e2fSMichael Klier    // parse limit to bytes
176113c08e2fSMichael Klier    $limit = php_to_byte($limit);
176213c08e2fSMichael Klier
176313c08e2fSMichael Klier    // get used memory if possible
176413c08e2fSMichael Klier    if(function_exists('memory_get_usage')) {
176513c08e2fSMichael Klier        $used = memory_get_usage();
176649eb6e38SAndreas Gohr    } else {
176749eb6e38SAndreas Gohr        $used = $bytes;
176813c08e2fSMichael Klier    }
176913c08e2fSMichael Klier
177013c08e2fSMichael Klier    if($used + $mem > $limit) {
177113c08e2fSMichael Klier        return false;
177213c08e2fSMichael Klier    }
177313c08e2fSMichael Klier
177413c08e2fSMichael Klier    return true;
177513c08e2fSMichael Klier}
177613c08e2fSMichael Klier
1777af2408d5SAndreas Gohr/**
1778af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1779af2408d5SAndreas Gohr *
1780af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1781af2408d5SAndreas Gohr *
1782af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1783af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1784140cfbcdSGerrit Uitslag *
1785140cfbcdSGerrit Uitslag * @param string $url url being directed to
1786af2408d5SAndreas Gohr */
1787af2408d5SAndreas Gohrfunction send_redirect($url) {
178898ca30d2SAndreas Gohr    $url = stripctl($url); // defend against HTTP Response Splitting
178998ca30d2SAndreas Gohr
1790585bf44eSChristopher Smith    /* @var Input $INPUT */
1791585bf44eSChristopher Smith    global $INPUT;
1792585bf44eSChristopher Smith
17930181f021SAndreas Gohr    //are there any undisplayed messages? keep them in session for display
17940181f021SAndreas Gohr    global $MSG;
17950181f021SAndreas Gohr    if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
17960181f021SAndreas Gohr        //reopen session, store data and close session again
17970181f021SAndreas Gohr        @session_start();
17980181f021SAndreas Gohr        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
17990181f021SAndreas Gohr    }
18000181f021SAndreas Gohr
1801d4869846SAndreas Gohr    // always close the session
1802d4869846SAndreas Gohr    session_write_close();
1803d4869846SAndreas Gohr
1804af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
1805585bf44eSChristopher Smith    if($INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1806585bf44eSChristopher Smith        (strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) &&
1807585bf44eSChristopher Smith        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
18083272d797SAndreas Gohr        $matches[1] < 6
18093272d797SAndreas Gohr    ) {
1810af2408d5SAndreas Gohr        header('Refresh: 0;url='.$url);
1811af2408d5SAndreas Gohr    } else {
1812af2408d5SAndreas Gohr        header('Location: '.$url);
1813af2408d5SAndreas Gohr    }
181481781cb6SAndreas Gohr
1815572dc222SLarsDW223    // no exits during unit tests
181627c0c399SAndreas Gohr    if(defined('DOKU_UNITTEST')) {
181727c0c399SAndreas Gohr        // pass info about the redirect back to the test suite
181827c0c399SAndreas Gohr        $testRequest = TestRequest::getRunning();
181927c0c399SAndreas Gohr        if($testRequest !== null) {
182027c0c399SAndreas Gohr            $testRequest->addData('send_redirect', $url);
182127c0c399SAndreas Gohr        }
1822572dc222SLarsDW223        return;
1823572dc222SLarsDW223    }
182427c0c399SAndreas Gohr
1825af2408d5SAndreas Gohr    exit;
1826af2408d5SAndreas Gohr}
1827af2408d5SAndreas Gohr
18285b75cd1fSAdrian Lang/**
18295b75cd1fSAdrian Lang * Validate a value using a set of valid values
18305b75cd1fSAdrian Lang *
18315b75cd1fSAdrian Lang * This function checks whether a specified value is set and in the array
18325b75cd1fSAdrian Lang * $valid_values. If not, the function returns a default value or, if no
18335b75cd1fSAdrian Lang * default is specified, throws an exception.
18345b75cd1fSAdrian Lang *
18355b75cd1fSAdrian Lang * @param string $param        The name of the parameter
18365b75cd1fSAdrian Lang * @param array  $valid_values A set of valid values; Optionally a default may
18375b75cd1fSAdrian Lang *                             be marked by the key “default”.
18385b75cd1fSAdrian Lang * @param array  $array        The array containing the value (typically $_POST
18395b75cd1fSAdrian Lang *                             or $_GET)
18405b75cd1fSAdrian Lang * @param string $exc          The text of the raised exception
18415b75cd1fSAdrian Lang *
18423272d797SAndreas Gohr * @throws Exception
18433272d797SAndreas Gohr * @return mixed
18445b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
18455b75cd1fSAdrian Lang */
18465b75cd1fSAdrian Langfunction valid_input_set($param, $valid_values, $array, $exc = '') {
18475b75cd1fSAdrian Lang    if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
18485b75cd1fSAdrian Lang        return $array[$param];
18495b75cd1fSAdrian Lang    } elseif(isset($valid_values['default'])) {
18505b75cd1fSAdrian Lang        return $valid_values['default'];
18515b75cd1fSAdrian Lang    } else {
18525b75cd1fSAdrian Lang        throw new Exception($exc);
18535b75cd1fSAdrian Lang    }
18545b75cd1fSAdrian Lang}
18555b75cd1fSAdrian Lang
185663703ba5SAndreas Gohr/**
185763703ba5SAndreas Gohr * Read a preference from the DokuWiki cookie
1858646a531aSChristopher Smith * (remembering both keys & values are urlencoded)
1859140cfbcdSGerrit Uitslag *
1860140cfbcdSGerrit Uitslag * @param string $pref     preference key
1861b4b6c9a1SGerrit Uitslag * @param mixed  $default  value returned when preference not found
1862140cfbcdSGerrit Uitslag * @return string preference value
186363703ba5SAndreas Gohr */
1864554a8c9fSAdrian Langfunction get_doku_pref($pref, $default) {
1865646a531aSChristopher Smith    $enc_pref = urlencode($pref);
186606c9ee33SMarius van Witzenburg    if(isset($_COOKIE['DOKU_PREFS']) && strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
1867554a8c9fSAdrian Lang        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
186863703ba5SAndreas Gohr        $cnt   = count($parts);
18691c3eca7dSPhy
18701c3eca7dSPhy        // due to #2721 there might be duplicate entries,
18711c3eca7dSPhy        // so we read from the end
18721c3eca7dSPhy        for($i = $cnt-2; $i >= 0; $i -= 2) {
1873646a531aSChristopher Smith            if($parts[$i] == $enc_pref) {
1874646a531aSChristopher Smith                return urldecode($parts[$i + 1]);
1875554a8c9fSAdrian Lang            }
1876554a8c9fSAdrian Lang        }
1877554a8c9fSAdrian Lang    }
1878554a8c9fSAdrian Lang    return $default;
1879554a8c9fSAdrian Lang}
1880554a8c9fSAdrian Lang
18813c94d07bSAnika Henke/**
18823c94d07bSAnika Henke * Add a preference to the DokuWiki cookie
188336ec377eSChristopher Smith * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
18843a970889SAnika Henke * Remove it by setting $val to false
1885140cfbcdSGerrit Uitslag *
1886140cfbcdSGerrit Uitslag * @param string $pref  preference key
1887140cfbcdSGerrit Uitslag * @param string $val   preference value
18883c94d07bSAnika Henke */
18893c94d07bSAnika Henkefunction set_doku_pref($pref, $val) {
18903c94d07bSAnika Henke    global $conf;
18913c94d07bSAnika Henke    $orig = get_doku_pref($pref, false);
18923c94d07bSAnika Henke    $cookieVal = '';
18933c94d07bSAnika Henke
18941c3eca7dSPhy    if($orig !== false && ($orig !== $val)) {
18953c94d07bSAnika Henke        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
18963c94d07bSAnika Henke        $cnt   = count($parts);
189736ec377eSChristopher Smith        // urlencode $pref for the comparison
189836ec377eSChristopher Smith        $enc_pref = rawurlencode($pref);
18991c3eca7dSPhy        $seen = false;
19003c94d07bSAnika Henke        for ($i = 0; $i < $cnt; $i += 2) {
190136ec377eSChristopher Smith            if ($parts[$i] == $enc_pref) {
19021c3eca7dSPhy                if (!$seen){
19033a970889SAnika Henke                    if ($val !== false) {
1904bf8f8509SAndreas Gohr                        $parts[$i + 1] = rawurlencode($val ?? '');
19053a970889SAnika Henke                    } else {
19063a970889SAnika Henke                        unset($parts[$i]);
19073a970889SAnika Henke                        unset($parts[$i + 1]);
19083a970889SAnika Henke                    }
19091c3eca7dSPhy                    $seen = true;
19101c3eca7dSPhy                } else {
19111c3eca7dSPhy                    // no break because we want to remove duplicate entries
19121c3eca7dSPhy                    unset($parts[$i]);
19131c3eca7dSPhy                    unset($parts[$i + 1]);
19141c3eca7dSPhy                }
19153c94d07bSAnika Henke            }
19163c94d07bSAnika Henke        }
19173c94d07bSAnika Henke        $cookieVal = implode('#', $parts);
19181c3eca7dSPhy    } else if ($orig === false && $val !== false) {
1919c10f256aSDamien Regad        $cookieVal = (isset($_COOKIE['DOKU_PREFS']) ? $_COOKIE['DOKU_PREFS'] . '#' : '') .
192064159a61SAndreas Gohr            rawurlencode($pref) . '#' . rawurlencode($val);
19213c94d07bSAnika Henke    }
19223c94d07bSAnika Henke
192375e4dd8aSGerrit Uitslag    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
19245833995aSPhy    if(defined('DOKU_UNITTEST')) {
19255833995aSPhy        $_COOKIE['DOKU_PREFS'] = $cookieVal;
19265833995aSPhy    }else{
192775e4dd8aSGerrit Uitslag        setcookie('DOKU_PREFS', $cookieVal, time()+365*24*3600, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
19283c94d07bSAnika Henke    }
19293c94d07bSAnika Henke}
19303c94d07bSAnika Henke
1931f8fb2d18SAndreas Gohr/**
1932f8fb2d18SAndreas Gohr * Strips source mapping declarations from given text #601
1933f8fb2d18SAndreas Gohr *
193442ea7f44SGerrit Uitslag * @param string &$text reference to the CSS or JavaScript code to clean
1935f8fb2d18SAndreas Gohr */
1936f8fb2d18SAndreas Gohrfunction stripsourcemaps(&$text){
1937f8fb2d18SAndreas Gohr    $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text);
1938f8fb2d18SAndreas Gohr}
1939f8fb2d18SAndreas Gohr
19403c27983bSAndreas Gohr/**
194171de5572SAndreas Gohr * Returns the contents of a given SVG file for embedding
19423c27983bSAndreas Gohr *
19433c27983bSAndreas Gohr * Inlining SVGs saves on HTTP requests and more importantly allows for styling them through
19443c27983bSAndreas Gohr * CSS. However it should used with small SVGs only. The $maxsize setting ensures only small
19453c27983bSAndreas Gohr * files are embedded.
19463c27983bSAndreas Gohr *
194771de5572SAndreas Gohr * This strips unneeded headers, comments and newline. The result is not a vaild standalone SVG!
194871de5572SAndreas Gohr *
19493c27983bSAndreas Gohr * @param string $file full path to the SVG file
19503c27983bSAndreas Gohr * @param int $maxsize maximum allowed size for the SVG to be embedded
195171de5572SAndreas Gohr * @return string|false the SVG content, false if the file couldn't be loaded
19523c27983bSAndreas Gohr */
19534cd2074fSAndreas Gohrfunction inlineSVG($file, $maxsize = 2048) {
19543c27983bSAndreas Gohr    $file = trim($file);
19553c27983bSAndreas Gohr    if($file === '') return false;
19563c27983bSAndreas Gohr    if(!file_exists($file)) return false;
19573c27983bSAndreas Gohr    if(filesize($file) > $maxsize) return false;
19583c27983bSAndreas Gohr    if(!is_readable($file)) return false;
19593c27983bSAndreas Gohr    $content = file_get_contents($file);
19600849fa88SAndreas Gohr    $content = preg_replace('/<!--.*?(-->)/s','', $content); // comments
19610849fa88SAndreas Gohr    $content = preg_replace('/<\?xml .*?\?>/i', '', $content); // xml header
19620849fa88SAndreas Gohr    $content = preg_replace('/<!DOCTYPE .*?>/i', '', $content); // doc type
19630849fa88SAndreas Gohr    $content = preg_replace('/>\s+</s', '><', $content); // newlines between tags
19643c27983bSAndreas Gohr    $content = trim($content);
19653c27983bSAndreas Gohr    if(substr($content, 0, 5) !== '<svg ') return false;
196671de5572SAndreas Gohr    return $content;
19673c27983bSAndreas Gohr}
19683c27983bSAndreas Gohr
1969e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1970