xref: /dokuwiki/inc/common.php (revision 24870174d2ee45460ba6bcfe5f5a0ae94715efd7)
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 */
8*24870174SAndreas Gohruse dokuwiki\PassHash;
9*24870174SAndreas Gohruse dokuwiki\Draft;
10*24870174SAndreas Gohruse dokuwiki\Utf8\Clean;
11*24870174SAndreas Gohruse dokuwiki\Utf8\PhpString;
12*24870174SAndreas Gohruse dokuwiki\Utf8\Conversion;
130db5771eSMichael Großeuse dokuwiki\Cache\CacheInstructions;
140db5771eSMichael Großeuse dokuwiki\Cache\CacheRenderer;
150c3a5702SAndreas Gohruse dokuwiki\ChangeLog\PageChangeLog;
16b24e9c4aSSatoshi Saharause dokuwiki\File\PageFile;
1766f4cdd4SSatoshi Saharause dokuwiki\Logger;
18704a815fSMichael Großeuse dokuwiki\Subscriptions\PageSubscriptionSender;
1975d66495SMichael Großeuse dokuwiki\Subscriptions\SubscriberManager;
20e1d9dcc8SAndreas Gohruse dokuwiki\Extension\AuthPlugin;
21e1d9dcc8SAndreas Gohruse dokuwiki\Extension\Event;
220c3a5702SAndreas Gohr
23f3f0262cSandi/**
24d5197206Schris * Wrapper around htmlspecialchars()
25d5197206Schris *
26d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
27d5197206Schris * @see    htmlspecialchars()
28140cfbcdSGerrit Uitslag *
29140cfbcdSGerrit Uitslag * @param string $string the string being converted
30140cfbcdSGerrit Uitslag * @return string converted string
31d5197206Schris */
32d5197206Schrisfunction hsc($string) {
33f7711f2bSAndreas Gohr    return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, 'UTF-8');
34d5197206Schris}
35d5197206Schris
36d5197206Schris/**
3712dd3cbcSAndreas Gohr * A safer explode for fixed length lists
3812dd3cbcSAndreas Gohr *
3912dd3cbcSAndreas Gohr * This works just like explode(), but will always return the wanted number of elements.
4012dd3cbcSAndreas Gohr * If the $input string does not contain enough elements, the missing elements will be
4112dd3cbcSAndreas Gohr * filled up with the $default value. If the input string contains more elements, the last
4212dd3cbcSAndreas Gohr * one will NOT be split up and will still contain $separator
4312dd3cbcSAndreas Gohr *
4412dd3cbcSAndreas Gohr * @param string $separator The boundary string
4512dd3cbcSAndreas Gohr * @param string $string The input string
4612dd3cbcSAndreas Gohr * @param int $limit The number of expected elements
4712dd3cbcSAndreas Gohr * @param mixed $default The value to use when filling up missing elements
4812dd3cbcSAndreas Gohr * @see explode
4912dd3cbcSAndreas Gohr * @return array
5012dd3cbcSAndreas Gohr */
5112dd3cbcSAndreas Gohrfunction sexplode($separator, $string, $limit, $default = null)
5212dd3cbcSAndreas Gohr{
5312dd3cbcSAndreas Gohr    return array_pad(explode($separator, $string, $limit), $limit, $default);
5412dd3cbcSAndreas Gohr}
5512dd3cbcSAndreas Gohr
5612dd3cbcSAndreas Gohr/**
575b571377SAndreas Gohr * Checks if the given input is blank
585b571377SAndreas Gohr *
595b571377SAndreas Gohr * This is similar to empty() but will return false for "0".
605b571377SAndreas Gohr *
6167234204SAndreas Gohr * Please note: when you pass uninitialized variables, they will implicitly be created
6267234204SAndreas Gohr * with a NULL value without warning.
6367234204SAndreas Gohr *
6467234204SAndreas Gohr * To avoid this it's recommended to guard the call with isset like this:
6567234204SAndreas Gohr *
6667234204SAndreas Gohr * (isset($foo) && !blank($foo))
6767234204SAndreas Gohr * (!isset($foo) || blank($foo))
6867234204SAndreas Gohr *
695b571377SAndreas Gohr * @param $in
705b571377SAndreas Gohr * @param bool $trim Consider a string of whitespace to be blank
715b571377SAndreas Gohr * @return bool
725b571377SAndreas Gohr */
735b571377SAndreas Gohrfunction blank(&$in, $trim = false) {
745b571377SAndreas Gohr    if(is_null($in)) return true;
75*24870174SAndreas Gohr    if(is_array($in)) return $in === [];
765b571377SAndreas Gohr    if($in === "\0") return true;
775b571377SAndreas Gohr    if($trim && trim($in) === '') return true;
785b571377SAndreas Gohr    if(strlen($in) > 0) return false;
795b571377SAndreas Gohr    return empty($in);
805b571377SAndreas Gohr}
815b571377SAndreas Gohr
825b571377SAndreas Gohr/**
83d5197206Schris * print a newline terminated string
84d5197206Schris *
85d5197206Schris * You can give an indention as optional parameter
86d5197206Schris *
87d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
88140cfbcdSGerrit Uitslag *
89140cfbcdSGerrit Uitslag * @param string $string  line of text
90140cfbcdSGerrit Uitslag * @param int    $indent  number of spaces indention
91d5197206Schris */
9225ec097bSChris Smithfunction ptln($string, $indent = 0) {
9325ec097bSChris Smith    echo str_repeat(' ', $indent)."$string\n";
9402b0b681SAndreas Gohr}
9502b0b681SAndreas Gohr
9602b0b681SAndreas Gohr/**
9702b0b681SAndreas Gohr * strips control characters (<32) from the given string
9802b0b681SAndreas Gohr *
9902b0b681SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
100140cfbcdSGerrit Uitslag *
10142ea7f44SGerrit Uitslag * @param string $string being stripped
102140cfbcdSGerrit Uitslag * @return string
10302b0b681SAndreas Gohr */
10402b0b681SAndreas Gohrfunction stripctl($string) {
10502b0b681SAndreas Gohr    return preg_replace('/[\x00-\x1F]+/s', '', $string);
106d5197206Schris}
107d5197206Schris
108d5197206Schris/**
109634d7150SAndreas Gohr * Return a secret token to be used for CSRF attack prevention
110634d7150SAndreas Gohr *
111634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
112634d7150SAndreas Gohr * @link    http://en.wikipedia.org/wiki/Cross-site_request_forgery
113634d7150SAndreas Gohr * @link    http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
11442ea7f44SGerrit Uitslag *
115634d7150SAndreas Gohr * @return  string
116634d7150SAndreas Gohr */
117634d7150SAndreas Gohrfunction getSecurityToken() {
118585bf44eSChristopher Smith    /** @var Input $INPUT */
119585bf44eSChristopher Smith    global $INPUT;
1203680e2cdSAndreas Gohr
1213680e2cdSAndreas Gohr    $user = $INPUT->server->str('REMOTE_USER');
1223680e2cdSAndreas Gohr    $session = session_id();
1233680e2cdSAndreas Gohr
1243680e2cdSAndreas Gohr    // CSRF checks are only for logged in users - do not generate for anonymous
1253680e2cdSAndreas Gohr    if(trim($user) == '' || trim($session) == '') return '';
126*24870174SAndreas Gohr    return PassHash::hmac('md5', $session.$user, auth_cookiesalt());
127634d7150SAndreas Gohr}
128634d7150SAndreas Gohr
129634d7150SAndreas Gohr/**
130634d7150SAndreas Gohr * Check the secret CSRF token
131140cfbcdSGerrit Uitslag *
132140cfbcdSGerrit Uitslag * @param null|string $token security token or null to read it from request variable
133140cfbcdSGerrit Uitslag * @return bool success if the token matched
134634d7150SAndreas Gohr */
135634d7150SAndreas Gohrfunction checkSecurityToken($token = null) {
136585bf44eSChristopher Smith    /** @var Input $INPUT */
1377d01a0eaSTom N Harris    global $INPUT;
138585bf44eSChristopher Smith    if(!$INPUT->server->str('REMOTE_USER')) return true; // no logged in user, no need for a check
139df97eaacSAndreas Gohr
1407d01a0eaSTom N Harris    if(is_null($token)) $token = $INPUT->str('sectok');
141634d7150SAndreas Gohr    if(getSecurityToken() != $token) {
142634d7150SAndreas Gohr        msg('Security Token did not match. Possible CSRF attack.', -1);
143634d7150SAndreas Gohr        return false;
144634d7150SAndreas Gohr    }
145634d7150SAndreas Gohr    return true;
146634d7150SAndreas Gohr}
147634d7150SAndreas Gohr
148634d7150SAndreas Gohr/**
149634d7150SAndreas Gohr * Print a hidden form field with a secret CSRF token
150634d7150SAndreas Gohr *
151634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
152140cfbcdSGerrit Uitslag *
153140cfbcdSGerrit Uitslag * @param bool $print  if true print the field, otherwise html of the field is returned
15442ea7f44SGerrit Uitslag * @return string html of hidden form field
155634d7150SAndreas Gohr */
156634d7150SAndreas Gohrfunction formSecurityToken($print = true) {
1572404d0edSAnika Henke    $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
1583272d797SAndreas Gohr    if($print) echo $ret;
159634d7150SAndreas Gohr    return $ret;
160634d7150SAndreas Gohr}
161634d7150SAndreas Gohr
162634d7150SAndreas Gohr/**
1631015a57dSChristopher Smith * Determine basic information for a request of $id
16415fae107Sandi *
16515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1667e87a794SChristopher Smith * @author Chris Smith <chris@jalakai.co.uk>
167140cfbcdSGerrit Uitslag *
168140cfbcdSGerrit Uitslag * @param string $id         pageid
169140cfbcdSGerrit Uitslag * @param bool   $htmlClient add info about whether is mobile browser
170140cfbcdSGerrit Uitslag * @return array with info for a request of $id
171140cfbcdSGerrit Uitslag *
172f3f0262cSandi */
1731015a57dSChristopher Smithfunction basicinfo($id, $htmlClient=true){
174f3f0262cSandi    global $USERINFO;
175585bf44eSChristopher Smith    /* @var Input $INPUT */
176585bf44eSChristopher Smith    global $INPUT;
1776afe8dcaSchris
178c66972f2SAdrian Lang    // set info about manager/admin status.
179*24870174SAndreas Gohr    $info = [];
180c66972f2SAdrian Lang    $info['isadmin']   = false;
181c66972f2SAdrian Lang    $info['ismanager'] = false;
182585bf44eSChristopher Smith    if($INPUT->server->has('REMOTE_USER')) {
183f3f0262cSandi        $info['userinfo']   = $USERINFO;
1841015a57dSChristopher Smith        $info['perm']       = auth_quickaclcheck($id);
185585bf44eSChristopher Smith        $info['client']     = $INPUT->server->str('REMOTE_USER');
18617ee7f66SAndreas Gohr
187f8cc712eSAndreas Gohr        if($info['perm'] == AUTH_ADMIN) {
188f8cc712eSAndreas Gohr            $info['isadmin']   = true;
189f8cc712eSAndreas Gohr            $info['ismanager'] = true;
190f8cc712eSAndreas Gohr        } elseif(auth_ismanager()) {
191f8cc712eSAndreas Gohr            $info['ismanager'] = true;
192f8cc712eSAndreas Gohr        }
193f8cc712eSAndreas Gohr
19417ee7f66SAndreas Gohr        // if some outside auth were used only REMOTE_USER is set
195a58fcbbcSAndreas Gohr        if(empty($info['userinfo']['name'])) {
196585bf44eSChristopher Smith            $info['userinfo']['name'] = $INPUT->server->str('REMOTE_USER');
19717ee7f66SAndreas Gohr        }
198ee4c4a1bSAndreas Gohr
199f3f0262cSandi    } else {
2001015a57dSChristopher Smith        $info['perm']       = auth_aclcheck($id, '', null);
201ee4c4a1bSAndreas Gohr        $info['client']     = clientIP(true);
202f3f0262cSandi    }
203f3f0262cSandi
2041015a57dSChristopher Smith    $info['namespace'] = getNS($id);
2051015a57dSChristopher Smith
2061015a57dSChristopher Smith    // mobile detection
2071015a57dSChristopher Smith    if ($htmlClient) {
2081015a57dSChristopher Smith        $info['ismobile'] = clientismobile();
2091015a57dSChristopher Smith    }
2101015a57dSChristopher Smith
2111015a57dSChristopher Smith    return $info;
2121015a57dSChristopher Smith }
2131015a57dSChristopher Smith
2141015a57dSChristopher Smith/**
2151015a57dSChristopher Smith * Return info about the current document as associative
2161015a57dSChristopher Smith * array.
2171015a57dSChristopher Smith *
2181015a57dSChristopher Smith * @author Andreas Gohr <andi@splitbrain.org>
219140cfbcdSGerrit Uitslag *
220140cfbcdSGerrit Uitslag * @return array with info about current document
2211015a57dSChristopher Smith */
2221015a57dSChristopher Smithfunction pageinfo() {
2231015a57dSChristopher Smith    global $ID;
2241015a57dSChristopher Smith    global $REV;
2251015a57dSChristopher Smith    global $RANGE;
2261015a57dSChristopher Smith    global $lang;
227585bf44eSChristopher Smith    /* @var Input $INPUT */
228585bf44eSChristopher Smith    global $INPUT;
2291015a57dSChristopher Smith
2301015a57dSChristopher Smith    $info = basicinfo($ID);
2311015a57dSChristopher Smith
2321015a57dSChristopher Smith    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
2331015a57dSChristopher Smith    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
2341015a57dSChristopher Smith    $info['id']  = $ID;
2351015a57dSChristopher Smith    $info['rev'] = $REV;
2361015a57dSChristopher Smith
23775d66495SMichael Große    $subManager = new SubscriberManager();
23875d66495SMichael Große    $info['subscribed'] = $subManager->userSubscription();
2397e87a794SChristopher Smith
240f3f0262cSandi    $info['locked']     = checklock($ID);
241317a04c4SSatoshi Sahara    $info['filepath']   = wikiFN($ID);
24279e79377SAndreas Gohr    $info['exists']     = file_exists($info['filepath']);
24301c9a118SAndreas Gohr    $info['currentrev'] = @filemtime($info['filepath']);
2445ec96136SSatoshi Sahara
2452ca9d91cSBen Coburn    if ($REV) {
2462ca9d91cSBen Coburn        //check if current revision was meant
24701c9a118SAndreas Gohr        if ($info['exists'] && ($info['currentrev'] == $REV)) {
2482ca9d91cSBen Coburn            $REV = '';
2497b3a6803SAndreas Gohr        } elseif ($RANGE) {
2507b3a6803SAndreas Gohr            //section editing does not work with old revisions!
2517b3a6803SAndreas Gohr            $REV   = '';
2527b3a6803SAndreas Gohr            $RANGE = '';
2537b3a6803SAndreas Gohr            msg($lang['nosecedit'], 0);
2542ca9d91cSBen Coburn        } else {
2552ca9d91cSBen Coburn            //really use old revision
256317a04c4SSatoshi Sahara            $info['filepath'] = wikiFN($ID, $REV);
25779e79377SAndreas Gohr            $info['exists']   = file_exists($info['filepath']);
258f3f0262cSandi        }
259f3f0262cSandi    }
260c112d578Sandi    $info['rev'] = $REV;
261f3f0262cSandi    if ($info['exists']) {
262252acce3SSatoshi Sahara        $info['writable'] = (is_writable($info['filepath']) && $info['perm'] >= AUTH_EDIT);
263f3f0262cSandi    } else {
264f3f0262cSandi        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
265f3f0262cSandi    }
26650e988b1SAndreas Gohr    $info['editable'] = ($info['writable'] && empty($info['locked']));
267f3f0262cSandi    $info['lastmod']  = @filemtime($info['filepath']);
268f3f0262cSandi
26971726d78SBen Coburn    //load page meta data
27071726d78SBen Coburn    $info['meta'] = p_get_metadata($ID);
27171726d78SBen Coburn
272652610a2Sandi    //who's the editor
273047bad06SGerrit Uitslag    $pagelog = new PageChangeLog($ID, 1024);
274652610a2Sandi    if ($REV) {
275f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($REV);
276*24870174SAndreas Gohr    } elseif (!empty($info['meta']['last_change']) && is_array($info['meta']['last_change'])) {
277aa27cf05SAndreas Gohr        $revinfo = $info['meta']['last_change'];
278aa27cf05SAndreas Gohr    } else {
279f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($info['lastmod']);
280cd00a034SBen Coburn        // cache most recent changelog line in metadata if missing and still valid
281cd00a034SBen Coburn        if ($revinfo !== false) {
282cd00a034SBen Coburn            $info['meta']['last_change'] = $revinfo;
283*24870174SAndreas Gohr            p_set_metadata($ID, ['last_change' => $revinfo]);
284cd00a034SBen Coburn        }
285cd00a034SBen Coburn    }
286cd00a034SBen Coburn    //and check for an external edit
287cd00a034SBen Coburn    if ($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
288cd00a034SBen Coburn        // cached changelog line no longer valid
289cd00a034SBen Coburn        $revinfo                     = false;
290cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
291*24870174SAndreas Gohr        p_set_metadata($ID, ['last_change' => $revinfo]);
292652610a2Sandi    }
293bb4866bdSchris
2940a444b5aSPhy    if ($revinfo !== false) {
295652610a2Sandi        $info['ip']   = $revinfo['ip'];
296652610a2Sandi        $info['user'] = $revinfo['user'];
297652610a2Sandi        $info['sum']  = $revinfo['sum'];
29871726d78SBen Coburn        // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
299ebf1501fSBen Coburn        // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
30059f257aeSchris
301252acce3SSatoshi Sahara        $info['editor'] = $revinfo['user'] ?: $revinfo['ip'];
3020a444b5aSPhy    } else {
3030a444b5aSPhy        $info['ip']     = null;
3040a444b5aSPhy        $info['user']   = null;
3050a444b5aSPhy        $info['sum']    = null;
3060a444b5aSPhy        $info['editor'] = null;
3070a444b5aSPhy    }
308652610a2Sandi
309ee4c4a1bSAndreas Gohr    // draft
310*24870174SAndreas Gohr    $draft = new Draft($ID, $info['client']);
3110aabe6f8SMichael Große    if ($draft->isDraftAvailable()) {
3120aabe6f8SMichael Große        $info['draft'] = $draft->getDraftFilename();
313ee4c4a1bSAndreas Gohr    }
314ee4c4a1bSAndreas Gohr
3151015a57dSChristopher Smith    return $info;
3161015a57dSChristopher Smith}
3171015a57dSChristopher Smith
3181015a57dSChristopher Smith/**
3190c39d46cSMichael Große * Initialize and/or fill global $JSINFO with some basic info to be given to javascript
3200c39d46cSMichael Große */
3210c39d46cSMichael Großefunction jsinfo() {
3220c39d46cSMichael Große    global $JSINFO, $ID, $INFO, $ACT;
3230c39d46cSMichael Große
3240c39d46cSMichael Große    if (!is_array($JSINFO)) {
3250c39d46cSMichael Große        $JSINFO = [];
3260c39d46cSMichael Große    }
3270c39d46cSMichael Große    //export minimal info to JS, plugins can add more
3280c39d46cSMichael Große    $JSINFO['id']                    = $ID;
32968491db9SPhy    $JSINFO['namespace']             = isset($INFO) ? (string) $INFO['namespace'] : '';
3300c39d46cSMichael Große    $JSINFO['ACT']                   = act_clean($ACT);
3310c39d46cSMichael Große    $JSINFO['useHeadingNavigation']  = (int) useHeading('navigation');
3320c39d46cSMichael Große    $JSINFO['useHeadingContent']     = (int) useHeading('content');
3330c39d46cSMichael Große}
3340c39d46cSMichael Große
3350c39d46cSMichael Große/**
3361015a57dSChristopher Smith * Return information about the current media item as an associative array.
337140cfbcdSGerrit Uitslag *
338140cfbcdSGerrit Uitslag * @return array with info about current media item
3391015a57dSChristopher Smith */
3401015a57dSChristopher Smithfunction mediainfo() {
3411015a57dSChristopher Smith    global $NS;
3421015a57dSChristopher Smith    global $IMG;
3431015a57dSChristopher Smith
3441015a57dSChristopher Smith    $info = basicinfo("$NS:*");
3451015a57dSChristopher Smith    $info['image'] = $IMG;
3461c548ebeSAndreas Gohr
347f3f0262cSandi    return $info;
348f3f0262cSandi}
349f3f0262cSandi
350f3f0262cSandi/**
3512684e50aSAndreas Gohr * Build an string of URL parameters
3522684e50aSAndreas Gohr *
3532684e50aSAndreas Gohr * @author Andreas Gohr
354140cfbcdSGerrit Uitslag *
355140cfbcdSGerrit Uitslag * @param array  $params    array with key-value pairs
356140cfbcdSGerrit Uitslag * @param string $sep       series of pairs are separated by this character
357140cfbcdSGerrit Uitslag * @return string query string
3582684e50aSAndreas Gohr */
359b174aeaeSchrisfunction buildURLparams($params, $sep = '&amp;') {
3602684e50aSAndreas Gohr    $url = '';
3612684e50aSAndreas Gohr    $amp = false;
3622684e50aSAndreas Gohr    foreach($params as $key => $val) {
363b174aeaeSchris        if($amp) $url .= $sep;
3642684e50aSAndreas Gohr
36585e6871fSAdrian Lang        $url .= rawurlencode($key).'=';
3663a50618cSgweissbach        $url .= rawurlencode((string) $val);
3672684e50aSAndreas Gohr        $amp = true;
3682684e50aSAndreas Gohr    }
3692684e50aSAndreas Gohr    return $url;
3702684e50aSAndreas Gohr}
3712684e50aSAndreas Gohr
3722684e50aSAndreas Gohr/**
3732684e50aSAndreas Gohr * Build an string of html tag attributes
3742684e50aSAndreas Gohr *
3757bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
3767bff22c0SAndreas Gohr *
3772684e50aSAndreas Gohr * @author Andreas Gohr
378140cfbcdSGerrit Uitslag *
379140cfbcdSGerrit Uitslag * @param array $params           array with (attribute name-attribute value) pairs
380246d3337SMichael Große * @param bool  $skipEmptyStrings skip empty string values?
381140cfbcdSGerrit Uitslag * @return string
3822684e50aSAndreas Gohr */
383246d3337SMichael Großefunction buildAttributes($params, $skipEmptyStrings = false) {
3842684e50aSAndreas Gohr    $url   = '';
3859063ec14SAdrian Lang    $white = false;
3862684e50aSAndreas Gohr    foreach($params as $key => $val) {
3872401f18dSSyntaxseed        if($key[0] == '_') continue;
388246d3337SMichael Große        if($val === '' && $skipEmptyStrings) continue;
3899063ec14SAdrian Lang        if($white) $url .= ' ';
3907bff22c0SAndreas Gohr
3912684e50aSAndreas Gohr        $url .= $key.'="';
392f7711f2bSAndreas Gohr        $url .= hsc($val);
3932684e50aSAndreas Gohr        $url .= '"';
3949063ec14SAdrian Lang        $white = true;
3952684e50aSAndreas Gohr    }
3962684e50aSAndreas Gohr    return $url;
3972684e50aSAndreas Gohr}
3982684e50aSAndreas Gohr
3992684e50aSAndreas Gohr/**
40015fae107Sandi * This builds the breadcrumb trail and returns it as array
40115fae107Sandi *
40215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
403140cfbcdSGerrit Uitslag *
404e3710957SGerrit Uitslag * @return string[] with the data: array(pageid=>name, ... )
405f3f0262cSandi */
406f3f0262cSandifunction breadcrumbs() {
4078746e727Sandi    // we prepare the breadcrumbs early for quick session closing
4088746e727Sandi    static $crumbs = null;
4098746e727Sandi    if($crumbs != null) return $crumbs;
4108746e727Sandi
411f3f0262cSandi    global $ID;
412f3f0262cSandi    global $ACT;
413f3f0262cSandi    global $conf;
4140ea5ebb4SB_S666    global $INFO;
415f3f0262cSandi
416f3f0262cSandi    //first visit?
417*24870174SAndreas Gohr    $crumbs = $_SESSION[DOKU_COOKIE]['bc'] ?? [];
4185603d3c1SHenry Pan    //we only save on show and existing visible readable wiki documents
419a77f5846Sjan    $file = wikiFN($ID);
4205603d3c1SHenry Pan    if($ACT != 'show' || $INFO['perm'] < AUTH_READ || isHiddenPage($ID) || !file_exists($file)) {
421e71ce681SAndreas Gohr        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
422f3f0262cSandi        return $crumbs;
423f3f0262cSandi    }
424a77f5846Sjan
425a77f5846Sjan    // page names
4261a84a0f3SAnika Henke    $name = noNSorNS($ID);
427fe9ec250SChris Smith    if(useHeading('navigation')) {
428a77f5846Sjan        // get page title
42967c15eceSMichael Hamann        $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
430a77f5846Sjan        if($title) {
431a77f5846Sjan            $name = $title;
432a77f5846Sjan        }
433a77f5846Sjan    }
434a77f5846Sjan
435f3f0262cSandi    //remove ID from array
436a77f5846Sjan    if(isset($crumbs[$ID])) {
437a77f5846Sjan        unset($crumbs[$ID]);
438f3f0262cSandi    }
439f3f0262cSandi
440f3f0262cSandi    //add to array
441a77f5846Sjan    $crumbs[$ID] = $name;
442f3f0262cSandi    //reduce size
443f3f0262cSandi    while(count($crumbs) > $conf['breadcrumbs']) {
444f3f0262cSandi        array_shift($crumbs);
445f3f0262cSandi    }
446f3f0262cSandi    //save to session
447e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
448f3f0262cSandi    return $crumbs;
449f3f0262cSandi}
450f3f0262cSandi
451f3f0262cSandi/**
45215fae107Sandi * Filter for page IDs
45315fae107Sandi *
454f3f0262cSandi * This is run on a ID before it is outputted somewhere
455f3f0262cSandi * currently used to replace the colon with something else
456907f24f7SAndreas Gohr * on Windows (non-IIS) systems and to have proper URL encoding
457907f24f7SAndreas Gohr *
458977aa967SAndreas Gohr * See discussions at https://github.com/dokuwiki/dokuwiki/pull/84 and
459977aa967SAndreas Gohr * https://github.com/dokuwiki/dokuwiki/pull/173 why we use a whitelist of
460907f24f7SAndreas Gohr * unaffected servers instead of blacklisting affected servers here.
46115fae107Sandi *
46249c713a3Sandi * Urlencoding is ommitted when the second parameter is false
46349c713a3Sandi *
46415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
465140cfbcdSGerrit Uitslag *
466140cfbcdSGerrit Uitslag * @param string $id pageid being filtered
467140cfbcdSGerrit Uitslag * @param bool   $ue apply urlencoding?
468140cfbcdSGerrit Uitslag * @return string
469f3f0262cSandi */
47049c713a3Sandifunction idfilter($id, $ue = true) {
471f3f0262cSandi    global $conf;
472585bf44eSChristopher Smith    /* @var Input $INPUT */
473585bf44eSChristopher Smith    global $INPUT;
474585bf44eSChristopher Smith
475bf8f8509SAndreas Gohr    $id = (string) $id;
476bf8f8509SAndreas Gohr
477f3f0262cSandi    if($conf['useslash'] && $conf['userewrite']) {
478f3f0262cSandi        $id = strtr($id, ':', '/');
479f3f0262cSandi    } elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
48058bedc8aSborekb        $conf['userewrite'] &&
481585bf44eSChristopher Smith        strpos($INPUT->server->str('SERVER_SOFTWARE'), 'Microsoft-IIS') === false
4823272d797SAndreas Gohr    ) {
483f3f0262cSandi        $id = strtr($id, ':', ';');
484f3f0262cSandi    }
48549c713a3Sandi    if($ue) {
486b6c6979fSAndreas Gohr        $id = rawurlencode($id);
487f3f0262cSandi        $id = str_replace('%3A', ':', $id); //keep as colon
488edd95259SGerrit Uitslag        $id = str_replace('%3B', ';', $id); //keep as semicolon
489f3f0262cSandi        $id = str_replace('%2F', '/', $id); //keep as slash
49049c713a3Sandi    }
491f3f0262cSandi    return $id;
492f3f0262cSandi}
493f3f0262cSandi
494f3f0262cSandi/**
495ed7b5f09Sandi * This builds a link to a wikipage
49615fae107Sandi *
4974bc480e5SAndreas Gohr * It handles URL rewriting and adds additional parameters
4986c7843b5Sandi *
49915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
5004bc480e5SAndreas Gohr *
5014bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
5024bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
5034bc480e5SAndreas Gohr * @param bool         $absolute       request an absolute URL instead of relative
5044bc480e5SAndreas Gohr * @param string       $separator      parameter separator
5054bc480e5SAndreas Gohr * @return string
506f3f0262cSandi */
50716f15a81SDominik Eckelmannfunction wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;') {
508f3f0262cSandi    global $conf;
50916f15a81SDominik Eckelmann    if(is_array($urlParameters)) {
5104bde2196Slisps        if(isset($urlParameters['rev']) && !$urlParameters['rev']) unset($urlParameters['rev']);
51164159a61SAndreas Gohr        if(isset($urlParameters['at']) && $conf['date_at_format']) {
51264159a61SAndreas Gohr            $urlParameters['at'] = date($conf['date_at_format'], $urlParameters['at']);
51364159a61SAndreas Gohr        }
51416f15a81SDominik Eckelmann        $urlParameters = buildURLparams($urlParameters, $separator);
5156de3759aSAndreas Gohr    } else {
51616f15a81SDominik Eckelmann        $urlParameters = str_replace(',', $separator, $urlParameters);
5176de3759aSAndreas Gohr    }
51816f15a81SDominik Eckelmann    if($id === '') {
51916f15a81SDominik Eckelmann        $id = $conf['start'];
52016f15a81SDominik Eckelmann    }
521f3f0262cSandi    $id = idfilter($id);
52216f15a81SDominik Eckelmann    if($absolute) {
523ed7b5f09Sandi        $xlink = DOKU_URL;
524ed7b5f09Sandi    } else {
525ed7b5f09Sandi        $xlink = DOKU_BASE;
526ed7b5f09Sandi    }
527f3f0262cSandi
5286c7843b5Sandi    if($conf['userewrite'] == 2) {
5296c7843b5Sandi        $xlink .= DOKU_SCRIPT.'/'.$id;
53016f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
5316c7843b5Sandi    } elseif($conf['userewrite']) {
532f3f0262cSandi        $xlink .= $id;
53316f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
53440b5fb5bSPhy    } elseif($id !== '') {
5356c7843b5Sandi        $xlink .= DOKU_SCRIPT.'?id='.$id;
53616f15a81SDominik Eckelmann        if($urlParameters) $xlink .= $separator.$urlParameters;
537bce3726dSAndreas Gohr    } else {
538bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
53916f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
540f3f0262cSandi    }
541f3f0262cSandi
542f3f0262cSandi    return $xlink;
543f3f0262cSandi}
544f3f0262cSandi
545f3f0262cSandi/**
546f5c2808fSBen Coburn * This builds a link to an alternate page format
547f5c2808fSBen Coburn *
548f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
549f5c2808fSBen Coburn *
550f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
5514bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
5524bc480e5SAndreas Gohr * @param string       $format         the export renderer to use
5534bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
5544bc480e5SAndreas Gohr * @param bool         $abs            request an absolute URL instead of relative
5554bc480e5SAndreas Gohr * @param string       $sep            parameter separator
5564bc480e5SAndreas Gohr * @return string
557f5c2808fSBen Coburn */
5584bc480e5SAndreas Gohrfunction exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;') {
559f5c2808fSBen Coburn    global $conf;
5604bc480e5SAndreas Gohr    if(is_array($urlParameters)) {
5614bc480e5SAndreas Gohr        $urlParameters = buildURLparams($urlParameters, $sep);
562f5c2808fSBen Coburn    } else {
5634bc480e5SAndreas Gohr        $urlParameters = str_replace(',', $sep, $urlParameters);
564f5c2808fSBen Coburn    }
565f5c2808fSBen Coburn
566f5c2808fSBen Coburn    $format = rawurlencode($format);
567f5c2808fSBen Coburn    $id     = idfilter($id);
568f5c2808fSBen Coburn    if($abs) {
569f5c2808fSBen Coburn        $xlink = DOKU_URL;
570f5c2808fSBen Coburn    } else {
571f5c2808fSBen Coburn        $xlink = DOKU_BASE;
572f5c2808fSBen Coburn    }
573f5c2808fSBen Coburn
574f5c2808fSBen Coburn    if($conf['userewrite'] == 2) {
575f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
5764bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
577f5c2808fSBen Coburn    } elseif($conf['userewrite'] == 1) {
578f5c2808fSBen Coburn        $xlink .= '_export/'.$format.'/'.$id;
5794bc480e5SAndreas Gohr        if($urlParameters) $xlink .= '?'.$urlParameters;
580f5c2808fSBen Coburn    } else {
581f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
5824bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
583f5c2808fSBen Coburn    }
584f5c2808fSBen Coburn
585f5c2808fSBen Coburn    return $xlink;
586f5c2808fSBen Coburn}
587f5c2808fSBen Coburn
588f5c2808fSBen Coburn/**
5896de3759aSAndreas Gohr * Build a link to a media file
5906de3759aSAndreas Gohr *
5916de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
5928c08db0aSAndreas Gohr *
5938c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
5948c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
5958c08db0aSAndreas Gohr *
5963272d797SAndreas Gohr * @param string  $id     the media file id or URL
5973272d797SAndreas Gohr * @param mixed   $more   string or array with additional parameters
5983272d797SAndreas Gohr * @param bool    $direct link to detail page if false
5993272d797SAndreas Gohr * @param string  $sep    URL parameter separator
6003272d797SAndreas Gohr * @param bool    $abs    Create an absolute URL
6013272d797SAndreas Gohr * @return string
6026de3759aSAndreas Gohr */
60355b2b31bSAndreas Gohrfunction ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false) {
6046de3759aSAndreas Gohr    global $conf;
605b9ee6a44SKlap-in    $isexternalimage = media_isexternal($id);
606826d2766SKlap-in    if(!$isexternalimage) {
607826d2766SKlap-in        $id = cleanID($id);
608826d2766SKlap-in    }
609826d2766SKlap-in
6106de3759aSAndreas Gohr    if(is_array($more)) {
6110f4e0092SChristopher Smith        // add token for resized images
612*24870174SAndreas Gohr        $w = $more['w'] ?? null;
613*24870174SAndreas Gohr        $h = $more['h'] ?? null;
61498fe1ac9SDamien Regad        if($w || $h || $isexternalimage){
615357c9a39SDamien Regad            $more['tok'] = media_get_token($id, $w, $h);
6160f4e0092SChristopher Smith        }
6178c08db0aSAndreas Gohr        // strip defaults for shorter URLs
6188c08db0aSAndreas Gohr        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
619443e135dSChristopher Smith        if(empty($more['w'])) unset($more['w']);
620443e135dSChristopher Smith        if(empty($more['h'])) unset($more['h']);
6218c08db0aSAndreas Gohr        if(isset($more['id']) && $direct) unset($more['id']);
62278b874e6Slisps        if(isset($more['rev']) && !$more['rev']) unset($more['rev']);
623b174aeaeSchris        $more = buildURLparams($more, $sep);
6246de3759aSAndreas Gohr    } else {
625*24870174SAndreas Gohr        $matches = [];
626cc036f74SKlap-in        if (preg_match_all('/\b(w|h)=(\d*)\b/',$more,$matches,PREG_SET_ORDER) || $isexternalimage){
627*24870174SAndreas Gohr            $resize = ['w'=>0, 'h'=>0];
6285e7db1e2SChristopher Smith            foreach ($matches as $match){
6295e7db1e2SChristopher Smith                $resize[$match[1]] = $match[2];
6305e7db1e2SChristopher Smith            }
631cc036f74SKlap-in            $more .= $more === '' ? '' : $sep;
632cc036f74SKlap-in            $more .= 'tok='.media_get_token($id,$resize['w'],$resize['h']);
6335e7db1e2SChristopher Smith        }
6348c08db0aSAndreas Gohr        $more = str_replace('cache=cache', '', $more); //skip default
6358c08db0aSAndreas Gohr        $more = str_replace(',,', ',', $more);
636b174aeaeSchris        $more = str_replace(',', $sep, $more);
6376de3759aSAndreas Gohr    }
6386de3759aSAndreas Gohr
63955b2b31bSAndreas Gohr    if($abs) {
64055b2b31bSAndreas Gohr        $xlink = DOKU_URL;
64155b2b31bSAndreas Gohr    } else {
6426de3759aSAndreas Gohr        $xlink = DOKU_BASE;
64355b2b31bSAndreas Gohr    }
6446de3759aSAndreas Gohr
6456de3759aSAndreas Gohr    // external URLs are always direct without rewriting
646826d2766SKlap-in    if($isexternalimage) {
6476de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
648cc036f74SKlap-in        $xlink .= '?'.$more;
649b174aeaeSchris        $xlink .= $sep.'media='.rawurlencode($id);
6506de3759aSAndreas Gohr        return $xlink;
6516de3759aSAndreas Gohr    }
6526de3759aSAndreas Gohr
6536de3759aSAndreas Gohr    $id = idfilter($id);
6546de3759aSAndreas Gohr
6556de3759aSAndreas Gohr    // decide on scriptname
6566de3759aSAndreas Gohr    if ($direct) {
6576de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
6586de3759aSAndreas Gohr            $script = '_media';
6596de3759aSAndreas Gohr        } else {
6606de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
6616de3759aSAndreas Gohr        }
662*24870174SAndreas Gohr    } elseif ($conf['userewrite'] == 1) {
6636de3759aSAndreas Gohr        $script = '_detail';
6646de3759aSAndreas Gohr    } else {
6656de3759aSAndreas Gohr        $script = 'lib/exe/detail.php';
6666de3759aSAndreas Gohr    }
6676de3759aSAndreas Gohr
6686de3759aSAndreas Gohr    // build URL based on rewrite mode
6696de3759aSAndreas Gohr    if ($conf['userewrite']) {
6706de3759aSAndreas Gohr        $xlink .= $script.'/'.$id;
6716de3759aSAndreas Gohr        if($more) $xlink .= '?'.$more;
672*24870174SAndreas Gohr    } elseif ($more) {
673a99d3236SEsther Brunner        $xlink .= $script.'?'.$more;
674b174aeaeSchris        $xlink .= $sep.'media='.$id;
6756de3759aSAndreas Gohr    } else {
676a99d3236SEsther Brunner        $xlink .= $script.'?media='.$id;
6776de3759aSAndreas Gohr    }
6786de3759aSAndreas Gohr
6796de3759aSAndreas Gohr    return $xlink;
6806de3759aSAndreas Gohr}
6816de3759aSAndreas Gohr
6826de3759aSAndreas Gohr/**
68325ca5b17SAndreas Gohr * Returns the URL to the DokuWiki base script
68415fae107Sandi *
68525ca5b17SAndreas Gohr * Consider using wl() instead, unless you absoutely need the doku.php endpoint
68625ca5b17SAndreas Gohr *
68715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
688140cfbcdSGerrit Uitslag *
689140cfbcdSGerrit Uitslag * @return string
690f3f0262cSandi */
69125ca5b17SAndreas Gohrfunction script() {
692ed7b5f09Sandi    return DOKU_BASE.DOKU_SCRIPT;
693f3f0262cSandi}
694f3f0262cSandi
695f3f0262cSandi/**
69615fae107Sandi * Spamcheck against wordlist
69715fae107Sandi *
698f3f0262cSandi * Checks the wikitext against a list of blocked expressions
699f3f0262cSandi * returns true if the text contains any bad words
70015fae107Sandi *
701e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
702e403cc58SMichael Klier *
703e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
704e403cc58SMichael Klier *  and gain information about the user who was blocked.
705e403cc58SMichael Klier *
706e403cc58SMichael Klier *  Event data:
707e403cc58SMichael Klier *    data['matches']  - array of matches
708e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
709e403cc58SMichael Klier *      [ip]           - ip address
710e403cc58SMichael Klier *      [user]         - username (if logged in)
711e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
712e403cc58SMichael Klier *      [name]         - real name (if logged in)
713e403cc58SMichael Klier *
71415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
7156dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
716140cfbcdSGerrit Uitslag *
7176dffa0e0SAndreas Gohr * @param  string $text - optional text to check, if not given the globals are used
7186dffa0e0SAndreas Gohr * @return bool         - true if a spam word was found
719f3f0262cSandi */
7206dffa0e0SAndreas Gohrfunction checkwordblock($text = '') {
721f3f0262cSandi    global $TEXT;
7226dffa0e0SAndreas Gohr    global $PRE;
7236dffa0e0SAndreas Gohr    global $SUF;
724e0086ca2SAndreas Gohr    global $SUM;
725f3f0262cSandi    global $conf;
726e403cc58SMichael Klier    global $INFO;
727585bf44eSChristopher Smith    /* @var Input $INPUT */
728585bf44eSChristopher Smith    global $INPUT;
729f3f0262cSandi
730f3f0262cSandi    if(!$conf['usewordblock']) return false;
731f3f0262cSandi
732e0086ca2SAndreas Gohr    if(!$text) $text = "$PRE $TEXT $SUF $SUM";
7336dffa0e0SAndreas Gohr
734041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
73564159a61SAndreas Gohr    // phpcs:disable Generic.Files.LineLength.TooLong
73664159a61SAndreas Gohr    $text = preg_replace(
73764159a61SAndreas Gohr        '!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i',
73864159a61SAndreas Gohr        '\1http://\2 \2\3',
73964159a61SAndreas Gohr        $text
74064159a61SAndreas Gohr    );
74164159a61SAndreas Gohr    // phpcs:enable
742041d1964SAndreas Gohr
743b9ac8716Schris    $wordblocks = getWordblocks();
744a51d08efSAndreas Gohr    // read file in chunks of 200 - this should work around the
7453e2965d7Sandi    // MAX_PATTERN_SIZE in modern PCRE
746a51d08efSAndreas Gohr    $chunksize = 200;
74764259528SAndreas Gohr
748b9ac8716Schris    while($blocks = array_splice($wordblocks, 0, $chunksize)) {
749*24870174SAndreas Gohr        $re = [];
75049eb6e38SAndreas Gohr        // build regexp from blocks
751f3f0262cSandi        foreach($blocks as $block) {
752f3f0262cSandi            $block = preg_replace('/#.*$/', '', $block);
753f3f0262cSandi            $block = trim($block);
754f3f0262cSandi            if(empty($block)) continue;
755f3f0262cSandi            $re[] = $block;
756f3f0262cSandi        }
757*24870174SAndreas Gohr        if(count($re) && preg_match('#('.implode('|', $re).')#si', $text, $matches)) {
758e403cc58SMichael Klier            // prepare event data
759*24870174SAndreas Gohr            $data = [];
760e403cc58SMichael Klier            $data['matches']        = $matches;
761585bf44eSChristopher Smith            $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
762585bf44eSChristopher Smith            if($INPUT->server->str('REMOTE_USER')) {
763585bf44eSChristopher Smith                $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
764e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
765e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
766e403cc58SMichael Klier            }
767*24870174SAndreas Gohr            $callback = static fn() => true;
768cbb44eabSAndreas Gohr            return Event::createAndTrigger('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
769b9ac8716Schris        }
770703f6fdeSandi    }
771f3f0262cSandi    return false;
772f3f0262cSandi}
773f3f0262cSandi
774f3f0262cSandi/**
77515fae107Sandi * Return the IP of the client
77615fae107Sandi *
7776d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
77815fae107Sandi *
7796d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
7806d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
7816d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
7826d8affe6SAndreas Gohr * headers
7836d8affe6SAndreas Gohr *
78415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
785140cfbcdSGerrit Uitslag *
7863272d797SAndreas Gohr * @param  boolean $single If set only a single IP is returned
7873272d797SAndreas Gohr * @return string
788f3f0262cSandi */
7896d8affe6SAndreas Gohrfunction clientIP($single = false) {
790585bf44eSChristopher Smith    /* @var Input $INPUT */
791925105e8SPhy    global $INPUT, $conf;
792585bf44eSChristopher Smith
793*24870174SAndreas Gohr    $ip   = [];
794585bf44eSChristopher Smith    $ip[] = $INPUT->server->str('REMOTE_ADDR');
795585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_FORWARDED_FOR')) {
796585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_FORWARDED_FOR'))));
797585bf44eSChristopher Smith    }
798585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_REAL_IP')) {
799585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_REAL_IP'))));
800585bf44eSChristopher Smith    }
8016d8affe6SAndreas Gohr
8026d8affe6SAndreas Gohr    // remove any non-IP stuff
8036d8affe6SAndreas Gohr    $cnt   = count($ip);
8046d8affe6SAndreas Gohr    for($i = 0; $i < $cnt; $i++) {
8050a5f08e5SAdaKaleh        if(filter_var($ip[$i], FILTER_VALIDATE_IP) === false) {
8060a5f08e5SAdaKaleh            unset($ip[$i]);
8074ff28443Schris        }
808f3f0262cSandi    }
8096d8affe6SAndreas Gohr    $ip = array_values(array_unique($ip));
810*24870174SAndreas Gohr    if($ip === [] || !$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
8116d8affe6SAndreas Gohr
812*24870174SAndreas Gohr    if(!$single) return implode(',', $ip);
8136d8affe6SAndreas Gohr
814925105e8SPhy    // skip trusted local addresses
8156d8affe6SAndreas Gohr    foreach($ip as $i) {
816925105e8SPhy        if(!empty($conf['trustedproxy']) && preg_match('/'.$conf['trustedproxy'].'/', $i)) {
8176d8affe6SAndreas Gohr            continue;
8186d8affe6SAndreas Gohr        } else {
8196d8affe6SAndreas Gohr            return $i;
8206d8affe6SAndreas Gohr        }
8216d8affe6SAndreas Gohr    }
822925105e8SPhy
823925105e8SPhy    // still here? just use the last address
824925105e8SPhy    // this case all ips in the list are trusted
825925105e8SPhy    return $ip[count($ip)-1];
826f3f0262cSandi}
827f3f0262cSandi
828f3f0262cSandi/**
8291c548ebeSAndreas Gohr * Check if the browser is on a mobile device
8301c548ebeSAndreas Gohr *
8311c548ebeSAndreas Gohr * Adapted from the example code at url below
8321c548ebeSAndreas Gohr *
8331c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
834140cfbcdSGerrit Uitslag *
83564159a61SAndreas Gohr * @deprecated 2018-04-27 you probably want media queries instead anyway
836140cfbcdSGerrit Uitslag * @return bool if true, client is mobile browser; otherwise false
8371c548ebeSAndreas Gohr */
8381c548ebeSAndreas Gohrfunction clientismobile() {
839585bf44eSChristopher Smith    /* @var Input $INPUT */
840585bf44eSChristopher Smith    global $INPUT;
8411c548ebeSAndreas Gohr
842585bf44eSChristopher Smith    if($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
8431c548ebeSAndreas Gohr
844585bf44eSChristopher Smith    if(preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
8451c548ebeSAndreas Gohr
846585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_USER_AGENT')) return false;
8471c548ebeSAndreas Gohr
848*24870174SAndreas Gohr    $uamatches = implode(
84964159a61SAndreas Gohr        '|',
85064159a61SAndreas Gohr        [
85164159a61SAndreas Gohr            'midp', 'j2me', 'avantg', 'docomo', 'novarra', 'palmos', 'palmsource', '240x320', 'opwv',
85264159a61SAndreas Gohr            'chtml', 'pda', 'windows ce', 'mmp\/', 'blackberry', 'mib\/', 'symbian', 'wireless', 'nokia',
85364159a61SAndreas Gohr            'hand', 'mobi', 'phone', 'cdm', 'up\.b', 'audio', 'SIE\-', 'SEC\-', 'samsung', 'HTC', 'mot\-',
85464159a61SAndreas Gohr            'mitsu', 'sagem', 'sony', 'alcatel', 'lg', 'erics', 'vx', 'NEC', 'philips', 'mmm', 'xx',
85564159a61SAndreas Gohr            'panasonic', 'sharp', 'wap', 'sch', 'rover', 'pocket', 'benq', 'java', 'pt', 'pg', 'vox',
85664159a61SAndreas Gohr            'amoi', 'bird', 'compal', 'kg', 'voda', 'sany', 'kdd', 'dbt', 'sendo', 'sgh', 'gradi', 'jb',
85764159a61SAndreas Gohr            '\d\d\di', 'moto'
85864159a61SAndreas Gohr        ]
85964159a61SAndreas Gohr    );
8601c548ebeSAndreas Gohr
861585bf44eSChristopher Smith    if(preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
8621c548ebeSAndreas Gohr
8631c548ebeSAndreas Gohr    return false;
8641c548ebeSAndreas Gohr}
8651c548ebeSAndreas Gohr
8661c548ebeSAndreas Gohr/**
8676efc45a2SDmitry Katsubo * check if a given link is interwiki link
8686efc45a2SDmitry Katsubo *
8696efc45a2SDmitry Katsubo * @param string $link the link, e.g. "wiki>page"
8706efc45a2SDmitry Katsubo * @return bool
8716efc45a2SDmitry Katsubo */
8726efc45a2SDmitry Katsubofunction link_isinterwiki($link){
8736efc45a2SDmitry Katsubo    if (preg_match('/^[a-zA-Z0-9\.]+>/u',$link)) return true;
8746efc45a2SDmitry Katsubo    return false;
8756efc45a2SDmitry Katsubo}
8766efc45a2SDmitry Katsubo
8776efc45a2SDmitry Katsubo/**
87863211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
87963211f61SGlen Harris *
88022ef1e32SAndreas Gohr * If $conf['dnslookups'] is disabled it simply returns the input string
88122ef1e32SAndreas Gohr *
88263211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
883140cfbcdSGerrit Uitslag *
8843272d797SAndreas Gohr * @param  string $ips comma separated list of IP addresses
8853272d797SAndreas Gohr * @return string a comma separated list of hostnames
88663211f61SGlen Harris */
88763211f61SGlen Harrisfunction gethostsbyaddrs($ips) {
88822ef1e32SAndreas Gohr    global $conf;
88922ef1e32SAndreas Gohr    if(!$conf['dnslookups']) return $ips;
89022ef1e32SAndreas Gohr
891*24870174SAndreas Gohr    $hosts = [];
89263211f61SGlen Harris    $ips   = explode(',', $ips);
893551a720fSMichael Klier
894551a720fSMichael Klier    if(is_array($ips)) {
8953886270dSAndreas Gohr        foreach($ips as $ip) {
896551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
89763211f61SGlen Harris        }
898*24870174SAndreas Gohr        return implode(',', $hosts);
899551a720fSMichael Klier    } else {
900551a720fSMichael Klier        return gethostbyaddr(trim($ips));
901551a720fSMichael Klier    }
90263211f61SGlen Harris}
90363211f61SGlen Harris
90463211f61SGlen Harris/**
90515fae107Sandi * Checks if a given page is currently locked.
90615fae107Sandi *
907f3f0262cSandi * removes stale lockfiles
90815fae107Sandi *
90915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
910140cfbcdSGerrit Uitslag *
911140cfbcdSGerrit Uitslag * @param string $id page id
912140cfbcdSGerrit Uitslag * @return bool page is locked?
913f3f0262cSandi */
914f3f0262cSandifunction checklock($id) {
915f3f0262cSandi    global $conf;
916585bf44eSChristopher Smith    /* @var Input $INPUT */
917585bf44eSChristopher Smith    global $INPUT;
918585bf44eSChristopher Smith
919c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
920f3f0262cSandi
921f3f0262cSandi    //no lockfile
92279e79377SAndreas Gohr    if(!file_exists($lock)) return false;
923f3f0262cSandi
924f3f0262cSandi    //lockfile expired
925f3f0262cSandi    if((time() - filemtime($lock)) > $conf['locktime']) {
926d8186216SBen Coburn        @unlink($lock);
927f3f0262cSandi        return false;
928f3f0262cSandi    }
929f3f0262cSandi
930f3f0262cSandi    //my own lock
931*24870174SAndreas Gohr    @[$ip, $session] = explode("\n", io_readFile($lock));
932*24870174SAndreas Gohr    if($ip == $INPUT->server->str('REMOTE_USER') || (session_id() && $session === session_id())) {
933f3f0262cSandi        return false;
934f3f0262cSandi    }
935f3f0262cSandi
936f3f0262cSandi    return $ip;
937f3f0262cSandi}
938f3f0262cSandi
939f3f0262cSandi/**
94015fae107Sandi * Lock a page for editing
94115fae107Sandi *
94215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
943140cfbcdSGerrit Uitslag *
944140cfbcdSGerrit Uitslag * @param string $id page id to lock
945f3f0262cSandi */
946f3f0262cSandifunction lock($id) {
947544ed901SDaniel Calviño Sánchez    global $conf;
948585bf44eSChristopher Smith    /* @var Input $INPUT */
949585bf44eSChristopher Smith    global $INPUT;
950544ed901SDaniel Calviño Sánchez
951544ed901SDaniel Calviño Sánchez    if($conf['locktime'] == 0) {
952544ed901SDaniel Calviño Sánchez        return;
953544ed901SDaniel Calviño Sánchez    }
954544ed901SDaniel Calviño Sánchez
955c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
956585bf44eSChristopher Smith    if($INPUT->server->str('REMOTE_USER')) {
957585bf44eSChristopher Smith        io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
958f3f0262cSandi    } else {
95985fef7e2SAndreas Gohr        io_saveFile($lock, clientIP()."\n".session_id());
960f3f0262cSandi    }
961f3f0262cSandi}
962f3f0262cSandi
963f3f0262cSandi/**
96415fae107Sandi * Unlock a page if it was locked by the user
965f3f0262cSandi *
96615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
967140cfbcdSGerrit Uitslag *
9683272d797SAndreas Gohr * @param string $id page id to unlock
96915fae107Sandi * @return bool true if a lock was removed
970f3f0262cSandi */
971f3f0262cSandifunction unlock($id) {
972585bf44eSChristopher Smith    /* @var Input $INPUT */
973585bf44eSChristopher Smith    global $INPUT;
974585bf44eSChristopher Smith
975c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
97679e79377SAndreas Gohr    if(file_exists($lock)) {
977*24870174SAndreas Gohr        @[$ip, $session] = explode("\n", io_readFile($lock));
978c0dd3914SAdaKaleh        if($ip == $INPUT->server->str('REMOTE_USER') || $session == session_id()) {
979f3f0262cSandi            @unlink($lock);
980f3f0262cSandi            return true;
981f3f0262cSandi        }
982f3f0262cSandi    }
983f3f0262cSandi    return false;
984f3f0262cSandi}
985f3f0262cSandi
986f3f0262cSandi/**
987f3f0262cSandi * convert line ending to unix format
988f3f0262cSandi *
9896db7468bSAndreas Gohr * also makes sure the given text is valid UTF-8
9906db7468bSAndreas Gohr *
99115fae107Sandi * @see    formText() for 2crlf conversion
99215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
993140cfbcdSGerrit Uitslag *
994140cfbcdSGerrit Uitslag * @param string $text
995140cfbcdSGerrit Uitslag * @return string
996f3f0262cSandi */
997f3f0262cSandifunction cleanText($text) {
998f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
9996db7468bSAndreas Gohr
10006db7468bSAndreas Gohr    // if the text is not valid UTF-8 we simply assume latin1
10016db7468bSAndreas Gohr    // this won't break any worse than it breaks with the wrong encoding
10026db7468bSAndreas Gohr    // but might actually fix the problem in many cases
1003*24870174SAndreas Gohr    if(!Clean::isUtf8($text)) $text = utf8_encode($text);
10046db7468bSAndreas Gohr
1005f3f0262cSandi    return $text;
1006f3f0262cSandi}
1007f3f0262cSandi
1008f3f0262cSandi/**
1009f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
1010f3f0262cSandi * It also converts line endings to Windows format which is
1011f3f0262cSandi * pseudo standard for webforms.
1012f3f0262cSandi *
101315fae107Sandi * @see    cleanText() for 2unix conversion
101415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1015140cfbcdSGerrit Uitslag *
1016140cfbcdSGerrit Uitslag * @param string $text
1017140cfbcdSGerrit Uitslag * @return string
1018f3f0262cSandi */
1019f3f0262cSandifunction formText($text) {
1020a46a37efSAndreas Gohr    $text = str_replace("\012", "\015\012", $text ?? '');
1021f3f0262cSandi    return htmlspecialchars($text);
1022f3f0262cSandi}
1023f3f0262cSandi
1024f3f0262cSandi/**
102515fae107Sandi * Returns the specified local text in raw format
102615fae107Sandi *
102715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1028140cfbcdSGerrit Uitslag *
1029140cfbcdSGerrit Uitslag * @param string $id   page id
1030140cfbcdSGerrit Uitslag * @param string $ext  extension of file being read, default 'txt'
1031140cfbcdSGerrit Uitslag * @return string
1032f3f0262cSandi */
10332adaf2b8SAndreas Gohrfunction rawLocale($id, $ext = 'txt') {
10342adaf2b8SAndreas Gohr    return io_readFile(localeFN($id, $ext));
1035f3f0262cSandi}
1036f3f0262cSandi
1037f3f0262cSandi/**
1038f3f0262cSandi * Returns the raw WikiText
103915fae107Sandi *
104015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1041140cfbcdSGerrit Uitslag *
1042140cfbcdSGerrit Uitslag * @param string $id   page id
1043e0c26282SGerrit Uitslag * @param string|int $rev  timestamp when a revision of wikitext is desired
1044140cfbcdSGerrit Uitslag * @return string
1045f3f0262cSandi */
1046f3f0262cSandifunction rawWiki($id, $rev = '') {
1047cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1048f3f0262cSandi}
1049f3f0262cSandi
1050f3f0262cSandi/**
10517146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
10527146cee2SAndreas Gohr *
10537b84afa2SAndreas Gohr * @triggers COMMON_PAGETPL_LOAD
10547146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1055140cfbcdSGerrit Uitslag *
1056140cfbcdSGerrit Uitslag * @param string $id the id of the page to be created
1057140cfbcdSGerrit Uitslag * @return string parsed pagetemplate content
10587146cee2SAndreas Gohr */
1059fe17917eSAdrian Langfunction pageTemplate($id) {
1060a15ce62dSEsther Brunner    global $conf;
1061e29549feSAndreas Gohr
1062fe17917eSAdrian Lang    if(is_array($id)) $id = $id[0];
1063e29549feSAndreas Gohr
10647b84afa2SAndreas Gohr    // prepare initial event data
1065*24870174SAndreas Gohr    $data = [
10667b84afa2SAndreas Gohr        'id'        => $id, // the id of the page to be created
10677b84afa2SAndreas Gohr        'tpl'       => '', // the text used as template
10687b84afa2SAndreas Gohr        'tplfile'   => '', // the file above text was/should be loaded from
1069*24870174SAndreas Gohr        'doreplace' => true,
1070*24870174SAndreas Gohr    ];
10717b84afa2SAndreas Gohr
1072e1d9dcc8SAndreas Gohr    $evt = new Event('COMMON_PAGETPL_LOAD', $data);
10737b84afa2SAndreas Gohr    if($evt->advise_before(true)) {
10747b84afa2SAndreas Gohr        // the before event might have loaded the content already
10757b84afa2SAndreas Gohr        if(empty($data['tpl'])) {
10767b84afa2SAndreas Gohr            // if the before event did not set a template file, try to find one
10777b84afa2SAndreas Gohr            if(empty($data['tplfile'])) {
1078fe17917eSAdrian Lang                $path = dirname(wikiFN($id));
107979e79377SAndreas Gohr                if(file_exists($path.'/_template.txt')) {
10807b84afa2SAndreas Gohr                    $data['tplfile'] = $path.'/_template.txt';
1081e29549feSAndreas Gohr                } else {
1082e29549feSAndreas Gohr                    // search upper namespaces for templates
1083e29549feSAndreas Gohr                    $len = strlen(rtrim($conf['datadir'], '/'));
1084e29549feSAndreas Gohr                    while(strlen($path) >= $len) {
108579e79377SAndreas Gohr                        if(file_exists($path.'/__template.txt')) {
10867b84afa2SAndreas Gohr                            $data['tplfile'] = $path.'/__template.txt';
1087e29549feSAndreas Gohr                            break;
1088e29549feSAndreas Gohr                        }
1089e29549feSAndreas Gohr                        $path = substr($path, 0, strrpos($path, '/'));
1090e29549feSAndreas Gohr                    }
1091e29549feSAndreas Gohr                }
10927b84afa2SAndreas Gohr            }
10937b84afa2SAndreas Gohr            // load the content
10943d7ac595SMichael Hamann            $data['tpl'] = io_readFile($data['tplfile']);
10957b84afa2SAndreas Gohr        }
1096a1bbd05bSMichael Hamann        if($data['doreplace']) parsePageTemplate($data);
10977b84afa2SAndreas Gohr    }
10987b84afa2SAndreas Gohr    $evt->advise_after();
10997b84afa2SAndreas Gohr    unset($evt);
11007b84afa2SAndreas Gohr
1101fe17917eSAdrian Lang    return $data['tpl'];
11022b1223ecSAdrian Lang}
11032b1223ecSAdrian Lang
11042b1223ecSAdrian Lang/**
11052b1223ecSAdrian Lang * Performs common page template replacements
11067b84afa2SAndreas Gohr * This works on data from COMMON_PAGETPL_LOAD
11072b1223ecSAdrian Lang *
11082b1223ecSAdrian Lang * @author Andreas Gohr <andi@splitbrain.org>
1109140cfbcdSGerrit Uitslag *
1110140cfbcdSGerrit Uitslag * @param array $data array with event data
1111140cfbcdSGerrit Uitslag * @return string
11122b1223ecSAdrian Lang */
1113d535a2e9Sstretchyboyfunction parsePageTemplate(&$data) {
11143272d797SAndreas Gohr    /**
11153272d797SAndreas Gohr     * @var string $id        the id of the page to be created
11163272d797SAndreas Gohr     * @var string $tpl       the text used as template
11173272d797SAndreas Gohr     * @var string $tplfile   the file above text was/should be loaded from
11183272d797SAndreas Gohr     * @var bool   $doreplace should wildcard replacements be done on the text?
11193272d797SAndreas Gohr     */
1120fe17917eSAdrian Lang    extract($data);
1121fe17917eSAdrian Lang
1122b856f7dfSAdrian Lang    global $USERINFO;
1123bce53b1fSAdrian Lang    global $conf;
1124585bf44eSChristopher Smith    /* @var Input $INPUT */
1125585bf44eSChristopher Smith    global $INPUT;
1126e29549feSAndreas Gohr
1127e29549feSAndreas Gohr    // replace placeholders
112826ece5a7SAndreas Gohr    $file = noNS($id);
112937c1acbdSAdrian Lang    $page = strtr($file, $conf['sepchar'], ' ');
113026ece5a7SAndreas Gohr
11313272d797SAndreas Gohr    $tpl = str_replace(
1132*24870174SAndreas Gohr        [
113326ece5a7SAndreas Gohr            '@ID@',
113426ece5a7SAndreas Gohr            '@NS@',
11358a7bcf66SShota Miyazaki            '@CURNS@',
1136a3db0ab0SSimon Lees            '@!CURNS@',
1137a3db0ab0SSimon Lees            '@!!CURNS@',
1138a3db0ab0SSimon Lees            '@!CURNS!@',
113926ece5a7SAndreas Gohr            '@FILE@',
114026ece5a7SAndreas Gohr            '@!FILE@',
114126ece5a7SAndreas Gohr            '@!FILE!@',
114226ece5a7SAndreas Gohr            '@PAGE@',
114326ece5a7SAndreas Gohr            '@!PAGE@',
114426ece5a7SAndreas Gohr            '@!!PAGE@',
114526ece5a7SAndreas Gohr            '@!PAGE!@',
114626ece5a7SAndreas Gohr            '@USER@',
114726ece5a7SAndreas Gohr            '@NAME@',
114826ece5a7SAndreas Gohr            '@MAIL@',
1149*24870174SAndreas Gohr            '@DATE@'
1150*24870174SAndreas Gohr        ],
1151*24870174SAndreas Gohr        [
115226ece5a7SAndreas Gohr            $id,
115326ece5a7SAndreas Gohr            getNS($id),
11548a7bcf66SShota Miyazaki            curNS($id),
1155*24870174SAndreas Gohr            PhpString::ucfirst(curNS($id)),
1156*24870174SAndreas Gohr            PhpString::ucwords(curNS($id)),
1157*24870174SAndreas Gohr            PhpString::strtoupper(curNS($id)),
115826ece5a7SAndreas Gohr            $file,
1159*24870174SAndreas Gohr            PhpString::ucfirst($file),
1160*24870174SAndreas Gohr            PhpString::strtoupper($file),
116126ece5a7SAndreas Gohr            $page,
1162*24870174SAndreas Gohr            PhpString::ucfirst($page),
1163*24870174SAndreas Gohr            PhpString::ucwords($page),
1164*24870174SAndreas Gohr            PhpString::strtoupper($page),
1165585bf44eSChristopher Smith            $INPUT->server->str('REMOTE_USER'),
11663e9ae63dSPhy            $USERINFO ? $USERINFO['name'] : '',
11673e9ae63dSPhy            $USERINFO ? $USERINFO['mail'] : '',
1168*24870174SAndreas Gohr            $conf['dformat']
1169*24870174SAndreas Gohr        ],
1170*24870174SAndreas Gohr        $tpl
11713272d797SAndreas Gohr    );
117226ece5a7SAndreas Gohr
11737d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
1174bad6fc0dSAndreas Gohr    $tpl = preg_replace_callback(
1175bad6fc0dSAndreas Gohr        '/%./',
1176*24870174SAndreas Gohr        static fn($m) => dformat(null, $m[0]),
1177bad6fc0dSAndreas Gohr        $tpl
1178bad6fc0dSAndreas Gohr    );
1179d535a2e9Sstretchyboy    $data['tpl'] = $tpl;
1180a15ce62dSEsther Brunner    return $tpl;
11817146cee2SAndreas Gohr}
11827146cee2SAndreas Gohr
11837146cee2SAndreas Gohr/**
118415fae107Sandi * Returns the raw Wiki Text in three slices.
118515fae107Sandi *
118615fae107Sandi * The range parameter needs to have the form "from-to"
118715cfe303Sandi * and gives the range of the section in bytes - no
118815cfe303Sandi * UTF-8 awareness is needed.
1189f3f0262cSandi * The returned order is prefix, section and suffix.
119015fae107Sandi *
119115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1192140cfbcdSGerrit Uitslag *
1193140cfbcdSGerrit Uitslag * @param string $range in form "from-to"
1194140cfbcdSGerrit Uitslag * @param string $id    page id
1195140cfbcdSGerrit Uitslag * @param string $rev   optional, the revision timestamp
119642ea7f44SGerrit Uitslag * @return string[] with three slices
1197f3f0262cSandi */
1198f3f0262cSandifunction rawWikiSlices($range, $id, $rev = '') {
1199cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1200f3f0262cSandi
120180fcb268SAdrian Lang    // Parse range
1202*24870174SAndreas Gohr    [$from, $to] = sexplode('-', $range, 2);
120380fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
1204*24870174SAndreas Gohr    $from = $from ? $from - 1 : (0);
1205*24870174SAndreas Gohr    $to   = $to ? $to - 1 : (strlen($text));
120680fcb268SAdrian Lang
1207*24870174SAndreas Gohr    $slices = [];
120880fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
120980fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to - $from);
121015cfe303Sandi    $slices[2] = substr($text, $to);
1211f3f0262cSandi    return $slices;
1212f3f0262cSandi}
1213f3f0262cSandi
1214f3f0262cSandi/**
121515fae107Sandi * Joins wiki text slices
121615fae107Sandi *
121780fcb268SAdrian Lang * function to join the text slices.
1218f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
1219f3f0262cSandi * lines between sections if needed (used on saving).
122015fae107Sandi *
122115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1222140cfbcdSGerrit Uitslag *
1223140cfbcdSGerrit Uitslag * @param string $pre   prefix
1224140cfbcdSGerrit Uitslag * @param string $text  text in the middle
1225140cfbcdSGerrit Uitslag * @param string $suf   suffix
1226140cfbcdSGerrit Uitslag * @param bool $pretty add additional empty lines between sections
1227140cfbcdSGerrit Uitslag * @return string
1228f3f0262cSandi */
1229f3f0262cSandifunction con($pre, $text, $suf, $pretty = false) {
1230f3f0262cSandi    if($pretty) {
123180fcb268SAdrian Lang        if($pre !== '' && substr($pre, -1) !== "\n" &&
12323272d797SAndreas Gohr            substr($text, 0, 1) !== "\n"
12333272d797SAndreas Gohr        ) {
123480fcb268SAdrian Lang            $pre .= "\n";
123580fcb268SAdrian Lang        }
123680fcb268SAdrian Lang        if($suf !== '' && substr($text, -1) !== "\n" &&
12373272d797SAndreas Gohr            substr($suf, 0, 1) !== "\n"
12383272d797SAndreas Gohr        ) {
123980fcb268SAdrian Lang            $text .= "\n";
124080fcb268SAdrian Lang        }
1241f3f0262cSandi    }
1242f3f0262cSandi
1243f3f0262cSandi    return $pre.$text.$suf;
1244f3f0262cSandi}
1245f3f0262cSandi
1246f3f0262cSandi/**
1247b24d9195SAndreas Gohr * Checks if the current page version is newer than the last entry in the page's
1248b24d9195SAndreas Gohr * changelog. If so, we assume it has been an external edit and we create an
1249b24d9195SAndreas Gohr * attic copy and add a proper changelog line.
1250b24d9195SAndreas Gohr *
1251b24d9195SAndreas Gohr * This check is only executed when the page is about to be saved again from the
1252b24d9195SAndreas Gohr * wiki, triggered in @see saveWikiText()
1253b24d9195SAndreas Gohr *
1254b24d9195SAndreas Gohr * @param string $id the page ID
125569f9b481SSatoshi Sahara * @deprecated 2021-11-28
1256b24d9195SAndreas Gohr */
1257b24d9195SAndreas Gohrfunction detectExternalEdit($id) {
125879a2d784SGerrit Uitslag    dbg_deprecated(PageFile::class .'::detectExternalEdit()');
1259b24e9c4aSSatoshi Sahara    (new PageFile($id))->detectExternalEdit();
1260b24d9195SAndreas Gohr}
1261b24d9195SAndreas Gohr
1262b24d9195SAndreas Gohr/**
1263a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
1264a701424fSBen Coburn * Also directs changelog and attic updates.
126515fae107Sandi *
126615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
126771726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
1268140cfbcdSGerrit Uitslag *
1269140cfbcdSGerrit Uitslag * @param string $id       page id
1270140cfbcdSGerrit Uitslag * @param string $text     wikitext being saved
1271140cfbcdSGerrit Uitslag * @param string $summary  summary of text update
1272140cfbcdSGerrit Uitslag * @param bool   $minor    mark this saved version as minor update
1273f3f0262cSandi */
1274b6912aeaSAndreas Gohrfunction saveWikiText($id, $text, $summary, $minor = false) {
1275585bf44eSChristopher Smith
1276b24e9c4aSSatoshi Sahara    // get COMMON_WIKIPAGE_SAVE event data
1277b24e9c4aSSatoshi Sahara    $data = (new PageFile($id))->saveWikiText($text, $summary, $minor);
1278a577fbc2SAndreas Gohr    if(!$data) return; // save was cancelled (for no changes or by a plugin)
1279ac3ed4afSGerrit Uitslag
128026a0801fSAndreas Gohr    // send notify mails
1281*24870174SAndreas Gohr    ['oldRevision' => $rev, 'newRevision' => $new_rev, 'summary' => $summary] = $data;
12823b813d43SSatoshi Sahara    notify($id, 'admin', $rev, $summary, $minor, $new_rev);
12833b813d43SSatoshi Sahara    notify($id, 'subscribers', $rev, $summary, $minor, $new_rev);
1284f3f0262cSandi
12852eccbdaaSGina Haeussge    // if useheading is enabled, purge the cache of all linking pages
1286fe9ec250SChris Smith    if (useHeading('content')) {
128707ff0babSMichael Hamann        $pages = ft_backlinks($id, true);
12882eccbdaaSGina Haeussge        foreach ($pages as $page) {
12890db5771eSMichael Große            $cache = new CacheRenderer($page, wikiFN($page), 'xhtml');
12902eccbdaaSGina Haeussge            $cache->removeCache();
12912eccbdaaSGina Haeussge        }
12922eccbdaaSGina Haeussge    }
1293f3f0262cSandi}
1294f3f0262cSandi
1295f3f0262cSandi/**
1296d5824ab9SSatoshi Sahara * moves the current version to the attic and returns its revision date
129715fae107Sandi *
129815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1299140cfbcdSGerrit Uitslag *
1300140cfbcdSGerrit Uitslag * @param string $id page id
1301140cfbcdSGerrit Uitslag * @return int|string revision timestamp
130269f9b481SSatoshi Sahara * @deprecated 2021-11-28
1303f3f0262cSandi */
1304f3f0262cSandifunction saveOldRevision($id) {
130579a2d784SGerrit Uitslag    dbg_deprecated(PageFile::class .'::saveOldRevision()');
1306b24e9c4aSSatoshi Sahara    return (new PageFile($id))->saveOldRevision();
1307f3f0262cSandi}
1308f3f0262cSandi
1309f3f0262cSandi/**
1310fde10de4SAdrian Lang * Sends a notify mail on page change or registration
131126a0801fSAndreas Gohr *
131226a0801fSAndreas Gohr * @param string     $id       The changed page
1313fde10de4SAdrian Lang * @param string     $who      Who to notify (admin|subscribers|register)
13143272d797SAndreas Gohr * @param int|string $rev      Old page revision
131526a0801fSAndreas Gohr * @param string     $summary  What changed
131690033e9dSAndreas Gohr * @param boolean    $minor    Is this a minor edit?
131742ea7f44SGerrit Uitslag * @param string[]   $replace  Additional string substitutions, @KEY@ to be replaced by value
131883734cddSPhy * @param int|string $current_rev  New page revision
13193272d797SAndreas Gohr * @return bool
1320140cfbcdSGerrit Uitslag *
132115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1322f3f0262cSandi */
1323*24870174SAndreas Gohrfunction notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = [], $current_rev = false) {
1324f3f0262cSandi    global $conf;
1325585bf44eSChristopher Smith    /* @var Input $INPUT */
1326585bf44eSChristopher Smith    global $INPUT;
1327b158d625SSteven Danz
13286df843eeSAndreas Gohr    // decide if there is something to do, eg. whom to mail
132926a0801fSAndreas Gohr    if ($who == 'admin') {
13303272d797SAndreas Gohr        if (empty($conf['notify'])) return false; //notify enabled?
13312ed38036SAndreas Gohr        $tpl = 'mailtext';
133226a0801fSAndreas Gohr        $to  = $conf['notify'];
133326a0801fSAndreas Gohr    } elseif ($who == 'subscribers') {
133484c1127cSAndreas Gohr        if (!actionOK('subscribe')) return false; //subscribers enabled?
1335585bf44eSChristopher Smith        if ($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
1336*24870174SAndreas Gohr        $data = ['id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace];
1337cbb44eabSAndreas Gohr        Event::createAndTrigger(
13383272d797SAndreas Gohr            'COMMON_NOTIFY_ADDRESSLIST', $data,
1339*24870174SAndreas Gohr            [new SubscriberManager(), 'notifyAddresses']
13403272d797SAndreas Gohr        );
13412ed38036SAndreas Gohr        $to = $data['addresslist'];
13422ed38036SAndreas Gohr        if (empty($to)) return false;
13432ed38036SAndreas Gohr        $tpl = 'subscr_single';
134426a0801fSAndreas Gohr    } else {
13453272d797SAndreas Gohr        return false; //just to be safe
134626a0801fSAndreas Gohr    }
134726a0801fSAndreas Gohr
13486df843eeSAndreas Gohr    // prepare content
1349704a815fSMichael Große    $subscription = new PageSubscriptionSender();
135083734cddSPhy    return $subscription->sendPageDiff($to, $tpl, $id, $rev, $summary, $current_rev);
1351f3f0262cSandi}
13522ed38036SAndreas Gohr
135315fae107Sandi/**
135471f7bde7SAndreas Gohr * extracts the query from a search engine referrer
135515fae107Sandi *
135615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
135771f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1358140cfbcdSGerrit Uitslag *
1359140cfbcdSGerrit Uitslag * @return array|string
1360f3f0262cSandi */
1361f3f0262cSandifunction getGoogleQuery() {
1362585bf44eSChristopher Smith    /* @var Input $INPUT */
1363585bf44eSChristopher Smith    global $INPUT;
1364585bf44eSChristopher Smith
1365585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_REFERER')) {
1366c66972f2SAdrian Lang        return '';
1367c66972f2SAdrian Lang    }
1368585bf44eSChristopher Smith    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1369f3f0262cSandi
1370079b3ac1SAndreas Gohr    // only handle common SEs
1371c7875401SJyoti S    if(!array_key_exists('host', $url)) return '';
1372079b3ac1SAndreas Gohr    if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/',$url['host'])) return '';
1373e4d8a516SKazutaka Miyasaka
1374*24870174SAndreas Gohr    $query = [];
1375181adffeSJulian Jeggle    if(!array_key_exists('query', $url)) return '';
1376f3f0262cSandi    parse_str($url['query'], $query);
1377e4d8a516SKazutaka Miyasaka
1378c66972f2SAdrian Lang    $q = '';
1379079b3ac1SAndreas Gohr    if(isset($query['q'])){
1380079b3ac1SAndreas Gohr        $q = $query['q'];
1381079b3ac1SAndreas Gohr    }elseif(isset($query['p'])){
1382079b3ac1SAndreas Gohr        $q = $query['p'];
1383079b3ac1SAndreas Gohr    }elseif(isset($query['query'])){
1384079b3ac1SAndreas Gohr        $q = $query['query'];
1385079b3ac1SAndreas Gohr    }
1386079b3ac1SAndreas Gohr    $q = trim($q);
1387f3f0262cSandi
1388079b3ac1SAndreas Gohr    if(!$q) return '';
1389c7dc833bSPhy    // ignore if query includes a full URL
1390c7dc833bSPhy    if(strpos($q, '//') !== false) return '';
13916531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1392f93b3b50SAndreas Gohr    return $q;
1393f3f0262cSandi}
1394f3f0262cSandi
1395f3f0262cSandi/**
1396f3f0262cSandi * Return the human readable size of a file
1397f3f0262cSandi *
1398f3f0262cSandi * @param int $size A file size
1399f3f0262cSandi * @param int $dec A number of decimal places
140074160ca1SGerrit Uitslag * @return string human readable size
1401140cfbcdSGerrit Uitslag *
1402f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1403f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1404f3f0262cSandi * @version     1.0.0
1405f3f0262cSandi */
1406f31d5b73Sandifunction filesize_h($size, $dec = 1) {
1407*24870174SAndreas Gohr    $sizes = ['B', 'KB', 'MB', 'GB'];
1408f3f0262cSandi    $count = count($sizes);
1409f3f0262cSandi    $i     = 0;
1410f3f0262cSandi
1411f3f0262cSandi    while($size >= 1024 && ($i < $count - 1)) {
1412f3f0262cSandi        $size /= 1024;
1413f3f0262cSandi        $i++;
1414f3f0262cSandi    }
1415f3f0262cSandi
1416ef08383eSAndreas Gohr    return round($size, $dec)."\xC2\xA0".$sizes[$i]; //non-breaking space
1417f3f0262cSandi}
1418f3f0262cSandi
141915fae107Sandi/**
1420c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1421c57e365eSAndreas Gohr *
1422c57e365eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1423140cfbcdSGerrit Uitslag *
1424140cfbcdSGerrit Uitslag * @param int $dt timestamp
1425140cfbcdSGerrit Uitslag * @return string
1426c57e365eSAndreas Gohr */
1427c57e365eSAndreas Gohrfunction datetime_h($dt) {
1428c57e365eSAndreas Gohr    global $lang;
1429c57e365eSAndreas Gohr
1430c57e365eSAndreas Gohr    $ago = time() - $dt;
1431c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1432c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1433c57e365eSAndreas Gohr    }
1434c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 2) {
1435c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1436c57e365eSAndreas Gohr    }
1437c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 7 * 2) {
1438c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1439c57e365eSAndreas Gohr    }
1440c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 2) {
1441c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1442c57e365eSAndreas Gohr    }
1443c57e365eSAndreas Gohr    if($ago > 60 * 60 * 2) {
1444c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago / (60 * 60)));
1445c57e365eSAndreas Gohr    }
1446c57e365eSAndreas Gohr    if($ago > 60 * 2) {
1447c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago / (60)));
1448c57e365eSAndreas Gohr    }
1449c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1450c57e365eSAndreas Gohr}
1451c57e365eSAndreas Gohr
1452c57e365eSAndreas Gohr/**
1453f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1454f2263577SAndreas Gohr *
1455f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1456f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1457f2263577SAndreas Gohr *
1458f2263577SAndreas Gohr * @see datetime_h
1459f2263577SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1460140cfbcdSGerrit Uitslag *
1461140cfbcdSGerrit Uitslag * @param int|null $dt      timestamp when given, null will take current timestamp
1462140cfbcdSGerrit Uitslag * @param string   $format  empty default to $conf['dformat'], or provide format as recognized by strftime()
1463140cfbcdSGerrit Uitslag * @return string
1464f2263577SAndreas Gohr */
1465f2263577SAndreas Gohrfunction dformat($dt = null, $format = '') {
1466f2263577SAndreas Gohr    global $conf;
1467f2263577SAndreas Gohr
1468f2263577SAndreas Gohr    if(is_null($dt)) $dt = time();
1469f2263577SAndreas Gohr    $dt = (int) $dt;
1470f2263577SAndreas Gohr    if(!$format) $format = $conf['dformat'];
1471f2263577SAndreas Gohr
1472f2263577SAndreas Gohr    $format = str_replace('%f', datetime_h($dt), $format);
1473f2263577SAndreas Gohr    return strftime($format, $dt);
1474f2263577SAndreas Gohr}
1475f2263577SAndreas Gohr
1476f2263577SAndreas Gohr/**
1477c4f79b71SMichael Hamann * Formats a timestamp as ISO 8601 date
1478c4f79b71SMichael Hamann *
1479c4f79b71SMichael Hamann * @author <ungu at terong dot com>
148059752844SAnders Sandblad * @link http://php.net/manual/en/function.date.php#54072
1481140cfbcdSGerrit Uitslag *
14827e8500eeSGerrit Uitslag * @param int $int_date current date in UNIX timestamp
14833272d797SAndreas Gohr * @return string
1484c4f79b71SMichael Hamann */
1485c4f79b71SMichael Hamannfunction date_iso8601($int_date) {
1486c4f79b71SMichael Hamann    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1487c4f79b71SMichael Hamann    $pre_timezone = date('O', $int_date);
1488c4f79b71SMichael Hamann    $time_zone    = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1489c4f79b71SMichael Hamann    $date_mod .= $time_zone;
1490c4f79b71SMichael Hamann    return $date_mod;
1491c4f79b71SMichael Hamann}
1492c4f79b71SMichael Hamann
1493c4f79b71SMichael Hamann/**
149400a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
149500a7b5adSEsther Brunner *
149600a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
149700a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
1498140cfbcdSGerrit Uitslag *
1499140cfbcdSGerrit Uitslag * @param string $email email address
1500140cfbcdSGerrit Uitslag * @return string
150100a7b5adSEsther Brunner */
150200a7b5adSEsther Brunnerfunction obfuscate($email) {
150300a7b5adSEsther Brunner    global $conf;
150400a7b5adSEsther Brunner
150500a7b5adSEsther Brunner    switch($conf['mailguard']) {
150600a7b5adSEsther Brunner        case 'visible' :
1507*24870174SAndreas Gohr            $obfuscate = ['@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] '];
150800a7b5adSEsther Brunner            return strtr($email, $obfuscate);
150900a7b5adSEsther Brunner
151000a7b5adSEsther Brunner        case 'hex' :
1511*24870174SAndreas Gohr            return Conversion::toHtml($email, true);
151200a7b5adSEsther Brunner
151300a7b5adSEsther Brunner        case 'none' :
151400a7b5adSEsther Brunner        default :
151500a7b5adSEsther Brunner            return $email;
151600a7b5adSEsther Brunner    }
151700a7b5adSEsther Brunner}
151800a7b5adSEsther Brunner
151900a7b5adSEsther Brunner/**
152089541d4bSAndreas Gohr * Removes quoting backslashes
152189541d4bSAndreas Gohr *
152289541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1523140cfbcdSGerrit Uitslag *
1524140cfbcdSGerrit Uitslag * @param string $string
1525140cfbcdSGerrit Uitslag * @param string $char backslashed character
1526140cfbcdSGerrit Uitslag * @return string
152789541d4bSAndreas Gohr */
152889541d4bSAndreas Gohrfunction unslash($string, $char = "'") {
152989541d4bSAndreas Gohr    return str_replace('\\'.$char, $char, $string);
153089541d4bSAndreas Gohr}
153189541d4bSAndreas Gohr
153273038c47SAndreas Gohr/**
153373038c47SAndreas Gohr * Convert php.ini shorthands to byte
153473038c47SAndreas Gohr *
1535a81f3d99SAndreas Gohr * On 32 bit systems values >= 2GB will fail!
1536140cfbcdSGerrit Uitslag *
1537a81f3d99SAndreas Gohr * -1 (infinite size) will be reported as -1
1538a81f3d99SAndreas Gohr *
1539a81f3d99SAndreas Gohr * @link   https://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
1540a81f3d99SAndreas Gohr * @param string $value PHP size shorthand
1541a81f3d99SAndreas Gohr * @return int
154273038c47SAndreas Gohr */
1543a81f3d99SAndreas Gohrfunction php_to_byte($value) {
1544f5c0c80bSAndreas Gohr    switch (strtoupper(substr($value,-1))) {
154573038c47SAndreas Gohr        case 'G':
1546*24870174SAndreas Gohr            $ret = (int) substr($value, 0, -1) * 1024 * 1024 * 1024;
154773038c47SAndreas Gohr            break;
154873038c47SAndreas Gohr        case 'M':
1549*24870174SAndreas Gohr            $ret = (int) substr($value, 0, -1) * 1024 * 1024;
1550a81f3d99SAndreas Gohr            break;
155173038c47SAndreas Gohr        case 'K':
1552*24870174SAndreas Gohr            $ret = (int) substr($value, 0, -1) * 1024;
155373038c47SAndreas Gohr            break;
15549eeeb775SAndreas Gohr        default:
1555*24870174SAndreas Gohr            $ret = (int) $value;
155649cbd23eSOtto Vainio            break;
155773038c47SAndreas Gohr    }
155873038c47SAndreas Gohr    return $ret;
155973038c47SAndreas Gohr}
156073038c47SAndreas Gohr
1561546d3a99SAndreas Gohr/**
1562546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1563140cfbcdSGerrit Uitslag *
1564140cfbcdSGerrit Uitslag * @param string $string
1565140cfbcdSGerrit Uitslag * @return string
1566546d3a99SAndreas Gohr */
1567546d3a99SAndreas Gohrfunction preg_quote_cb($string) {
1568546d3a99SAndreas Gohr    return preg_quote($string, '/');
1569546d3a99SAndreas Gohr}
157073038c47SAndreas Gohr
1571bd2f6c2fSAndreas Gohr/**
1572bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1573bd2f6c2fSAndreas Gohr *
1574c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1575bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1576bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1577bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1578bd2f6c2fSAndreas Gohr *
1579bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1580bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1581bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1582bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1583bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
15843272d797SAndreas Gohr * @return string
1585bd2f6c2fSAndreas Gohr */
1586a5d27328SAndreas Gohrfunction shorten($keep, $short, $max, $min = 9, $char = '…') {
1587*24870174SAndreas Gohr    $max -= PhpString::strlen($keep);
1588bd2f6c2fSAndreas Gohr    if($max < $min) return $keep;
1589*24870174SAndreas Gohr    $len = PhpString::strlen($short);
1590bd2f6c2fSAndreas Gohr    if($len <= $max) return $keep.$short;
1591bd2f6c2fSAndreas Gohr    $half = floor($max / 2);
15926ce3e5f8SAndreas Gohr    return $keep .
1593*24870174SAndreas Gohr        PhpString::substr($short, 0, $half - 1) .
15946ce3e5f8SAndreas Gohr        $char .
1595*24870174SAndreas Gohr        PhpString::substr($short, $len - $half);
1596bd2f6c2fSAndreas Gohr}
1597bd2f6c2fSAndreas Gohr
1598dc58b6f4SAndy Webber/**
1599dc58b6f4SAndy Webber * Return the users real name or e-mail address for use
1600dc58b6f4SAndy Webber * in page footer and recent changes pages
1601dc58b6f4SAndy Webber *
1602b4b6c9a1SGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
160315f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1604c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
160515f3bc49SGerrit Uitslag *
1606dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1607dc58b6f4SAndy Webber */
160815f3bc49SGerrit Uitslagfunction editorinfo($username, $textonly = false) {
1609cd4635eeSGerrit Uitslag    return userlink($username, $textonly);
1610dc58b6f4SAndy Webber}
1611dc58b6f4SAndy Webber
161260a396c8SGerrit Uitslag/**
161360a396c8SGerrit Uitslag * Returns users realname w/o link
161460a396c8SGerrit Uitslag *
1615f168548cSGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
161615f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1617c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
161860a396c8SGerrit Uitslag *
161960a396c8SGerrit Uitslag * @triggers COMMON_USER_LINK
162060a396c8SGerrit Uitslag */
1621cd4635eeSGerrit Uitslagfunction userlink($username = null, $textonly = false) {
162260a396c8SGerrit Uitslag    global $conf, $INFO;
1623e1d9dcc8SAndreas Gohr    /** @var AuthPlugin $auth */
162460a396c8SGerrit Uitslag    global $auth;
162530f6ec4bSGerrit Uitslag    /** @var Input $INPUT */
162630f6ec4bSGerrit Uitslag    global $INPUT;
162760a396c8SGerrit Uitslag
162860a396c8SGerrit Uitslag    // prepare initial event data
1629*24870174SAndreas Gohr    $data = [
163060a396c8SGerrit Uitslag        'username' => $username, // the unique user name
163160a396c8SGerrit Uitslag        'name' => '',
1632*24870174SAndreas Gohr        'link' => [
1633*24870174SAndreas Gohr            //setting 'link' to false disables linking
163460a396c8SGerrit Uitslag            'target' => '',
163560a396c8SGerrit Uitslag            'pre' => '',
163660a396c8SGerrit Uitslag            'suf' => '',
163760a396c8SGerrit Uitslag            'style' => '',
163860a396c8SGerrit Uitslag            'more' => '',
163960a396c8SGerrit Uitslag            'url' => '',
164060a396c8SGerrit Uitslag            'title' => '',
1641*24870174SAndreas Gohr            'class' => '',
1642*24870174SAndreas Gohr        ],
16434d5fc927SGerrit Uitslag        'userlink' => '', // formatted user name as will be returned
1644*24870174SAndreas Gohr        'textonly' => $textonly,
1645*24870174SAndreas Gohr    ];
164662c8004eSGerrit Uitslag    if($username === null) {
164730f6ec4bSGerrit Uitslag        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
164815f3bc49SGerrit Uitslag        if($textonly){
164915f3bc49SGerrit Uitslag            $data['name'] = $INFO['userinfo']['name']. ' (' . $INPUT->server->str('REMOTE_USER') . ')';
165015f3bc49SGerrit Uitslag        }else {
165164159a61SAndreas Gohr            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> '.
165264159a61SAndreas Gohr                '(<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
165360a396c8SGerrit Uitslag        }
165415f3bc49SGerrit Uitslag    }
165560a396c8SGerrit Uitslag
1656e1d9dcc8SAndreas Gohr    $evt = new Event('COMMON_USER_LINK', $data);
165760a396c8SGerrit Uitslag    if($evt->advise_before(true)) {
165860a396c8SGerrit Uitslag        if(empty($data['name'])) {
165960a396c8SGerrit Uitslag            if($auth) $info = $auth->getUserData($username);
166065833968SGerrit Uitslag            if($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1661dc58b6f4SAndy Webber                switch($conf['showuseras']) {
1662dc58b6f4SAndy Webber                    case 'username':
16637f081821SGerrit Uitslag                    case 'username_link':
166415f3bc49SGerrit Uitslag                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
166560a396c8SGerrit Uitslag                        break;
1666dc58b6f4SAndy Webber                    case 'email':
1667dc58b6f4SAndy Webber                    case 'email_link':
166860a396c8SGerrit Uitslag                        $data['name'] = obfuscate($info['mail']);
166960a396c8SGerrit Uitslag                        break;
1670dc58b6f4SAndy Webber                }
167165833968SGerrit Uitslag            } else {
167265833968SGerrit Uitslag                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
167360a396c8SGerrit Uitslag            }
167460a396c8SGerrit Uitslag        }
16757f081821SGerrit Uitslag
16767f081821SGerrit Uitslag        /** @var Doku_Renderer_xhtml $xhtml_renderer */
16777f081821SGerrit Uitslag        static $xhtml_renderer = null;
16787f081821SGerrit Uitslag
167915f3bc49SGerrit Uitslag        if(!$data['textonly'] && empty($data['link']['url'])) {
16807f081821SGerrit Uitslag
1681*24870174SAndreas Gohr            if(in_array($conf['showuseras'], ['email_link', 'username_link'])) {
168260a396c8SGerrit Uitslag                if(!isset($info)) {
168360a396c8SGerrit Uitslag                    if($auth) $info = $auth->getUserData($username);
168460a396c8SGerrit Uitslag                }
168560a396c8SGerrit Uitslag                if(isset($info) && $info) {
16867f081821SGerrit Uitslag                    if($conf['showuseras'] == 'email_link') {
168760a396c8SGerrit Uitslag                        $data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
1688dc58b6f4SAndy Webber                    } else {
16897f081821SGerrit Uitslag                        if(is_null($xhtml_renderer)) {
16907f081821SGerrit Uitslag                            $xhtml_renderer = p_get_renderer('xhtml');
16917f081821SGerrit Uitslag                        }
16927f081821SGerrit Uitslag                        if(empty($xhtml_renderer->interwiki)) {
16937f081821SGerrit Uitslag                            $xhtml_renderer->interwiki = getInterwiki();
16947f081821SGerrit Uitslag                        }
16957f081821SGerrit Uitslag                        $shortcut = 'user';
1696533772e1SGerrit Uitslag                        $exists = null;
16976496c33fSGerrit Uitslag                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
16982a2a43c4SGerrit Uitslag                        $data['link']['class'] .= ' interwiki iw_user';
16996496c33fSGerrit Uitslag                        if($exists !== null) {
17006496c33fSGerrit Uitslag                            if($exists) {
17016496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink1';
17026496c33fSGerrit Uitslag                            } else {
17036496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink2';
17046496c33fSGerrit Uitslag                                $data['link']['rel'] = 'nofollow';
17056496c33fSGerrit Uitslag                            }
17066496c33fSGerrit Uitslag                        }
1707dc58b6f4SAndy Webber                    }
1708dc58b6f4SAndy Webber                } else {
170915f3bc49SGerrit Uitslag                    $data['textonly'] = true;
1710dc58b6f4SAndy Webber                }
171160a396c8SGerrit Uitslag
171260a396c8SGerrit Uitslag            } else {
171315f3bc49SGerrit Uitslag                $data['textonly'] = true;
171460a396c8SGerrit Uitslag            }
171560a396c8SGerrit Uitslag        }
171660a396c8SGerrit Uitslag
171715f3bc49SGerrit Uitslag        if($data['textonly']) {
17184d5fc927SGerrit Uitslag            $data['userlink'] = $data['name'];
171960a396c8SGerrit Uitslag        } else {
172060a396c8SGerrit Uitslag            $data['link']['name'] = $data['name'];
172160a396c8SGerrit Uitslag            if(is_null($xhtml_renderer)) {
172260a396c8SGerrit Uitslag                $xhtml_renderer = p_get_renderer('xhtml');
172360a396c8SGerrit Uitslag            }
17244d5fc927SGerrit Uitslag            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
172560a396c8SGerrit Uitslag        }
172660a396c8SGerrit Uitslag    }
172760a396c8SGerrit Uitslag    $evt->advise_after();
172860a396c8SGerrit Uitslag    unset($evt);
172960a396c8SGerrit Uitslag
17304d5fc927SGerrit Uitslag    return $data['userlink'];
1731066fee30SAndreas Gohr}
1732066fee30SAndreas Gohr
1733066fee30SAndreas Gohr/**
1734066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1735066fee30SAndreas Gohr * When no image exists, returns an empty string
1736066fee30SAndreas Gohr *
1737066fee30SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1738140cfbcdSGerrit Uitslag *
1739066fee30SAndreas Gohr * @param  string $type - type of image 'badge' or 'button'
17403272d797SAndreas Gohr * @return string
1741066fee30SAndreas Gohr */
1742066fee30SAndreas Gohrfunction license_img($type) {
1743066fee30SAndreas Gohr    global $license;
1744066fee30SAndreas Gohr    global $conf;
1745066fee30SAndreas Gohr    if(!$conf['license']) return '';
1746066fee30SAndreas Gohr    if(!is_array($license[$conf['license']])) return '';
1747*24870174SAndreas Gohr    $try   = [];
1748066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1749066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1750066fee30SAndreas Gohr    if(substr($conf['license'], 0, 3) == 'cc-') {
1751066fee30SAndreas Gohr        $try[] = 'lib/images/license/'.$type.'/cc.png';
1752066fee30SAndreas Gohr    }
1753066fee30SAndreas Gohr    foreach($try as $src) {
175479e79377SAndreas Gohr        if(file_exists(DOKU_INC.$src)) return $src;
1755066fee30SAndreas Gohr    }
1756066fee30SAndreas Gohr    return '';
1757dc58b6f4SAndy Webber}
1758dc58b6f4SAndy Webber
175913c08e2fSMichael Klier/**
176013c08e2fSMichael Klier * Checks if the given amount of memory is available
176113c08e2fSMichael Klier *
176213c08e2fSMichael Klier * If the memory_get_usage() function is not available the
176313c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
176413c08e2fSMichael Klier *
176513c08e2fSMichael Klier * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
176613c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
17673272d797SAndreas Gohr *
17683272d797SAndreas Gohr * @param int  $mem    Size of memory you want to allocate in bytes
1769140cfbcdSGerrit Uitslag * @param int  $bytes  already allocated memory (see above)
17703272d797SAndreas Gohr * @return bool
177113c08e2fSMichael Klier */
1772*24870174SAndreas Gohrfunction is_mem_available($mem, $bytes = 1_048_576) {
177313c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
177413c08e2fSMichael Klier    if(empty($limit)) return true; // no limit set!
1775985d6187SElenchus    if($limit == -1) return true; // unlimited
177613c08e2fSMichael Klier
177713c08e2fSMichael Klier    // parse limit to bytes
177813c08e2fSMichael Klier    $limit = php_to_byte($limit);
177913c08e2fSMichael Klier
178013c08e2fSMichael Klier    // get used memory if possible
178113c08e2fSMichael Klier    if(function_exists('memory_get_usage')) {
178213c08e2fSMichael Klier        $used = memory_get_usage();
178349eb6e38SAndreas Gohr    } else {
178449eb6e38SAndreas Gohr        $used = $bytes;
178513c08e2fSMichael Klier    }
178613c08e2fSMichael Klier
178713c08e2fSMichael Klier    if($used + $mem > $limit) {
178813c08e2fSMichael Klier        return false;
178913c08e2fSMichael Klier    }
179013c08e2fSMichael Klier
179113c08e2fSMichael Klier    return true;
179213c08e2fSMichael Klier}
179313c08e2fSMichael Klier
1794af2408d5SAndreas Gohr/**
1795af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1796af2408d5SAndreas Gohr *
1797af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1798af2408d5SAndreas Gohr *
1799af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1800af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1801140cfbcdSGerrit Uitslag *
1802140cfbcdSGerrit Uitslag * @param string $url url being directed to
1803af2408d5SAndreas Gohr */
1804af2408d5SAndreas Gohrfunction send_redirect($url) {
180598ca30d2SAndreas Gohr    $url = stripctl($url); // defend against HTTP Response Splitting
180698ca30d2SAndreas Gohr
1807585bf44eSChristopher Smith    /* @var Input $INPUT */
1808585bf44eSChristopher Smith    global $INPUT;
1809585bf44eSChristopher Smith
18100181f021SAndreas Gohr    //are there any undisplayed messages? keep them in session for display
18110181f021SAndreas Gohr    global $MSG;
18120181f021SAndreas Gohr    if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
18130181f021SAndreas Gohr        //reopen session, store data and close session again
18140181f021SAndreas Gohr        @session_start();
18150181f021SAndreas Gohr        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
18160181f021SAndreas Gohr    }
18170181f021SAndreas Gohr
1818d4869846SAndreas Gohr    // always close the session
1819d4869846SAndreas Gohr    session_write_close();
1820d4869846SAndreas Gohr
1821af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
1822585bf44eSChristopher Smith    if($INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1823585bf44eSChristopher Smith        (strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) &&
1824585bf44eSChristopher Smith        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
18253272d797SAndreas Gohr        $matches[1] < 6
18263272d797SAndreas Gohr    ) {
1827af2408d5SAndreas Gohr        header('Refresh: 0;url='.$url);
1828af2408d5SAndreas Gohr    } else {
1829af2408d5SAndreas Gohr        header('Location: '.$url);
1830af2408d5SAndreas Gohr    }
183181781cb6SAndreas Gohr
1832572dc222SLarsDW223    // no exits during unit tests
183327c0c399SAndreas Gohr    if(defined('DOKU_UNITTEST')) {
183427c0c399SAndreas Gohr        // pass info about the redirect back to the test suite
183527c0c399SAndreas Gohr        $testRequest = TestRequest::getRunning();
183627c0c399SAndreas Gohr        if($testRequest !== null) {
183727c0c399SAndreas Gohr            $testRequest->addData('send_redirect', $url);
183827c0c399SAndreas Gohr        }
1839572dc222SLarsDW223        return;
1840572dc222SLarsDW223    }
184127c0c399SAndreas Gohr
1842af2408d5SAndreas Gohr    exit;
1843af2408d5SAndreas Gohr}
1844af2408d5SAndreas Gohr
18455b75cd1fSAdrian Lang/**
18465b75cd1fSAdrian Lang * Validate a value using a set of valid values
18475b75cd1fSAdrian Lang *
18485b75cd1fSAdrian Lang * This function checks whether a specified value is set and in the array
18495b75cd1fSAdrian Lang * $valid_values. If not, the function returns a default value or, if no
18505b75cd1fSAdrian Lang * default is specified, throws an exception.
18515b75cd1fSAdrian Lang *
18525b75cd1fSAdrian Lang * @param string $param        The name of the parameter
18535b75cd1fSAdrian Lang * @param array  $valid_values A set of valid values; Optionally a default may
18545b75cd1fSAdrian Lang *                             be marked by the key “default”.
18555b75cd1fSAdrian Lang * @param array  $array        The array containing the value (typically $_POST
18565b75cd1fSAdrian Lang *                             or $_GET)
18575b75cd1fSAdrian Lang * @param string $exc          The text of the raised exception
18585b75cd1fSAdrian Lang *
18593272d797SAndreas Gohr * @throws Exception
18603272d797SAndreas Gohr * @return mixed
18615b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
18625b75cd1fSAdrian Lang */
18635b75cd1fSAdrian Langfunction valid_input_set($param, $valid_values, $array, $exc = '') {
18645b75cd1fSAdrian Lang    if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
18655b75cd1fSAdrian Lang        return $array[$param];
18665b75cd1fSAdrian Lang    } elseif(isset($valid_values['default'])) {
18675b75cd1fSAdrian Lang        return $valid_values['default'];
18685b75cd1fSAdrian Lang    } else {
18695b75cd1fSAdrian Lang        throw new Exception($exc);
18705b75cd1fSAdrian Lang    }
18715b75cd1fSAdrian Lang}
18725b75cd1fSAdrian Lang
187363703ba5SAndreas Gohr/**
187463703ba5SAndreas Gohr * Read a preference from the DokuWiki cookie
1875646a531aSChristopher Smith * (remembering both keys & values are urlencoded)
1876140cfbcdSGerrit Uitslag *
1877140cfbcdSGerrit Uitslag * @param string $pref     preference key
1878b4b6c9a1SGerrit Uitslag * @param mixed  $default  value returned when preference not found
1879140cfbcdSGerrit Uitslag * @return string preference value
188063703ba5SAndreas Gohr */
1881554a8c9fSAdrian Langfunction get_doku_pref($pref, $default) {
1882646a531aSChristopher Smith    $enc_pref = urlencode($pref);
188306c9ee33SMarius van Witzenburg    if(isset($_COOKIE['DOKU_PREFS']) && strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
1884554a8c9fSAdrian Lang        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
188563703ba5SAndreas Gohr        $cnt   = count($parts);
18861c3eca7dSPhy
18871c3eca7dSPhy        // due to #2721 there might be duplicate entries,
18881c3eca7dSPhy        // so we read from the end
18891c3eca7dSPhy        for($i = $cnt-2; $i >= 0; $i -= 2) {
1890*24870174SAndreas Gohr            if($parts[$i] === $enc_pref) {
1891646a531aSChristopher Smith                return urldecode($parts[$i + 1]);
1892554a8c9fSAdrian Lang            }
1893554a8c9fSAdrian Lang        }
1894554a8c9fSAdrian Lang    }
1895554a8c9fSAdrian Lang    return $default;
1896554a8c9fSAdrian Lang}
1897554a8c9fSAdrian Lang
18983c94d07bSAnika Henke/**
18993c94d07bSAnika Henke * Add a preference to the DokuWiki cookie
190036ec377eSChristopher Smith * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
19013a970889SAnika Henke * Remove it by setting $val to false
1902140cfbcdSGerrit Uitslag *
1903140cfbcdSGerrit Uitslag * @param string $pref  preference key
1904140cfbcdSGerrit Uitslag * @param string $val   preference value
19053c94d07bSAnika Henke */
19063c94d07bSAnika Henkefunction set_doku_pref($pref, $val) {
19073c94d07bSAnika Henke    global $conf;
19083c94d07bSAnika Henke    $orig = get_doku_pref($pref, false);
19093c94d07bSAnika Henke    $cookieVal = '';
19103c94d07bSAnika Henke
19111c3eca7dSPhy    if ($orig !== false && ($orig !== $val)) {
19123c94d07bSAnika Henke        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
19133c94d07bSAnika Henke        $cnt   = count($parts);
191436ec377eSChristopher Smith        // urlencode $pref for the comparison
191536ec377eSChristopher Smith        $enc_pref = rawurlencode($pref);
19161c3eca7dSPhy        $seen = false;
19173c94d07bSAnika Henke        for ($i = 0; $i < $cnt; $i += 2) {
1918*24870174SAndreas Gohr            if ($parts[$i] === $enc_pref) {
19191c3eca7dSPhy                if (!$seen){
19203a970889SAnika Henke                    if ($val !== false) {
1921bf8f8509SAndreas Gohr                        $parts[$i + 1] = rawurlencode($val ?? '');
19223a970889SAnika Henke                    } else {
19233a970889SAnika Henke                        unset($parts[$i]);
19243a970889SAnika Henke                        unset($parts[$i + 1]);
19253a970889SAnika Henke                    }
19261c3eca7dSPhy                    $seen = true;
19271c3eca7dSPhy                } else {
19281c3eca7dSPhy                    // no break because we want to remove duplicate entries
19291c3eca7dSPhy                    unset($parts[$i]);
19301c3eca7dSPhy                    unset($parts[$i + 1]);
19311c3eca7dSPhy                }
19323c94d07bSAnika Henke            }
19333c94d07bSAnika Henke        }
19343c94d07bSAnika Henke        $cookieVal = implode('#', $parts);
19351c3eca7dSPhy    } elseif ($orig === false && $val !== false) {
1936c10f256aSDamien Regad        $cookieVal = (isset($_COOKIE['DOKU_PREFS']) ? $_COOKIE['DOKU_PREFS'] . '#' : '') .
193764159a61SAndreas Gohr            rawurlencode($pref) . '#' . rawurlencode($val);
19383c94d07bSAnika Henke    }
19393c94d07bSAnika Henke
194075e4dd8aSGerrit Uitslag    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
19415833995aSPhy    if(defined('DOKU_UNITTEST')) {
19425833995aSPhy        $_COOKIE['DOKU_PREFS'] = $cookieVal;
19435833995aSPhy    }else{
1944bf8392ebSAndreas Gohr        setcookie('DOKU_PREFS', $cookieVal, [
1945bf8392ebSAndreas Gohr            'expires' => time() + 365 * 24 * 3600,
1946bf8392ebSAndreas Gohr            'path' => $cookieDir,
1947bf8392ebSAndreas Gohr            'secure' => ($conf['securecookie'] && is_ssl()),
1948bf8392ebSAndreas Gohr            'samesite' => 'Lax'
1949bf8392ebSAndreas Gohr        ]);
19503c94d07bSAnika Henke    }
19513c94d07bSAnika Henke}
19523c94d07bSAnika Henke
1953f8fb2d18SAndreas Gohr/**
1954f8fb2d18SAndreas Gohr * Strips source mapping declarations from given text #601
1955f8fb2d18SAndreas Gohr *
195642ea7f44SGerrit Uitslag * @param string &$text reference to the CSS or JavaScript code to clean
1957f8fb2d18SAndreas Gohr */
1958f8fb2d18SAndreas Gohrfunction stripsourcemaps(&$text){
1959f8fb2d18SAndreas Gohr    $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text);
1960f8fb2d18SAndreas Gohr}
1961f8fb2d18SAndreas Gohr
19623c27983bSAndreas Gohr/**
196371de5572SAndreas Gohr * Returns the contents of a given SVG file for embedding
19643c27983bSAndreas Gohr *
19653c27983bSAndreas Gohr * Inlining SVGs saves on HTTP requests and more importantly allows for styling them through
19663c27983bSAndreas Gohr * CSS. However it should used with small SVGs only. The $maxsize setting ensures only small
19673c27983bSAndreas Gohr * files are embedded.
19683c27983bSAndreas Gohr *
196971de5572SAndreas Gohr * This strips unneeded headers, comments and newline. The result is not a vaild standalone SVG!
197071de5572SAndreas Gohr *
19713c27983bSAndreas Gohr * @param string $file full path to the SVG file
19723c27983bSAndreas Gohr * @param int $maxsize maximum allowed size for the SVG to be embedded
197371de5572SAndreas Gohr * @return string|false the SVG content, false if the file couldn't be loaded
19743c27983bSAndreas Gohr */
19754cd2074fSAndreas Gohrfunction inlineSVG($file, $maxsize = 2048) {
19763c27983bSAndreas Gohr    $file = trim($file);
19773c27983bSAndreas Gohr    if($file === '') return false;
19783c27983bSAndreas Gohr    if(!file_exists($file)) return false;
19793c27983bSAndreas Gohr    if(filesize($file) > $maxsize) return false;
19803c27983bSAndreas Gohr    if(!is_readable($file)) return false;
19813c27983bSAndreas Gohr    $content = file_get_contents($file);
19820849fa88SAndreas Gohr    $content = preg_replace('/<!--.*?(-->)/s','', $content); // comments
19830849fa88SAndreas Gohr    $content = preg_replace('/<\?xml .*?\?>/i', '', $content); // xml header
19840849fa88SAndreas Gohr    $content = preg_replace('/<!DOCTYPE .*?>/i', '', $content); // doc type
19850849fa88SAndreas Gohr    $content = preg_replace('/>\s+</s', '><', $content); // newlines between tags
19863c27983bSAndreas Gohr    $content = trim($content);
19873c27983bSAndreas Gohr    if(substr($content, 0, 5) !== '<svg ') return false;
198871de5572SAndreas Gohr    return $content;
19893c27983bSAndreas Gohr}
19903c27983bSAndreas Gohr
1991e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1992