xref: /dokuwiki/inc/common.php (revision 98b599a697d5188f9a6c1080fc70144e37061abe)
1ed7b5f09Sandi<?php
2d4f83172SAndreas Gohr
315fae107Sandi/**
415fae107Sandi * Common DokuWiki functions
515fae107Sandi *
615fae107Sandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
715fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
815fae107Sandi */
9d4f83172SAndreas Gohr
1024870174SAndreas Gohruse dokuwiki\PassHash;
1124870174SAndreas Gohruse dokuwiki\Draft;
1224870174SAndreas Gohruse dokuwiki\Utf8\Clean;
1324870174SAndreas Gohruse dokuwiki\Utf8\PhpString;
1424870174SAndreas Gohruse dokuwiki\Utf8\Conversion;
150db5771eSMichael Großeuse dokuwiki\Cache\CacheRenderer;
160c3a5702SAndreas Gohruse dokuwiki\ChangeLog\PageChangeLog;
17b24e9c4aSSatoshi Saharause dokuwiki\File\PageFile;
18704a815fSMichael Großeuse dokuwiki\Subscriptions\PageSubscriptionSender;
1975d66495SMichael Großeuse dokuwiki\Subscriptions\SubscriberManager;
20e1d9dcc8SAndreas Gohruse dokuwiki\Extension\AuthPlugin;
21e1d9dcc8SAndreas Gohruse dokuwiki\Extension\Event;
222aba9aedSAndreas Gohruse dokuwiki\Ip;
230c3a5702SAndreas Gohr
248b19906eSAndreas Gohruse function PHP81_BC\strftime;
258b19906eSAndreas Gohr
26f3f0262cSandi/**
27d5197206Schris * Wrapper around htmlspecialchars()
28d5197206Schris *
298b19906eSAndreas Gohr * @param string $string the string being converted
308b19906eSAndreas Gohr * @return string converted string
31d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
32d5197206Schris * @see    htmlspecialchars()
33140cfbcdSGerrit Uitslag *
34d5197206Schris */
35d868eb89SAndreas Gohrfunction hsc($string)
36d868eb89SAndreas Gohr{
37f7711f2bSAndreas Gohr    return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, 'UTF-8');
38d5197206Schris}
39d5197206Schris
40d5197206Schris/**
4112dd3cbcSAndreas Gohr * A safer explode for fixed length lists
4212dd3cbcSAndreas Gohr *
4312dd3cbcSAndreas Gohr * This works just like explode(), but will always return the wanted number of elements.
4412dd3cbcSAndreas Gohr * If the $input string does not contain enough elements, the missing elements will be
4512dd3cbcSAndreas Gohr * filled up with the $default value. If the input string contains more elements, the last
4612dd3cbcSAndreas Gohr * one will NOT be split up and will still contain $separator
4712dd3cbcSAndreas Gohr *
4812dd3cbcSAndreas Gohr * @param string $separator The boundary string
4912dd3cbcSAndreas Gohr * @param string $string The input string
5012dd3cbcSAndreas Gohr * @param int $limit The number of expected elements
5112dd3cbcSAndreas Gohr * @param mixed $default The value to use when filling up missing elements
5212dd3cbcSAndreas Gohr * @return array
538b19906eSAndreas Gohr * @see explode
5412dd3cbcSAndreas Gohr */
5512dd3cbcSAndreas Gohrfunction sexplode($separator, $string, $limit, $default = null)
5612dd3cbcSAndreas Gohr{
5712dd3cbcSAndreas Gohr    return array_pad(explode($separator, $string, $limit), $limit, $default);
5812dd3cbcSAndreas Gohr}
5912dd3cbcSAndreas Gohr
6012dd3cbcSAndreas Gohr/**
615b571377SAndreas Gohr * Checks if the given input is blank
625b571377SAndreas Gohr *
635b571377SAndreas Gohr * This is similar to empty() but will return false for "0".
645b571377SAndreas Gohr *
6567234204SAndreas Gohr * Please note: when you pass uninitialized variables, they will implicitly be created
6667234204SAndreas Gohr * with a NULL value without warning.
6767234204SAndreas Gohr *
6867234204SAndreas Gohr * To avoid this it's recommended to guard the call with isset like this:
6967234204SAndreas Gohr *
7067234204SAndreas Gohr * (isset($foo) && !blank($foo))
7167234204SAndreas Gohr * (!isset($foo) || blank($foo))
7267234204SAndreas Gohr *
735b571377SAndreas Gohr * @param $in
745b571377SAndreas Gohr * @param bool $trim Consider a string of whitespace to be blank
755b571377SAndreas Gohr * @return bool
765b571377SAndreas Gohr */
77d868eb89SAndreas Gohrfunction blank(&$in, $trim = false)
78d868eb89SAndreas Gohr{
795b571377SAndreas Gohr    if (is_null($in)) return true;
8024870174SAndreas Gohr    if (is_array($in)) return $in === [];
815b571377SAndreas Gohr    if ($in === "\0") return true;
825b571377SAndreas Gohr    if ($trim && trim($in) === '') return true;
835b571377SAndreas Gohr    if (strlen($in) > 0) return false;
845b571377SAndreas Gohr    return empty($in);
855b571377SAndreas Gohr}
865b571377SAndreas Gohr
875b571377SAndreas Gohr/**
8802b0b681SAndreas Gohr * strips control characters (<32) from the given string
8902b0b681SAndreas Gohr *
9042ea7f44SGerrit Uitslag * @param string $string being stripped
91140cfbcdSGerrit Uitslag * @return string
928b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
938b19906eSAndreas Gohr *
9402b0b681SAndreas Gohr */
95d868eb89SAndreas Gohrfunction stripctl($string)
96d868eb89SAndreas Gohr{
9702b0b681SAndreas Gohr    return preg_replace('/[\x00-\x1F]+/s', '', $string);
98d5197206Schris}
99d5197206Schris
100d5197206Schris/**
101634d7150SAndreas Gohr * Return a secret token to be used for CSRF attack prevention
102634d7150SAndreas Gohr *
1038b19906eSAndreas Gohr * @return  string
104634d7150SAndreas Gohr * @link    http://en.wikipedia.org/wiki/Cross-site_request_forgery
105634d7150SAndreas Gohr * @link    http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
10642ea7f44SGerrit Uitslag *
1078b19906eSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
108634d7150SAndreas Gohr */
109d868eb89SAndreas Gohrfunction getSecurityToken()
110d868eb89SAndreas Gohr{
111585bf44eSChristopher Smith    /** @var Input $INPUT */
112585bf44eSChristopher Smith    global $INPUT;
1133680e2cdSAndreas Gohr
1143680e2cdSAndreas Gohr    $user = $INPUT->server->str('REMOTE_USER');
1153680e2cdSAndreas Gohr    $session = session_id();
1163680e2cdSAndreas Gohr
1173680e2cdSAndreas Gohr    // CSRF checks are only for logged in users - do not generate for anonymous
1183680e2cdSAndreas Gohr    if (trim($user) == '' || trim($session) == '') return '';
11924870174SAndreas Gohr    return PassHash::hmac('md5', $session . $user, auth_cookiesalt());
120634d7150SAndreas Gohr}
121634d7150SAndreas Gohr
122634d7150SAndreas Gohr/**
123634d7150SAndreas Gohr * Check the secret CSRF token
124140cfbcdSGerrit Uitslag *
125140cfbcdSGerrit Uitslag * @param null|string $token security token or null to read it from request variable
126140cfbcdSGerrit Uitslag * @return bool success if the token matched
127634d7150SAndreas Gohr */
128d868eb89SAndreas Gohrfunction checkSecurityToken($token = null)
129d868eb89SAndreas Gohr{
130585bf44eSChristopher Smith    /** @var Input $INPUT */
1317d01a0eaSTom N Harris    global $INPUT;
132585bf44eSChristopher Smith    if (!$INPUT->server->str('REMOTE_USER')) return true; // no logged in user, no need for a check
133df97eaacSAndreas Gohr
1347d01a0eaSTom N Harris    if (is_null($token)) $token = $INPUT->str('sectok');
135634d7150SAndreas Gohr    if (getSecurityToken() != $token) {
136634d7150SAndreas Gohr        msg('Security Token did not match. Possible CSRF attack.', -1);
137634d7150SAndreas Gohr        return false;
138634d7150SAndreas Gohr    }
139634d7150SAndreas Gohr    return true;
140634d7150SAndreas Gohr}
141634d7150SAndreas Gohr
142634d7150SAndreas Gohr/**
143634d7150SAndreas Gohr * Print a hidden form field with a secret CSRF token
144634d7150SAndreas Gohr *
145140cfbcdSGerrit Uitslag * @param bool $print if true print the field, otherwise html of the field is returned
14642ea7f44SGerrit Uitslag * @return string html of hidden form field
1478b19906eSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
1488b19906eSAndreas Gohr *
149634d7150SAndreas Gohr */
150d868eb89SAndreas Gohrfunction formSecurityToken($print = true)
151d868eb89SAndreas Gohr{
1522404d0edSAnika Henke    $ret = '<div class="no"><input type="hidden" name="sectok" value="' . getSecurityToken() . '" /></div>' . "\n";
1533272d797SAndreas Gohr    if ($print) echo $ret;
154634d7150SAndreas Gohr    return $ret;
155634d7150SAndreas Gohr}
156634d7150SAndreas Gohr
157634d7150SAndreas Gohr/**
1581015a57dSChristopher Smith * Determine basic information for a request of $id
15915fae107Sandi *
160140cfbcdSGerrit Uitslag * @param string $id pageid
161140cfbcdSGerrit Uitslag * @param bool $htmlClient add info about whether is mobile browser
162140cfbcdSGerrit Uitslag * @return array with info for a request of $id
163140cfbcdSGerrit Uitslag *
1648b19906eSAndreas Gohr * @author Chris Smith <chris@jalakai.co.uk>
1658b19906eSAndreas Gohr *
1668b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
167f3f0262cSandi */
168d868eb89SAndreas Gohrfunction basicinfo($id, $htmlClient = true)
169d868eb89SAndreas Gohr{
170f3f0262cSandi    global $USERINFO;
171585bf44eSChristopher Smith    /* @var Input $INPUT */
172585bf44eSChristopher Smith    global $INPUT;
1736afe8dcaSchris
174c66972f2SAdrian Lang    // set info about manager/admin status.
17524870174SAndreas Gohr    $info = [];
176c66972f2SAdrian Lang    $info['isadmin'] = false;
177c66972f2SAdrian Lang    $info['ismanager'] = false;
178585bf44eSChristopher Smith    if ($INPUT->server->has('REMOTE_USER')) {
179f3f0262cSandi        $info['userinfo'] = $USERINFO;
1801015a57dSChristopher Smith        $info['perm'] = auth_quickaclcheck($id);
181585bf44eSChristopher Smith        $info['client'] = $INPUT->server->str('REMOTE_USER');
18217ee7f66SAndreas Gohr
183f8cc712eSAndreas Gohr        if ($info['perm'] == AUTH_ADMIN) {
184f8cc712eSAndreas Gohr            $info['isadmin'] = true;
185f8cc712eSAndreas Gohr            $info['ismanager'] = true;
186f8cc712eSAndreas Gohr        } elseif (auth_ismanager()) {
187f8cc712eSAndreas Gohr            $info['ismanager'] = true;
188f8cc712eSAndreas Gohr        }
189f8cc712eSAndreas Gohr
19017ee7f66SAndreas Gohr        // if some outside auth were used only REMOTE_USER is set
191a58fcbbcSAndreas Gohr        if (empty($info['userinfo']['name'])) {
192585bf44eSChristopher Smith            $info['userinfo']['name'] = $INPUT->server->str('REMOTE_USER');
19317ee7f66SAndreas Gohr        }
194f3f0262cSandi    } else {
1951015a57dSChristopher Smith        $info['perm'] = auth_aclcheck($id, '', null);
196ee4c4a1bSAndreas Gohr        $info['client'] = clientIP(true);
197f3f0262cSandi    }
198f3f0262cSandi
1991015a57dSChristopher Smith    $info['namespace'] = getNS($id);
2001015a57dSChristopher Smith
2011015a57dSChristopher Smith    // mobile detection
2021015a57dSChristopher Smith    if ($htmlClient) {
2031015a57dSChristopher Smith        $info['ismobile'] = clientismobile();
2041015a57dSChristopher Smith    }
2051015a57dSChristopher Smith
2061015a57dSChristopher Smith    return $info;
2071015a57dSChristopher Smith}
2081015a57dSChristopher Smith
2091015a57dSChristopher Smith/**
2101015a57dSChristopher Smith * Return info about the current document as associative
2111015a57dSChristopher Smith * array.
2121015a57dSChristopher Smith *
213140cfbcdSGerrit Uitslag * @return array with info about current document
2144dc42f7fSGerrit Uitslag * @throws Exception
2154dc42f7fSGerrit Uitslag *
2164dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
2171015a57dSChristopher Smith */
218d868eb89SAndreas Gohrfunction pageinfo()
219d868eb89SAndreas Gohr{
2201015a57dSChristopher Smith    global $ID;
2211015a57dSChristopher Smith    global $REV;
2221015a57dSChristopher Smith    global $RANGE;
2231015a57dSChristopher Smith    global $lang;
2241015a57dSChristopher Smith
2251015a57dSChristopher Smith    $info = basicinfo($ID);
2261015a57dSChristopher Smith
2271015a57dSChristopher Smith    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
2281015a57dSChristopher Smith    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
2291015a57dSChristopher Smith    $info['id'] = $ID;
2301015a57dSChristopher Smith    $info['rev'] = $REV;
2311015a57dSChristopher Smith
23275d66495SMichael Große    $subManager = new SubscriberManager();
23375d66495SMichael Große    $info['subscribed'] = $subManager->userSubscription();
2347e87a794SChristopher Smith
235f3f0262cSandi    $info['locked'] = checklock($ID);
236317a04c4SSatoshi Sahara    $info['filepath'] = wikiFN($ID);
23779e79377SAndreas Gohr    $info['exists'] = file_exists($info['filepath']);
23801c9a118SAndreas Gohr    $info['currentrev'] = @filemtime($info['filepath']);
2395ec96136SSatoshi Sahara
2402ca9d91cSBen Coburn    if ($REV) {
2412ca9d91cSBen Coburn        //check if current revision was meant
24201c9a118SAndreas Gohr        if ($info['exists'] && ($info['currentrev'] == $REV)) {
2432ca9d91cSBen Coburn            $REV = '';
2447b3a6803SAndreas Gohr        } elseif ($RANGE) {
2457b3a6803SAndreas Gohr            //section editing does not work with old revisions!
2467b3a6803SAndreas Gohr            $REV = '';
2477b3a6803SAndreas Gohr            $RANGE = '';
2487b3a6803SAndreas Gohr            msg($lang['nosecedit'], 0);
2492ca9d91cSBen Coburn        } else {
2502ca9d91cSBen Coburn            //really use old revision
251317a04c4SSatoshi Sahara            $info['filepath'] = wikiFN($ID, $REV);
25279e79377SAndreas Gohr            $info['exists'] = file_exists($info['filepath']);
253f3f0262cSandi        }
254f3f0262cSandi    }
255c112d578Sandi    $info['rev'] = $REV;
256f3f0262cSandi    if ($info['exists']) {
257252acce3SSatoshi Sahara        $info['writable'] = (is_writable($info['filepath']) && $info['perm'] >= AUTH_EDIT);
258f3f0262cSandi    } else {
259f3f0262cSandi        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
260f3f0262cSandi    }
26150e988b1SAndreas Gohr    $info['editable'] = ($info['writable'] && empty($info['locked']));
262f3f0262cSandi    $info['lastmod'] = @filemtime($info['filepath']);
263f3f0262cSandi
26471726d78SBen Coburn    //load page meta data
26571726d78SBen Coburn    $info['meta'] = p_get_metadata($ID);
26671726d78SBen Coburn
267652610a2Sandi    //who's the editor
268047bad06SGerrit Uitslag    $pagelog = new PageChangeLog($ID, 1024);
269652610a2Sandi    if ($REV) {
270f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($REV);
27124870174SAndreas Gohr    } elseif (!empty($info['meta']['last_change']) && is_array($info['meta']['last_change'])) {
272aa27cf05SAndreas Gohr        $revinfo = $info['meta']['last_change'];
273aa27cf05SAndreas Gohr    } else {
274f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($info['lastmod']);
275cd00a034SBen Coburn        // cache most recent changelog line in metadata if missing and still valid
276cd00a034SBen Coburn        if ($revinfo !== false) {
277cd00a034SBen Coburn            $info['meta']['last_change'] = $revinfo;
27824870174SAndreas Gohr            p_set_metadata($ID, ['last_change' => $revinfo]);
279cd00a034SBen Coburn        }
280cd00a034SBen Coburn    }
281cd00a034SBen Coburn    //and check for an external edit
282cd00a034SBen Coburn    if ($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
283cd00a034SBen Coburn        // cached changelog line no longer valid
284cd00a034SBen Coburn        $revinfo = false;
285cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
28624870174SAndreas Gohr        p_set_metadata($ID, ['last_change' => $revinfo]);
287652610a2Sandi    }
288bb4866bdSchris
2890a444b5aSPhy    if ($revinfo !== false) {
290652610a2Sandi        $info['ip'] = $revinfo['ip'];
291652610a2Sandi        $info['user'] = $revinfo['user'];
292652610a2Sandi        $info['sum'] = $revinfo['sum'];
29371726d78SBen Coburn        // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
294ebf1501fSBen Coburn        // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
29559f257aeSchris
296252acce3SSatoshi Sahara        $info['editor'] = $revinfo['user'] ?: $revinfo['ip'];
2970a444b5aSPhy    } else {
2980a444b5aSPhy        $info['ip'] = null;
2990a444b5aSPhy        $info['user'] = null;
3000a444b5aSPhy        $info['sum'] = null;
3010a444b5aSPhy        $info['editor'] = null;
3020a444b5aSPhy    }
303652610a2Sandi
304ee4c4a1bSAndreas Gohr    // draft
30524870174SAndreas Gohr    $draft = new Draft($ID, $info['client']);
3060aabe6f8SMichael Große    if ($draft->isDraftAvailable()) {
3070aabe6f8SMichael Große        $info['draft'] = $draft->getDraftFilename();
308ee4c4a1bSAndreas Gohr    }
309ee4c4a1bSAndreas Gohr
3101015a57dSChristopher Smith    return $info;
3111015a57dSChristopher Smith}
3121015a57dSChristopher Smith
3131015a57dSChristopher Smith/**
3140c39d46cSMichael Große * Initialize and/or fill global $JSINFO with some basic info to be given to javascript
3150c39d46cSMichael Große */
316d868eb89SAndreas Gohrfunction jsinfo()
317d868eb89SAndreas Gohr{
3180c39d46cSMichael Große    global $JSINFO, $ID, $INFO, $ACT;
3190c39d46cSMichael Große
3200c39d46cSMichael Große    if (!is_array($JSINFO)) {
3210c39d46cSMichael Große        $JSINFO = [];
3220c39d46cSMichael Große    }
3230c39d46cSMichael Große    //export minimal info to JS, plugins can add more
3240c39d46cSMichael Große    $JSINFO['id'] = $ID;
32568491db9SPhy    $JSINFO['namespace'] = isset($INFO) ? (string)$INFO['namespace'] : '';
3260c39d46cSMichael Große    $JSINFO['ACT'] = act_clean($ACT);
3270c39d46cSMichael Große    $JSINFO['useHeadingNavigation'] = (int)useHeading('navigation');
3280c39d46cSMichael Große    $JSINFO['useHeadingContent'] = (int)useHeading('content');
3290c39d46cSMichael Große}
3300c39d46cSMichael Große
3310c39d46cSMichael Große/**
3321015a57dSChristopher Smith * Return information about the current media item as an associative array.
333140cfbcdSGerrit Uitslag *
334140cfbcdSGerrit Uitslag * @return array with info about current media item
3351015a57dSChristopher Smith */
336d868eb89SAndreas Gohrfunction mediainfo()
337d868eb89SAndreas Gohr{
3381015a57dSChristopher Smith    global $NS;
3391015a57dSChristopher Smith    global $IMG;
3401015a57dSChristopher Smith
3411015a57dSChristopher Smith    $info = basicinfo("$NS:*");
3421015a57dSChristopher Smith    $info['image'] = $IMG;
3431c548ebeSAndreas Gohr
344f3f0262cSandi    return $info;
345f3f0262cSandi}
346f3f0262cSandi
347f3f0262cSandi/**
3482684e50aSAndreas Gohr * Build an string of URL parameters
3492684e50aSAndreas Gohr *
350140cfbcdSGerrit Uitslag * @param array $params array with key-value pairs
351140cfbcdSGerrit Uitslag * @param string $sep series of pairs are separated by this character
352140cfbcdSGerrit Uitslag * @return string query string
3538b19906eSAndreas Gohr * @author Andreas Gohr
3548b19906eSAndreas Gohr *
3552684e50aSAndreas Gohr */
356d868eb89SAndreas Gohrfunction buildURLparams($params, $sep = '&amp;')
357d868eb89SAndreas Gohr{
3582684e50aSAndreas Gohr    $url = '';
3592684e50aSAndreas Gohr    $amp = false;
3602684e50aSAndreas Gohr    foreach ($params as $key => $val) {
361b174aeaeSchris        if ($amp) $url .= $sep;
3622684e50aSAndreas Gohr
36385e6871fSAdrian Lang        $url .= rawurlencode($key) . '=';
3643a50618cSgweissbach        $url .= rawurlencode((string)$val);
3652684e50aSAndreas Gohr        $amp = true;
3662684e50aSAndreas Gohr    }
3672684e50aSAndreas Gohr    return $url;
3682684e50aSAndreas Gohr}
3692684e50aSAndreas Gohr
3702684e50aSAndreas Gohr/**
3712684e50aSAndreas Gohr * Build an string of html tag attributes
3722684e50aSAndreas Gohr *
3737bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
3747bff22c0SAndreas Gohr *
375140cfbcdSGerrit Uitslag * @param array $params array with (attribute name-attribute value) pairs
376246d3337SMichael Große * @param bool $skipEmptyStrings skip empty string values?
377140cfbcdSGerrit Uitslag * @return string
3788b19906eSAndreas Gohr * @author Andreas Gohr
3798b19906eSAndreas Gohr *
3802684e50aSAndreas Gohr */
381d868eb89SAndreas Gohrfunction buildAttributes($params, $skipEmptyStrings = false)
382d868eb89SAndreas Gohr{
3832684e50aSAndreas Gohr    $url = '';
3849063ec14SAdrian Lang    $white = false;
3852684e50aSAndreas Gohr    foreach ($params as $key => $val) {
3862401f18dSSyntaxseed        if ($key[0] == '_') continue;
387246d3337SMichael Große        if ($val === '' && $skipEmptyStrings) continue;
3889063ec14SAdrian Lang        if ($white) $url .= ' ';
3897bff22c0SAndreas Gohr
3902684e50aSAndreas Gohr        $url .= $key . '="';
391f7711f2bSAndreas Gohr        $url .= hsc($val);
3922684e50aSAndreas Gohr        $url .= '"';
3939063ec14SAdrian Lang        $white = true;
3942684e50aSAndreas Gohr    }
3952684e50aSAndreas Gohr    return $url;
3962684e50aSAndreas Gohr}
3972684e50aSAndreas Gohr
3982684e50aSAndreas Gohr/**
39915fae107Sandi * This builds the breadcrumb trail and returns it as array
40015fae107Sandi *
4018b19906eSAndreas Gohr * @return string[] with the data: array(pageid=>name, ... )
40215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
403140cfbcdSGerrit Uitslag *
404f3f0262cSandi */
405d868eb89SAndreas Gohrfunction breadcrumbs()
406d868eb89SAndreas Gohr{
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?
41724870174SAndreas 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 *
464140cfbcdSGerrit Uitslag * @param string $id pageid being filtered
465140cfbcdSGerrit Uitslag * @param bool $ue apply urlencoding?
466140cfbcdSGerrit Uitslag * @return string
4678b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
4688b19906eSAndreas Gohr *
469f3f0262cSandi */
470d868eb89SAndreas Gohrfunction idfilter($id, $ue = true)
471d868eb89SAndreas Gohr{
472f3f0262cSandi    global $conf;
473585bf44eSChristopher Smith    /* @var Input $INPUT */
474585bf44eSChristopher Smith    global $INPUT;
475585bf44eSChristopher Smith
476bf8f8509SAndreas Gohr    $id = (string)$id;
477bf8f8509SAndreas Gohr
478f3f0262cSandi    if ($conf['useslash'] && $conf['userewrite']) {
479f3f0262cSandi        $id = strtr($id, ':', '/');
4807d34963bSAndreas Gohr    } elseif (
4816c16a3a9Sfiwswe        str_starts_with(strtoupper(PHP_OS), 'WIN') &&
48258bedc8aSborekb        $conf['userewrite'] &&
483585bf44eSChristopher Smith        strpos($INPUT->server->str('SERVER_SOFTWARE'), 'Microsoft-IIS') === false
4843272d797SAndreas Gohr    ) {
485f3f0262cSandi        $id = strtr($id, ':', ';');
486f3f0262cSandi    }
48749c713a3Sandi    if ($ue) {
488b6c6979fSAndreas Gohr        $id = rawurlencode($id);
489f3f0262cSandi        $id = str_replace('%3A', ':', $id); //keep as colon
490edd95259SGerrit Uitslag        $id = str_replace('%3B', ';', $id); //keep as semicolon
491f3f0262cSandi        $id = str_replace('%2F', '/', $id); //keep as slash
49249c713a3Sandi    }
493f3f0262cSandi    return $id;
494f3f0262cSandi}
495f3f0262cSandi
496f3f0262cSandi/**
497ed7b5f09Sandi * This builds a link to a wikipage
49815fae107Sandi *
4994bc480e5SAndreas Gohr * It handles URL rewriting and adds additional parameters
5006c7843b5Sandi *
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
5068b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
5078b19906eSAndreas Gohr *
508f3f0262cSandi */
509d868eb89SAndreas Gohrfunction wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;')
510d868eb89SAndreas Gohr{
511f3f0262cSandi    global $conf;
51216f15a81SDominik Eckelmann    if (is_array($urlParameters)) {
5134bde2196Slisps        if (isset($urlParameters['rev']) && !$urlParameters['rev']) unset($urlParameters['rev']);
51464159a61SAndreas Gohr        if (isset($urlParameters['at']) && $conf['date_at_format']) {
51564159a61SAndreas Gohr            $urlParameters['at'] = date($conf['date_at_format'], $urlParameters['at']);
51664159a61SAndreas Gohr        }
51716f15a81SDominik Eckelmann        $urlParameters = buildURLparams($urlParameters, $separator);
5186de3759aSAndreas Gohr    } else {
51916f15a81SDominik Eckelmann        $urlParameters = str_replace(',', $separator, $urlParameters);
5206de3759aSAndreas Gohr    }
52116f15a81SDominik Eckelmann    if ($id === '') {
52216f15a81SDominik Eckelmann        $id = $conf['start'];
52316f15a81SDominik Eckelmann    }
524f3f0262cSandi    $id = idfilter($id);
52516f15a81SDominik Eckelmann    if ($absolute) {
526ed7b5f09Sandi        $xlink = DOKU_URL;
527ed7b5f09Sandi    } else {
528ed7b5f09Sandi        $xlink = DOKU_BASE;
529ed7b5f09Sandi    }
530f3f0262cSandi
5316c7843b5Sandi    if ($conf['userewrite'] == 2) {
5326c7843b5Sandi        $xlink .= DOKU_SCRIPT . '/' . $id;
53316f15a81SDominik Eckelmann        if ($urlParameters) $xlink .= '?' . $urlParameters;
5346c7843b5Sandi    } elseif ($conf['userewrite']) {
535f3f0262cSandi        $xlink .= $id;
53616f15a81SDominik Eckelmann        if ($urlParameters) $xlink .= '?' . $urlParameters;
53740b5fb5bSPhy    } elseif ($id !== '') {
5386c7843b5Sandi        $xlink .= DOKU_SCRIPT . '?id=' . $id;
53916f15a81SDominik Eckelmann        if ($urlParameters) $xlink .= $separator . $urlParameters;
540bce3726dSAndreas Gohr    } else {
541bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
54216f15a81SDominik Eckelmann        if ($urlParameters) $xlink .= '?' . $urlParameters;
543f3f0262cSandi    }
544f3f0262cSandi
545f3f0262cSandi    return $xlink;
546f3f0262cSandi}
547f3f0262cSandi
548f3f0262cSandi/**
549f5c2808fSBen Coburn * This builds a link to an alternate page format
550f5c2808fSBen Coburn *
551f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
552f5c2808fSBen Coburn *
5534bc480e5SAndreas Gohr * @param string $id page id, defaults to start page
5544bc480e5SAndreas Gohr * @param string $format the export renderer to use
5554bc480e5SAndreas Gohr * @param string|array $urlParameters URL parameters, associative array recommended
5564bc480e5SAndreas Gohr * @param bool $abs request an absolute URL instead of relative
5574bc480e5SAndreas Gohr * @param string $sep parameter separator
5584bc480e5SAndreas Gohr * @return string
5598b19906eSAndreas Gohr * @author Ben Coburn <btcoburn@silicodon.net>
560f5c2808fSBen Coburn */
561d868eb89SAndreas Gohrfunction exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;')
562d868eb89SAndreas Gohr{
563f5c2808fSBen Coburn    global $conf;
5644bc480e5SAndreas Gohr    if (is_array($urlParameters)) {
5654bc480e5SAndreas Gohr        $urlParameters = buildURLparams($urlParameters, $sep);
566f5c2808fSBen Coburn    } else {
5674bc480e5SAndreas Gohr        $urlParameters = str_replace(',', $sep, $urlParameters);
568f5c2808fSBen Coburn    }
569f5c2808fSBen Coburn
570f5c2808fSBen Coburn    $format = rawurlencode($format);
571f5c2808fSBen Coburn    $id = idfilter($id);
572f5c2808fSBen Coburn    if ($abs) {
573f5c2808fSBen Coburn        $xlink = DOKU_URL;
574f5c2808fSBen Coburn    } else {
575f5c2808fSBen Coburn        $xlink = DOKU_BASE;
576f5c2808fSBen Coburn    }
577f5c2808fSBen Coburn
578f5c2808fSBen Coburn    if ($conf['userewrite'] == 2) {
579f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT . '/' . $id . '?do=export_' . $format;
5804bc480e5SAndreas Gohr        if ($urlParameters) $xlink .= $sep . $urlParameters;
581f5c2808fSBen Coburn    } elseif ($conf['userewrite'] == 1) {
582f5c2808fSBen Coburn        $xlink .= '_export/' . $format . '/' . $id;
5834bc480e5SAndreas Gohr        if ($urlParameters) $xlink .= '?' . $urlParameters;
584f5c2808fSBen Coburn    } else {
585f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT . '?do=export_' . $format . $sep . 'id=' . $id;
5864bc480e5SAndreas Gohr        if ($urlParameters) $xlink .= $sep . $urlParameters;
587f5c2808fSBen Coburn    }
588f5c2808fSBen Coburn
589f5c2808fSBen Coburn    return $xlink;
590f5c2808fSBen Coburn}
591f5c2808fSBen Coburn
592f5c2808fSBen Coburn/**
5936de3759aSAndreas Gohr * Build a link to a media file
5946de3759aSAndreas Gohr *
5956de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
5968c08db0aSAndreas Gohr *
5978c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
5988c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
5998c08db0aSAndreas Gohr *
6003272d797SAndreas Gohr * @param string $id the media file id or URL
6013272d797SAndreas Gohr * @param mixed $more string or array with additional parameters
6023272d797SAndreas Gohr * @param bool $direct link to detail page if false
6033272d797SAndreas Gohr * @param string $sep URL parameter separator
6043272d797SAndreas Gohr * @param bool $abs Create an absolute URL
6053272d797SAndreas Gohr * @return string
6066de3759aSAndreas Gohr */
607d868eb89SAndreas Gohrfunction ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false)
608d868eb89SAndreas Gohr{
6096de3759aSAndreas Gohr    global $conf;
610b9ee6a44SKlap-in    $isexternalimage = media_isexternal($id);
611826d2766SKlap-in    if (!$isexternalimage) {
612826d2766SKlap-in        $id = cleanID($id);
613826d2766SKlap-in    }
614826d2766SKlap-in
6156de3759aSAndreas Gohr    if (is_array($more)) {
6160f4e0092SChristopher Smith        // add token for resized images
61724870174SAndreas Gohr        $w = $more['w'] ?? null;
61824870174SAndreas Gohr        $h = $more['h'] ?? null;
61998fe1ac9SDamien Regad        if ($w || $h || $isexternalimage) {
620357c9a39SDamien Regad            $more['tok'] = media_get_token($id, $w, $h);
6210f4e0092SChristopher Smith        }
6228c08db0aSAndreas Gohr        // strip defaults for shorter URLs
6238c08db0aSAndreas Gohr        if (isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
624443e135dSChristopher Smith        if (empty($more['w'])) unset($more['w']);
625443e135dSChristopher Smith        if (empty($more['h'])) unset($more['h']);
6268c08db0aSAndreas Gohr        if (isset($more['id']) && $direct) unset($more['id']);
62778b874e6Slisps        if (isset($more['rev']) && !$more['rev']) unset($more['rev']);
628b174aeaeSchris        $more = buildURLparams($more, $sep);
6296de3759aSAndreas Gohr    } else {
63024870174SAndreas Gohr        $matches = [];
631cc036f74SKlap-in        if (preg_match_all('/\b(w|h)=(\d*)\b/', $more, $matches, PREG_SET_ORDER) || $isexternalimage) {
63224870174SAndreas Gohr            $resize = ['w' => 0, 'h' => 0];
6335e7db1e2SChristopher Smith            foreach ($matches as $match) {
6345e7db1e2SChristopher Smith                $resize[$match[1]] = $match[2];
6355e7db1e2SChristopher Smith            }
636cc036f74SKlap-in            $more .= $more === '' ? '' : $sep;
637cc036f74SKlap-in            $more .= 'tok=' . media_get_token($id, $resize['w'], $resize['h']);
6385e7db1e2SChristopher Smith        }
6398c08db0aSAndreas Gohr        $more = str_replace('cache=cache', '', $more); //skip default
6408c08db0aSAndreas Gohr        $more = str_replace(',,', ',', $more);
641b174aeaeSchris        $more = str_replace(',', $sep, $more);
6426de3759aSAndreas Gohr    }
6436de3759aSAndreas Gohr
64455b2b31bSAndreas Gohr    if ($abs) {
64555b2b31bSAndreas Gohr        $xlink = DOKU_URL;
64655b2b31bSAndreas Gohr    } else {
6476de3759aSAndreas Gohr        $xlink = DOKU_BASE;
64855b2b31bSAndreas Gohr    }
6496de3759aSAndreas Gohr
6506de3759aSAndreas Gohr    // external URLs are always direct without rewriting
651826d2766SKlap-in    if ($isexternalimage) {
6526de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
653cc036f74SKlap-in        $xlink .= '?' . $more;
654b174aeaeSchris        $xlink .= $sep . 'media=' . rawurlencode($id);
6556de3759aSAndreas Gohr        return $xlink;
6566de3759aSAndreas Gohr    }
6576de3759aSAndreas Gohr
6586de3759aSAndreas Gohr    $id = idfilter($id);
6596de3759aSAndreas Gohr
6606de3759aSAndreas Gohr    // decide on scriptname
6616de3759aSAndreas Gohr    if ($direct) {
6626de3759aSAndreas Gohr        if ($conf['userewrite'] == 1) {
6636de3759aSAndreas Gohr            $script = '_media';
6646de3759aSAndreas Gohr        } else {
6656de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
6666de3759aSAndreas Gohr        }
66724870174SAndreas Gohr    } elseif ($conf['userewrite'] == 1) {
6686de3759aSAndreas Gohr        $script = '_detail';
6696de3759aSAndreas Gohr    } else {
6706de3759aSAndreas Gohr        $script = 'lib/exe/detail.php';
6716de3759aSAndreas Gohr    }
6726de3759aSAndreas Gohr
6736de3759aSAndreas Gohr    // build URL based on rewrite mode
6746de3759aSAndreas Gohr    if ($conf['userewrite']) {
6756de3759aSAndreas Gohr        $xlink .= $script . '/' . $id;
6766de3759aSAndreas Gohr        if ($more) $xlink .= '?' . $more;
67724870174SAndreas Gohr    } elseif ($more) {
678a99d3236SEsther Brunner        $xlink .= $script . '?' . $more;
679b174aeaeSchris        $xlink .= $sep . 'media=' . $id;
6806de3759aSAndreas Gohr    } else {
681a99d3236SEsther Brunner        $xlink .= $script . '?media=' . $id;
6826de3759aSAndreas Gohr    }
6836de3759aSAndreas Gohr
6846de3759aSAndreas Gohr    return $xlink;
6856de3759aSAndreas Gohr}
6866de3759aSAndreas Gohr
6876de3759aSAndreas Gohr/**
68825ca5b17SAndreas Gohr * Returns the URL to the DokuWiki base script
68915fae107Sandi *
69025ca5b17SAndreas Gohr * Consider using wl() instead, unless you absoutely need the doku.php endpoint
69125ca5b17SAndreas Gohr *
6928b19906eSAndreas Gohr * @return string
69315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
694140cfbcdSGerrit Uitslag *
695f3f0262cSandi */
696d868eb89SAndreas Gohrfunction script()
697d868eb89SAndreas Gohr{
698ed7b5f09Sandi    return DOKU_BASE . DOKU_SCRIPT;
699f3f0262cSandi}
700f3f0262cSandi
701f3f0262cSandi/**
70215fae107Sandi * Spamcheck against wordlist
70315fae107Sandi *
704f3f0262cSandi * Checks the wikitext against a list of blocked expressions
705f3f0262cSandi * returns true if the text contains any bad words
70615fae107Sandi *
707e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
708e403cc58SMichael Klier *
709e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
710e403cc58SMichael Klier *  and gain information about the user who was blocked.
711e403cc58SMichael Klier *
712e403cc58SMichael Klier *  Event data:
713e403cc58SMichael Klier *    data['matches']  - array of matches
714e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
715e403cc58SMichael Klier *      [ip]           - ip address
716e403cc58SMichael Klier *      [user]         - username (if logged in)
717e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
718e403cc58SMichael Klier *      [name]         - real name (if logged in)
719e403cc58SMichael Klier *
7208b19906eSAndreas Gohr * @param string $text - optional text to check, if not given the globals are used
7218b19906eSAndreas Gohr * @return bool         - true if a spam word was found
72215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
7236dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
724140cfbcdSGerrit Uitslag *
725f3f0262cSandi */
726d868eb89SAndreas Gohrfunction checkwordblock($text = '')
727d868eb89SAndreas Gohr{
728f3f0262cSandi    global $TEXT;
7296dffa0e0SAndreas Gohr    global $PRE;
7306dffa0e0SAndreas Gohr    global $SUF;
731e0086ca2SAndreas Gohr    global $SUM;
732f3f0262cSandi    global $conf;
733e403cc58SMichael Klier    global $INFO;
734585bf44eSChristopher Smith    /* @var Input $INPUT */
735585bf44eSChristopher Smith    global $INPUT;
736f3f0262cSandi
737f3f0262cSandi    if (!$conf['usewordblock']) return false;
738f3f0262cSandi
739e0086ca2SAndreas Gohr    if (!$text) $text = "$PRE $TEXT $SUF $SUM";
7406dffa0e0SAndreas Gohr
741041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
74264159a61SAndreas Gohr    // phpcs:disable Generic.Files.LineLength.TooLong
74364159a61SAndreas Gohr    $text = preg_replace(
74464159a61SAndreas Gohr        '!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i',
74564159a61SAndreas Gohr        '\1http://\2 \2\3',
74664159a61SAndreas Gohr        $text
74764159a61SAndreas Gohr    );
74864159a61SAndreas Gohr    // phpcs:enable
749041d1964SAndreas Gohr
750b9ac8716Schris    $wordblocks = getWordblocks();
751a51d08efSAndreas Gohr    // read file in chunks of 200 - this should work around the
7523e2965d7Sandi    // MAX_PATTERN_SIZE in modern PCRE
753a51d08efSAndreas Gohr    $chunksize = 200;
75464259528SAndreas Gohr
755b9ac8716Schris    while ($blocks = array_splice($wordblocks, 0, $chunksize)) {
75624870174SAndreas Gohr        $re = [];
75749eb6e38SAndreas Gohr        // build regexp from blocks
758f3f0262cSandi        foreach ($blocks as $block) {
759f3f0262cSandi            $block = preg_replace('/#.*$/', '', $block);
760f3f0262cSandi            $block = trim($block);
761f3f0262cSandi            if (empty($block)) continue;
762f3f0262cSandi            $re[] = $block;
763f3f0262cSandi        }
76424870174SAndreas Gohr        if (count($re) && preg_match('#(' . implode('|', $re) . ')#si', $text, $matches)) {
765e403cc58SMichael Klier            // prepare event data
76624870174SAndreas Gohr            $data = [];
767e403cc58SMichael Klier            $data['matches'] = $matches;
768585bf44eSChristopher Smith            $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
769585bf44eSChristopher Smith            if ($INPUT->server->str('REMOTE_USER')) {
770585bf44eSChristopher Smith                $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
771e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
772e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
773e403cc58SMichael Klier            }
77424870174SAndreas Gohr            $callback = static fn() => true;
775cbb44eabSAndreas Gohr            return Event::createAndTrigger('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
776b9ac8716Schris        }
777703f6fdeSandi    }
778f3f0262cSandi    return false;
779f3f0262cSandi}
780f3f0262cSandi
781f3f0262cSandi/**
782a7580321SZebra North * Return the IP of the client.
78315fae107Sandi *
784a7580321SZebra North * The IP is sourced from, in order of preference:
78515fae107Sandi *
786a7580321SZebra North *   - The X-Real-IP header if $conf[realip] is true.
787d5dd5d1bSAndreas Gohr *   - The X-Forwarded-For header if all the proxies are trusted by $conf[trustedproxies].
788a7580321SZebra North *   - The TCP/IP connection remote address.
789a7580321SZebra North *   - 0.0.0.0 if all else fails.
7906d8affe6SAndreas Gohr *
791a7580321SZebra North * The 'realip' config value should only be set to true if the X-Real-IP header
792a7580321SZebra North * is being added by the web server, otherwise it may be spoofed by the client.
7938b19906eSAndreas Gohr *
794d5dd5d1bSAndreas Gohr * The 'trustedproxies' setting must not allow any IP, otherwise the X-Forwarded-For
795a7580321SZebra North * may be spoofed by the client.
796a7580321SZebra North *
797608cdefcSZebra North * @param bool $single If set only a single IP is returned.
798608cdefcSZebra North *
799a7580321SZebra North * @return string Returns an IP address if 'single' is true, or a comma-separated list
800a7580321SZebra North *                of IP addresses otherwise.
8012f828abfSAndreas Gohr * @author Zebra North <mrzebra@mrzebra.co.uk>
8022f828abfSAndreas Gohr *
803f3f0262cSandi */
8042f828abfSAndreas Gohrfunction clientIP($single = false)
8052f828abfSAndreas Gohr{
806a7580321SZebra North    // Return the first IP in single mode, or all the IPs.
807*98b599a6Ssplitbrain    return $single ? Ip::clientIp() : implode(',', Ip::clientIps());
808f3f0262cSandi}
809f3f0262cSandi
810f3f0262cSandi/**
8111c548ebeSAndreas Gohr * Check if the browser is on a mobile device
8121c548ebeSAndreas Gohr *
8131c548ebeSAndreas Gohr * Adapted from the example code at url below
8141c548ebeSAndreas Gohr *
8151c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
816140cfbcdSGerrit Uitslag *
81764159a61SAndreas Gohr * @deprecated 2018-04-27 you probably want media queries instead anyway
818140cfbcdSGerrit Uitslag * @return bool if true, client is mobile browser; otherwise false
8191c548ebeSAndreas Gohr */
820d868eb89SAndreas Gohrfunction clientismobile()
821d868eb89SAndreas Gohr{
822585bf44eSChristopher Smith    /* @var Input $INPUT */
823585bf44eSChristopher Smith    global $INPUT;
8241c548ebeSAndreas Gohr
825585bf44eSChristopher Smith    if ($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
8261c548ebeSAndreas Gohr
827585bf44eSChristopher Smith    if (preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
8281c548ebeSAndreas Gohr
829585bf44eSChristopher Smith    if (!$INPUT->server->has('HTTP_USER_AGENT')) return false;
8301c548ebeSAndreas Gohr
83124870174SAndreas Gohr    $uamatches = implode(
83264159a61SAndreas Gohr        '|',
83364159a61SAndreas Gohr        [
83464159a61SAndreas Gohr            'midp', 'j2me', 'avantg', 'docomo', 'novarra', 'palmos', 'palmsource', '240x320', 'opwv',
83564159a61SAndreas Gohr            'chtml', 'pda', 'windows ce', 'mmp\/', 'blackberry', 'mib\/', 'symbian', 'wireless', 'nokia',
83664159a61SAndreas Gohr            'hand', 'mobi', 'phone', 'cdm', 'up\.b', 'audio', 'SIE\-', 'SEC\-', 'samsung', 'HTC', 'mot\-',
83764159a61SAndreas Gohr            'mitsu', 'sagem', 'sony', 'alcatel', 'lg', 'erics', 'vx', 'NEC', 'philips', 'mmm', 'xx',
83864159a61SAndreas Gohr            'panasonic', 'sharp', 'wap', 'sch', 'rover', 'pocket', 'benq', 'java', 'pt', 'pg', 'vox',
83964159a61SAndreas Gohr            'amoi', 'bird', 'compal', 'kg', 'voda', 'sany', 'kdd', 'dbt', 'sendo', 'sgh', 'gradi', 'jb',
84064159a61SAndreas Gohr            '\d\d\di', 'moto'
84164159a61SAndreas Gohr        ]
84264159a61SAndreas Gohr    );
8431c548ebeSAndreas Gohr
844585bf44eSChristopher Smith    if (preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
8451c548ebeSAndreas Gohr
8461c548ebeSAndreas Gohr    return false;
8471c548ebeSAndreas Gohr}
8481c548ebeSAndreas Gohr
8491c548ebeSAndreas Gohr/**
8506efc45a2SDmitry Katsubo * check if a given link is interwiki link
8516efc45a2SDmitry Katsubo *
8526efc45a2SDmitry Katsubo * @param string $link the link, e.g. "wiki>page"
8536efc45a2SDmitry Katsubo * @return bool
8546efc45a2SDmitry Katsubo */
855d868eb89SAndreas Gohrfunction link_isinterwiki($link)
856d868eb89SAndreas Gohr{
8576efc45a2SDmitry Katsubo    if (preg_match('/^[a-zA-Z0-9\.]+>/u', $link)) return true;
8586efc45a2SDmitry Katsubo    return false;
8596efc45a2SDmitry Katsubo}
8606efc45a2SDmitry Katsubo
8616efc45a2SDmitry Katsubo/**
86263211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
86363211f61SGlen Harris *
86422ef1e32SAndreas Gohr * If $conf['dnslookups'] is disabled it simply returns the input string
86522ef1e32SAndreas Gohr *
8663272d797SAndreas Gohr * @param string $ips comma separated list of IP addresses
8673272d797SAndreas Gohr * @return string a comma separated list of hostnames
8688b19906eSAndreas Gohr * @author Glen Harris <astfgl@iamnota.org>
8698b19906eSAndreas Gohr *
87063211f61SGlen Harris */
871d868eb89SAndreas Gohrfunction gethostsbyaddrs($ips)
872d868eb89SAndreas Gohr{
87322ef1e32SAndreas Gohr    global $conf;
87422ef1e32SAndreas Gohr    if (!$conf['dnslookups']) return $ips;
87522ef1e32SAndreas Gohr
87624870174SAndreas Gohr    $hosts = [];
87763211f61SGlen Harris    $ips = explode(',', $ips);
878551a720fSMichael Klier
879551a720fSMichael Klier    if (is_array($ips)) {
8803886270dSAndreas Gohr        foreach ($ips as $ip) {
881551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
88263211f61SGlen Harris        }
88324870174SAndreas Gohr        return implode(',', $hosts);
884551a720fSMichael Klier    } else {
885551a720fSMichael Klier        return gethostbyaddr(trim($ips));
886551a720fSMichael Klier    }
88763211f61SGlen Harris}
88863211f61SGlen Harris
88963211f61SGlen Harris/**
89015fae107Sandi * Checks if a given page is currently locked.
89115fae107Sandi *
892f3f0262cSandi * removes stale lockfiles
89315fae107Sandi *
894140cfbcdSGerrit Uitslag * @param string $id page id
895140cfbcdSGerrit Uitslag * @return bool page is locked?
8968b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
8978b19906eSAndreas Gohr *
898f3f0262cSandi */
899d868eb89SAndreas Gohrfunction checklock($id)
900d868eb89SAndreas Gohr{
901f3f0262cSandi    global $conf;
902585bf44eSChristopher Smith    /* @var Input $INPUT */
903585bf44eSChristopher Smith    global $INPUT;
904585bf44eSChristopher Smith
905c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
906f3f0262cSandi
907f3f0262cSandi    //no lockfile
90879e79377SAndreas Gohr    if (!file_exists($lock)) return false;
909f3f0262cSandi
910f3f0262cSandi    //lockfile expired
911f3f0262cSandi    if ((time() - filemtime($lock)) > $conf['locktime']) {
912d8186216SBen Coburn        @unlink($lock);
913f3f0262cSandi        return false;
914f3f0262cSandi    }
915f3f0262cSandi
916f3f0262cSandi    //my own lock
9175f21556dSDamien Regad    [$ip, $session] = sexplode("\n", io_readFile($lock), 2);
91824870174SAndreas Gohr    if ($ip == $INPUT->server->str('REMOTE_USER') || (session_id() && $session === session_id())) {
919f3f0262cSandi        return false;
920f3f0262cSandi    }
921f3f0262cSandi
922f3f0262cSandi    return $ip;
923f3f0262cSandi}
924f3f0262cSandi
925f3f0262cSandi/**
92615fae107Sandi * Lock a page for editing
92715fae107Sandi *
9288b19906eSAndreas Gohr * @param string $id page id to lock
92915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
930140cfbcdSGerrit Uitslag *
931f3f0262cSandi */
932d868eb89SAndreas Gohrfunction lock($id)
933d868eb89SAndreas Gohr{
934544ed901SDaniel Calviño Sánchez    global $conf;
935585bf44eSChristopher Smith    /* @var Input $INPUT */
936585bf44eSChristopher Smith    global $INPUT;
937544ed901SDaniel Calviño Sánchez
938544ed901SDaniel Calviño Sánchez    if ($conf['locktime'] == 0) {
939544ed901SDaniel Calviño Sánchez        return;
940544ed901SDaniel Calviño Sánchez    }
941544ed901SDaniel Calviño Sánchez
942c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
943585bf44eSChristopher Smith    if ($INPUT->server->str('REMOTE_USER')) {
944585bf44eSChristopher Smith        io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
945f3f0262cSandi    } else {
94685fef7e2SAndreas Gohr        io_saveFile($lock, clientIP() . "\n" . session_id());
947f3f0262cSandi    }
948f3f0262cSandi}
949f3f0262cSandi
950f3f0262cSandi/**
95115fae107Sandi * Unlock a page if it was locked by the user
952f3f0262cSandi *
9533272d797SAndreas Gohr * @param string $id page id to unlock
95415fae107Sandi * @return bool true if a lock was removed
9558b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
9568b19906eSAndreas Gohr *
957f3f0262cSandi */
958d868eb89SAndreas Gohrfunction unlock($id)
959d868eb89SAndreas Gohr{
960585bf44eSChristopher Smith    /* @var Input $INPUT */
961585bf44eSChristopher Smith    global $INPUT;
962585bf44eSChristopher Smith
963c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
96479e79377SAndreas Gohr    if (file_exists($lock)) {
96524870174SAndreas Gohr        @[$ip, $session] = explode("\n", io_readFile($lock));
966c0dd3914SAdaKaleh        if ($ip == $INPUT->server->str('REMOTE_USER') || $session == session_id()) {
967f3f0262cSandi            @unlink($lock);
968f3f0262cSandi            return true;
969f3f0262cSandi        }
970f3f0262cSandi    }
971f3f0262cSandi    return false;
972f3f0262cSandi}
973f3f0262cSandi
974f3f0262cSandi/**
975f3f0262cSandi * convert line ending to unix format
976f3f0262cSandi *
9776db7468bSAndreas Gohr * also makes sure the given text is valid UTF-8
9786db7468bSAndreas Gohr *
9798b19906eSAndreas Gohr * @param string $text
9808b19906eSAndreas Gohr * @return string
98115fae107Sandi * @see    formText() for 2crlf conversion
98215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
983140cfbcdSGerrit Uitslag *
984f3f0262cSandi */
985d868eb89SAndreas Gohrfunction cleanText($text)
986d868eb89SAndreas Gohr{
987f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
9886db7468bSAndreas Gohr
9896db7468bSAndreas Gohr    // if the text is not valid UTF-8 we simply assume latin1
9906db7468bSAndreas Gohr    // this won't break any worse than it breaks with the wrong encoding
9916db7468bSAndreas Gohr    // but might actually fix the problem in many cases
99253c68e5cSAndreas Gohr    if (!Clean::isUtf8($text)) $text = Conversion::fromLatin1($text);
9936db7468bSAndreas Gohr
994f3f0262cSandi    return $text;
995f3f0262cSandi}
996f3f0262cSandi
997f3f0262cSandi/**
998f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
999f3f0262cSandi * It also converts line endings to Windows format which is
1000f3f0262cSandi * pseudo standard for webforms.
1001f3f0262cSandi *
10028b19906eSAndreas Gohr * @param string $text
10038b19906eSAndreas Gohr * @return string
100415fae107Sandi * @see    cleanText() for 2unix conversion
100515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1006140cfbcdSGerrit Uitslag *
1007f3f0262cSandi */
1008d868eb89SAndreas Gohrfunction formText($text)
1009d868eb89SAndreas Gohr{
1010a46a37efSAndreas Gohr    $text = str_replace("\012", "\015\012", $text ?? '');
1011f3f0262cSandi    return htmlspecialchars($text);
1012f3f0262cSandi}
1013f3f0262cSandi
1014f3f0262cSandi/**
101515fae107Sandi * Returns the specified local text in raw format
101615fae107Sandi *
1017140cfbcdSGerrit Uitslag * @param string $id page id
1018140cfbcdSGerrit Uitslag * @param string $ext extension of file being read, default 'txt'
1019140cfbcdSGerrit Uitslag * @return string
10208b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10218b19906eSAndreas Gohr *
1022f3f0262cSandi */
1023d868eb89SAndreas Gohrfunction rawLocale($id, $ext = 'txt')
1024d868eb89SAndreas Gohr{
10252adaf2b8SAndreas Gohr    return io_readFile(localeFN($id, $ext));
1026f3f0262cSandi}
1027f3f0262cSandi
1028f3f0262cSandi/**
1029f3f0262cSandi * Returns the raw WikiText
103015fae107Sandi *
1031140cfbcdSGerrit Uitslag * @param string $id page id
1032e0c26282SGerrit Uitslag * @param string|int $rev timestamp when a revision of wikitext is desired
1033140cfbcdSGerrit Uitslag * @return string
10348b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10358b19906eSAndreas Gohr *
1036f3f0262cSandi */
1037d868eb89SAndreas Gohrfunction rawWiki($id, $rev = '')
1038d868eb89SAndreas Gohr{
1039cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1040f3f0262cSandi}
1041f3f0262cSandi
1042f3f0262cSandi/**
10437146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
10447146cee2SAndreas Gohr *
10457b84afa2SAndreas Gohr * @triggers COMMON_PAGETPL_LOAD
1046140cfbcdSGerrit Uitslag * @param string $id the id of the page to be created
1047140cfbcdSGerrit Uitslag * @return string parsed pagetemplate content
10488b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10498b19906eSAndreas Gohr *
10507146cee2SAndreas Gohr */
1051d868eb89SAndreas Gohrfunction pageTemplate($id)
1052d868eb89SAndreas Gohr{
1053a15ce62dSEsther Brunner    global $conf;
1054e29549feSAndreas Gohr
1055fe17917eSAdrian Lang    if (is_array($id)) $id = $id[0];
1056e29549feSAndreas Gohr
10577b84afa2SAndreas Gohr    // prepare initial event data
105824870174SAndreas Gohr    $data = [
10597b84afa2SAndreas Gohr        'id' => $id, // the id of the page to be created
10607b84afa2SAndreas Gohr        'tpl' => '', // the text used as template
10617b84afa2SAndreas Gohr        'tplfile' => '', // the file above text was/should be loaded from
106224870174SAndreas Gohr        'doreplace' => true,
106324870174SAndreas Gohr    ];
10647b84afa2SAndreas Gohr
1065e1d9dcc8SAndreas Gohr    $evt = new Event('COMMON_PAGETPL_LOAD', $data);
10667b84afa2SAndreas Gohr    if ($evt->advise_before(true)) {
10677b84afa2SAndreas Gohr        // the before event might have loaded the content already
10687b84afa2SAndreas Gohr        if (empty($data['tpl'])) {
10697b84afa2SAndreas Gohr            // if the before event did not set a template file, try to find one
10707b84afa2SAndreas Gohr            if (empty($data['tplfile'])) {
1071fe17917eSAdrian Lang                $path = dirname(wikiFN($id));
107279e79377SAndreas Gohr                if (file_exists($path . '/_template.txt')) {
10737b84afa2SAndreas Gohr                    $data['tplfile'] = $path . '/_template.txt';
1074e29549feSAndreas Gohr                } else {
1075e29549feSAndreas Gohr                    // search upper namespaces for templates
1076e29549feSAndreas Gohr                    $len = strlen(rtrim($conf['datadir'], '/'));
1077e29549feSAndreas Gohr                    while (strlen($path) >= $len) {
107879e79377SAndreas Gohr                        if (file_exists($path . '/__template.txt')) {
10797b84afa2SAndreas Gohr                            $data['tplfile'] = $path . '/__template.txt';
1080e29549feSAndreas Gohr                            break;
1081e29549feSAndreas Gohr                        }
1082e29549feSAndreas Gohr                        $path = substr($path, 0, strrpos($path, '/'));
1083e29549feSAndreas Gohr                    }
1084e29549feSAndreas Gohr                }
10857b84afa2SAndreas Gohr            }
10867b84afa2SAndreas Gohr            // load the content
10873d7ac595SMichael Hamann            $data['tpl'] = io_readFile($data['tplfile']);
10887b84afa2SAndreas Gohr        }
1089a1bbd05bSMichael Hamann        if ($data['doreplace']) parsePageTemplate($data);
10907b84afa2SAndreas Gohr    }
10917b84afa2SAndreas Gohr    $evt->advise_after();
10927b84afa2SAndreas Gohr    unset($evt);
10937b84afa2SAndreas Gohr
1094fe17917eSAdrian Lang    return $data['tpl'];
10952b1223ecSAdrian Lang}
10962b1223ecSAdrian Lang
10972b1223ecSAdrian Lang/**
10982b1223ecSAdrian Lang * Performs common page template replacements
10997b84afa2SAndreas Gohr * This works on data from COMMON_PAGETPL_LOAD
11002b1223ecSAdrian Lang *
1101140cfbcdSGerrit Uitslag * @param array $data array with event data
1102140cfbcdSGerrit Uitslag * @return string
11038b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
11048b19906eSAndreas Gohr *
11052b1223ecSAdrian Lang */
1106d868eb89SAndreas Gohrfunction parsePageTemplate(&$data)
1107d868eb89SAndreas Gohr{
11083272d797SAndreas Gohr    /**
11093272d797SAndreas Gohr     * @var string $id the id of the page to be created
11103272d797SAndreas Gohr     * @var string $tpl the text used as template
11113272d797SAndreas Gohr     * @var string $tplfile the file above text was/should be loaded from
11123272d797SAndreas Gohr     * @var bool $doreplace should wildcard replacements be done on the text?
11133272d797SAndreas Gohr     */
1114fe17917eSAdrian Lang    extract($data);
1115fe17917eSAdrian Lang
1116b856f7dfSAdrian Lang    global $USERINFO;
1117bce53b1fSAdrian Lang    global $conf;
1118585bf44eSChristopher Smith    /* @var Input $INPUT */
1119585bf44eSChristopher Smith    global $INPUT;
1120e29549feSAndreas Gohr
1121e29549feSAndreas Gohr    // replace placeholders
112226ece5a7SAndreas Gohr    $file = noNS($id);
112337c1acbdSAdrian Lang    $page = strtr($file, $conf['sepchar'], ' ');
112426ece5a7SAndreas Gohr
11253272d797SAndreas Gohr    $tpl = str_replace(
112624870174SAndreas Gohr        [
112726ece5a7SAndreas Gohr            '@ID@',
112826ece5a7SAndreas Gohr            '@NS@',
11298a7bcf66SShota Miyazaki            '@CURNS@',
1130a3db0ab0SSimon Lees            '@!CURNS@',
1131a3db0ab0SSimon Lees            '@!!CURNS@',
1132a3db0ab0SSimon Lees            '@!CURNS!@',
113326ece5a7SAndreas Gohr            '@FILE@',
113426ece5a7SAndreas Gohr            '@!FILE@',
113526ece5a7SAndreas Gohr            '@!FILE!@',
113626ece5a7SAndreas Gohr            '@PAGE@',
113726ece5a7SAndreas Gohr            '@!PAGE@',
113826ece5a7SAndreas Gohr            '@!!PAGE@',
113926ece5a7SAndreas Gohr            '@!PAGE!@',
114026ece5a7SAndreas Gohr            '@USER@',
114126ece5a7SAndreas Gohr            '@NAME@',
114226ece5a7SAndreas Gohr            '@MAIL@',
114324870174SAndreas Gohr            '@DATE@'
114424870174SAndreas Gohr        ],
114524870174SAndreas Gohr        [
114626ece5a7SAndreas Gohr            $id,
114726ece5a7SAndreas Gohr            getNS($id),
11488a7bcf66SShota Miyazaki            curNS($id),
114924870174SAndreas Gohr            PhpString::ucfirst(curNS($id)),
115024870174SAndreas Gohr            PhpString::ucwords(curNS($id)),
115124870174SAndreas Gohr            PhpString::strtoupper(curNS($id)),
115226ece5a7SAndreas Gohr            $file,
115324870174SAndreas Gohr            PhpString::ucfirst($file),
115424870174SAndreas Gohr            PhpString::strtoupper($file),
115526ece5a7SAndreas Gohr            $page,
115624870174SAndreas Gohr            PhpString::ucfirst($page),
115724870174SAndreas Gohr            PhpString::ucwords($page),
115824870174SAndreas Gohr            PhpString::strtoupper($page),
1159585bf44eSChristopher Smith            $INPUT->server->str('REMOTE_USER'),
11603e9ae63dSPhy            $USERINFO ? $USERINFO['name'] : '',
11613e9ae63dSPhy            $USERINFO ? $USERINFO['mail'] : '',
116224870174SAndreas Gohr            $conf['dformat']
116324870174SAndreas Gohr        ],
116424870174SAndreas Gohr        $tpl
11653272d797SAndreas Gohr    );
116626ece5a7SAndreas Gohr
11677d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
1168bad6fc0dSAndreas Gohr    $tpl = preg_replace_callback(
1169bad6fc0dSAndreas Gohr        '/%./',
117024870174SAndreas Gohr        static fn($m) => dformat(null, $m[0]),
1171bad6fc0dSAndreas Gohr        $tpl
1172bad6fc0dSAndreas Gohr    );
1173d535a2e9Sstretchyboy    $data['tpl'] = $tpl;
1174a15ce62dSEsther Brunner    return $tpl;
11757146cee2SAndreas Gohr}
11767146cee2SAndreas Gohr
11777146cee2SAndreas Gohr/**
117815fae107Sandi * Returns the raw Wiki Text in three slices.
117915fae107Sandi *
118015fae107Sandi * The range parameter needs to have the form "from-to"
118115cfe303Sandi * and gives the range of the section in bytes - no
118215cfe303Sandi * UTF-8 awareness is needed.
1183f3f0262cSandi * The returned order is prefix, section and suffix.
118415fae107Sandi *
1185140cfbcdSGerrit Uitslag * @param string $range in form "from-to"
1186140cfbcdSGerrit Uitslag * @param string $id page id
1187140cfbcdSGerrit Uitslag * @param string $rev optional, the revision timestamp
118842ea7f44SGerrit Uitslag * @return string[] with three slices
11898b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
11908b19906eSAndreas Gohr *
1191f3f0262cSandi */
1192d868eb89SAndreas Gohrfunction rawWikiSlices($range, $id, $rev = '')
1193d868eb89SAndreas Gohr{
1194cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1195f3f0262cSandi
119680fcb268SAdrian Lang    // Parse range
119724870174SAndreas Gohr    [$from, $to] = sexplode('-', $range, 2);
119880fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
119924870174SAndreas Gohr    $from = $from ? $from - 1 : (0);
120024870174SAndreas Gohr    $to = $to ? $to - 1 : (strlen($text));
120180fcb268SAdrian Lang
120224870174SAndreas Gohr    $slices = [];
120380fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
120480fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to - $from);
120515cfe303Sandi    $slices[2] = substr($text, $to);
1206f3f0262cSandi    return $slices;
1207f3f0262cSandi}
1208f3f0262cSandi
1209f3f0262cSandi/**
121015fae107Sandi * Joins wiki text slices
121115fae107Sandi *
121280fcb268SAdrian Lang * function to join the text slices.
1213f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
1214f3f0262cSandi * lines between sections if needed (used on saving).
121515fae107Sandi *
1216140cfbcdSGerrit Uitslag * @param string $pre prefix
1217140cfbcdSGerrit Uitslag * @param string $text text in the middle
1218140cfbcdSGerrit Uitslag * @param string $suf suffix
1219140cfbcdSGerrit Uitslag * @param bool $pretty add additional empty lines between sections
1220140cfbcdSGerrit Uitslag * @return string
12218b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
12228b19906eSAndreas Gohr *
1223f3f0262cSandi */
1224d868eb89SAndreas Gohrfunction con($pre, $text, $suf, $pretty = false)
1225d868eb89SAndreas Gohr{
1226f3f0262cSandi    if ($pretty) {
12277d34963bSAndreas Gohr        if (
12286c16a3a9Sfiwswe            $pre !== '' && !str_ends_with($pre, "\n") &&
12296c16a3a9Sfiwswe            !str_starts_with($text, "\n")
12303272d797SAndreas Gohr        ) {
123180fcb268SAdrian Lang            $pre .= "\n";
123280fcb268SAdrian Lang        }
12337d34963bSAndreas Gohr        if (
12346c16a3a9Sfiwswe            $suf !== '' && !str_ends_with($text, "\n") &&
12356c16a3a9Sfiwswe            !str_starts_with($suf, "\n")
12363272d797SAndreas Gohr        ) {
123780fcb268SAdrian Lang            $text .= "\n";
123880fcb268SAdrian Lang        }
1239f3f0262cSandi    }
1240f3f0262cSandi
1241f3f0262cSandi    return $pre . $text . $suf;
1242f3f0262cSandi}
1243f3f0262cSandi
1244f3f0262cSandi/**
1245b24d9195SAndreas Gohr * Checks if the current page version is newer than the last entry in the page's
1246b24d9195SAndreas Gohr * changelog. If so, we assume it has been an external edit and we create an
1247b24d9195SAndreas Gohr * attic copy and add a proper changelog line.
1248b24d9195SAndreas Gohr *
1249b24d9195SAndreas Gohr * This check is only executed when the page is about to be saved again from the
12508b19906eSAndreas Gohr * wiki, triggered in @param string $id the page ID
12518b19906eSAndreas Gohr * @see saveWikiText()
1252b24d9195SAndreas Gohr *
125369f9b481SSatoshi Sahara * @deprecated 2021-11-28
1254b24d9195SAndreas Gohr */
1255d868eb89SAndreas Gohrfunction detectExternalEdit($id)
1256d868eb89SAndreas Gohr{
125779a2d784SGerrit Uitslag    dbg_deprecated(PageFile::class . '::detectExternalEdit()');
1258b24e9c4aSSatoshi Sahara    (new PageFile($id))->detectExternalEdit();
1259b24d9195SAndreas Gohr}
1260b24d9195SAndreas Gohr
1261b24d9195SAndreas Gohr/**
1262a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
1263a701424fSBen Coburn * Also directs changelog and attic updates.
126415fae107Sandi *
1265140cfbcdSGerrit Uitslag * @param string $id page id
1266140cfbcdSGerrit Uitslag * @param string $text wikitext being saved
1267140cfbcdSGerrit Uitslag * @param string $summary summary of text update
1268140cfbcdSGerrit Uitslag * @param bool $minor mark this saved version as minor update
12698b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
12708b19906eSAndreas Gohr * @author Ben Coburn <btcoburn@silicodon.net>
12718b19906eSAndreas Gohr *
1272f3f0262cSandi */
1273d868eb89SAndreas Gohrfunction saveWikiText($id, $text, $summary, $minor = false)
1274d868eb89SAndreas Gohr{
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
128124870174SAndreas 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 *
1298140cfbcdSGerrit Uitslag * @param string $id page id
1299140cfbcdSGerrit Uitslag * @return int|string revision timestamp
13008b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
13018b19906eSAndreas Gohr *
130269f9b481SSatoshi Sahara * @deprecated 2021-11-28
1303f3f0262cSandi */
1304d868eb89SAndreas Gohrfunction saveOldRevision($id)
1305d868eb89SAndreas Gohr{
130679a2d784SGerrit Uitslag    dbg_deprecated(PageFile::class . '::saveOldRevision()');
1307b24e9c4aSSatoshi Sahara    return (new PageFile($id))->saveOldRevision();
1308f3f0262cSandi}
1309f3f0262cSandi
1310f3f0262cSandi/**
1311fde10de4SAdrian Lang * Sends a notify mail on page change or registration
131226a0801fSAndreas Gohr *
131326a0801fSAndreas Gohr * @param string $id The changed page
1314fde10de4SAdrian Lang * @param string $who Who to notify (admin|subscribers|register)
13153272d797SAndreas Gohr * @param int|string $rev Old page revision
131626a0801fSAndreas Gohr * @param string $summary What changed
131790033e9dSAndreas Gohr * @param boolean $minor Is this a minor edit?
131842ea7f44SGerrit Uitslag * @param string[] $replace Additional string substitutions, @KEY@ to be replaced by value
131983734cddSPhy * @param int|string $current_rev New page revision
13203272d797SAndreas Gohr * @return bool
1321140cfbcdSGerrit Uitslag *
132215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1323f3f0262cSandi */
1324d868eb89SAndreas Gohrfunction notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = [], $current_rev = false)
1325d868eb89SAndreas Gohr{
1326f3f0262cSandi    global $conf;
1327585bf44eSChristopher Smith    /* @var Input $INPUT */
1328585bf44eSChristopher Smith    global $INPUT;
1329b158d625SSteven Danz
13306df843eeSAndreas Gohr    // decide if there is something to do, eg. whom to mail
133126a0801fSAndreas Gohr    if ($who == 'admin') {
13323272d797SAndreas Gohr        if (empty($conf['notify'])) return false; //notify enabled?
13332ed38036SAndreas Gohr        $tpl = 'mailtext';
133426a0801fSAndreas Gohr        $to = $conf['notify'];
133526a0801fSAndreas Gohr    } elseif ($who == 'subscribers') {
133684c1127cSAndreas Gohr        if (!actionOK('subscribe')) return false; //subscribers enabled?
1337585bf44eSChristopher Smith        if ($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
133824870174SAndreas Gohr        $data = ['id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace];
1339cbb44eabSAndreas Gohr        Event::createAndTrigger(
1340dccd6b2bSAndreas Gohr            'COMMON_NOTIFY_ADDRESSLIST',
1341dccd6b2bSAndreas Gohr            $data,
134224870174SAndreas Gohr            [new SubscriberManager(), 'notifyAddresses']
13433272d797SAndreas Gohr        );
13442ed38036SAndreas Gohr        $to = $data['addresslist'];
13452ed38036SAndreas Gohr        if (empty($to)) return false;
13462ed38036SAndreas Gohr        $tpl = 'subscr_single';
134726a0801fSAndreas Gohr    } else {
13483272d797SAndreas Gohr        return false; //just to be safe
134926a0801fSAndreas Gohr    }
135026a0801fSAndreas Gohr
13516df843eeSAndreas Gohr    // prepare content
1352704a815fSMichael Große    $subscription = new PageSubscriptionSender();
135383734cddSPhy    return $subscription->sendPageDiff($to, $tpl, $id, $rev, $summary, $current_rev);
1354f3f0262cSandi}
13552ed38036SAndreas Gohr
135615fae107Sandi/**
135771f7bde7SAndreas Gohr * extracts the query from a search engine referrer
135815fae107Sandi *
13598b19906eSAndreas Gohr * @return array|string
136071f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1361140cfbcdSGerrit Uitslag *
13628b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1363f3f0262cSandi */
1364d868eb89SAndreas Gohrfunction getGoogleQuery()
1365d868eb89SAndreas Gohr{
1366585bf44eSChristopher Smith    /* @var Input $INPUT */
1367585bf44eSChristopher Smith    global $INPUT;
1368585bf44eSChristopher Smith
1369585bf44eSChristopher Smith    if (!$INPUT->server->has('HTTP_REFERER')) {
1370c66972f2SAdrian Lang        return '';
1371c66972f2SAdrian Lang    }
1372585bf44eSChristopher Smith    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1373f3f0262cSandi
1374079b3ac1SAndreas Gohr    // only handle common SEs
1375c7875401SJyoti S    if (!array_key_exists('host', $url)) return '';
1376079b3ac1SAndreas Gohr    if (!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/', $url['host'])) return '';
1377e4d8a516SKazutaka Miyasaka
137824870174SAndreas Gohr    $query = [];
1379181adffeSJulian Jeggle    if (!array_key_exists('query', $url)) return '';
1380f3f0262cSandi    parse_str($url['query'], $query);
1381e4d8a516SKazutaka Miyasaka
1382c66972f2SAdrian Lang    $q = '';
1383079b3ac1SAndreas Gohr    if (isset($query['q'])) {
1384079b3ac1SAndreas Gohr        $q = $query['q'];
1385079b3ac1SAndreas Gohr    } elseif (isset($query['p'])) {
1386079b3ac1SAndreas Gohr        $q = $query['p'];
1387079b3ac1SAndreas Gohr    } elseif (isset($query['query'])) {
1388079b3ac1SAndreas Gohr        $q = $query['query'];
1389079b3ac1SAndreas Gohr    }
1390079b3ac1SAndreas Gohr    $q = trim($q);
1391f3f0262cSandi
1392079b3ac1SAndreas Gohr    if (!$q) return '';
1393c7dc833bSPhy    // ignore if query includes a full URL
1394c7dc833bSPhy    if (strpos($q, '//') !== false) return '';
13956531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1396f93b3b50SAndreas Gohr    return $q;
1397f3f0262cSandi}
1398f3f0262cSandi
1399f3f0262cSandi/**
1400f3f0262cSandi * Return the human readable size of a file
1401f3f0262cSandi *
1402f3f0262cSandi * @param int $size A file size
1403f3f0262cSandi * @param int $dec A number of decimal places
140474160ca1SGerrit Uitslag * @return string human readable size
1405140cfbcdSGerrit Uitslag *
1406f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1407f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1408f3f0262cSandi * @version     1.0.0
1409f3f0262cSandi */
1410d868eb89SAndreas Gohrfunction filesize_h($size, $dec = 1)
1411d868eb89SAndreas Gohr{
141224870174SAndreas Gohr    $sizes = ['B', 'KB', 'MB', 'GB'];
1413f3f0262cSandi    $count = count($sizes);
1414f3f0262cSandi    $i = 0;
1415f3f0262cSandi
1416f3f0262cSandi    while ($size >= 1024 && ($i < $count - 1)) {
1417f3f0262cSandi        $size /= 1024;
1418f3f0262cSandi        $i++;
1419f3f0262cSandi    }
1420f3f0262cSandi
1421ef08383eSAndreas Gohr    return round($size, $dec) . "\xC2\xA0" . $sizes[$i]; //non-breaking space
1422f3f0262cSandi}
1423f3f0262cSandi
142415fae107Sandi/**
1425c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1426c57e365eSAndreas Gohr *
1427140cfbcdSGerrit Uitslag * @param int $dt timestamp
1428140cfbcdSGerrit Uitslag * @return string
14298b19906eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
14308b19906eSAndreas Gohr *
1431c57e365eSAndreas Gohr */
1432d868eb89SAndreas Gohrfunction datetime_h($dt)
1433d868eb89SAndreas Gohr{
1434c57e365eSAndreas Gohr    global $lang;
1435c57e365eSAndreas Gohr
1436c57e365eSAndreas Gohr    $ago = time() - $dt;
1437c57e365eSAndreas Gohr    if ($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1438c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1439c57e365eSAndreas Gohr    }
1440c57e365eSAndreas Gohr    if ($ago > 24 * 60 * 60 * 30 * 2) {
1441c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1442c57e365eSAndreas Gohr    }
1443c57e365eSAndreas Gohr    if ($ago > 24 * 60 * 60 * 7 * 2) {
1444c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1445c57e365eSAndreas Gohr    }
1446c57e365eSAndreas Gohr    if ($ago > 24 * 60 * 60 * 2) {
1447c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1448c57e365eSAndreas Gohr    }
1449c57e365eSAndreas Gohr    if ($ago > 60 * 60 * 2) {
1450c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago / (60 * 60)));
1451c57e365eSAndreas Gohr    }
1452c57e365eSAndreas Gohr    if ($ago > 60 * 2) {
1453c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago / (60)));
1454c57e365eSAndreas Gohr    }
1455c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1456c57e365eSAndreas Gohr}
1457c57e365eSAndreas Gohr
1458c57e365eSAndreas Gohr/**
1459f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1460f2263577SAndreas Gohr *
1461f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1462f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1463f2263577SAndreas Gohr *
1464140cfbcdSGerrit Uitslag * @param int|null $dt timestamp when given, null will take current timestamp
1465140cfbcdSGerrit Uitslag * @param string $format empty default to $conf['dformat'], or provide format as recognized by strftime()
1466140cfbcdSGerrit Uitslag * @return string
14678b19906eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
14688b19906eSAndreas Gohr *
14698b19906eSAndreas Gohr * @see datetime_h
1470f2263577SAndreas Gohr */
1471d868eb89SAndreas Gohrfunction dformat($dt = null, $format = '')
1472d868eb89SAndreas Gohr{
1473f2263577SAndreas Gohr    global $conf;
1474f2263577SAndreas Gohr
1475f2263577SAndreas Gohr    if (is_null($dt)) $dt = time();
1476f2263577SAndreas Gohr    $dt = (int)$dt;
1477f2263577SAndreas Gohr    if (!$format) $format = $conf['dformat'];
1478f2263577SAndreas Gohr
1479f2263577SAndreas Gohr    $format = str_replace('%f', datetime_h($dt), $format);
1480b3894732Ssplitbrain    return strftime($format, $dt);
1481f2263577SAndreas Gohr}
1482f2263577SAndreas Gohr
1483f2263577SAndreas Gohr/**
1484c4f79b71SMichael Hamann * Formats a timestamp as ISO 8601 date
1485c4f79b71SMichael Hamann *
14868b19906eSAndreas Gohr * @param int $int_date current date in UNIX timestamp
14878b19906eSAndreas Gohr * @return string
1488c4f79b71SMichael Hamann * @author <ungu at terong dot com>
148959752844SAnders Sandblad * @link http://php.net/manual/en/function.date.php#54072
1490140cfbcdSGerrit Uitslag *
1491c4f79b71SMichael Hamann */
1492d868eb89SAndreas Gohrfunction date_iso8601($int_date)
1493d868eb89SAndreas Gohr{
1494c4f79b71SMichael Hamann    $date_mod = date('Y-m-d\TH:i:s', $int_date);
1495c4f79b71SMichael Hamann    $pre_timezone = date('O', $int_date);
1496c4f79b71SMichael Hamann    $time_zone = substr($pre_timezone, 0, 3) . ":" . substr($pre_timezone, 3, 2);
1497c4f79b71SMichael Hamann    $date_mod .= $time_zone;
1498c4f79b71SMichael Hamann    return $date_mod;
1499c4f79b71SMichael Hamann}
1500c4f79b71SMichael Hamann
1501c4f79b71SMichael Hamann/**
150200a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
150300a7b5adSEsther Brunner *
15048b19906eSAndreas Gohr * @param string $email email address
15058b19906eSAndreas Gohr * @return string
150600a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
150700a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
1508140cfbcdSGerrit Uitslag *
150900a7b5adSEsther Brunner */
1510d868eb89SAndreas Gohrfunction obfuscate($email)
1511d868eb89SAndreas Gohr{
151200a7b5adSEsther Brunner    global $conf;
151300a7b5adSEsther Brunner
151400a7b5adSEsther Brunner    switch ($conf['mailguard']) {
151500a7b5adSEsther Brunner        case 'visible':
151624870174SAndreas Gohr            $obfuscate = ['@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] '];
151700a7b5adSEsther Brunner            return strtr($email, $obfuscate);
151800a7b5adSEsther Brunner
151900a7b5adSEsther Brunner        case 'hex':
152024870174SAndreas Gohr            return Conversion::toHtml($email, true);
152100a7b5adSEsther Brunner
152200a7b5adSEsther Brunner        case 'none':
152300a7b5adSEsther Brunner        default:
152400a7b5adSEsther Brunner            return $email;
152500a7b5adSEsther Brunner    }
152600a7b5adSEsther Brunner}
152700a7b5adSEsther Brunner
152800a7b5adSEsther Brunner/**
152989541d4bSAndreas Gohr * Removes quoting backslashes
153089541d4bSAndreas Gohr *
1531140cfbcdSGerrit Uitslag * @param string $string
1532140cfbcdSGerrit Uitslag * @param string $char backslashed character
1533140cfbcdSGerrit Uitslag * @return string
15348b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
15358b19906eSAndreas Gohr *
153689541d4bSAndreas Gohr */
1537d868eb89SAndreas Gohrfunction unslash($string, $char = "'")
1538d868eb89SAndreas Gohr{
153989541d4bSAndreas Gohr    return str_replace('\\' . $char, $char, $string);
154089541d4bSAndreas Gohr}
154189541d4bSAndreas Gohr
154273038c47SAndreas Gohr/**
154373038c47SAndreas Gohr * Convert php.ini shorthands to byte
154473038c47SAndreas Gohr *
1545a81f3d99SAndreas Gohr * On 32 bit systems values >= 2GB will fail!
1546140cfbcdSGerrit Uitslag *
1547a81f3d99SAndreas Gohr * -1 (infinite size) will be reported as -1
1548a81f3d99SAndreas Gohr *
1549a81f3d99SAndreas Gohr * @link   https://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
1550a81f3d99SAndreas Gohr * @param string $value PHP size shorthand
1551a81f3d99SAndreas Gohr * @return int
155273038c47SAndreas Gohr */
1553d868eb89SAndreas Gohrfunction php_to_byte($value)
1554d868eb89SAndreas Gohr{
1555f5c0c80bSAndreas Gohr    switch (strtoupper(substr($value, -1))) {
155673038c47SAndreas Gohr        case 'G':
155724870174SAndreas Gohr            $ret = (int)substr($value, 0, -1) * 1024 * 1024 * 1024;
155873038c47SAndreas Gohr            break;
155973038c47SAndreas Gohr        case 'M':
156024870174SAndreas Gohr            $ret = (int)substr($value, 0, -1) * 1024 * 1024;
1561a81f3d99SAndreas Gohr            break;
156273038c47SAndreas Gohr        case 'K':
156324870174SAndreas Gohr            $ret = (int)substr($value, 0, -1) * 1024;
156473038c47SAndreas Gohr            break;
15659eeeb775SAndreas Gohr        default:
156624870174SAndreas Gohr            $ret = (int)$value;
156749cbd23eSOtto Vainio            break;
156873038c47SAndreas Gohr    }
156973038c47SAndreas Gohr    return $ret;
157073038c47SAndreas Gohr}
157173038c47SAndreas Gohr
1572546d3a99SAndreas Gohr/**
1573546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1574140cfbcdSGerrit Uitslag *
1575140cfbcdSGerrit Uitslag * @param string $string
1576140cfbcdSGerrit Uitslag * @return string
1577546d3a99SAndreas Gohr */
1578d868eb89SAndreas Gohrfunction preg_quote_cb($string)
1579d868eb89SAndreas Gohr{
1580546d3a99SAndreas Gohr    return preg_quote($string, '/');
1581546d3a99SAndreas Gohr}
158273038c47SAndreas Gohr
1583bd2f6c2fSAndreas Gohr/**
1584bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1585bd2f6c2fSAndreas Gohr *
1586c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1587bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1588bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1589bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1590bd2f6c2fSAndreas Gohr *
1591bd2f6c2fSAndreas Gohr * @param string $keep the part to keep
1592bd2f6c2fSAndreas Gohr * @param string $short the part to shorten
1593bd2f6c2fSAndreas Gohr * @param int $max maximum chars you want for the whole string
1594bd2f6c2fSAndreas Gohr * @param int $min minimum number of chars to have left for middle shortening
1595bd2f6c2fSAndreas Gohr * @param string $char the shortening character to use
15963272d797SAndreas Gohr * @return string
1597bd2f6c2fSAndreas Gohr */
1598d868eb89SAndreas Gohrfunction shorten($keep, $short, $max, $min = 9, $char = '…')
1599d868eb89SAndreas Gohr{
160024870174SAndreas Gohr    $max -= PhpString::strlen($keep);
1601bd2f6c2fSAndreas Gohr    if ($max < $min) return $keep;
160224870174SAndreas Gohr    $len = PhpString::strlen($short);
1603bd2f6c2fSAndreas Gohr    if ($len <= $max) return $keep . $short;
1604bd2f6c2fSAndreas Gohr    $half = floor($max / 2);
16056ce3e5f8SAndreas Gohr    return $keep .
160624870174SAndreas Gohr        PhpString::substr($short, 0, $half - 1) .
16076ce3e5f8SAndreas Gohr        $char .
160824870174SAndreas Gohr        PhpString::substr($short, $len - $half);
1609bd2f6c2fSAndreas Gohr}
1610bd2f6c2fSAndreas Gohr
1611dc58b6f4SAndy Webber/**
1612dc58b6f4SAndy Webber * Return the users real name or e-mail address for use
1613dc58b6f4SAndy Webber * in page footer and recent changes pages
1614dc58b6f4SAndy Webber *
1615b4b6c9a1SGerrit 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
161815f3bc49SGerrit Uitslag *
1619dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1620dc58b6f4SAndy Webber */
1621d868eb89SAndreas Gohrfunction editorinfo($username, $textonly = false)
1622d868eb89SAndreas Gohr{
1623cd4635eeSGerrit Uitslag    return userlink($username, $textonly);
1624dc58b6f4SAndy Webber}
1625dc58b6f4SAndy Webber
162660a396c8SGerrit Uitslag/**
162760a396c8SGerrit Uitslag * Returns users realname w/o link
162860a396c8SGerrit Uitslag *
1629f168548cSGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
163015f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1631c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
163260a396c8SGerrit Uitslag *
163360a396c8SGerrit Uitslag * @triggers COMMON_USER_LINK
163460a396c8SGerrit Uitslag */
1635d868eb89SAndreas Gohrfunction userlink($username = null, $textonly = false)
1636d868eb89SAndreas Gohr{
163760a396c8SGerrit Uitslag    global $conf, $INFO;
1638e1d9dcc8SAndreas Gohr    /** @var AuthPlugin $auth */
163960a396c8SGerrit Uitslag    global $auth;
164030f6ec4bSGerrit Uitslag    /** @var Input $INPUT */
164130f6ec4bSGerrit Uitslag    global $INPUT;
164260a396c8SGerrit Uitslag
164360a396c8SGerrit Uitslag    // prepare initial event data
164424870174SAndreas Gohr    $data = [
164560a396c8SGerrit Uitslag        'username' => $username, // the unique user name
164660a396c8SGerrit Uitslag        'name' => '',
164724870174SAndreas Gohr        'link' => [
164824870174SAndreas Gohr            //setting 'link' to false disables linking
164960a396c8SGerrit Uitslag            'target' => '',
165060a396c8SGerrit Uitslag            'pre' => '',
165160a396c8SGerrit Uitslag            'suf' => '',
165260a396c8SGerrit Uitslag            'style' => '',
165360a396c8SGerrit Uitslag            'more' => '',
165460a396c8SGerrit Uitslag            'url' => '',
165560a396c8SGerrit Uitslag            'title' => '',
165624870174SAndreas Gohr            'class' => '',
165724870174SAndreas Gohr        ],
16584d5fc927SGerrit Uitslag        'userlink' => '', // formatted user name as will be returned
165924870174SAndreas Gohr        'textonly' => $textonly,
166024870174SAndreas Gohr    ];
166162c8004eSGerrit Uitslag    if ($username === null) {
166230f6ec4bSGerrit Uitslag        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
166315f3bc49SGerrit Uitslag        if ($textonly) {
166415f3bc49SGerrit Uitslag            $data['name'] = $INFO['userinfo']['name'] . ' (' . $INPUT->server->str('REMOTE_USER') . ')';
166515f3bc49SGerrit Uitslag        } else {
166664159a61SAndreas Gohr            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> ' .
166764159a61SAndreas Gohr                '(<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
166860a396c8SGerrit Uitslag        }
166915f3bc49SGerrit Uitslag    }
167060a396c8SGerrit Uitslag
1671e1d9dcc8SAndreas Gohr    $evt = new Event('COMMON_USER_LINK', $data);
167260a396c8SGerrit Uitslag    if ($evt->advise_before(true)) {
167360a396c8SGerrit Uitslag        if (empty($data['name'])) {
16746547cfc7SGerrit Uitslag            if ($auth instanceof AuthPlugin) {
16756547cfc7SGerrit Uitslag                $info = $auth->getUserData($username);
16766547cfc7SGerrit Uitslag            }
167765833968SGerrit Uitslag            if ($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1678dc58b6f4SAndy Webber                switch ($conf['showuseras']) {
1679dc58b6f4SAndy Webber                    case 'username':
16807f081821SGerrit Uitslag                    case 'username_link':
168115f3bc49SGerrit Uitslag                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
168260a396c8SGerrit Uitslag                        break;
1683dc58b6f4SAndy Webber                    case 'email':
1684dc58b6f4SAndy Webber                    case 'email_link':
168560a396c8SGerrit Uitslag                        $data['name'] = obfuscate($info['mail']);
168660a396c8SGerrit Uitslag                        break;
1687dc58b6f4SAndy Webber                }
168865833968SGerrit Uitslag            } else {
168965833968SGerrit Uitslag                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
169060a396c8SGerrit Uitslag            }
169160a396c8SGerrit Uitslag        }
16927f081821SGerrit Uitslag
16937f081821SGerrit Uitslag        /** @var Doku_Renderer_xhtml $xhtml_renderer */
16947f081821SGerrit Uitslag        static $xhtml_renderer = null;
16957f081821SGerrit Uitslag
169615f3bc49SGerrit Uitslag        if (!$data['textonly'] && empty($data['link']['url'])) {
169724870174SAndreas Gohr            if (in_array($conf['showuseras'], ['email_link', 'username_link'])) {
16986547cfc7SGerrit Uitslag                if (!isset($info) && $auth instanceof AuthPlugin) {
16996547cfc7SGerrit Uitslag                    $info = $auth->getUserData($username);
170060a396c8SGerrit Uitslag                }
170160a396c8SGerrit Uitslag                if (isset($info) && $info) {
17027f081821SGerrit Uitslag                    if ($conf['showuseras'] == 'email_link') {
170360a396c8SGerrit Uitslag                        $data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
1704dc58b6f4SAndy Webber                    } else {
17057f081821SGerrit Uitslag                        if (is_null($xhtml_renderer)) {
17067f081821SGerrit Uitslag                            $xhtml_renderer = p_get_renderer('xhtml');
17077f081821SGerrit Uitslag                        }
17088407f251Ssplitbrain                        if ($xhtml_renderer->interwiki === []) {
17097f081821SGerrit Uitslag                            $xhtml_renderer->interwiki = getInterwiki();
17107f081821SGerrit Uitslag                        }
17117f081821SGerrit Uitslag                        $shortcut = 'user';
1712533772e1SGerrit Uitslag                        $exists = null;
17136496c33fSGerrit Uitslag                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
17142a2a43c4SGerrit Uitslag                        $data['link']['class'] .= ' interwiki iw_user';
17156496c33fSGerrit Uitslag                        if ($exists !== null) {
17166496c33fSGerrit Uitslag                            if ($exists) {
17176496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink1';
17186496c33fSGerrit Uitslag                            } else {
17196496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink2';
17206496c33fSGerrit Uitslag                                $data['link']['rel'] = 'nofollow';
17216496c33fSGerrit Uitslag                            }
17226496c33fSGerrit Uitslag                        }
1723dc58b6f4SAndy Webber                    }
1724dc58b6f4SAndy Webber                } else {
172515f3bc49SGerrit Uitslag                    $data['textonly'] = true;
1726dc58b6f4SAndy Webber                }
172760a396c8SGerrit Uitslag            } else {
172815f3bc49SGerrit Uitslag                $data['textonly'] = true;
172960a396c8SGerrit Uitslag            }
173060a396c8SGerrit Uitslag        }
173160a396c8SGerrit Uitslag
173215f3bc49SGerrit Uitslag        if ($data['textonly']) {
17334d5fc927SGerrit Uitslag            $data['userlink'] = $data['name'];
173460a396c8SGerrit Uitslag        } else {
173560a396c8SGerrit Uitslag            $data['link']['name'] = $data['name'];
173660a396c8SGerrit Uitslag            if (is_null($xhtml_renderer)) {
173760a396c8SGerrit Uitslag                $xhtml_renderer = p_get_renderer('xhtml');
173860a396c8SGerrit Uitslag            }
17394d5fc927SGerrit Uitslag            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
174060a396c8SGerrit Uitslag        }
174160a396c8SGerrit Uitslag    }
174260a396c8SGerrit Uitslag    $evt->advise_after();
174360a396c8SGerrit Uitslag    unset($evt);
174460a396c8SGerrit Uitslag
17454d5fc927SGerrit Uitslag    return $data['userlink'];
1746066fee30SAndreas Gohr}
1747066fee30SAndreas Gohr
1748066fee30SAndreas Gohr/**
1749066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1750066fee30SAndreas Gohr * When no image exists, returns an empty string
1751066fee30SAndreas Gohr *
1752066fee30SAndreas Gohr * @param string $type - type of image 'badge' or 'button'
17533272d797SAndreas Gohr * @return string
17548b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
17558b19906eSAndreas Gohr *
1756066fee30SAndreas Gohr */
1757d868eb89SAndreas Gohrfunction license_img($type)
1758d868eb89SAndreas Gohr{
1759066fee30SAndreas Gohr    global $license;
1760066fee30SAndreas Gohr    global $conf;
1761066fee30SAndreas Gohr    if (!$conf['license']) return '';
1762066fee30SAndreas Gohr    if (!is_array($license[$conf['license']])) return '';
176324870174SAndreas Gohr    $try = [];
1764066fee30SAndreas Gohr    $try[] = 'lib/images/license/' . $type . '/' . $conf['license'] . '.png';
1765066fee30SAndreas Gohr    $try[] = 'lib/images/license/' . $type . '/' . $conf['license'] . '.gif';
17666c16a3a9Sfiwswe    if (str_starts_with($conf['license'], 'cc-')) {
1767066fee30SAndreas Gohr        $try[] = 'lib/images/license/' . $type . '/cc.png';
1768066fee30SAndreas Gohr    }
1769066fee30SAndreas Gohr    foreach ($try as $src) {
177079e79377SAndreas Gohr        if (file_exists(DOKU_INC . $src)) return $src;
1771066fee30SAndreas Gohr    }
1772066fee30SAndreas Gohr    return '';
1773dc58b6f4SAndy Webber}
1774dc58b6f4SAndy Webber
177513c08e2fSMichael Klier/**
177613c08e2fSMichael Klier * Checks if the given amount of memory is available
177713c08e2fSMichael Klier *
177813c08e2fSMichael Klier * If the memory_get_usage() function is not available the
177913c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
178013c08e2fSMichael Klier *
17813272d797SAndreas Gohr * @param int $mem Size of memory you want to allocate in bytes
1782140cfbcdSGerrit Uitslag * @param int $bytes already allocated memory (see above)
17833272d797SAndreas Gohr * @return bool
17848b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
17858b19906eSAndreas Gohr *
17868b19906eSAndreas Gohr * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
178713c08e2fSMichael Klier */
1788d868eb89SAndreas Gohrfunction is_mem_available($mem, $bytes = 1_048_576)
1789d868eb89SAndreas Gohr{
179013c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
179113c08e2fSMichael Klier    if (empty($limit)) return true; // no limit set!
1792985d6187SElenchus    if ($limit == -1) return true; // unlimited
179313c08e2fSMichael Klier
179413c08e2fSMichael Klier    // parse limit to bytes
179513c08e2fSMichael Klier    $limit = php_to_byte($limit);
179613c08e2fSMichael Klier
179713c08e2fSMichael Klier    // get used memory if possible
179813c08e2fSMichael Klier    if (function_exists('memory_get_usage')) {
179913c08e2fSMichael Klier        $used = memory_get_usage();
180049eb6e38SAndreas Gohr    } else {
180149eb6e38SAndreas Gohr        $used = $bytes;
180213c08e2fSMichael Klier    }
180313c08e2fSMichael Klier
180413c08e2fSMichael Klier    if ($used + $mem > $limit) {
180513c08e2fSMichael Klier        return false;
180613c08e2fSMichael Klier    }
180713c08e2fSMichael Klier
180813c08e2fSMichael Klier    return true;
180913c08e2fSMichael Klier}
181013c08e2fSMichael Klier
1811af2408d5SAndreas Gohr/**
1812af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1813af2408d5SAndreas Gohr *
1814af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1815af2408d5SAndreas Gohr *
1816af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1817af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1818140cfbcdSGerrit Uitslag *
1819140cfbcdSGerrit Uitslag * @param string $url url being directed to
1820af2408d5SAndreas Gohr */
1821d868eb89SAndreas Gohrfunction send_redirect($url)
1822d868eb89SAndreas Gohr{
182398ca30d2SAndreas Gohr    $url = stripctl($url); // defend against HTTP Response Splitting
182498ca30d2SAndreas Gohr
1825585bf44eSChristopher Smith    /* @var Input $INPUT */
1826585bf44eSChristopher Smith    global $INPUT;
1827585bf44eSChristopher Smith
18280181f021SAndreas Gohr    //are there any undisplayed messages? keep them in session for display
18290181f021SAndreas Gohr    global $MSG;
18300181f021SAndreas Gohr    if (isset($MSG) && count($MSG) && !defined('NOSESSION')) {
18310181f021SAndreas Gohr        //reopen session, store data and close session again
18320181f021SAndreas Gohr        @session_start();
18330181f021SAndreas Gohr        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
18340181f021SAndreas Gohr    }
18350181f021SAndreas Gohr
1836d4869846SAndreas Gohr    // always close the session
1837d4869846SAndreas Gohr    session_write_close();
1838d4869846SAndreas Gohr
1839af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
18407d34963bSAndreas Gohr    if (
18417d34963bSAndreas Gohr        $INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1842585bf44eSChristopher Smith        (strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) &&
1843585bf44eSChristopher Smith        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
18443272d797SAndreas Gohr        $matches[1] < 6
18453272d797SAndreas Gohr    ) {
1846af2408d5SAndreas Gohr        header('Refresh: 0;url=' . $url);
1847af2408d5SAndreas Gohr    } else {
1848af2408d5SAndreas Gohr        header('Location: ' . $url);
1849af2408d5SAndreas Gohr    }
185081781cb6SAndreas Gohr
1851572dc222SLarsDW223    // no exits during unit tests
185227c0c399SAndreas Gohr    if (defined('DOKU_UNITTEST')) {
185327c0c399SAndreas Gohr        // pass info about the redirect back to the test suite
185427c0c399SAndreas Gohr        $testRequest = TestRequest::getRunning();
185527c0c399SAndreas Gohr        if ($testRequest !== null) {
185627c0c399SAndreas Gohr            $testRequest->addData('send_redirect', $url);
185727c0c399SAndreas Gohr        }
1858572dc222SLarsDW223        return;
1859572dc222SLarsDW223    }
186027c0c399SAndreas Gohr
1861af2408d5SAndreas Gohr    exit;
1862af2408d5SAndreas Gohr}
1863af2408d5SAndreas Gohr
18645b75cd1fSAdrian Lang/**
18655b75cd1fSAdrian Lang * Validate a value using a set of valid values
18665b75cd1fSAdrian Lang *
18675b75cd1fSAdrian Lang * This function checks whether a specified value is set and in the array
18685b75cd1fSAdrian Lang * $valid_values. If not, the function returns a default value or, if no
18695b75cd1fSAdrian Lang * default is specified, throws an exception.
18705b75cd1fSAdrian Lang *
18715b75cd1fSAdrian Lang * @param string $param The name of the parameter
18725b75cd1fSAdrian Lang * @param array $valid_values A set of valid values; Optionally a default may
18735b75cd1fSAdrian Lang *                             be marked by the key “default”.
18745b75cd1fSAdrian Lang * @param array $array The array containing the value (typically $_POST
18755b75cd1fSAdrian Lang *                             or $_GET)
18765b75cd1fSAdrian Lang * @param string $exc The text of the raised exception
18775b75cd1fSAdrian Lang *
18783272d797SAndreas Gohr * @return mixed
18798b19906eSAndreas Gohr * @throws Exception
18805b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
18815b75cd1fSAdrian Lang */
1882d868eb89SAndreas Gohrfunction valid_input_set($param, $valid_values, $array, $exc = '')
1883d868eb89SAndreas Gohr{
18845b75cd1fSAdrian Lang    if (isset($array[$param]) && in_array($array[$param], $valid_values)) {
18855b75cd1fSAdrian Lang        return $array[$param];
18865b75cd1fSAdrian Lang    } elseif (isset($valid_values['default'])) {
18875b75cd1fSAdrian Lang        return $valid_values['default'];
18885b75cd1fSAdrian Lang    } else {
18895b75cd1fSAdrian Lang        throw new Exception($exc);
18905b75cd1fSAdrian Lang    }
18915b75cd1fSAdrian Lang}
18925b75cd1fSAdrian Lang
189363703ba5SAndreas Gohr/**
189463703ba5SAndreas Gohr * Read a preference from the DokuWiki cookie
1895646a531aSChristopher Smith * (remembering both keys & values are urlencoded)
1896140cfbcdSGerrit Uitslag *
1897140cfbcdSGerrit Uitslag * @param string $pref preference key
1898b4b6c9a1SGerrit Uitslag * @param mixed $default value returned when preference not found
1899140cfbcdSGerrit Uitslag * @return string preference value
190063703ba5SAndreas Gohr */
1901d868eb89SAndreas Gohrfunction get_doku_pref($pref, $default)
1902d868eb89SAndreas Gohr{
1903646a531aSChristopher Smith    $enc_pref = urlencode($pref);
190406c9ee33SMarius van Witzenburg    if (isset($_COOKIE['DOKU_PREFS']) && strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
1905554a8c9fSAdrian Lang        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
190663703ba5SAndreas Gohr        $cnt = count($parts);
19071c3eca7dSPhy
19081c3eca7dSPhy        // due to #2721 there might be duplicate entries,
19091c3eca7dSPhy        // so we read from the end
19101c3eca7dSPhy        for ($i = $cnt - 2; $i >= 0; $i -= 2) {
191124870174SAndreas Gohr            if ($parts[$i] === $enc_pref) {
1912646a531aSChristopher Smith                return urldecode($parts[$i + 1]);
1913554a8c9fSAdrian Lang            }
1914554a8c9fSAdrian Lang        }
1915554a8c9fSAdrian Lang    }
1916554a8c9fSAdrian Lang    return $default;
1917554a8c9fSAdrian Lang}
1918554a8c9fSAdrian Lang
19193c94d07bSAnika Henke/**
19203c94d07bSAnika Henke * Add a preference to the DokuWiki cookie
192136ec377eSChristopher Smith * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
19223a970889SAnika Henke * Remove it by setting $val to false
1923140cfbcdSGerrit Uitslag *
1924140cfbcdSGerrit Uitslag * @param string $pref preference key
1925140cfbcdSGerrit Uitslag * @param string $val preference value
19263c94d07bSAnika Henke */
1927d868eb89SAndreas Gohrfunction set_doku_pref($pref, $val)
1928d868eb89SAndreas Gohr{
19293c94d07bSAnika Henke    global $conf;
19303c94d07bSAnika Henke    $orig = get_doku_pref($pref, false);
19313c94d07bSAnika Henke    $cookieVal = '';
19323c94d07bSAnika Henke
19331c3eca7dSPhy    if ($orig !== false && ($orig !== $val)) {
19343c94d07bSAnika Henke        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
19353c94d07bSAnika Henke        $cnt = count($parts);
193636ec377eSChristopher Smith        // urlencode $pref for the comparison
193736ec377eSChristopher Smith        $enc_pref = rawurlencode($pref);
19381c3eca7dSPhy        $seen = false;
19393c94d07bSAnika Henke        for ($i = 0; $i < $cnt; $i += 2) {
194024870174SAndreas Gohr            if ($parts[$i] === $enc_pref) {
19411c3eca7dSPhy                if (!$seen) {
19423a970889SAnika Henke                    if ($val !== false) {
1943bf8f8509SAndreas Gohr                        $parts[$i + 1] = rawurlencode($val ?? '');
19443a970889SAnika Henke                    } else {
19453a970889SAnika Henke                        unset($parts[$i]);
19463a970889SAnika Henke                        unset($parts[$i + 1]);
19473a970889SAnika Henke                    }
19481c3eca7dSPhy                    $seen = true;
19491c3eca7dSPhy                } else {
19501c3eca7dSPhy                    // no break because we want to remove duplicate entries
19511c3eca7dSPhy                    unset($parts[$i]);
19521c3eca7dSPhy                    unset($parts[$i + 1]);
19531c3eca7dSPhy                }
19543c94d07bSAnika Henke            }
19553c94d07bSAnika Henke        }
19563c94d07bSAnika Henke        $cookieVal = implode('#', $parts);
19571c3eca7dSPhy    } elseif ($orig === false && $val !== false) {
1958c10f256aSDamien Regad        $cookieVal = (isset($_COOKIE['DOKU_PREFS']) ? $_COOKIE['DOKU_PREFS'] . '#' : '') .
195964159a61SAndreas Gohr            rawurlencode($pref) . '#' . rawurlencode($val);
19603c94d07bSAnika Henke    }
19613c94d07bSAnika Henke
196275e4dd8aSGerrit Uitslag    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
19635833995aSPhy    if (defined('DOKU_UNITTEST')) {
19645833995aSPhy        $_COOKIE['DOKU_PREFS'] = $cookieVal;
19655833995aSPhy    } else {
1966bf8392ebSAndreas Gohr        setcookie('DOKU_PREFS', $cookieVal, [
1967bf8392ebSAndreas Gohr            'expires' => time() + 365 * 24 * 3600,
1968bf8392ebSAndreas Gohr            'path' => $cookieDir,
1969bf8392ebSAndreas Gohr            'secure' => ($conf['securecookie'] && is_ssl()),
1970bf8392ebSAndreas Gohr            'samesite' => 'Lax'
1971bf8392ebSAndreas Gohr        ]);
19723c94d07bSAnika Henke    }
19733c94d07bSAnika Henke}
19743c94d07bSAnika Henke
1975f8fb2d18SAndreas Gohr/**
1976f8fb2d18SAndreas Gohr * Strips source mapping declarations from given text #601
1977f8fb2d18SAndreas Gohr *
197842ea7f44SGerrit Uitslag * @param string &$text reference to the CSS or JavaScript code to clean
1979f8fb2d18SAndreas Gohr */
1980d868eb89SAndreas Gohrfunction stripsourcemaps(&$text)
1981d868eb89SAndreas Gohr{
1982f8fb2d18SAndreas Gohr    $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text);
1983f8fb2d18SAndreas Gohr}
1984f8fb2d18SAndreas Gohr
19853c27983bSAndreas Gohr/**
198671de5572SAndreas Gohr * Returns the contents of a given SVG file for embedding
19873c27983bSAndreas Gohr *
19883c27983bSAndreas Gohr * Inlining SVGs saves on HTTP requests and more importantly allows for styling them through
19893c27983bSAndreas Gohr * CSS. However it should used with small SVGs only. The $maxsize setting ensures only small
19903c27983bSAndreas Gohr * files are embedded.
19913c27983bSAndreas Gohr *
199271de5572SAndreas Gohr * This strips unneeded headers, comments and newline. The result is not a vaild standalone SVG!
199371de5572SAndreas Gohr *
19943c27983bSAndreas Gohr * @param string $file full path to the SVG file
19953c27983bSAndreas Gohr * @param int $maxsize maximum allowed size for the SVG to be embedded
199671de5572SAndreas Gohr * @return string|false the SVG content, false if the file couldn't be loaded
19973c27983bSAndreas Gohr */
1998d868eb89SAndreas Gohrfunction inlineSVG($file, $maxsize = 2048)
1999d868eb89SAndreas Gohr{
20003c27983bSAndreas Gohr    $file = trim($file);
20013c27983bSAndreas Gohr    if ($file === '') return false;
20023c27983bSAndreas Gohr    if (!file_exists($file)) return false;
20033c27983bSAndreas Gohr    if (filesize($file) > $maxsize) return false;
20043c27983bSAndreas Gohr    if (!is_readable($file)) return false;
20053c27983bSAndreas Gohr    $content = file_get_contents($file);
20060849fa88SAndreas Gohr    $content = preg_replace('/<!--.*?(-->)/s', '', $content); // comments
20070849fa88SAndreas Gohr    $content = preg_replace('/<\?xml .*?\?>/i', '', $content); // xml header
20080849fa88SAndreas Gohr    $content = preg_replace('/<!DOCTYPE .*?>/i', '', $content); // doc type
20090849fa88SAndreas Gohr    $content = preg_replace('/>\s+</s', '><', $content); // newlines between tags
20103c27983bSAndreas Gohr    $content = trim($content);
20116c16a3a9Sfiwswe    if (!str_starts_with($content, '<svg ')) return false;
201271de5572SAndreas Gohr    return $content;
20133c27983bSAndreas Gohr}
20143c27983bSAndreas Gohr
2015e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
2016