xref: /dokuwiki/inc/common.php (revision 5f21556db6ddf2b17f0409b0f973217e221e767a)
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;
220c3a5702SAndreas Gohr
23f3f0262cSandi/**
24d5197206Schris * Wrapper around htmlspecialchars()
25d5197206Schris *
26d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
27d5197206Schris * @see    htmlspecialchars()
28140cfbcdSGerrit Uitslag *
29140cfbcdSGerrit Uitslag * @param string $string the string being converted
30140cfbcdSGerrit Uitslag * @return string converted string
31d5197206Schris */
32d868eb89SAndreas Gohrfunction hsc($string)
33d868eb89SAndreas Gohr{
34f7711f2bSAndreas Gohr    return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, 'UTF-8');
35d5197206Schris}
36d5197206Schris
37d5197206Schris/**
3812dd3cbcSAndreas Gohr * A safer explode for fixed length lists
3912dd3cbcSAndreas Gohr *
4012dd3cbcSAndreas Gohr * This works just like explode(), but will always return the wanted number of elements.
4112dd3cbcSAndreas Gohr * If the $input string does not contain enough elements, the missing elements will be
4212dd3cbcSAndreas Gohr * filled up with the $default value. If the input string contains more elements, the last
4312dd3cbcSAndreas Gohr * one will NOT be split up and will still contain $separator
4412dd3cbcSAndreas Gohr *
4512dd3cbcSAndreas Gohr * @param string $separator The boundary string
4612dd3cbcSAndreas Gohr * @param string $string The input string
4712dd3cbcSAndreas Gohr * @param int $limit The number of expected elements
4812dd3cbcSAndreas Gohr * @param mixed $default The value to use when filling up missing elements
4912dd3cbcSAndreas Gohr * @see explode
5012dd3cbcSAndreas Gohr * @return array
5112dd3cbcSAndreas Gohr */
5212dd3cbcSAndreas Gohrfunction sexplode($separator, $string, $limit, $default = null)
5312dd3cbcSAndreas Gohr{
5412dd3cbcSAndreas Gohr    return array_pad(explode($separator, $string, $limit), $limit, $default);
5512dd3cbcSAndreas Gohr}
5612dd3cbcSAndreas Gohr
5712dd3cbcSAndreas Gohr/**
585b571377SAndreas Gohr * Checks if the given input is blank
595b571377SAndreas Gohr *
605b571377SAndreas Gohr * This is similar to empty() but will return false for "0".
615b571377SAndreas Gohr *
6267234204SAndreas Gohr * Please note: when you pass uninitialized variables, they will implicitly be created
6367234204SAndreas Gohr * with a NULL value without warning.
6467234204SAndreas Gohr *
6567234204SAndreas Gohr * To avoid this it's recommended to guard the call with isset like this:
6667234204SAndreas Gohr *
6767234204SAndreas Gohr * (isset($foo) && !blank($foo))
6867234204SAndreas Gohr * (!isset($foo) || blank($foo))
6967234204SAndreas Gohr *
705b571377SAndreas Gohr * @param $in
715b571377SAndreas Gohr * @param bool $trim Consider a string of whitespace to be blank
725b571377SAndreas Gohr * @return bool
735b571377SAndreas Gohr */
74d868eb89SAndreas Gohrfunction blank(&$in, $trim = false)
75d868eb89SAndreas Gohr{
765b571377SAndreas Gohr    if (is_null($in)) return true;
7724870174SAndreas Gohr    if (is_array($in)) return $in === [];
785b571377SAndreas Gohr    if ($in === "\0") return true;
795b571377SAndreas Gohr    if ($trim && trim($in) === '') return true;
805b571377SAndreas Gohr    if (strlen($in) > 0) return false;
815b571377SAndreas Gohr    return empty($in);
825b571377SAndreas Gohr}
835b571377SAndreas Gohr
845b571377SAndreas Gohr/**
8502b0b681SAndreas Gohr * strips control characters (<32) from the given string
8602b0b681SAndreas Gohr *
8702b0b681SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
88140cfbcdSGerrit Uitslag *
8942ea7f44SGerrit Uitslag * @param string $string being stripped
90140cfbcdSGerrit Uitslag * @return string
9102b0b681SAndreas Gohr */
92d868eb89SAndreas Gohrfunction stripctl($string)
93d868eb89SAndreas Gohr{
9402b0b681SAndreas Gohr    return preg_replace('/[\x00-\x1F]+/s', '', $string);
95d5197206Schris}
96d5197206Schris
97d5197206Schris/**
98634d7150SAndreas Gohr * Return a secret token to be used for CSRF attack prevention
99634d7150SAndreas Gohr *
100634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
101634d7150SAndreas Gohr * @link    http://en.wikipedia.org/wiki/Cross-site_request_forgery
102634d7150SAndreas Gohr * @link    http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
10342ea7f44SGerrit Uitslag *
104634d7150SAndreas Gohr * @return  string
105634d7150SAndreas Gohr */
106d868eb89SAndreas Gohrfunction getSecurityToken()
107d868eb89SAndreas Gohr{
108585bf44eSChristopher Smith    /** @var Input $INPUT */
109585bf44eSChristopher Smith    global $INPUT;
1103680e2cdSAndreas Gohr
1113680e2cdSAndreas Gohr    $user = $INPUT->server->str('REMOTE_USER');
1123680e2cdSAndreas Gohr    $session = session_id();
1133680e2cdSAndreas Gohr
1143680e2cdSAndreas Gohr    // CSRF checks are only for logged in users - do not generate for anonymous
1153680e2cdSAndreas Gohr    if (trim($user) == '' || trim($session) == '') return '';
11624870174SAndreas Gohr    return PassHash::hmac('md5', $session . $user, auth_cookiesalt());
117634d7150SAndreas Gohr}
118634d7150SAndreas Gohr
119634d7150SAndreas Gohr/**
120634d7150SAndreas Gohr * Check the secret CSRF token
121140cfbcdSGerrit Uitslag *
122140cfbcdSGerrit Uitslag * @param null|string $token security token or null to read it from request variable
123140cfbcdSGerrit Uitslag * @return bool success if the token matched
124634d7150SAndreas Gohr */
125d868eb89SAndreas Gohrfunction checkSecurityToken($token = null)
126d868eb89SAndreas Gohr{
127585bf44eSChristopher Smith    /** @var Input $INPUT */
1287d01a0eaSTom N Harris    global $INPUT;
129585bf44eSChristopher Smith    if (!$INPUT->server->str('REMOTE_USER')) return true; // no logged in user, no need for a check
130df97eaacSAndreas Gohr
1317d01a0eaSTom N Harris    if (is_null($token)) $token = $INPUT->str('sectok');
132634d7150SAndreas Gohr    if (getSecurityToken() != $token) {
133634d7150SAndreas Gohr        msg('Security Token did not match. Possible CSRF attack.', -1);
134634d7150SAndreas Gohr        return false;
135634d7150SAndreas Gohr    }
136634d7150SAndreas Gohr    return true;
137634d7150SAndreas Gohr}
138634d7150SAndreas Gohr
139634d7150SAndreas Gohr/**
140634d7150SAndreas Gohr * Print a hidden form field with a secret CSRF token
141634d7150SAndreas Gohr *
142634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
143140cfbcdSGerrit Uitslag *
144140cfbcdSGerrit Uitslag * @param bool $print  if true print the field, otherwise html of the field is returned
14542ea7f44SGerrit Uitslag * @return string html of hidden form field
146634d7150SAndreas Gohr */
147d868eb89SAndreas Gohrfunction formSecurityToken($print = true)
148d868eb89SAndreas Gohr{
1492404d0edSAnika Henke    $ret = '<div class="no"><input type="hidden" name="sectok" value="' . getSecurityToken() . '" /></div>' . "\n";
1503272d797SAndreas Gohr    if ($print) echo $ret;
151634d7150SAndreas Gohr    return $ret;
152634d7150SAndreas Gohr}
153634d7150SAndreas Gohr
154634d7150SAndreas Gohr/**
1551015a57dSChristopher Smith * Determine basic information for a request of $id
15615fae107Sandi *
15715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1587e87a794SChristopher Smith * @author Chris Smith <chris@jalakai.co.uk>
159140cfbcdSGerrit Uitslag *
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 *
164f3f0262cSandi */
165d868eb89SAndreas Gohrfunction basicinfo($id, $htmlClient = true)
166d868eb89SAndreas Gohr{
167f3f0262cSandi    global $USERINFO;
168585bf44eSChristopher Smith    /* @var Input $INPUT */
169585bf44eSChristopher Smith    global $INPUT;
1706afe8dcaSchris
171c66972f2SAdrian Lang    // set info about manager/admin status.
17224870174SAndreas Gohr    $info = [];
173c66972f2SAdrian Lang    $info['isadmin']   = false;
174c66972f2SAdrian Lang    $info['ismanager'] = false;
175585bf44eSChristopher Smith    if ($INPUT->server->has('REMOTE_USER')) {
176f3f0262cSandi        $info['userinfo']   = $USERINFO;
1771015a57dSChristopher Smith        $info['perm']       = auth_quickaclcheck($id);
178585bf44eSChristopher Smith        $info['client']     = $INPUT->server->str('REMOTE_USER');
17917ee7f66SAndreas Gohr
180f8cc712eSAndreas Gohr        if ($info['perm'] == AUTH_ADMIN) {
181f8cc712eSAndreas Gohr            $info['isadmin']   = true;
182f8cc712eSAndreas Gohr            $info['ismanager'] = true;
183f8cc712eSAndreas Gohr        } elseif (auth_ismanager()) {
184f8cc712eSAndreas Gohr            $info['ismanager'] = true;
185f8cc712eSAndreas Gohr        }
186f8cc712eSAndreas Gohr
18717ee7f66SAndreas Gohr        // if some outside auth were used only REMOTE_USER is set
188a58fcbbcSAndreas Gohr        if (empty($info['userinfo']['name'])) {
189585bf44eSChristopher Smith            $info['userinfo']['name'] = $INPUT->server->str('REMOTE_USER');
19017ee7f66SAndreas Gohr        }
191f3f0262cSandi    } else {
1921015a57dSChristopher Smith        $info['perm']       = auth_aclcheck($id, '', null);
193ee4c4a1bSAndreas Gohr        $info['client']     = clientIP(true);
194f3f0262cSandi    }
195f3f0262cSandi
1961015a57dSChristopher Smith    $info['namespace'] = getNS($id);
1971015a57dSChristopher Smith
1981015a57dSChristopher Smith    // mobile detection
1991015a57dSChristopher Smith    if ($htmlClient) {
2001015a57dSChristopher Smith        $info['ismobile'] = clientismobile();
2011015a57dSChristopher Smith    }
2021015a57dSChristopher Smith
2031015a57dSChristopher Smith    return $info;
2041015a57dSChristopher Smith}
2051015a57dSChristopher Smith
2061015a57dSChristopher Smith/**
2071015a57dSChristopher Smith * Return info about the current document as associative
2081015a57dSChristopher Smith * array.
2091015a57dSChristopher Smith *
210140cfbcdSGerrit Uitslag * @return array with info about current document
2114dc42f7fSGerrit Uitslag * @throws Exception
2124dc42f7fSGerrit Uitslag *
2134dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
2141015a57dSChristopher Smith */
215d868eb89SAndreas Gohrfunction pageinfo()
216d868eb89SAndreas Gohr{
2171015a57dSChristopher Smith    global $ID;
2181015a57dSChristopher Smith    global $REV;
2191015a57dSChristopher Smith    global $RANGE;
2201015a57dSChristopher Smith    global $lang;
2211015a57dSChristopher Smith
2221015a57dSChristopher Smith    $info = basicinfo($ID);
2231015a57dSChristopher Smith
2241015a57dSChristopher Smith    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
2251015a57dSChristopher Smith    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
2261015a57dSChristopher Smith    $info['id']  = $ID;
2271015a57dSChristopher Smith    $info['rev'] = $REV;
2281015a57dSChristopher Smith
22975d66495SMichael Große    $subManager = new SubscriberManager();
23075d66495SMichael Große    $info['subscribed'] = $subManager->userSubscription();
2317e87a794SChristopher Smith
232f3f0262cSandi    $info['locked']     = checklock($ID);
233317a04c4SSatoshi Sahara    $info['filepath']   = wikiFN($ID);
23479e79377SAndreas Gohr    $info['exists']     = file_exists($info['filepath']);
23501c9a118SAndreas Gohr    $info['currentrev'] = @filemtime($info['filepath']);
2365ec96136SSatoshi Sahara
2372ca9d91cSBen Coburn    if ($REV) {
2382ca9d91cSBen Coburn        //check if current revision was meant
23901c9a118SAndreas Gohr        if ($info['exists'] && ($info['currentrev'] == $REV)) {
2402ca9d91cSBen Coburn            $REV = '';
2417b3a6803SAndreas Gohr        } elseif ($RANGE) {
2427b3a6803SAndreas Gohr            //section editing does not work with old revisions!
2437b3a6803SAndreas Gohr            $REV   = '';
2447b3a6803SAndreas Gohr            $RANGE = '';
2457b3a6803SAndreas Gohr            msg($lang['nosecedit'], 0);
2462ca9d91cSBen Coburn        } else {
2472ca9d91cSBen Coburn            //really use old revision
248317a04c4SSatoshi Sahara            $info['filepath'] = wikiFN($ID, $REV);
24979e79377SAndreas Gohr            $info['exists']   = file_exists($info['filepath']);
250f3f0262cSandi        }
251f3f0262cSandi    }
252c112d578Sandi    $info['rev'] = $REV;
253f3f0262cSandi    if ($info['exists']) {
254252acce3SSatoshi Sahara        $info['writable'] = (is_writable($info['filepath']) && $info['perm'] >= AUTH_EDIT);
255f3f0262cSandi    } else {
256f3f0262cSandi        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
257f3f0262cSandi    }
25850e988b1SAndreas Gohr    $info['editable'] = ($info['writable'] && empty($info['locked']));
259f3f0262cSandi    $info['lastmod']  = @filemtime($info['filepath']);
260f3f0262cSandi
26171726d78SBen Coburn    //load page meta data
26271726d78SBen Coburn    $info['meta'] = p_get_metadata($ID);
26371726d78SBen Coburn
264652610a2Sandi    //who's the editor
265047bad06SGerrit Uitslag    $pagelog = new PageChangeLog($ID, 1024);
266652610a2Sandi    if ($REV) {
267f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($REV);
26824870174SAndreas Gohr    } elseif (!empty($info['meta']['last_change']) && is_array($info['meta']['last_change'])) {
269aa27cf05SAndreas Gohr        $revinfo = $info['meta']['last_change'];
270aa27cf05SAndreas Gohr    } else {
271f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($info['lastmod']);
272cd00a034SBen Coburn        // cache most recent changelog line in metadata if missing and still valid
273cd00a034SBen Coburn        if ($revinfo !== false) {
274cd00a034SBen Coburn            $info['meta']['last_change'] = $revinfo;
27524870174SAndreas Gohr            p_set_metadata($ID, ['last_change' => $revinfo]);
276cd00a034SBen Coburn        }
277cd00a034SBen Coburn    }
278cd00a034SBen Coburn    //and check for an external edit
279cd00a034SBen Coburn    if ($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
280cd00a034SBen Coburn        // cached changelog line no longer valid
281cd00a034SBen Coburn        $revinfo                     = false;
282cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
28324870174SAndreas Gohr        p_set_metadata($ID, ['last_change' => $revinfo]);
284652610a2Sandi    }
285bb4866bdSchris
2860a444b5aSPhy    if ($revinfo !== false) {
287652610a2Sandi        $info['ip']   = $revinfo['ip'];
288652610a2Sandi        $info['user'] = $revinfo['user'];
289652610a2Sandi        $info['sum']  = $revinfo['sum'];
29071726d78SBen Coburn        // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
291ebf1501fSBen Coburn        // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
29259f257aeSchris
293252acce3SSatoshi Sahara        $info['editor'] = $revinfo['user'] ?: $revinfo['ip'];
2940a444b5aSPhy    } else {
2950a444b5aSPhy        $info['ip']     = null;
2960a444b5aSPhy        $info['user']   = null;
2970a444b5aSPhy        $info['sum']    = null;
2980a444b5aSPhy        $info['editor'] = null;
2990a444b5aSPhy    }
300652610a2Sandi
301ee4c4a1bSAndreas Gohr    // draft
30224870174SAndreas Gohr    $draft = new Draft($ID, $info['client']);
3030aabe6f8SMichael Große    if ($draft->isDraftAvailable()) {
3040aabe6f8SMichael Große        $info['draft'] = $draft->getDraftFilename();
305ee4c4a1bSAndreas Gohr    }
306ee4c4a1bSAndreas Gohr
3071015a57dSChristopher Smith    return $info;
3081015a57dSChristopher Smith}
3091015a57dSChristopher Smith
3101015a57dSChristopher Smith/**
3110c39d46cSMichael Große * Initialize and/or fill global $JSINFO with some basic info to be given to javascript
3120c39d46cSMichael Große */
313d868eb89SAndreas Gohrfunction jsinfo()
314d868eb89SAndreas Gohr{
3150c39d46cSMichael Große    global $JSINFO, $ID, $INFO, $ACT;
3160c39d46cSMichael Große
3170c39d46cSMichael Große    if (!is_array($JSINFO)) {
3180c39d46cSMichael Große        $JSINFO = [];
3190c39d46cSMichael Große    }
3200c39d46cSMichael Große    //export minimal info to JS, plugins can add more
3210c39d46cSMichael Große    $JSINFO['id']                    = $ID;
32268491db9SPhy    $JSINFO['namespace']             = isset($INFO) ? (string) $INFO['namespace'] : '';
3230c39d46cSMichael Große    $JSINFO['ACT']                   = act_clean($ACT);
3240c39d46cSMichael Große    $JSINFO['useHeadingNavigation']  = (int) useHeading('navigation');
3250c39d46cSMichael Große    $JSINFO['useHeadingContent']     = (int) useHeading('content');
3260c39d46cSMichael Große}
3270c39d46cSMichael Große
3280c39d46cSMichael Große/**
3291015a57dSChristopher Smith * Return information about the current media item as an associative array.
330140cfbcdSGerrit Uitslag *
331140cfbcdSGerrit Uitslag * @return array with info about current media item
3321015a57dSChristopher Smith */
333d868eb89SAndreas Gohrfunction mediainfo()
334d868eb89SAndreas Gohr{
3351015a57dSChristopher Smith    global $NS;
3361015a57dSChristopher Smith    global $IMG;
3371015a57dSChristopher Smith
3381015a57dSChristopher Smith    $info = basicinfo("$NS:*");
3391015a57dSChristopher Smith    $info['image'] = $IMG;
3401c548ebeSAndreas Gohr
341f3f0262cSandi    return $info;
342f3f0262cSandi}
343f3f0262cSandi
344f3f0262cSandi/**
3452684e50aSAndreas Gohr * Build an string of URL parameters
3462684e50aSAndreas Gohr *
3472684e50aSAndreas Gohr * @author Andreas Gohr
348140cfbcdSGerrit Uitslag *
349140cfbcdSGerrit Uitslag * @param array  $params    array with key-value pairs
350140cfbcdSGerrit Uitslag * @param string $sep       series of pairs are separated by this character
351140cfbcdSGerrit Uitslag * @return string query string
3522684e50aSAndreas Gohr */
353d868eb89SAndreas Gohrfunction buildURLparams($params, $sep = '&amp;')
354d868eb89SAndreas Gohr{
3552684e50aSAndreas Gohr    $url = '';
3562684e50aSAndreas Gohr    $amp = false;
3572684e50aSAndreas Gohr    foreach ($params as $key => $val) {
358b174aeaeSchris        if ($amp) $url .= $sep;
3592684e50aSAndreas Gohr
36085e6871fSAdrian Lang        $url .= rawurlencode($key) . '=';
3613a50618cSgweissbach        $url .= rawurlencode((string) $val);
3622684e50aSAndreas Gohr        $amp = true;
3632684e50aSAndreas Gohr    }
3642684e50aSAndreas Gohr    return $url;
3652684e50aSAndreas Gohr}
3662684e50aSAndreas Gohr
3672684e50aSAndreas Gohr/**
3682684e50aSAndreas Gohr * Build an string of html tag attributes
3692684e50aSAndreas Gohr *
3707bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
3717bff22c0SAndreas Gohr *
3722684e50aSAndreas Gohr * @author Andreas Gohr
373140cfbcdSGerrit Uitslag *
374140cfbcdSGerrit Uitslag * @param array $params           array with (attribute name-attribute value) pairs
375246d3337SMichael Große * @param bool  $skipEmptyStrings skip empty string values?
376140cfbcdSGerrit Uitslag * @return string
3772684e50aSAndreas Gohr */
378d868eb89SAndreas Gohrfunction buildAttributes($params, $skipEmptyStrings = false)
379d868eb89SAndreas Gohr{
3802684e50aSAndreas Gohr    $url   = '';
3819063ec14SAdrian Lang    $white = false;
3822684e50aSAndreas Gohr    foreach ($params as $key => $val) {
3832401f18dSSyntaxseed        if ($key[0] == '_') continue;
384246d3337SMichael Große        if ($val === '' && $skipEmptyStrings) continue;
3859063ec14SAdrian Lang        if ($white) $url .= ' ';
3867bff22c0SAndreas Gohr
3872684e50aSAndreas Gohr        $url .= $key . '="';
388f7711f2bSAndreas Gohr        $url .= hsc($val);
3892684e50aSAndreas Gohr        $url .= '"';
3909063ec14SAdrian Lang        $white = true;
3912684e50aSAndreas Gohr    }
3922684e50aSAndreas Gohr    return $url;
3932684e50aSAndreas Gohr}
3942684e50aSAndreas Gohr
3952684e50aSAndreas Gohr/**
39615fae107Sandi * This builds the breadcrumb trail and returns it as array
39715fae107Sandi *
39815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
399140cfbcdSGerrit Uitslag *
400e3710957SGerrit Uitslag * @return string[] with the data: array(pageid=>name, ... )
401f3f0262cSandi */
402d868eb89SAndreas Gohrfunction breadcrumbs()
403d868eb89SAndreas Gohr{
4048746e727Sandi    // we prepare the breadcrumbs early for quick session closing
4058746e727Sandi    static $crumbs = null;
4068746e727Sandi    if ($crumbs != null) return $crumbs;
4078746e727Sandi
408f3f0262cSandi    global $ID;
409f3f0262cSandi    global $ACT;
410f3f0262cSandi    global $conf;
4110ea5ebb4SB_S666    global $INFO;
412f3f0262cSandi
413f3f0262cSandi    //first visit?
41424870174SAndreas Gohr    $crumbs = $_SESSION[DOKU_COOKIE]['bc'] ?? [];
4155603d3c1SHenry Pan    //we only save on show and existing visible readable wiki documents
416a77f5846Sjan    $file = wikiFN($ID);
4175603d3c1SHenry Pan    if ($ACT != 'show' || $INFO['perm'] < AUTH_READ || isHiddenPage($ID) || !file_exists($file)) {
418e71ce681SAndreas Gohr        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
419f3f0262cSandi        return $crumbs;
420f3f0262cSandi    }
421a77f5846Sjan
422a77f5846Sjan    // page names
4231a84a0f3SAnika Henke    $name = noNSorNS($ID);
424fe9ec250SChris Smith    if (useHeading('navigation')) {
425a77f5846Sjan        // get page title
42667c15eceSMichael Hamann        $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
427a77f5846Sjan        if ($title) {
428a77f5846Sjan            $name = $title;
429a77f5846Sjan        }
430a77f5846Sjan    }
431a77f5846Sjan
432f3f0262cSandi    //remove ID from array
433a77f5846Sjan    if (isset($crumbs[$ID])) {
434a77f5846Sjan        unset($crumbs[$ID]);
435f3f0262cSandi    }
436f3f0262cSandi
437f3f0262cSandi    //add to array
438a77f5846Sjan    $crumbs[$ID] = $name;
439f3f0262cSandi    //reduce size
440f3f0262cSandi    while (count($crumbs) > $conf['breadcrumbs']) {
441f3f0262cSandi        array_shift($crumbs);
442f3f0262cSandi    }
443f3f0262cSandi    //save to session
444e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
445f3f0262cSandi    return $crumbs;
446f3f0262cSandi}
447f3f0262cSandi
448f3f0262cSandi/**
44915fae107Sandi * Filter for page IDs
45015fae107Sandi *
451f3f0262cSandi * This is run on a ID before it is outputted somewhere
452f3f0262cSandi * currently used to replace the colon with something else
453907f24f7SAndreas Gohr * on Windows (non-IIS) systems and to have proper URL encoding
454907f24f7SAndreas Gohr *
455977aa967SAndreas Gohr * See discussions at https://github.com/dokuwiki/dokuwiki/pull/84 and
456977aa967SAndreas Gohr * https://github.com/dokuwiki/dokuwiki/pull/173 why we use a whitelist of
457907f24f7SAndreas Gohr * unaffected servers instead of blacklisting affected servers here.
45815fae107Sandi *
45949c713a3Sandi * Urlencoding is ommitted when the second parameter is false
46049c713a3Sandi *
46115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
462140cfbcdSGerrit Uitslag *
463140cfbcdSGerrit Uitslag * @param string $id pageid being filtered
464140cfbcdSGerrit Uitslag * @param bool   $ue apply urlencoding?
465140cfbcdSGerrit Uitslag * @return string
466f3f0262cSandi */
467d868eb89SAndreas Gohrfunction idfilter($id, $ue = true)
468d868eb89SAndreas Gohr{
469f3f0262cSandi    global $conf;
470585bf44eSChristopher Smith    /* @var Input $INPUT */
471585bf44eSChristopher Smith    global $INPUT;
472585bf44eSChristopher Smith
473bf8f8509SAndreas Gohr    $id = (string) $id;
474bf8f8509SAndreas Gohr
475f3f0262cSandi    if ($conf['useslash'] && $conf['userewrite']) {
476f3f0262cSandi        $id = strtr($id, ':', '/');
4777d34963bSAndreas Gohr    } elseif (
4786c16a3a9Sfiwswe        str_starts_with(strtoupper(PHP_OS), 'WIN') &&
47958bedc8aSborekb        $conf['userewrite'] &&
480585bf44eSChristopher Smith        strpos($INPUT->server->str('SERVER_SOFTWARE'), 'Microsoft-IIS') === false
4813272d797SAndreas Gohr    ) {
482f3f0262cSandi        $id = strtr($id, ':', ';');
483f3f0262cSandi    }
48449c713a3Sandi    if ($ue) {
485b6c6979fSAndreas Gohr        $id = rawurlencode($id);
486f3f0262cSandi        $id = str_replace('%3A', ':', $id); //keep as colon
487edd95259SGerrit Uitslag        $id = str_replace('%3B', ';', $id); //keep as semicolon
488f3f0262cSandi        $id = str_replace('%2F', '/', $id); //keep as slash
48949c713a3Sandi    }
490f3f0262cSandi    return $id;
491f3f0262cSandi}
492f3f0262cSandi
493f3f0262cSandi/**
494ed7b5f09Sandi * This builds a link to a wikipage
49515fae107Sandi *
4964bc480e5SAndreas Gohr * It handles URL rewriting and adds additional parameters
4976c7843b5Sandi *
49815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
4994bc480e5SAndreas Gohr *
5004bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
5014bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
5024bc480e5SAndreas Gohr * @param bool         $absolute       request an absolute URL instead of relative
5034bc480e5SAndreas Gohr * @param string       $separator      parameter separator
5044bc480e5SAndreas Gohr * @return string
505f3f0262cSandi */
506d868eb89SAndreas Gohrfunction wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;')
507d868eb89SAndreas Gohr{
508f3f0262cSandi    global $conf;
50916f15a81SDominik Eckelmann    if (is_array($urlParameters)) {
5104bde2196Slisps        if (isset($urlParameters['rev']) && !$urlParameters['rev']) unset($urlParameters['rev']);
51164159a61SAndreas Gohr        if (isset($urlParameters['at']) && $conf['date_at_format']) {
51264159a61SAndreas Gohr            $urlParameters['at'] = date($conf['date_at_format'], $urlParameters['at']);
51364159a61SAndreas Gohr        }
51416f15a81SDominik Eckelmann        $urlParameters = buildURLparams($urlParameters, $separator);
5156de3759aSAndreas Gohr    } else {
51616f15a81SDominik Eckelmann        $urlParameters = str_replace(',', $separator, $urlParameters);
5176de3759aSAndreas Gohr    }
51816f15a81SDominik Eckelmann    if ($id === '') {
51916f15a81SDominik Eckelmann        $id = $conf['start'];
52016f15a81SDominik Eckelmann    }
521f3f0262cSandi    $id = idfilter($id);
52216f15a81SDominik Eckelmann    if ($absolute) {
523ed7b5f09Sandi        $xlink = DOKU_URL;
524ed7b5f09Sandi    } else {
525ed7b5f09Sandi        $xlink = DOKU_BASE;
526ed7b5f09Sandi    }
527f3f0262cSandi
5286c7843b5Sandi    if ($conf['userewrite'] == 2) {
5296c7843b5Sandi        $xlink .= DOKU_SCRIPT . '/' . $id;
53016f15a81SDominik Eckelmann        if ($urlParameters) $xlink .= '?' . $urlParameters;
5316c7843b5Sandi    } elseif ($conf['userewrite']) {
532f3f0262cSandi        $xlink .= $id;
53316f15a81SDominik Eckelmann        if ($urlParameters) $xlink .= '?' . $urlParameters;
53440b5fb5bSPhy    } elseif ($id !== '') {
5356c7843b5Sandi        $xlink .= DOKU_SCRIPT . '?id=' . $id;
53616f15a81SDominik Eckelmann        if ($urlParameters) $xlink .= $separator . $urlParameters;
537bce3726dSAndreas Gohr    } else {
538bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
53916f15a81SDominik Eckelmann        if ($urlParameters) $xlink .= '?' . $urlParameters;
540f3f0262cSandi    }
541f3f0262cSandi
542f3f0262cSandi    return $xlink;
543f3f0262cSandi}
544f3f0262cSandi
545f3f0262cSandi/**
546f5c2808fSBen Coburn * This builds a link to an alternate page format
547f5c2808fSBen Coburn *
548f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
549f5c2808fSBen Coburn *
550f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
5514bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
5524bc480e5SAndreas Gohr * @param string       $format         the export renderer to use
5534bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
5544bc480e5SAndreas Gohr * @param bool         $abs            request an absolute URL instead of relative
5554bc480e5SAndreas Gohr * @param string       $sep            parameter separator
5564bc480e5SAndreas Gohr * @return string
557f5c2808fSBen Coburn */
558d868eb89SAndreas Gohrfunction exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;')
559d868eb89SAndreas Gohr{
560f5c2808fSBen Coburn    global $conf;
5614bc480e5SAndreas Gohr    if (is_array($urlParameters)) {
5624bc480e5SAndreas Gohr        $urlParameters = buildURLparams($urlParameters, $sep);
563f5c2808fSBen Coburn    } else {
5644bc480e5SAndreas Gohr        $urlParameters = str_replace(',', $sep, $urlParameters);
565f5c2808fSBen Coburn    }
566f5c2808fSBen Coburn
567f5c2808fSBen Coburn    $format = rawurlencode($format);
568f5c2808fSBen Coburn    $id     = idfilter($id);
569f5c2808fSBen Coburn    if ($abs) {
570f5c2808fSBen Coburn        $xlink = DOKU_URL;
571f5c2808fSBen Coburn    } else {
572f5c2808fSBen Coburn        $xlink = DOKU_BASE;
573f5c2808fSBen Coburn    }
574f5c2808fSBen Coburn
575f5c2808fSBen Coburn    if ($conf['userewrite'] == 2) {
576f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT . '/' . $id . '?do=export_' . $format;
5774bc480e5SAndreas Gohr        if ($urlParameters) $xlink .= $sep . $urlParameters;
578f5c2808fSBen Coburn    } elseif ($conf['userewrite'] == 1) {
579f5c2808fSBen Coburn        $xlink .= '_export/' . $format . '/' . $id;
5804bc480e5SAndreas Gohr        if ($urlParameters) $xlink .= '?' . $urlParameters;
581f5c2808fSBen Coburn    } else {
582f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT . '?do=export_' . $format . $sep . 'id=' . $id;
5834bc480e5SAndreas Gohr        if ($urlParameters) $xlink .= $sep . $urlParameters;
584f5c2808fSBen Coburn    }
585f5c2808fSBen Coburn
586f5c2808fSBen Coburn    return $xlink;
587f5c2808fSBen Coburn}
588f5c2808fSBen Coburn
589f5c2808fSBen Coburn/**
5906de3759aSAndreas Gohr * Build a link to a media file
5916de3759aSAndreas Gohr *
5926de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
5938c08db0aSAndreas Gohr *
5948c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
5958c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
5968c08db0aSAndreas Gohr *
5973272d797SAndreas Gohr * @param string  $id     the media file id or URL
5983272d797SAndreas Gohr * @param mixed   $more   string or array with additional parameters
5993272d797SAndreas Gohr * @param bool    $direct link to detail page if false
6003272d797SAndreas Gohr * @param string  $sep    URL parameter separator
6013272d797SAndreas Gohr * @param bool    $abs    Create an absolute URL
6023272d797SAndreas Gohr * @return string
6036de3759aSAndreas Gohr */
604d868eb89SAndreas Gohrfunction ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false)
605d868eb89SAndreas Gohr{
6066de3759aSAndreas Gohr    global $conf;
607b9ee6a44SKlap-in    $isexternalimage = media_isexternal($id);
608826d2766SKlap-in    if (!$isexternalimage) {
609826d2766SKlap-in        $id = cleanID($id);
610826d2766SKlap-in    }
611826d2766SKlap-in
6126de3759aSAndreas Gohr    if (is_array($more)) {
6130f4e0092SChristopher Smith        // add token for resized images
61424870174SAndreas Gohr        $w = $more['w'] ?? null;
61524870174SAndreas Gohr        $h = $more['h'] ?? null;
61698fe1ac9SDamien Regad        if ($w || $h || $isexternalimage) {
617357c9a39SDamien Regad            $more['tok'] = media_get_token($id, $w, $h);
6180f4e0092SChristopher Smith        }
6198c08db0aSAndreas Gohr        // strip defaults for shorter URLs
6208c08db0aSAndreas Gohr        if (isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
621443e135dSChristopher Smith        if (empty($more['w'])) unset($more['w']);
622443e135dSChristopher Smith        if (empty($more['h'])) unset($more['h']);
6238c08db0aSAndreas Gohr        if (isset($more['id']) && $direct) unset($more['id']);
62478b874e6Slisps        if (isset($more['rev']) && !$more['rev']) unset($more['rev']);
625b174aeaeSchris        $more = buildURLparams($more, $sep);
6266de3759aSAndreas Gohr    } else {
62724870174SAndreas Gohr        $matches = [];
628cc036f74SKlap-in        if (preg_match_all('/\b(w|h)=(\d*)\b/', $more, $matches, PREG_SET_ORDER) || $isexternalimage) {
62924870174SAndreas Gohr            $resize = ['w' => 0, 'h' => 0];
6305e7db1e2SChristopher Smith            foreach ($matches as $match) {
6315e7db1e2SChristopher Smith                $resize[$match[1]] = $match[2];
6325e7db1e2SChristopher Smith            }
633cc036f74SKlap-in            $more .= $more === '' ? '' : $sep;
634cc036f74SKlap-in            $more .= 'tok=' . media_get_token($id, $resize['w'], $resize['h']);
6355e7db1e2SChristopher Smith        }
6368c08db0aSAndreas Gohr        $more = str_replace('cache=cache', '', $more); //skip default
6378c08db0aSAndreas Gohr        $more = str_replace(',,', ',', $more);
638b174aeaeSchris        $more = str_replace(',', $sep, $more);
6396de3759aSAndreas Gohr    }
6406de3759aSAndreas Gohr
64155b2b31bSAndreas Gohr    if ($abs) {
64255b2b31bSAndreas Gohr        $xlink = DOKU_URL;
64355b2b31bSAndreas Gohr    } else {
6446de3759aSAndreas Gohr        $xlink = DOKU_BASE;
64555b2b31bSAndreas Gohr    }
6466de3759aSAndreas Gohr
6476de3759aSAndreas Gohr    // external URLs are always direct without rewriting
648826d2766SKlap-in    if ($isexternalimage) {
6496de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
650cc036f74SKlap-in        $xlink .= '?' . $more;
651b174aeaeSchris        $xlink .= $sep . 'media=' . rawurlencode($id);
6526de3759aSAndreas Gohr        return $xlink;
6536de3759aSAndreas Gohr    }
6546de3759aSAndreas Gohr
6556de3759aSAndreas Gohr    $id = idfilter($id);
6566de3759aSAndreas Gohr
6576de3759aSAndreas Gohr    // decide on scriptname
6586de3759aSAndreas Gohr    if ($direct) {
6596de3759aSAndreas Gohr        if ($conf['userewrite'] == 1) {
6606de3759aSAndreas Gohr            $script = '_media';
6616de3759aSAndreas Gohr        } else {
6626de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
6636de3759aSAndreas Gohr        }
66424870174SAndreas Gohr    } elseif ($conf['userewrite'] == 1) {
6656de3759aSAndreas Gohr        $script = '_detail';
6666de3759aSAndreas Gohr    } else {
6676de3759aSAndreas Gohr        $script = 'lib/exe/detail.php';
6686de3759aSAndreas Gohr    }
6696de3759aSAndreas Gohr
6706de3759aSAndreas Gohr    // build URL based on rewrite mode
6716de3759aSAndreas Gohr    if ($conf['userewrite']) {
6726de3759aSAndreas Gohr        $xlink .= $script . '/' . $id;
6736de3759aSAndreas Gohr        if ($more) $xlink .= '?' . $more;
67424870174SAndreas Gohr    } elseif ($more) {
675a99d3236SEsther Brunner        $xlink .= $script . '?' . $more;
676b174aeaeSchris        $xlink .= $sep . 'media=' . $id;
6776de3759aSAndreas Gohr    } else {
678a99d3236SEsther Brunner        $xlink .= $script . '?media=' . $id;
6796de3759aSAndreas Gohr    }
6806de3759aSAndreas Gohr
6816de3759aSAndreas Gohr    return $xlink;
6826de3759aSAndreas Gohr}
6836de3759aSAndreas Gohr
6846de3759aSAndreas Gohr/**
68525ca5b17SAndreas Gohr * Returns the URL to the DokuWiki base script
68615fae107Sandi *
68725ca5b17SAndreas Gohr * Consider using wl() instead, unless you absoutely need the doku.php endpoint
68825ca5b17SAndreas Gohr *
68915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
690140cfbcdSGerrit Uitslag *
691140cfbcdSGerrit Uitslag * @return string
692f3f0262cSandi */
693d868eb89SAndreas Gohrfunction script()
694d868eb89SAndreas Gohr{
695ed7b5f09Sandi    return DOKU_BASE . DOKU_SCRIPT;
696f3f0262cSandi}
697f3f0262cSandi
698f3f0262cSandi/**
69915fae107Sandi * Spamcheck against wordlist
70015fae107Sandi *
701f3f0262cSandi * Checks the wikitext against a list of blocked expressions
702f3f0262cSandi * returns true if the text contains any bad words
70315fae107Sandi *
704e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
705e403cc58SMichael Klier *
706e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
707e403cc58SMichael Klier *  and gain information about the user who was blocked.
708e403cc58SMichael Klier *
709e403cc58SMichael Klier *  Event data:
710e403cc58SMichael Klier *    data['matches']  - array of matches
711e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
712e403cc58SMichael Klier *      [ip]           - ip address
713e403cc58SMichael Klier *      [user]         - username (if logged in)
714e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
715e403cc58SMichael Klier *      [name]         - real name (if logged in)
716e403cc58SMichael Klier *
71715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
7186dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
719140cfbcdSGerrit Uitslag *
7206dffa0e0SAndreas Gohr * @param  string $text - optional text to check, if not given the globals are used
7216dffa0e0SAndreas Gohr * @return bool         - true if a spam word was found
722f3f0262cSandi */
723d868eb89SAndreas Gohrfunction checkwordblock($text = '')
724d868eb89SAndreas Gohr{
725f3f0262cSandi    global $TEXT;
7266dffa0e0SAndreas Gohr    global $PRE;
7276dffa0e0SAndreas Gohr    global $SUF;
728e0086ca2SAndreas Gohr    global $SUM;
729f3f0262cSandi    global $conf;
730e403cc58SMichael Klier    global $INFO;
731585bf44eSChristopher Smith    /* @var Input $INPUT */
732585bf44eSChristopher Smith    global $INPUT;
733f3f0262cSandi
734f3f0262cSandi    if (!$conf['usewordblock']) return false;
735f3f0262cSandi
736e0086ca2SAndreas Gohr    if (!$text) $text = "$PRE $TEXT $SUF $SUM";
7376dffa0e0SAndreas Gohr
738041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
73964159a61SAndreas Gohr    // phpcs:disable Generic.Files.LineLength.TooLong
74064159a61SAndreas Gohr    $text = preg_replace(
74164159a61SAndreas Gohr        '!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i',
74264159a61SAndreas Gohr        '\1http://\2 \2\3',
74364159a61SAndreas Gohr        $text
74464159a61SAndreas Gohr    );
74564159a61SAndreas Gohr    // phpcs:enable
746041d1964SAndreas Gohr
747b9ac8716Schris    $wordblocks = getWordblocks();
748a51d08efSAndreas Gohr    // read file in chunks of 200 - this should work around the
7493e2965d7Sandi    // MAX_PATTERN_SIZE in modern PCRE
750a51d08efSAndreas Gohr    $chunksize = 200;
75164259528SAndreas Gohr
752b9ac8716Schris    while ($blocks = array_splice($wordblocks, 0, $chunksize)) {
75324870174SAndreas Gohr        $re = [];
75449eb6e38SAndreas Gohr        // build regexp from blocks
755f3f0262cSandi        foreach ($blocks as $block) {
756f3f0262cSandi            $block = preg_replace('/#.*$/', '', $block);
757f3f0262cSandi            $block = trim($block);
758f3f0262cSandi            if (empty($block)) continue;
759f3f0262cSandi            $re[] = $block;
760f3f0262cSandi        }
76124870174SAndreas Gohr        if (count($re) && preg_match('#(' . implode('|', $re) . ')#si', $text, $matches)) {
762e403cc58SMichael Klier            // prepare event data
76324870174SAndreas Gohr            $data = [];
764e403cc58SMichael Klier            $data['matches']        = $matches;
765585bf44eSChristopher Smith            $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
766585bf44eSChristopher Smith            if ($INPUT->server->str('REMOTE_USER')) {
767585bf44eSChristopher Smith                $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
768e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
769e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
770e403cc58SMichael Klier            }
77124870174SAndreas Gohr            $callback = static fn() => true;
772cbb44eabSAndreas Gohr            return Event::createAndTrigger('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
773b9ac8716Schris        }
774703f6fdeSandi    }
775f3f0262cSandi    return false;
776f3f0262cSandi}
777f3f0262cSandi
778f3f0262cSandi/**
77915fae107Sandi * Return the IP of the client
78015fae107Sandi *
7816d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
78215fae107Sandi *
7836d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
7846d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
7856d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
7866d8affe6SAndreas Gohr * headers
7876d8affe6SAndreas Gohr *
78815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
789140cfbcdSGerrit Uitslag *
7903272d797SAndreas Gohr * @param  boolean $single If set only a single IP is returned
7913272d797SAndreas Gohr * @return string
792f3f0262cSandi */
793d868eb89SAndreas Gohrfunction clientIP($single = false)
794d868eb89SAndreas Gohr{
795585bf44eSChristopher Smith    /* @var Input $INPUT */
796925105e8SPhy    global $INPUT, $conf;
797585bf44eSChristopher Smith
79824870174SAndreas Gohr    $ip   = [];
799585bf44eSChristopher Smith    $ip[] = $INPUT->server->str('REMOTE_ADDR');
800585bf44eSChristopher Smith    if ($INPUT->server->str('HTTP_X_FORWARDED_FOR')) {
801585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_FORWARDED_FOR'))));
802585bf44eSChristopher Smith    }
803585bf44eSChristopher Smith    if ($INPUT->server->str('HTTP_X_REAL_IP')) {
804585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_REAL_IP'))));
805585bf44eSChristopher Smith    }
8066d8affe6SAndreas Gohr
8076d8affe6SAndreas Gohr    // remove any non-IP stuff
8086d8affe6SAndreas Gohr    $cnt   = count($ip);
8096d8affe6SAndreas Gohr    for ($i = 0; $i < $cnt; $i++) {
8100a5f08e5SAdaKaleh        if (filter_var($ip[$i], FILTER_VALIDATE_IP) === false) {
8110a5f08e5SAdaKaleh            unset($ip[$i]);
8124ff28443Schris        }
813f3f0262cSandi    }
8146d8affe6SAndreas Gohr    $ip = array_values(array_unique($ip));
81524870174SAndreas Gohr    if ($ip === [] || !$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
8166d8affe6SAndreas Gohr
81724870174SAndreas Gohr    if (!$single) return implode(',', $ip);
8186d8affe6SAndreas Gohr
819925105e8SPhy    // skip trusted local addresses
8206d8affe6SAndreas Gohr    foreach ($ip as $i) {
821925105e8SPhy        if (!empty($conf['trustedproxy']) && preg_match('/' . $conf['trustedproxy'] . '/', $i)) {
8226d8affe6SAndreas Gohr            continue;
8236d8affe6SAndreas Gohr        } else {
8246d8affe6SAndreas Gohr            return $i;
8256d8affe6SAndreas Gohr        }
8266d8affe6SAndreas Gohr    }
827925105e8SPhy
828925105e8SPhy    // still here? just use the last address
829925105e8SPhy    // this case all ips in the list are trusted
830925105e8SPhy    return $ip[count($ip) - 1];
831f3f0262cSandi}
832f3f0262cSandi
833f3f0262cSandi/**
8341c548ebeSAndreas Gohr * Check if the browser is on a mobile device
8351c548ebeSAndreas Gohr *
8361c548ebeSAndreas Gohr * Adapted from the example code at url below
8371c548ebeSAndreas Gohr *
8381c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
839140cfbcdSGerrit Uitslag *
84064159a61SAndreas Gohr * @deprecated 2018-04-27 you probably want media queries instead anyway
841140cfbcdSGerrit Uitslag * @return bool if true, client is mobile browser; otherwise false
8421c548ebeSAndreas Gohr */
843d868eb89SAndreas Gohrfunction clientismobile()
844d868eb89SAndreas Gohr{
845585bf44eSChristopher Smith    /* @var Input $INPUT */
846585bf44eSChristopher Smith    global $INPUT;
8471c548ebeSAndreas Gohr
848585bf44eSChristopher Smith    if ($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
8491c548ebeSAndreas Gohr
850585bf44eSChristopher Smith    if (preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
8511c548ebeSAndreas Gohr
852585bf44eSChristopher Smith    if (!$INPUT->server->has('HTTP_USER_AGENT')) return false;
8531c548ebeSAndreas Gohr
85424870174SAndreas Gohr    $uamatches = implode(
85564159a61SAndreas Gohr        '|',
85664159a61SAndreas Gohr        [
85764159a61SAndreas Gohr            'midp', 'j2me', 'avantg', 'docomo', 'novarra', 'palmos', 'palmsource', '240x320', 'opwv',
85864159a61SAndreas Gohr            'chtml', 'pda', 'windows ce', 'mmp\/', 'blackberry', 'mib\/', 'symbian', 'wireless', 'nokia',
85964159a61SAndreas Gohr            'hand', 'mobi', 'phone', 'cdm', 'up\.b', 'audio', 'SIE\-', 'SEC\-', 'samsung', 'HTC', 'mot\-',
86064159a61SAndreas Gohr            'mitsu', 'sagem', 'sony', 'alcatel', 'lg', 'erics', 'vx', 'NEC', 'philips', 'mmm', 'xx',
86164159a61SAndreas Gohr            'panasonic', 'sharp', 'wap', 'sch', 'rover', 'pocket', 'benq', 'java', 'pt', 'pg', 'vox',
86264159a61SAndreas Gohr            'amoi', 'bird', 'compal', 'kg', 'voda', 'sany', 'kdd', 'dbt', 'sendo', 'sgh', 'gradi', 'jb',
86364159a61SAndreas Gohr            '\d\d\di', 'moto'
86464159a61SAndreas Gohr        ]
86564159a61SAndreas Gohr    );
8661c548ebeSAndreas Gohr
867585bf44eSChristopher Smith    if (preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
8681c548ebeSAndreas Gohr
8691c548ebeSAndreas Gohr    return false;
8701c548ebeSAndreas Gohr}
8711c548ebeSAndreas Gohr
8721c548ebeSAndreas Gohr/**
8736efc45a2SDmitry Katsubo * check if a given link is interwiki link
8746efc45a2SDmitry Katsubo *
8756efc45a2SDmitry Katsubo * @param string $link the link, e.g. "wiki>page"
8766efc45a2SDmitry Katsubo * @return bool
8776efc45a2SDmitry Katsubo */
878d868eb89SAndreas Gohrfunction link_isinterwiki($link)
879d868eb89SAndreas Gohr{
8806efc45a2SDmitry Katsubo    if (preg_match('/^[a-zA-Z0-9\.]+>/u', $link)) return true;
8816efc45a2SDmitry Katsubo    return false;
8826efc45a2SDmitry Katsubo}
8836efc45a2SDmitry Katsubo
8846efc45a2SDmitry Katsubo/**
88563211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
88663211f61SGlen Harris *
88722ef1e32SAndreas Gohr * If $conf['dnslookups'] is disabled it simply returns the input string
88822ef1e32SAndreas Gohr *
88963211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
890140cfbcdSGerrit Uitslag *
8913272d797SAndreas Gohr * @param  string $ips comma separated list of IP addresses
8923272d797SAndreas Gohr * @return string a comma separated list of hostnames
89363211f61SGlen Harris */
894d868eb89SAndreas Gohrfunction gethostsbyaddrs($ips)
895d868eb89SAndreas Gohr{
89622ef1e32SAndreas Gohr    global $conf;
89722ef1e32SAndreas Gohr    if (!$conf['dnslookups']) return $ips;
89822ef1e32SAndreas Gohr
89924870174SAndreas Gohr    $hosts = [];
90063211f61SGlen Harris    $ips   = explode(',', $ips);
901551a720fSMichael Klier
902551a720fSMichael Klier    if (is_array($ips)) {
9033886270dSAndreas Gohr        foreach ($ips as $ip) {
904551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
90563211f61SGlen Harris        }
90624870174SAndreas Gohr        return implode(',', $hosts);
907551a720fSMichael Klier    } else {
908551a720fSMichael Klier        return gethostbyaddr(trim($ips));
909551a720fSMichael Klier    }
91063211f61SGlen Harris}
91163211f61SGlen Harris
91263211f61SGlen Harris/**
91315fae107Sandi * Checks if a given page is currently locked.
91415fae107Sandi *
915f3f0262cSandi * removes stale lockfiles
91615fae107Sandi *
91715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
918140cfbcdSGerrit Uitslag *
919140cfbcdSGerrit Uitslag * @param string $id page id
920140cfbcdSGerrit Uitslag * @return bool page is locked?
921f3f0262cSandi */
922d868eb89SAndreas Gohrfunction checklock($id)
923d868eb89SAndreas Gohr{
924f3f0262cSandi    global $conf;
925585bf44eSChristopher Smith    /* @var Input $INPUT */
926585bf44eSChristopher Smith    global $INPUT;
927585bf44eSChristopher Smith
928c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
929f3f0262cSandi
930f3f0262cSandi    //no lockfile
93179e79377SAndreas Gohr    if (!file_exists($lock)) return false;
932f3f0262cSandi
933f3f0262cSandi    //lockfile expired
934f3f0262cSandi    if ((time() - filemtime($lock)) > $conf['locktime']) {
935d8186216SBen Coburn        @unlink($lock);
936f3f0262cSandi        return false;
937f3f0262cSandi    }
938f3f0262cSandi
939f3f0262cSandi    //my own lock
940*5f21556dSDamien Regad    [$ip, $session] = sexplode("\n", io_readFile($lock), 2);
94124870174SAndreas Gohr    if ($ip == $INPUT->server->str('REMOTE_USER') || (session_id() && $session === session_id())) {
942f3f0262cSandi        return false;
943f3f0262cSandi    }
944f3f0262cSandi
945f3f0262cSandi    return $ip;
946f3f0262cSandi}
947f3f0262cSandi
948f3f0262cSandi/**
94915fae107Sandi * Lock a page for editing
95015fae107Sandi *
95115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
952140cfbcdSGerrit Uitslag *
953140cfbcdSGerrit Uitslag * @param string $id page id to lock
954f3f0262cSandi */
955d868eb89SAndreas Gohrfunction lock($id)
956d868eb89SAndreas Gohr{
957544ed901SDaniel Calviño Sánchez    global $conf;
958585bf44eSChristopher Smith    /* @var Input $INPUT */
959585bf44eSChristopher Smith    global $INPUT;
960544ed901SDaniel Calviño Sánchez
961544ed901SDaniel Calviño Sánchez    if ($conf['locktime'] == 0) {
962544ed901SDaniel Calviño Sánchez        return;
963544ed901SDaniel Calviño Sánchez    }
964544ed901SDaniel Calviño Sánchez
965c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
966585bf44eSChristopher Smith    if ($INPUT->server->str('REMOTE_USER')) {
967585bf44eSChristopher Smith        io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
968f3f0262cSandi    } else {
96985fef7e2SAndreas Gohr        io_saveFile($lock, clientIP() . "\n" . session_id());
970f3f0262cSandi    }
971f3f0262cSandi}
972f3f0262cSandi
973f3f0262cSandi/**
97415fae107Sandi * Unlock a page if it was locked by the user
975f3f0262cSandi *
97615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
977140cfbcdSGerrit Uitslag *
9783272d797SAndreas Gohr * @param string $id page id to unlock
97915fae107Sandi * @return bool true if a lock was removed
980f3f0262cSandi */
981d868eb89SAndreas Gohrfunction unlock($id)
982d868eb89SAndreas Gohr{
983585bf44eSChristopher Smith    /* @var Input $INPUT */
984585bf44eSChristopher Smith    global $INPUT;
985585bf44eSChristopher Smith
986c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
98779e79377SAndreas Gohr    if (file_exists($lock)) {
98824870174SAndreas Gohr        @[$ip, $session] = explode("\n", io_readFile($lock));
989c0dd3914SAdaKaleh        if ($ip == $INPUT->server->str('REMOTE_USER') || $session == session_id()) {
990f3f0262cSandi            @unlink($lock);
991f3f0262cSandi            return true;
992f3f0262cSandi        }
993f3f0262cSandi    }
994f3f0262cSandi    return false;
995f3f0262cSandi}
996f3f0262cSandi
997f3f0262cSandi/**
998f3f0262cSandi * convert line ending to unix format
999f3f0262cSandi *
10006db7468bSAndreas Gohr * also makes sure the given text is valid UTF-8
10016db7468bSAndreas Gohr *
100215fae107Sandi * @see    formText() for 2crlf conversion
100315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1004140cfbcdSGerrit Uitslag *
1005140cfbcdSGerrit Uitslag * @param string $text
1006140cfbcdSGerrit Uitslag * @return string
1007f3f0262cSandi */
1008d868eb89SAndreas Gohrfunction cleanText($text)
1009d868eb89SAndreas Gohr{
1010f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
10116db7468bSAndreas Gohr
10126db7468bSAndreas Gohr    // if the text is not valid UTF-8 we simply assume latin1
10136db7468bSAndreas Gohr    // this won't break any worse than it breaks with the wrong encoding
10146db7468bSAndreas Gohr    // but might actually fix the problem in many cases
101524870174SAndreas Gohr    if (!Clean::isUtf8($text)) $text = utf8_encode($text);
10166db7468bSAndreas Gohr
1017f3f0262cSandi    return $text;
1018f3f0262cSandi}
1019f3f0262cSandi
1020f3f0262cSandi/**
1021f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
1022f3f0262cSandi * It also converts line endings to Windows format which is
1023f3f0262cSandi * pseudo standard for webforms.
1024f3f0262cSandi *
102515fae107Sandi * @see    cleanText() for 2unix conversion
102615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1027140cfbcdSGerrit Uitslag *
1028140cfbcdSGerrit Uitslag * @param string $text
1029140cfbcdSGerrit Uitslag * @return string
1030f3f0262cSandi */
1031d868eb89SAndreas Gohrfunction formText($text)
1032d868eb89SAndreas Gohr{
1033a46a37efSAndreas Gohr    $text = str_replace("\012", "\015\012", $text ?? '');
1034f3f0262cSandi    return htmlspecialchars($text);
1035f3f0262cSandi}
1036f3f0262cSandi
1037f3f0262cSandi/**
103815fae107Sandi * Returns the specified local text in raw format
103915fae107Sandi *
104015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1041140cfbcdSGerrit Uitslag *
1042140cfbcdSGerrit Uitslag * @param string $id   page id
1043140cfbcdSGerrit Uitslag * @param string $ext  extension of file being read, default 'txt'
1044140cfbcdSGerrit Uitslag * @return string
1045f3f0262cSandi */
1046d868eb89SAndreas Gohrfunction rawLocale($id, $ext = 'txt')
1047d868eb89SAndreas Gohr{
10482adaf2b8SAndreas Gohr    return io_readFile(localeFN($id, $ext));
1049f3f0262cSandi}
1050f3f0262cSandi
1051f3f0262cSandi/**
1052f3f0262cSandi * Returns the raw WikiText
105315fae107Sandi *
105415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1055140cfbcdSGerrit Uitslag *
1056140cfbcdSGerrit Uitslag * @param string $id   page id
1057e0c26282SGerrit Uitslag * @param string|int $rev  timestamp when a revision of wikitext is desired
1058140cfbcdSGerrit Uitslag * @return string
1059f3f0262cSandi */
1060d868eb89SAndreas Gohrfunction rawWiki($id, $rev = '')
1061d868eb89SAndreas Gohr{
1062cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1063f3f0262cSandi}
1064f3f0262cSandi
1065f3f0262cSandi/**
10667146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
10677146cee2SAndreas Gohr *
10687b84afa2SAndreas Gohr * @triggers COMMON_PAGETPL_LOAD
10697146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1070140cfbcdSGerrit Uitslag *
1071140cfbcdSGerrit Uitslag * @param string $id the id of the page to be created
1072140cfbcdSGerrit Uitslag * @return string parsed pagetemplate content
10737146cee2SAndreas Gohr */
1074d868eb89SAndreas Gohrfunction pageTemplate($id)
1075d868eb89SAndreas Gohr{
1076a15ce62dSEsther Brunner    global $conf;
1077e29549feSAndreas Gohr
1078fe17917eSAdrian Lang    if (is_array($id)) $id = $id[0];
1079e29549feSAndreas Gohr
10807b84afa2SAndreas Gohr    // prepare initial event data
108124870174SAndreas Gohr    $data = [
10827b84afa2SAndreas Gohr        'id'        => $id, // the id of the page to be created
10837b84afa2SAndreas Gohr        'tpl'       => '', // the text used as template
10847b84afa2SAndreas Gohr        'tplfile'   => '', // the file above text was/should be loaded from
108524870174SAndreas Gohr        'doreplace' => true,
108624870174SAndreas Gohr    ];
10877b84afa2SAndreas Gohr
1088e1d9dcc8SAndreas Gohr    $evt = new Event('COMMON_PAGETPL_LOAD', $data);
10897b84afa2SAndreas Gohr    if ($evt->advise_before(true)) {
10907b84afa2SAndreas Gohr        // the before event might have loaded the content already
10917b84afa2SAndreas Gohr        if (empty($data['tpl'])) {
10927b84afa2SAndreas Gohr            // if the before event did not set a template file, try to find one
10937b84afa2SAndreas Gohr            if (empty($data['tplfile'])) {
1094fe17917eSAdrian Lang                $path = dirname(wikiFN($id));
109579e79377SAndreas Gohr                if (file_exists($path . '/_template.txt')) {
10967b84afa2SAndreas Gohr                    $data['tplfile'] = $path . '/_template.txt';
1097e29549feSAndreas Gohr                } else {
1098e29549feSAndreas Gohr                    // search upper namespaces for templates
1099e29549feSAndreas Gohr                    $len = strlen(rtrim($conf['datadir'], '/'));
1100e29549feSAndreas Gohr                    while (strlen($path) >= $len) {
110179e79377SAndreas Gohr                        if (file_exists($path . '/__template.txt')) {
11027b84afa2SAndreas Gohr                            $data['tplfile'] = $path . '/__template.txt';
1103e29549feSAndreas Gohr                            break;
1104e29549feSAndreas Gohr                        }
1105e29549feSAndreas Gohr                        $path = substr($path, 0, strrpos($path, '/'));
1106e29549feSAndreas Gohr                    }
1107e29549feSAndreas Gohr                }
11087b84afa2SAndreas Gohr            }
11097b84afa2SAndreas Gohr            // load the content
11103d7ac595SMichael Hamann            $data['tpl'] = io_readFile($data['tplfile']);
11117b84afa2SAndreas Gohr        }
1112a1bbd05bSMichael Hamann        if ($data['doreplace']) parsePageTemplate($data);
11137b84afa2SAndreas Gohr    }
11147b84afa2SAndreas Gohr    $evt->advise_after();
11157b84afa2SAndreas Gohr    unset($evt);
11167b84afa2SAndreas Gohr
1117fe17917eSAdrian Lang    return $data['tpl'];
11182b1223ecSAdrian Lang}
11192b1223ecSAdrian Lang
11202b1223ecSAdrian Lang/**
11212b1223ecSAdrian Lang * Performs common page template replacements
11227b84afa2SAndreas Gohr * This works on data from COMMON_PAGETPL_LOAD
11232b1223ecSAdrian Lang *
11242b1223ecSAdrian Lang * @author Andreas Gohr <andi@splitbrain.org>
1125140cfbcdSGerrit Uitslag *
1126140cfbcdSGerrit Uitslag * @param array $data array with event data
1127140cfbcdSGerrit Uitslag * @return string
11282b1223ecSAdrian Lang */
1129d868eb89SAndreas Gohrfunction parsePageTemplate(&$data)
1130d868eb89SAndreas Gohr{
11313272d797SAndreas Gohr    /**
11323272d797SAndreas Gohr     * @var string $id        the id of the page to be created
11333272d797SAndreas Gohr     * @var string $tpl       the text used as template
11343272d797SAndreas Gohr     * @var string $tplfile   the file above text was/should be loaded from
11353272d797SAndreas Gohr     * @var bool   $doreplace should wildcard replacements be done on the text?
11363272d797SAndreas Gohr     */
1137fe17917eSAdrian Lang    extract($data);
1138fe17917eSAdrian Lang
1139b856f7dfSAdrian Lang    global $USERINFO;
1140bce53b1fSAdrian Lang    global $conf;
1141585bf44eSChristopher Smith    /* @var Input $INPUT */
1142585bf44eSChristopher Smith    global $INPUT;
1143e29549feSAndreas Gohr
1144e29549feSAndreas Gohr    // replace placeholders
114526ece5a7SAndreas Gohr    $file = noNS($id);
114637c1acbdSAdrian Lang    $page = strtr($file, $conf['sepchar'], ' ');
114726ece5a7SAndreas Gohr
11483272d797SAndreas Gohr    $tpl = str_replace(
114924870174SAndreas Gohr        [
115026ece5a7SAndreas Gohr            '@ID@',
115126ece5a7SAndreas Gohr            '@NS@',
11528a7bcf66SShota Miyazaki            '@CURNS@',
1153a3db0ab0SSimon Lees            '@!CURNS@',
1154a3db0ab0SSimon Lees            '@!!CURNS@',
1155a3db0ab0SSimon Lees            '@!CURNS!@',
115626ece5a7SAndreas Gohr            '@FILE@',
115726ece5a7SAndreas Gohr            '@!FILE@',
115826ece5a7SAndreas Gohr            '@!FILE!@',
115926ece5a7SAndreas Gohr            '@PAGE@',
116026ece5a7SAndreas Gohr            '@!PAGE@',
116126ece5a7SAndreas Gohr            '@!!PAGE@',
116226ece5a7SAndreas Gohr            '@!PAGE!@',
116326ece5a7SAndreas Gohr            '@USER@',
116426ece5a7SAndreas Gohr            '@NAME@',
116526ece5a7SAndreas Gohr            '@MAIL@',
116624870174SAndreas Gohr            '@DATE@'
116724870174SAndreas Gohr        ],
116824870174SAndreas Gohr        [
116926ece5a7SAndreas Gohr            $id,
117026ece5a7SAndreas Gohr            getNS($id),
11718a7bcf66SShota Miyazaki            curNS($id),
117224870174SAndreas Gohr            PhpString::ucfirst(curNS($id)),
117324870174SAndreas Gohr            PhpString::ucwords(curNS($id)),
117424870174SAndreas Gohr            PhpString::strtoupper(curNS($id)),
117526ece5a7SAndreas Gohr            $file,
117624870174SAndreas Gohr            PhpString::ucfirst($file),
117724870174SAndreas Gohr            PhpString::strtoupper($file),
117826ece5a7SAndreas Gohr            $page,
117924870174SAndreas Gohr            PhpString::ucfirst($page),
118024870174SAndreas Gohr            PhpString::ucwords($page),
118124870174SAndreas Gohr            PhpString::strtoupper($page),
1182585bf44eSChristopher Smith            $INPUT->server->str('REMOTE_USER'),
11833e9ae63dSPhy            $USERINFO ? $USERINFO['name'] : '',
11843e9ae63dSPhy            $USERINFO ? $USERINFO['mail'] : '',
118524870174SAndreas Gohr            $conf['dformat']
118624870174SAndreas Gohr        ],
118724870174SAndreas Gohr        $tpl
11883272d797SAndreas Gohr    );
118926ece5a7SAndreas Gohr
11907d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
1191bad6fc0dSAndreas Gohr    $tpl = preg_replace_callback(
1192bad6fc0dSAndreas Gohr        '/%./',
119324870174SAndreas Gohr        static fn($m) => dformat(null, $m[0]),
1194bad6fc0dSAndreas Gohr        $tpl
1195bad6fc0dSAndreas Gohr    );
1196d535a2e9Sstretchyboy    $data['tpl'] = $tpl;
1197a15ce62dSEsther Brunner    return $tpl;
11987146cee2SAndreas Gohr}
11997146cee2SAndreas Gohr
12007146cee2SAndreas Gohr/**
120115fae107Sandi * Returns the raw Wiki Text in three slices.
120215fae107Sandi *
120315fae107Sandi * The range parameter needs to have the form "from-to"
120415cfe303Sandi * and gives the range of the section in bytes - no
120515cfe303Sandi * UTF-8 awareness is needed.
1206f3f0262cSandi * The returned order is prefix, section and suffix.
120715fae107Sandi *
120815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1209140cfbcdSGerrit Uitslag *
1210140cfbcdSGerrit Uitslag * @param string $range in form "from-to"
1211140cfbcdSGerrit Uitslag * @param string $id    page id
1212140cfbcdSGerrit Uitslag * @param string $rev   optional, the revision timestamp
121342ea7f44SGerrit Uitslag * @return string[] with three slices
1214f3f0262cSandi */
1215d868eb89SAndreas Gohrfunction rawWikiSlices($range, $id, $rev = '')
1216d868eb89SAndreas Gohr{
1217cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1218f3f0262cSandi
121980fcb268SAdrian Lang    // Parse range
122024870174SAndreas Gohr    [$from, $to] = sexplode('-', $range, 2);
122180fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
122224870174SAndreas Gohr    $from = $from ? $from - 1 : (0);
122324870174SAndreas Gohr    $to   = $to ? $to - 1 : (strlen($text));
122480fcb268SAdrian Lang
122524870174SAndreas Gohr    $slices = [];
122680fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
122780fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to - $from);
122815cfe303Sandi    $slices[2] = substr($text, $to);
1229f3f0262cSandi    return $slices;
1230f3f0262cSandi}
1231f3f0262cSandi
1232f3f0262cSandi/**
123315fae107Sandi * Joins wiki text slices
123415fae107Sandi *
123580fcb268SAdrian Lang * function to join the text slices.
1236f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
1237f3f0262cSandi * lines between sections if needed (used on saving).
123815fae107Sandi *
123915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1240140cfbcdSGerrit Uitslag *
1241140cfbcdSGerrit Uitslag * @param string $pre   prefix
1242140cfbcdSGerrit Uitslag * @param string $text  text in the middle
1243140cfbcdSGerrit Uitslag * @param string $suf   suffix
1244140cfbcdSGerrit Uitslag * @param bool $pretty add additional empty lines between sections
1245140cfbcdSGerrit Uitslag * @return string
1246f3f0262cSandi */
1247d868eb89SAndreas Gohrfunction con($pre, $text, $suf, $pretty = false)
1248d868eb89SAndreas Gohr{
1249f3f0262cSandi    if ($pretty) {
12507d34963bSAndreas Gohr        if (
12516c16a3a9Sfiwswe            $pre !== '' && !str_ends_with($pre, "\n") &&
12526c16a3a9Sfiwswe            !str_starts_with($text, "\n")
12533272d797SAndreas Gohr        ) {
125480fcb268SAdrian Lang            $pre .= "\n";
125580fcb268SAdrian Lang        }
12567d34963bSAndreas Gohr        if (
12576c16a3a9Sfiwswe            $suf !== '' && !str_ends_with($text, "\n") &&
12586c16a3a9Sfiwswe            !str_starts_with($suf, "\n")
12593272d797SAndreas Gohr        ) {
126080fcb268SAdrian Lang            $text .= "\n";
126180fcb268SAdrian Lang        }
1262f3f0262cSandi    }
1263f3f0262cSandi
1264f3f0262cSandi    return $pre . $text . $suf;
1265f3f0262cSandi}
1266f3f0262cSandi
1267f3f0262cSandi/**
1268b24d9195SAndreas Gohr * Checks if the current page version is newer than the last entry in the page's
1269b24d9195SAndreas Gohr * changelog. If so, we assume it has been an external edit and we create an
1270b24d9195SAndreas Gohr * attic copy and add a proper changelog line.
1271b24d9195SAndreas Gohr *
1272b24d9195SAndreas Gohr * This check is only executed when the page is about to be saved again from the
1273b24d9195SAndreas Gohr * wiki, triggered in @see saveWikiText()
1274b24d9195SAndreas Gohr *
1275b24d9195SAndreas Gohr * @param string $id the page ID
127669f9b481SSatoshi Sahara * @deprecated 2021-11-28
1277b24d9195SAndreas Gohr */
1278d868eb89SAndreas Gohrfunction detectExternalEdit($id)
1279d868eb89SAndreas Gohr{
128079a2d784SGerrit Uitslag    dbg_deprecated(PageFile::class . '::detectExternalEdit()');
1281b24e9c4aSSatoshi Sahara    (new PageFile($id))->detectExternalEdit();
1282b24d9195SAndreas Gohr}
1283b24d9195SAndreas Gohr
1284b24d9195SAndreas Gohr/**
1285a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
1286a701424fSBen Coburn * Also directs changelog and attic updates.
128715fae107Sandi *
128815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
128971726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
1290140cfbcdSGerrit Uitslag *
1291140cfbcdSGerrit Uitslag * @param string $id       page id
1292140cfbcdSGerrit Uitslag * @param string $text     wikitext being saved
1293140cfbcdSGerrit Uitslag * @param string $summary  summary of text update
1294140cfbcdSGerrit Uitslag * @param bool   $minor    mark this saved version as minor update
1295f3f0262cSandi */
1296d868eb89SAndreas Gohrfunction saveWikiText($id, $text, $summary, $minor = false)
1297d868eb89SAndreas Gohr{
1298585bf44eSChristopher Smith
1299b24e9c4aSSatoshi Sahara    // get COMMON_WIKIPAGE_SAVE event data
1300b24e9c4aSSatoshi Sahara    $data = (new PageFile($id))->saveWikiText($text, $summary, $minor);
1301a577fbc2SAndreas Gohr    if (!$data) return; // save was cancelled (for no changes or by a plugin)
1302ac3ed4afSGerrit Uitslag
130326a0801fSAndreas Gohr    // send notify mails
130424870174SAndreas Gohr    ['oldRevision' => $rev, 'newRevision' => $new_rev, 'summary' => $summary] = $data;
13053b813d43SSatoshi Sahara    notify($id, 'admin', $rev, $summary, $minor, $new_rev);
13063b813d43SSatoshi Sahara    notify($id, 'subscribers', $rev, $summary, $minor, $new_rev);
1307f3f0262cSandi
13082eccbdaaSGina Haeussge    // if useheading is enabled, purge the cache of all linking pages
1309fe9ec250SChris Smith    if (useHeading('content')) {
131007ff0babSMichael Hamann        $pages = ft_backlinks($id, true);
13112eccbdaaSGina Haeussge        foreach ($pages as $page) {
13120db5771eSMichael Große            $cache = new CacheRenderer($page, wikiFN($page), 'xhtml');
13132eccbdaaSGina Haeussge            $cache->removeCache();
13142eccbdaaSGina Haeussge        }
13152eccbdaaSGina Haeussge    }
1316f3f0262cSandi}
1317f3f0262cSandi
1318f3f0262cSandi/**
1319d5824ab9SSatoshi Sahara * moves the current version to the attic and returns its revision date
132015fae107Sandi *
132115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1322140cfbcdSGerrit Uitslag *
1323140cfbcdSGerrit Uitslag * @param string $id page id
1324140cfbcdSGerrit Uitslag * @return int|string revision timestamp
132569f9b481SSatoshi Sahara * @deprecated 2021-11-28
1326f3f0262cSandi */
1327d868eb89SAndreas Gohrfunction saveOldRevision($id)
1328d868eb89SAndreas Gohr{
132979a2d784SGerrit Uitslag    dbg_deprecated(PageFile::class . '::saveOldRevision()');
1330b24e9c4aSSatoshi Sahara    return (new PageFile($id))->saveOldRevision();
1331f3f0262cSandi}
1332f3f0262cSandi
1333f3f0262cSandi/**
1334fde10de4SAdrian Lang * Sends a notify mail on page change or registration
133526a0801fSAndreas Gohr *
133626a0801fSAndreas Gohr * @param string     $id       The changed page
1337fde10de4SAdrian Lang * @param string     $who      Who to notify (admin|subscribers|register)
13383272d797SAndreas Gohr * @param int|string $rev      Old page revision
133926a0801fSAndreas Gohr * @param string     $summary  What changed
134090033e9dSAndreas Gohr * @param boolean    $minor    Is this a minor edit?
134142ea7f44SGerrit Uitslag * @param string[]   $replace  Additional string substitutions, @KEY@ to be replaced by value
134283734cddSPhy * @param int|string $current_rev  New page revision
13433272d797SAndreas Gohr * @return bool
1344140cfbcdSGerrit Uitslag *
134515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1346f3f0262cSandi */
1347d868eb89SAndreas Gohrfunction notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = [], $current_rev = false)
1348d868eb89SAndreas Gohr{
1349f3f0262cSandi    global $conf;
1350585bf44eSChristopher Smith    /* @var Input $INPUT */
1351585bf44eSChristopher Smith    global $INPUT;
1352b158d625SSteven Danz
13536df843eeSAndreas Gohr    // decide if there is something to do, eg. whom to mail
135426a0801fSAndreas Gohr    if ($who == 'admin') {
13553272d797SAndreas Gohr        if (empty($conf['notify'])) return false; //notify enabled?
13562ed38036SAndreas Gohr        $tpl = 'mailtext';
135726a0801fSAndreas Gohr        $to  = $conf['notify'];
135826a0801fSAndreas Gohr    } elseif ($who == 'subscribers') {
135984c1127cSAndreas Gohr        if (!actionOK('subscribe')) return false; //subscribers enabled?
1360585bf44eSChristopher Smith        if ($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
136124870174SAndreas Gohr        $data = ['id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace];
1362cbb44eabSAndreas Gohr        Event::createAndTrigger(
1363dccd6b2bSAndreas Gohr            'COMMON_NOTIFY_ADDRESSLIST',
1364dccd6b2bSAndreas Gohr            $data,
136524870174SAndreas Gohr            [new SubscriberManager(), 'notifyAddresses']
13663272d797SAndreas Gohr        );
13672ed38036SAndreas Gohr        $to = $data['addresslist'];
13682ed38036SAndreas Gohr        if (empty($to)) return false;
13692ed38036SAndreas Gohr        $tpl = 'subscr_single';
137026a0801fSAndreas Gohr    } else {
13713272d797SAndreas Gohr        return false; //just to be safe
137226a0801fSAndreas Gohr    }
137326a0801fSAndreas Gohr
13746df843eeSAndreas Gohr    // prepare content
1375704a815fSMichael Große    $subscription = new PageSubscriptionSender();
137683734cddSPhy    return $subscription->sendPageDiff($to, $tpl, $id, $rev, $summary, $current_rev);
1377f3f0262cSandi}
13782ed38036SAndreas Gohr
137915fae107Sandi/**
138071f7bde7SAndreas Gohr * extracts the query from a search engine referrer
138115fae107Sandi *
138215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
138371f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1384140cfbcdSGerrit Uitslag *
1385140cfbcdSGerrit Uitslag * @return array|string
1386f3f0262cSandi */
1387d868eb89SAndreas Gohrfunction getGoogleQuery()
1388d868eb89SAndreas Gohr{
1389585bf44eSChristopher Smith    /* @var Input $INPUT */
1390585bf44eSChristopher Smith    global $INPUT;
1391585bf44eSChristopher Smith
1392585bf44eSChristopher Smith    if (!$INPUT->server->has('HTTP_REFERER')) {
1393c66972f2SAdrian Lang        return '';
1394c66972f2SAdrian Lang    }
1395585bf44eSChristopher Smith    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1396f3f0262cSandi
1397079b3ac1SAndreas Gohr    // only handle common SEs
1398c7875401SJyoti S    if (!array_key_exists('host', $url)) return '';
1399079b3ac1SAndreas Gohr    if (!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/', $url['host'])) return '';
1400e4d8a516SKazutaka Miyasaka
140124870174SAndreas Gohr    $query = [];
1402181adffeSJulian Jeggle    if (!array_key_exists('query', $url)) return '';
1403f3f0262cSandi    parse_str($url['query'], $query);
1404e4d8a516SKazutaka Miyasaka
1405c66972f2SAdrian Lang    $q = '';
1406079b3ac1SAndreas Gohr    if (isset($query['q'])) {
1407079b3ac1SAndreas Gohr        $q = $query['q'];
1408079b3ac1SAndreas Gohr    } elseif (isset($query['p'])) {
1409079b3ac1SAndreas Gohr        $q = $query['p'];
1410079b3ac1SAndreas Gohr    } elseif (isset($query['query'])) {
1411079b3ac1SAndreas Gohr        $q = $query['query'];
1412079b3ac1SAndreas Gohr    }
1413079b3ac1SAndreas Gohr    $q = trim($q);
1414f3f0262cSandi
1415079b3ac1SAndreas Gohr    if (!$q) return '';
1416c7dc833bSPhy    // ignore if query includes a full URL
1417c7dc833bSPhy    if (strpos($q, '//') !== false) return '';
14186531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1419f93b3b50SAndreas Gohr    return $q;
1420f3f0262cSandi}
1421f3f0262cSandi
1422f3f0262cSandi/**
1423f3f0262cSandi * Return the human readable size of a file
1424f3f0262cSandi *
1425f3f0262cSandi * @param int $size A file size
1426f3f0262cSandi * @param int $dec A number of decimal places
142774160ca1SGerrit Uitslag * @return string human readable size
1428140cfbcdSGerrit Uitslag *
1429f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1430f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1431f3f0262cSandi * @version     1.0.0
1432f3f0262cSandi */
1433d868eb89SAndreas Gohrfunction filesize_h($size, $dec = 1)
1434d868eb89SAndreas Gohr{
143524870174SAndreas Gohr    $sizes = ['B', 'KB', 'MB', 'GB'];
1436f3f0262cSandi    $count = count($sizes);
1437f3f0262cSandi    $i     = 0;
1438f3f0262cSandi
1439f3f0262cSandi    while ($size >= 1024 && ($i < $count - 1)) {
1440f3f0262cSandi        $size /= 1024;
1441f3f0262cSandi        $i++;
1442f3f0262cSandi    }
1443f3f0262cSandi
1444ef08383eSAndreas Gohr    return round($size, $dec) . "\xC2\xA0" . $sizes[$i]; //non-breaking space
1445f3f0262cSandi}
1446f3f0262cSandi
144715fae107Sandi/**
1448c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1449c57e365eSAndreas Gohr *
1450c57e365eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1451140cfbcdSGerrit Uitslag *
1452140cfbcdSGerrit Uitslag * @param int $dt timestamp
1453140cfbcdSGerrit Uitslag * @return string
1454c57e365eSAndreas Gohr */
1455d868eb89SAndreas Gohrfunction datetime_h($dt)
1456d868eb89SAndreas Gohr{
1457c57e365eSAndreas Gohr    global $lang;
1458c57e365eSAndreas Gohr
1459c57e365eSAndreas Gohr    $ago = time() - $dt;
1460c57e365eSAndreas Gohr    if ($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1461c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1462c57e365eSAndreas Gohr    }
1463c57e365eSAndreas Gohr    if ($ago > 24 * 60 * 60 * 30 * 2) {
1464c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1465c57e365eSAndreas Gohr    }
1466c57e365eSAndreas Gohr    if ($ago > 24 * 60 * 60 * 7 * 2) {
1467c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1468c57e365eSAndreas Gohr    }
1469c57e365eSAndreas Gohr    if ($ago > 24 * 60 * 60 * 2) {
1470c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1471c57e365eSAndreas Gohr    }
1472c57e365eSAndreas Gohr    if ($ago > 60 * 60 * 2) {
1473c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago / (60 * 60)));
1474c57e365eSAndreas Gohr    }
1475c57e365eSAndreas Gohr    if ($ago > 60 * 2) {
1476c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago / (60)));
1477c57e365eSAndreas Gohr    }
1478c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1479c57e365eSAndreas Gohr}
1480c57e365eSAndreas Gohr
1481c57e365eSAndreas Gohr/**
1482f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1483f2263577SAndreas Gohr *
1484f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1485f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1486f2263577SAndreas Gohr *
1487f2263577SAndreas Gohr * @see datetime_h
1488f2263577SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1489140cfbcdSGerrit Uitslag *
1490140cfbcdSGerrit Uitslag * @param int|null $dt      timestamp when given, null will take current timestamp
1491140cfbcdSGerrit Uitslag * @param string   $format  empty default to $conf['dformat'], or provide format as recognized by strftime()
1492140cfbcdSGerrit Uitslag * @return string
1493f2263577SAndreas Gohr */
1494d868eb89SAndreas Gohrfunction dformat($dt = null, $format = '')
1495d868eb89SAndreas Gohr{
1496f2263577SAndreas Gohr    global $conf;
1497f2263577SAndreas Gohr
1498f2263577SAndreas Gohr    if (is_null($dt)) $dt = time();
1499f2263577SAndreas Gohr    $dt = (int) $dt;
1500f2263577SAndreas Gohr    if (!$format) $format = $conf['dformat'];
1501f2263577SAndreas Gohr
1502f2263577SAndreas Gohr    $format = str_replace('%f', datetime_h($dt), $format);
1503f2263577SAndreas Gohr    return strftime($format, $dt);
1504f2263577SAndreas Gohr}
1505f2263577SAndreas Gohr
1506f2263577SAndreas Gohr/**
1507c4f79b71SMichael Hamann * Formats a timestamp as ISO 8601 date
1508c4f79b71SMichael Hamann *
1509c4f79b71SMichael Hamann * @author <ungu at terong dot com>
151059752844SAnders Sandblad * @link http://php.net/manual/en/function.date.php#54072
1511140cfbcdSGerrit Uitslag *
15127e8500eeSGerrit Uitslag * @param int $int_date current date in UNIX timestamp
15133272d797SAndreas Gohr * @return string
1514c4f79b71SMichael Hamann */
1515d868eb89SAndreas Gohrfunction date_iso8601($int_date)
1516d868eb89SAndreas Gohr{
1517c4f79b71SMichael Hamann    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1518c4f79b71SMichael Hamann    $pre_timezone = date('O', $int_date);
1519c4f79b71SMichael Hamann    $time_zone    = substr($pre_timezone, 0, 3) . ":" . substr($pre_timezone, 3, 2);
1520c4f79b71SMichael Hamann    $date_mod .= $time_zone;
1521c4f79b71SMichael Hamann    return $date_mod;
1522c4f79b71SMichael Hamann}
1523c4f79b71SMichael Hamann
1524c4f79b71SMichael Hamann/**
152500a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
152600a7b5adSEsther Brunner *
152700a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
152800a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
1529140cfbcdSGerrit Uitslag *
1530140cfbcdSGerrit Uitslag * @param string $email email address
1531140cfbcdSGerrit Uitslag * @return string
153200a7b5adSEsther Brunner */
1533d868eb89SAndreas Gohrfunction obfuscate($email)
1534d868eb89SAndreas Gohr{
153500a7b5adSEsther Brunner    global $conf;
153600a7b5adSEsther Brunner
153700a7b5adSEsther Brunner    switch ($conf['mailguard']) {
153800a7b5adSEsther Brunner        case 'visible':
153924870174SAndreas Gohr            $obfuscate = ['@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] '];
154000a7b5adSEsther Brunner            return strtr($email, $obfuscate);
154100a7b5adSEsther Brunner
154200a7b5adSEsther Brunner        case 'hex':
154324870174SAndreas Gohr            return Conversion::toHtml($email, true);
154400a7b5adSEsther Brunner
154500a7b5adSEsther Brunner        case 'none':
154600a7b5adSEsther Brunner        default:
154700a7b5adSEsther Brunner            return $email;
154800a7b5adSEsther Brunner    }
154900a7b5adSEsther Brunner}
155000a7b5adSEsther Brunner
155100a7b5adSEsther Brunner/**
155289541d4bSAndreas Gohr * Removes quoting backslashes
155389541d4bSAndreas Gohr *
155489541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1555140cfbcdSGerrit Uitslag *
1556140cfbcdSGerrit Uitslag * @param string $string
1557140cfbcdSGerrit Uitslag * @param string $char backslashed character
1558140cfbcdSGerrit Uitslag * @return string
155989541d4bSAndreas Gohr */
1560d868eb89SAndreas Gohrfunction unslash($string, $char = "'")
1561d868eb89SAndreas Gohr{
156289541d4bSAndreas Gohr    return str_replace('\\' . $char, $char, $string);
156389541d4bSAndreas Gohr}
156489541d4bSAndreas Gohr
156573038c47SAndreas Gohr/**
156673038c47SAndreas Gohr * Convert php.ini shorthands to byte
156773038c47SAndreas Gohr *
1568a81f3d99SAndreas Gohr * On 32 bit systems values >= 2GB will fail!
1569140cfbcdSGerrit Uitslag *
1570a81f3d99SAndreas Gohr * -1 (infinite size) will be reported as -1
1571a81f3d99SAndreas Gohr *
1572a81f3d99SAndreas Gohr * @link   https://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
1573a81f3d99SAndreas Gohr * @param string $value PHP size shorthand
1574a81f3d99SAndreas Gohr * @return int
157573038c47SAndreas Gohr */
1576d868eb89SAndreas Gohrfunction php_to_byte($value)
1577d868eb89SAndreas Gohr{
1578f5c0c80bSAndreas Gohr    switch (strtoupper(substr($value, -1))) {
157973038c47SAndreas Gohr        case 'G':
158024870174SAndreas Gohr            $ret = (int) substr($value, 0, -1) * 1024 * 1024 * 1024;
158173038c47SAndreas Gohr            break;
158273038c47SAndreas Gohr        case 'M':
158324870174SAndreas Gohr            $ret = (int) substr($value, 0, -1) * 1024 * 1024;
1584a81f3d99SAndreas Gohr            break;
158573038c47SAndreas Gohr        case 'K':
158624870174SAndreas Gohr            $ret = (int) substr($value, 0, -1) * 1024;
158773038c47SAndreas Gohr            break;
15889eeeb775SAndreas Gohr        default:
158924870174SAndreas Gohr            $ret = (int) $value;
159049cbd23eSOtto Vainio            break;
159173038c47SAndreas Gohr    }
159273038c47SAndreas Gohr    return $ret;
159373038c47SAndreas Gohr}
159473038c47SAndreas Gohr
1595546d3a99SAndreas Gohr/**
1596546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1597140cfbcdSGerrit Uitslag *
1598140cfbcdSGerrit Uitslag * @param string $string
1599140cfbcdSGerrit Uitslag * @return string
1600546d3a99SAndreas Gohr */
1601d868eb89SAndreas Gohrfunction preg_quote_cb($string)
1602d868eb89SAndreas Gohr{
1603546d3a99SAndreas Gohr    return preg_quote($string, '/');
1604546d3a99SAndreas Gohr}
160573038c47SAndreas Gohr
1606bd2f6c2fSAndreas Gohr/**
1607bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1608bd2f6c2fSAndreas Gohr *
1609c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1610bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1611bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1612bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1613bd2f6c2fSAndreas Gohr *
1614bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1615bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1616bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1617bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1618bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
16193272d797SAndreas Gohr * @return string
1620bd2f6c2fSAndreas Gohr */
1621d868eb89SAndreas Gohrfunction shorten($keep, $short, $max, $min = 9, $char = '…')
1622d868eb89SAndreas Gohr{
162324870174SAndreas Gohr    $max -= PhpString::strlen($keep);
1624bd2f6c2fSAndreas Gohr    if ($max < $min) return $keep;
162524870174SAndreas Gohr    $len = PhpString::strlen($short);
1626bd2f6c2fSAndreas Gohr    if ($len <= $max) return $keep . $short;
1627bd2f6c2fSAndreas Gohr    $half = floor($max / 2);
16286ce3e5f8SAndreas Gohr    return $keep .
162924870174SAndreas Gohr        PhpString::substr($short, 0, $half - 1) .
16306ce3e5f8SAndreas Gohr        $char .
163124870174SAndreas Gohr        PhpString::substr($short, $len - $half);
1632bd2f6c2fSAndreas Gohr}
1633bd2f6c2fSAndreas Gohr
1634dc58b6f4SAndy Webber/**
1635dc58b6f4SAndy Webber * Return the users real name or e-mail address for use
1636dc58b6f4SAndy Webber * in page footer and recent changes pages
1637dc58b6f4SAndy Webber *
1638b4b6c9a1SGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
163915f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1640c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
164115f3bc49SGerrit Uitslag *
1642dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1643dc58b6f4SAndy Webber */
1644d868eb89SAndreas Gohrfunction editorinfo($username, $textonly = false)
1645d868eb89SAndreas Gohr{
1646cd4635eeSGerrit Uitslag    return userlink($username, $textonly);
1647dc58b6f4SAndy Webber}
1648dc58b6f4SAndy Webber
164960a396c8SGerrit Uitslag/**
165060a396c8SGerrit Uitslag * Returns users realname w/o link
165160a396c8SGerrit Uitslag *
1652f168548cSGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
165315f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1654c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
165560a396c8SGerrit Uitslag *
165660a396c8SGerrit Uitslag * @triggers COMMON_USER_LINK
165760a396c8SGerrit Uitslag */
1658d868eb89SAndreas Gohrfunction userlink($username = null, $textonly = false)
1659d868eb89SAndreas Gohr{
166060a396c8SGerrit Uitslag    global $conf, $INFO;
1661e1d9dcc8SAndreas Gohr    /** @var AuthPlugin $auth */
166260a396c8SGerrit Uitslag    global $auth;
166330f6ec4bSGerrit Uitslag    /** @var Input $INPUT */
166430f6ec4bSGerrit Uitslag    global $INPUT;
166560a396c8SGerrit Uitslag
166660a396c8SGerrit Uitslag    // prepare initial event data
166724870174SAndreas Gohr    $data = [
166860a396c8SGerrit Uitslag        'username' => $username, // the unique user name
166960a396c8SGerrit Uitslag        'name' => '',
167024870174SAndreas Gohr        'link' => [
167124870174SAndreas Gohr            //setting 'link' to false disables linking
167260a396c8SGerrit Uitslag            'target' => '',
167360a396c8SGerrit Uitslag            'pre' => '',
167460a396c8SGerrit Uitslag            'suf' => '',
167560a396c8SGerrit Uitslag            'style' => '',
167660a396c8SGerrit Uitslag            'more' => '',
167760a396c8SGerrit Uitslag            'url' => '',
167860a396c8SGerrit Uitslag            'title' => '',
167924870174SAndreas Gohr            'class' => '',
168024870174SAndreas Gohr        ],
16814d5fc927SGerrit Uitslag        'userlink' => '', // formatted user name as will be returned
168224870174SAndreas Gohr        'textonly' => $textonly,
168324870174SAndreas Gohr    ];
168462c8004eSGerrit Uitslag    if ($username === null) {
168530f6ec4bSGerrit Uitslag        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
168615f3bc49SGerrit Uitslag        if ($textonly) {
168715f3bc49SGerrit Uitslag            $data['name'] = $INFO['userinfo']['name'] . ' (' . $INPUT->server->str('REMOTE_USER') . ')';
168815f3bc49SGerrit Uitslag        } else {
168964159a61SAndreas Gohr            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> ' .
169064159a61SAndreas Gohr                '(<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
169160a396c8SGerrit Uitslag        }
169215f3bc49SGerrit Uitslag    }
169360a396c8SGerrit Uitslag
1694e1d9dcc8SAndreas Gohr    $evt = new Event('COMMON_USER_LINK', $data);
169560a396c8SGerrit Uitslag    if ($evt->advise_before(true)) {
169660a396c8SGerrit Uitslag        if (empty($data['name'])) {
16976547cfc7SGerrit Uitslag            if ($auth instanceof AuthPlugin) {
16986547cfc7SGerrit Uitslag                $info = $auth->getUserData($username);
16996547cfc7SGerrit Uitslag            }
170065833968SGerrit Uitslag            if ($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1701dc58b6f4SAndy Webber                switch ($conf['showuseras']) {
1702dc58b6f4SAndy Webber                    case 'username':
17037f081821SGerrit Uitslag                    case 'username_link':
170415f3bc49SGerrit Uitslag                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
170560a396c8SGerrit Uitslag                        break;
1706dc58b6f4SAndy Webber                    case 'email':
1707dc58b6f4SAndy Webber                    case 'email_link':
170860a396c8SGerrit Uitslag                        $data['name'] = obfuscate($info['mail']);
170960a396c8SGerrit Uitslag                        break;
1710dc58b6f4SAndy Webber                }
171165833968SGerrit Uitslag            } else {
171265833968SGerrit Uitslag                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
171360a396c8SGerrit Uitslag            }
171460a396c8SGerrit Uitslag        }
17157f081821SGerrit Uitslag
17167f081821SGerrit Uitslag        /** @var Doku_Renderer_xhtml $xhtml_renderer */
17177f081821SGerrit Uitslag        static $xhtml_renderer = null;
17187f081821SGerrit Uitslag
171915f3bc49SGerrit Uitslag        if (!$data['textonly'] && empty($data['link']['url'])) {
172024870174SAndreas Gohr            if (in_array($conf['showuseras'], ['email_link', 'username_link'])) {
17216547cfc7SGerrit Uitslag                if (!isset($info) && $auth instanceof AuthPlugin) {
17226547cfc7SGerrit Uitslag                    $info = $auth->getUserData($username);
172360a396c8SGerrit Uitslag                }
172460a396c8SGerrit Uitslag                if (isset($info) && $info) {
17257f081821SGerrit Uitslag                    if ($conf['showuseras'] == 'email_link') {
172660a396c8SGerrit Uitslag                        $data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
1727dc58b6f4SAndy Webber                    } else {
17287f081821SGerrit Uitslag                        if (is_null($xhtml_renderer)) {
17297f081821SGerrit Uitslag                            $xhtml_renderer = p_get_renderer('xhtml');
17307f081821SGerrit Uitslag                        }
17317f081821SGerrit Uitslag                        if (empty($xhtml_renderer->interwiki)) {
17327f081821SGerrit Uitslag                            $xhtml_renderer->interwiki = getInterwiki();
17337f081821SGerrit Uitslag                        }
17347f081821SGerrit Uitslag                        $shortcut = 'user';
1735533772e1SGerrit Uitslag                        $exists = null;
17366496c33fSGerrit Uitslag                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
17372a2a43c4SGerrit Uitslag                        $data['link']['class'] .= ' interwiki iw_user';
17386496c33fSGerrit Uitslag                        if ($exists !== null) {
17396496c33fSGerrit Uitslag                            if ($exists) {
17406496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink1';
17416496c33fSGerrit Uitslag                            } else {
17426496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink2';
17436496c33fSGerrit Uitslag                                $data['link']['rel'] = 'nofollow';
17446496c33fSGerrit Uitslag                            }
17456496c33fSGerrit Uitslag                        }
1746dc58b6f4SAndy Webber                    }
1747dc58b6f4SAndy Webber                } else {
174815f3bc49SGerrit Uitslag                    $data['textonly'] = true;
1749dc58b6f4SAndy Webber                }
175060a396c8SGerrit Uitslag            } else {
175115f3bc49SGerrit Uitslag                $data['textonly'] = true;
175260a396c8SGerrit Uitslag            }
175360a396c8SGerrit Uitslag        }
175460a396c8SGerrit Uitslag
175515f3bc49SGerrit Uitslag        if ($data['textonly']) {
17564d5fc927SGerrit Uitslag            $data['userlink'] = $data['name'];
175760a396c8SGerrit Uitslag        } else {
175860a396c8SGerrit Uitslag            $data['link']['name'] = $data['name'];
175960a396c8SGerrit Uitslag            if (is_null($xhtml_renderer)) {
176060a396c8SGerrit Uitslag                $xhtml_renderer = p_get_renderer('xhtml');
176160a396c8SGerrit Uitslag            }
17624d5fc927SGerrit Uitslag            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
176360a396c8SGerrit Uitslag        }
176460a396c8SGerrit Uitslag    }
176560a396c8SGerrit Uitslag    $evt->advise_after();
176660a396c8SGerrit Uitslag    unset($evt);
176760a396c8SGerrit Uitslag
17684d5fc927SGerrit Uitslag    return $data['userlink'];
1769066fee30SAndreas Gohr}
1770066fee30SAndreas Gohr
1771066fee30SAndreas Gohr/**
1772066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1773066fee30SAndreas Gohr * When no image exists, returns an empty string
1774066fee30SAndreas Gohr *
1775066fee30SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1776140cfbcdSGerrit Uitslag *
1777066fee30SAndreas Gohr * @param  string $type - type of image 'badge' or 'button'
17783272d797SAndreas Gohr * @return string
1779066fee30SAndreas Gohr */
1780d868eb89SAndreas Gohrfunction license_img($type)
1781d868eb89SAndreas Gohr{
1782066fee30SAndreas Gohr    global $license;
1783066fee30SAndreas Gohr    global $conf;
1784066fee30SAndreas Gohr    if (!$conf['license']) return '';
1785066fee30SAndreas Gohr    if (!is_array($license[$conf['license']])) return '';
178624870174SAndreas Gohr    $try   = [];
1787066fee30SAndreas Gohr    $try[] = 'lib/images/license/' . $type . '/' . $conf['license'] . '.png';
1788066fee30SAndreas Gohr    $try[] = 'lib/images/license/' . $type . '/' . $conf['license'] . '.gif';
17896c16a3a9Sfiwswe    if (str_starts_with($conf['license'], 'cc-')) {
1790066fee30SAndreas Gohr        $try[] = 'lib/images/license/' . $type . '/cc.png';
1791066fee30SAndreas Gohr    }
1792066fee30SAndreas Gohr    foreach ($try as $src) {
179379e79377SAndreas Gohr        if (file_exists(DOKU_INC . $src)) return $src;
1794066fee30SAndreas Gohr    }
1795066fee30SAndreas Gohr    return '';
1796dc58b6f4SAndy Webber}
1797dc58b6f4SAndy Webber
179813c08e2fSMichael Klier/**
179913c08e2fSMichael Klier * Checks if the given amount of memory is available
180013c08e2fSMichael Klier *
180113c08e2fSMichael Klier * If the memory_get_usage() function is not available the
180213c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
180313c08e2fSMichael Klier *
180413c08e2fSMichael Klier * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
180513c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
18063272d797SAndreas Gohr *
18073272d797SAndreas Gohr * @param int  $mem    Size of memory you want to allocate in bytes
1808140cfbcdSGerrit Uitslag * @param int  $bytes  already allocated memory (see above)
18093272d797SAndreas Gohr * @return bool
181013c08e2fSMichael Klier */
1811d868eb89SAndreas Gohrfunction is_mem_available($mem, $bytes = 1_048_576)
1812d868eb89SAndreas Gohr{
181313c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
181413c08e2fSMichael Klier    if (empty($limit)) return true; // no limit set!
1815985d6187SElenchus    if ($limit == -1) return true; // unlimited
181613c08e2fSMichael Klier
181713c08e2fSMichael Klier    // parse limit to bytes
181813c08e2fSMichael Klier    $limit = php_to_byte($limit);
181913c08e2fSMichael Klier
182013c08e2fSMichael Klier    // get used memory if possible
182113c08e2fSMichael Klier    if (function_exists('memory_get_usage')) {
182213c08e2fSMichael Klier        $used = memory_get_usage();
182349eb6e38SAndreas Gohr    } else {
182449eb6e38SAndreas Gohr        $used = $bytes;
182513c08e2fSMichael Klier    }
182613c08e2fSMichael Klier
182713c08e2fSMichael Klier    if ($used + $mem > $limit) {
182813c08e2fSMichael Klier        return false;
182913c08e2fSMichael Klier    }
183013c08e2fSMichael Klier
183113c08e2fSMichael Klier    return true;
183213c08e2fSMichael Klier}
183313c08e2fSMichael Klier
1834af2408d5SAndreas Gohr/**
1835af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1836af2408d5SAndreas Gohr *
1837af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1838af2408d5SAndreas Gohr *
1839af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1840af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1841140cfbcdSGerrit Uitslag *
1842140cfbcdSGerrit Uitslag * @param string $url url being directed to
1843af2408d5SAndreas Gohr */
1844d868eb89SAndreas Gohrfunction send_redirect($url)
1845d868eb89SAndreas Gohr{
184698ca30d2SAndreas Gohr    $url = stripctl($url); // defend against HTTP Response Splitting
184798ca30d2SAndreas Gohr
1848585bf44eSChristopher Smith    /* @var Input $INPUT */
1849585bf44eSChristopher Smith    global $INPUT;
1850585bf44eSChristopher Smith
18510181f021SAndreas Gohr    //are there any undisplayed messages? keep them in session for display
18520181f021SAndreas Gohr    global $MSG;
18530181f021SAndreas Gohr    if (isset($MSG) && count($MSG) && !defined('NOSESSION')) {
18540181f021SAndreas Gohr        //reopen session, store data and close session again
18550181f021SAndreas Gohr        @session_start();
18560181f021SAndreas Gohr        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
18570181f021SAndreas Gohr    }
18580181f021SAndreas Gohr
1859d4869846SAndreas Gohr    // always close the session
1860d4869846SAndreas Gohr    session_write_close();
1861d4869846SAndreas Gohr
1862af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
18637d34963bSAndreas Gohr    if (
18647d34963bSAndreas Gohr        $INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1865585bf44eSChristopher Smith        (strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) &&
1866585bf44eSChristopher Smith        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
18673272d797SAndreas Gohr        $matches[1] < 6
18683272d797SAndreas Gohr    ) {
1869af2408d5SAndreas Gohr        header('Refresh: 0;url=' . $url);
1870af2408d5SAndreas Gohr    } else {
1871af2408d5SAndreas Gohr        header('Location: ' . $url);
1872af2408d5SAndreas Gohr    }
187381781cb6SAndreas Gohr
1874572dc222SLarsDW223    // no exits during unit tests
187527c0c399SAndreas Gohr    if (defined('DOKU_UNITTEST')) {
187627c0c399SAndreas Gohr        // pass info about the redirect back to the test suite
187727c0c399SAndreas Gohr        $testRequest = TestRequest::getRunning();
187827c0c399SAndreas Gohr        if ($testRequest !== null) {
187927c0c399SAndreas Gohr            $testRequest->addData('send_redirect', $url);
188027c0c399SAndreas Gohr        }
1881572dc222SLarsDW223        return;
1882572dc222SLarsDW223    }
188327c0c399SAndreas Gohr
1884af2408d5SAndreas Gohr    exit;
1885af2408d5SAndreas Gohr}
1886af2408d5SAndreas Gohr
18875b75cd1fSAdrian Lang/**
18885b75cd1fSAdrian Lang * Validate a value using a set of valid values
18895b75cd1fSAdrian Lang *
18905b75cd1fSAdrian Lang * This function checks whether a specified value is set and in the array
18915b75cd1fSAdrian Lang * $valid_values. If not, the function returns a default value or, if no
18925b75cd1fSAdrian Lang * default is specified, throws an exception.
18935b75cd1fSAdrian Lang *
18945b75cd1fSAdrian Lang * @param string $param        The name of the parameter
18955b75cd1fSAdrian Lang * @param array  $valid_values A set of valid values; Optionally a default may
18965b75cd1fSAdrian Lang *                             be marked by the key “default”.
18975b75cd1fSAdrian Lang * @param array  $array        The array containing the value (typically $_POST
18985b75cd1fSAdrian Lang *                             or $_GET)
18995b75cd1fSAdrian Lang * @param string $exc          The text of the raised exception
19005b75cd1fSAdrian Lang *
19013272d797SAndreas Gohr * @throws Exception
19023272d797SAndreas Gohr * @return mixed
19035b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
19045b75cd1fSAdrian Lang */
1905d868eb89SAndreas Gohrfunction valid_input_set($param, $valid_values, $array, $exc = '')
1906d868eb89SAndreas Gohr{
19075b75cd1fSAdrian Lang    if (isset($array[$param]) && in_array($array[$param], $valid_values)) {
19085b75cd1fSAdrian Lang        return $array[$param];
19095b75cd1fSAdrian Lang    } elseif (isset($valid_values['default'])) {
19105b75cd1fSAdrian Lang        return $valid_values['default'];
19115b75cd1fSAdrian Lang    } else {
19125b75cd1fSAdrian Lang        throw new Exception($exc);
19135b75cd1fSAdrian Lang    }
19145b75cd1fSAdrian Lang}
19155b75cd1fSAdrian Lang
191663703ba5SAndreas Gohr/**
191763703ba5SAndreas Gohr * Read a preference from the DokuWiki cookie
1918646a531aSChristopher Smith * (remembering both keys & values are urlencoded)
1919140cfbcdSGerrit Uitslag *
1920140cfbcdSGerrit Uitslag * @param string $pref     preference key
1921b4b6c9a1SGerrit Uitslag * @param mixed  $default  value returned when preference not found
1922140cfbcdSGerrit Uitslag * @return string preference value
192363703ba5SAndreas Gohr */
1924d868eb89SAndreas Gohrfunction get_doku_pref($pref, $default)
1925d868eb89SAndreas Gohr{
1926646a531aSChristopher Smith    $enc_pref = urlencode($pref);
192706c9ee33SMarius van Witzenburg    if (isset($_COOKIE['DOKU_PREFS']) && strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
1928554a8c9fSAdrian Lang        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
192963703ba5SAndreas Gohr        $cnt   = count($parts);
19301c3eca7dSPhy
19311c3eca7dSPhy        // due to #2721 there might be duplicate entries,
19321c3eca7dSPhy        // so we read from the end
19331c3eca7dSPhy        for ($i = $cnt - 2; $i >= 0; $i -= 2) {
193424870174SAndreas Gohr            if ($parts[$i] === $enc_pref) {
1935646a531aSChristopher Smith                return urldecode($parts[$i + 1]);
1936554a8c9fSAdrian Lang            }
1937554a8c9fSAdrian Lang        }
1938554a8c9fSAdrian Lang    }
1939554a8c9fSAdrian Lang    return $default;
1940554a8c9fSAdrian Lang}
1941554a8c9fSAdrian Lang
19423c94d07bSAnika Henke/**
19433c94d07bSAnika Henke * Add a preference to the DokuWiki cookie
194436ec377eSChristopher Smith * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
19453a970889SAnika Henke * Remove it by setting $val to false
1946140cfbcdSGerrit Uitslag *
1947140cfbcdSGerrit Uitslag * @param string $pref  preference key
1948140cfbcdSGerrit Uitslag * @param string $val   preference value
19493c94d07bSAnika Henke */
1950d868eb89SAndreas Gohrfunction set_doku_pref($pref, $val)
1951d868eb89SAndreas Gohr{
19523c94d07bSAnika Henke    global $conf;
19533c94d07bSAnika Henke    $orig = get_doku_pref($pref, false);
19543c94d07bSAnika Henke    $cookieVal = '';
19553c94d07bSAnika Henke
19561c3eca7dSPhy    if ($orig !== false && ($orig !== $val)) {
19573c94d07bSAnika Henke        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
19583c94d07bSAnika Henke        $cnt   = count($parts);
195936ec377eSChristopher Smith        // urlencode $pref for the comparison
196036ec377eSChristopher Smith        $enc_pref = rawurlencode($pref);
19611c3eca7dSPhy        $seen = false;
19623c94d07bSAnika Henke        for ($i = 0; $i < $cnt; $i += 2) {
196324870174SAndreas Gohr            if ($parts[$i] === $enc_pref) {
19641c3eca7dSPhy                if (!$seen) {
19653a970889SAnika Henke                    if ($val !== false) {
1966bf8f8509SAndreas Gohr                        $parts[$i + 1] = rawurlencode($val ?? '');
19673a970889SAnika Henke                    } else {
19683a970889SAnika Henke                        unset($parts[$i]);
19693a970889SAnika Henke                        unset($parts[$i + 1]);
19703a970889SAnika Henke                    }
19711c3eca7dSPhy                    $seen = true;
19721c3eca7dSPhy                } else {
19731c3eca7dSPhy                    // no break because we want to remove duplicate entries
19741c3eca7dSPhy                    unset($parts[$i]);
19751c3eca7dSPhy                    unset($parts[$i + 1]);
19761c3eca7dSPhy                }
19773c94d07bSAnika Henke            }
19783c94d07bSAnika Henke        }
19793c94d07bSAnika Henke        $cookieVal = implode('#', $parts);
19801c3eca7dSPhy    } elseif ($orig === false && $val !== false) {
1981c10f256aSDamien Regad        $cookieVal = (isset($_COOKIE['DOKU_PREFS']) ? $_COOKIE['DOKU_PREFS'] . '#' : '') .
198264159a61SAndreas Gohr            rawurlencode($pref) . '#' . rawurlencode($val);
19833c94d07bSAnika Henke    }
19843c94d07bSAnika Henke
198575e4dd8aSGerrit Uitslag    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
19865833995aSPhy    if (defined('DOKU_UNITTEST')) {
19875833995aSPhy        $_COOKIE['DOKU_PREFS'] = $cookieVal;
19885833995aSPhy    } else {
1989bf8392ebSAndreas Gohr        setcookie('DOKU_PREFS', $cookieVal, [
1990bf8392ebSAndreas Gohr            'expires' => time() + 365 * 24 * 3600,
1991bf8392ebSAndreas Gohr            'path' => $cookieDir,
1992bf8392ebSAndreas Gohr            'secure' => ($conf['securecookie'] && is_ssl()),
1993bf8392ebSAndreas Gohr            'samesite' => 'Lax'
1994bf8392ebSAndreas Gohr        ]);
19953c94d07bSAnika Henke    }
19963c94d07bSAnika Henke}
19973c94d07bSAnika Henke
1998f8fb2d18SAndreas Gohr/**
1999f8fb2d18SAndreas Gohr * Strips source mapping declarations from given text #601
2000f8fb2d18SAndreas Gohr *
200142ea7f44SGerrit Uitslag * @param string &$text reference to the CSS or JavaScript code to clean
2002f8fb2d18SAndreas Gohr */
2003d868eb89SAndreas Gohrfunction stripsourcemaps(&$text)
2004d868eb89SAndreas Gohr{
2005f8fb2d18SAndreas Gohr    $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text);
2006f8fb2d18SAndreas Gohr}
2007f8fb2d18SAndreas Gohr
20083c27983bSAndreas Gohr/**
200971de5572SAndreas Gohr * Returns the contents of a given SVG file for embedding
20103c27983bSAndreas Gohr *
20113c27983bSAndreas Gohr * Inlining SVGs saves on HTTP requests and more importantly allows for styling them through
20123c27983bSAndreas Gohr * CSS. However it should used with small SVGs only. The $maxsize setting ensures only small
20133c27983bSAndreas Gohr * files are embedded.
20143c27983bSAndreas Gohr *
201571de5572SAndreas Gohr * This strips unneeded headers, comments and newline. The result is not a vaild standalone SVG!
201671de5572SAndreas Gohr *
20173c27983bSAndreas Gohr * @param string $file full path to the SVG file
20183c27983bSAndreas Gohr * @param int $maxsize maximum allowed size for the SVG to be embedded
201971de5572SAndreas Gohr * @return string|false the SVG content, false if the file couldn't be loaded
20203c27983bSAndreas Gohr */
2021d868eb89SAndreas Gohrfunction inlineSVG($file, $maxsize = 2048)
2022d868eb89SAndreas Gohr{
20233c27983bSAndreas Gohr    $file = trim($file);
20243c27983bSAndreas Gohr    if ($file === '') return false;
20253c27983bSAndreas Gohr    if (!file_exists($file)) return false;
20263c27983bSAndreas Gohr    if (filesize($file) > $maxsize) return false;
20273c27983bSAndreas Gohr    if (!is_readable($file)) return false;
20283c27983bSAndreas Gohr    $content = file_get_contents($file);
20290849fa88SAndreas Gohr    $content = preg_replace('/<!--.*?(-->)/s', '', $content); // comments
20300849fa88SAndreas Gohr    $content = preg_replace('/<\?xml .*?\?>/i', '', $content); // xml header
20310849fa88SAndreas Gohr    $content = preg_replace('/<!DOCTYPE .*?>/i', '', $content); // doc type
20320849fa88SAndreas Gohr    $content = preg_replace('/>\s+</s', '><', $content); // newlines between tags
20333c27983bSAndreas Gohr    $content = trim($content);
20346c16a3a9Sfiwswe    if (!str_starts_with($content, '<svg ')) return false;
203571de5572SAndreas Gohr    return $content;
20363c27983bSAndreas Gohr}
20373c27983bSAndreas Gohr
2038e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
2039