xref: /dokuwiki/inc/common.php (revision d868eb89f182718a31113373a6272670bd7f8012)
1ed7b5f09Sandi<?php
215fae107Sandi/**
315fae107Sandi * Common DokuWiki functions
415fae107Sandi *
515fae107Sandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
615fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
715fae107Sandi */
824870174SAndreas Gohruse dokuwiki\PassHash;
924870174SAndreas Gohruse dokuwiki\Draft;
1024870174SAndreas Gohruse dokuwiki\Utf8\Clean;
1124870174SAndreas Gohruse dokuwiki\Utf8\PhpString;
1224870174SAndreas Gohruse dokuwiki\Utf8\Conversion;
130db5771eSMichael Großeuse dokuwiki\Cache\CacheInstructions;
140db5771eSMichael Großeuse dokuwiki\Cache\CacheRenderer;
150c3a5702SAndreas Gohruse dokuwiki\ChangeLog\PageChangeLog;
16b24e9c4aSSatoshi Saharause dokuwiki\File\PageFile;
1766f4cdd4SSatoshi Saharause dokuwiki\Logger;
18704a815fSMichael Großeuse dokuwiki\Subscriptions\PageSubscriptionSender;
1975d66495SMichael Großeuse dokuwiki\Subscriptions\SubscriberManager;
20e1d9dcc8SAndreas Gohruse dokuwiki\Extension\AuthPlugin;
21e1d9dcc8SAndreas Gohruse dokuwiki\Extension\Event;
220c3a5702SAndreas Gohr
23f3f0262cSandi/**
24d5197206Schris * Wrapper around htmlspecialchars()
25d5197206Schris *
26d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
27d5197206Schris * @see    htmlspecialchars()
28140cfbcdSGerrit Uitslag *
29140cfbcdSGerrit Uitslag * @param string $string the string being converted
30140cfbcdSGerrit Uitslag * @return string converted string
31d5197206Schris */
32*d868eb89SAndreas Gohrfunction hsc($string)
33*d868eb89SAndreas 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 */
74*d868eb89SAndreas Gohrfunction blank(&$in, $trim = false)
75*d868eb89SAndreas 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/**
85d5197206Schris * print a newline terminated string
86d5197206Schris *
87d5197206Schris * You can give an indention as optional parameter
88d5197206Schris *
89d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
90140cfbcdSGerrit Uitslag *
91140cfbcdSGerrit Uitslag * @param string $string  line of text
92140cfbcdSGerrit Uitslag * @param int    $indent  number of spaces indention
93d5197206Schris */
94*d868eb89SAndreas Gohrfunction ptln($string, $indent = 0)
95*d868eb89SAndreas Gohr{
9625ec097bSChris Smith    echo str_repeat(' ', $indent)."$string\n";
9702b0b681SAndreas Gohr}
9802b0b681SAndreas Gohr
9902b0b681SAndreas Gohr/**
10002b0b681SAndreas Gohr * strips control characters (<32) from the given string
10102b0b681SAndreas Gohr *
10202b0b681SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
103140cfbcdSGerrit Uitslag *
10442ea7f44SGerrit Uitslag * @param string $string being stripped
105140cfbcdSGerrit Uitslag * @return string
10602b0b681SAndreas Gohr */
107*d868eb89SAndreas Gohrfunction stripctl($string)
108*d868eb89SAndreas Gohr{
10902b0b681SAndreas Gohr    return preg_replace('/[\x00-\x1F]+/s', '', $string);
110d5197206Schris}
111d5197206Schris
112d5197206Schris/**
113634d7150SAndreas Gohr * Return a secret token to be used for CSRF attack prevention
114634d7150SAndreas Gohr *
115634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
116634d7150SAndreas Gohr * @link    http://en.wikipedia.org/wiki/Cross-site_request_forgery
117634d7150SAndreas Gohr * @link    http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
11842ea7f44SGerrit Uitslag *
119634d7150SAndreas Gohr * @return  string
120634d7150SAndreas Gohr */
121*d868eb89SAndreas Gohrfunction getSecurityToken()
122*d868eb89SAndreas Gohr{
123585bf44eSChristopher Smith    /** @var Input $INPUT */
124585bf44eSChristopher Smith    global $INPUT;
1253680e2cdSAndreas Gohr
1263680e2cdSAndreas Gohr    $user = $INPUT->server->str('REMOTE_USER');
1273680e2cdSAndreas Gohr    $session = session_id();
1283680e2cdSAndreas Gohr
1293680e2cdSAndreas Gohr    // CSRF checks are only for logged in users - do not generate for anonymous
1303680e2cdSAndreas Gohr    if(trim($user) == '' || trim($session) == '') return '';
13124870174SAndreas Gohr    return PassHash::hmac('md5', $session.$user, auth_cookiesalt());
132634d7150SAndreas Gohr}
133634d7150SAndreas Gohr
134634d7150SAndreas Gohr/**
135634d7150SAndreas Gohr * Check the secret CSRF token
136140cfbcdSGerrit Uitslag *
137140cfbcdSGerrit Uitslag * @param null|string $token security token or null to read it from request variable
138140cfbcdSGerrit Uitslag * @return bool success if the token matched
139634d7150SAndreas Gohr */
140*d868eb89SAndreas Gohrfunction checkSecurityToken($token = null)
141*d868eb89SAndreas Gohr{
142585bf44eSChristopher Smith    /** @var Input $INPUT */
1437d01a0eaSTom N Harris    global $INPUT;
144585bf44eSChristopher Smith    if(!$INPUT->server->str('REMOTE_USER')) return true; // no logged in user, no need for a check
145df97eaacSAndreas Gohr
1467d01a0eaSTom N Harris    if(is_null($token)) $token = $INPUT->str('sectok');
147634d7150SAndreas Gohr    if(getSecurityToken() != $token) {
148634d7150SAndreas Gohr        msg('Security Token did not match. Possible CSRF attack.', -1);
149634d7150SAndreas Gohr        return false;
150634d7150SAndreas Gohr    }
151634d7150SAndreas Gohr    return true;
152634d7150SAndreas Gohr}
153634d7150SAndreas Gohr
154634d7150SAndreas Gohr/**
155634d7150SAndreas Gohr * Print a hidden form field with a secret CSRF token
156634d7150SAndreas Gohr *
157634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
158140cfbcdSGerrit Uitslag *
159140cfbcdSGerrit Uitslag * @param bool $print  if true print the field, otherwise html of the field is returned
16042ea7f44SGerrit Uitslag * @return string html of hidden form field
161634d7150SAndreas Gohr */
162*d868eb89SAndreas Gohrfunction formSecurityToken($print = true)
163*d868eb89SAndreas Gohr{
1642404d0edSAnika Henke    $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
1653272d797SAndreas Gohr    if($print) echo $ret;
166634d7150SAndreas Gohr    return $ret;
167634d7150SAndreas Gohr}
168634d7150SAndreas Gohr
169634d7150SAndreas Gohr/**
1701015a57dSChristopher Smith * Determine basic information for a request of $id
17115fae107Sandi *
17215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1737e87a794SChristopher Smith * @author Chris Smith <chris@jalakai.co.uk>
174140cfbcdSGerrit Uitslag *
175140cfbcdSGerrit Uitslag * @param string $id         pageid
176140cfbcdSGerrit Uitslag * @param bool   $htmlClient add info about whether is mobile browser
177140cfbcdSGerrit Uitslag * @return array with info for a request of $id
178140cfbcdSGerrit Uitslag *
179f3f0262cSandi */
180*d868eb89SAndreas Gohrfunction basicinfo($id, $htmlClient = true)
181*d868eb89SAndreas Gohr{
182f3f0262cSandi    global $USERINFO;
183585bf44eSChristopher Smith    /* @var Input $INPUT */
184585bf44eSChristopher Smith    global $INPUT;
1856afe8dcaSchris
186c66972f2SAdrian Lang    // set info about manager/admin status.
18724870174SAndreas Gohr    $info = [];
188c66972f2SAdrian Lang    $info['isadmin']   = false;
189c66972f2SAdrian Lang    $info['ismanager'] = false;
190585bf44eSChristopher Smith    if($INPUT->server->has('REMOTE_USER')) {
191f3f0262cSandi        $info['userinfo']   = $USERINFO;
1921015a57dSChristopher Smith        $info['perm']       = auth_quickaclcheck($id);
193585bf44eSChristopher Smith        $info['client']     = $INPUT->server->str('REMOTE_USER');
19417ee7f66SAndreas Gohr
195f8cc712eSAndreas Gohr        if($info['perm'] == AUTH_ADMIN) {
196f8cc712eSAndreas Gohr            $info['isadmin']   = true;
197f8cc712eSAndreas Gohr            $info['ismanager'] = true;
198f8cc712eSAndreas Gohr        } elseif(auth_ismanager()) {
199f8cc712eSAndreas Gohr            $info['ismanager'] = true;
200f8cc712eSAndreas Gohr        }
201f8cc712eSAndreas Gohr
20217ee7f66SAndreas Gohr        // if some outside auth were used only REMOTE_USER is set
203a58fcbbcSAndreas Gohr        if(empty($info['userinfo']['name'])) {
204585bf44eSChristopher Smith            $info['userinfo']['name'] = $INPUT->server->str('REMOTE_USER');
20517ee7f66SAndreas Gohr        }
206ee4c4a1bSAndreas Gohr
207f3f0262cSandi    } else {
2081015a57dSChristopher Smith        $info['perm']       = auth_aclcheck($id, '', null);
209ee4c4a1bSAndreas Gohr        $info['client']     = clientIP(true);
210f3f0262cSandi    }
211f3f0262cSandi
2121015a57dSChristopher Smith    $info['namespace'] = getNS($id);
2131015a57dSChristopher Smith
2141015a57dSChristopher Smith    // mobile detection
2151015a57dSChristopher Smith    if ($htmlClient) {
2161015a57dSChristopher Smith        $info['ismobile'] = clientismobile();
2171015a57dSChristopher Smith    }
2181015a57dSChristopher Smith
2191015a57dSChristopher Smith    return $info;
2201015a57dSChristopher Smith }
2211015a57dSChristopher Smith
2221015a57dSChristopher Smith/**
2231015a57dSChristopher Smith * Return info about the current document as associative
2241015a57dSChristopher Smith * array.
2251015a57dSChristopher Smith *
2261015a57dSChristopher Smith * @author Andreas Gohr <andi@splitbrain.org>
227140cfbcdSGerrit Uitslag *
228140cfbcdSGerrit Uitslag * @return array with info about current document
2291015a57dSChristopher Smith */
230*d868eb89SAndreas Gohrfunction pageinfo()
231*d868eb89SAndreas Gohr{
2321015a57dSChristopher Smith    global $ID;
2331015a57dSChristopher Smith    global $REV;
2341015a57dSChristopher Smith    global $RANGE;
2351015a57dSChristopher Smith    global $lang;
236585bf44eSChristopher Smith    /* @var Input $INPUT */
237585bf44eSChristopher Smith    global $INPUT;
2381015a57dSChristopher Smith
2391015a57dSChristopher Smith    $info = basicinfo($ID);
2401015a57dSChristopher Smith
2411015a57dSChristopher Smith    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
2421015a57dSChristopher Smith    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
2431015a57dSChristopher Smith    $info['id']  = $ID;
2441015a57dSChristopher Smith    $info['rev'] = $REV;
2451015a57dSChristopher Smith
24675d66495SMichael Große    $subManager = new SubscriberManager();
24775d66495SMichael Große    $info['subscribed'] = $subManager->userSubscription();
2487e87a794SChristopher Smith
249f3f0262cSandi    $info['locked']     = checklock($ID);
250317a04c4SSatoshi Sahara    $info['filepath']   = wikiFN($ID);
25179e79377SAndreas Gohr    $info['exists']     = file_exists($info['filepath']);
25201c9a118SAndreas Gohr    $info['currentrev'] = @filemtime($info['filepath']);
2535ec96136SSatoshi Sahara
2542ca9d91cSBen Coburn    if ($REV) {
2552ca9d91cSBen Coburn        //check if current revision was meant
25601c9a118SAndreas Gohr        if ($info['exists'] && ($info['currentrev'] == $REV)) {
2572ca9d91cSBen Coburn            $REV = '';
2587b3a6803SAndreas Gohr        } elseif ($RANGE) {
2597b3a6803SAndreas Gohr            //section editing does not work with old revisions!
2607b3a6803SAndreas Gohr            $REV   = '';
2617b3a6803SAndreas Gohr            $RANGE = '';
2627b3a6803SAndreas Gohr            msg($lang['nosecedit'], 0);
2632ca9d91cSBen Coburn        } else {
2642ca9d91cSBen Coburn            //really use old revision
265317a04c4SSatoshi Sahara            $info['filepath'] = wikiFN($ID, $REV);
26679e79377SAndreas Gohr            $info['exists']   = file_exists($info['filepath']);
267f3f0262cSandi        }
268f3f0262cSandi    }
269c112d578Sandi    $info['rev'] = $REV;
270f3f0262cSandi    if ($info['exists']) {
271252acce3SSatoshi Sahara        $info['writable'] = (is_writable($info['filepath']) && $info['perm'] >= AUTH_EDIT);
272f3f0262cSandi    } else {
273f3f0262cSandi        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
274f3f0262cSandi    }
27550e988b1SAndreas Gohr    $info['editable'] = ($info['writable'] && empty($info['locked']));
276f3f0262cSandi    $info['lastmod']  = @filemtime($info['filepath']);
277f3f0262cSandi
27871726d78SBen Coburn    //load page meta data
27971726d78SBen Coburn    $info['meta'] = p_get_metadata($ID);
28071726d78SBen Coburn
281652610a2Sandi    //who's the editor
282047bad06SGerrit Uitslag    $pagelog = new PageChangeLog($ID, 1024);
283652610a2Sandi    if ($REV) {
284f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($REV);
28524870174SAndreas Gohr    } elseif (!empty($info['meta']['last_change']) && is_array($info['meta']['last_change'])) {
286aa27cf05SAndreas Gohr        $revinfo = $info['meta']['last_change'];
287aa27cf05SAndreas Gohr    } else {
288f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($info['lastmod']);
289cd00a034SBen Coburn        // cache most recent changelog line in metadata if missing and still valid
290cd00a034SBen Coburn        if ($revinfo !== false) {
291cd00a034SBen Coburn            $info['meta']['last_change'] = $revinfo;
29224870174SAndreas Gohr            p_set_metadata($ID, ['last_change' => $revinfo]);
293cd00a034SBen Coburn        }
294cd00a034SBen Coburn    }
295cd00a034SBen Coburn    //and check for an external edit
296cd00a034SBen Coburn    if ($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
297cd00a034SBen Coburn        // cached changelog line no longer valid
298cd00a034SBen Coburn        $revinfo                     = false;
299cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
30024870174SAndreas Gohr        p_set_metadata($ID, ['last_change' => $revinfo]);
301652610a2Sandi    }
302bb4866bdSchris
3030a444b5aSPhy    if ($revinfo !== false) {
304652610a2Sandi        $info['ip']   = $revinfo['ip'];
305652610a2Sandi        $info['user'] = $revinfo['user'];
306652610a2Sandi        $info['sum']  = $revinfo['sum'];
30771726d78SBen Coburn        // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
308ebf1501fSBen Coburn        // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
30959f257aeSchris
310252acce3SSatoshi Sahara        $info['editor'] = $revinfo['user'] ?: $revinfo['ip'];
3110a444b5aSPhy    } else {
3120a444b5aSPhy        $info['ip']     = null;
3130a444b5aSPhy        $info['user']   = null;
3140a444b5aSPhy        $info['sum']    = null;
3150a444b5aSPhy        $info['editor'] = null;
3160a444b5aSPhy    }
317652610a2Sandi
318ee4c4a1bSAndreas Gohr    // draft
31924870174SAndreas Gohr    $draft = new Draft($ID, $info['client']);
3200aabe6f8SMichael Große    if ($draft->isDraftAvailable()) {
3210aabe6f8SMichael Große        $info['draft'] = $draft->getDraftFilename();
322ee4c4a1bSAndreas Gohr    }
323ee4c4a1bSAndreas Gohr
3241015a57dSChristopher Smith    return $info;
3251015a57dSChristopher Smith}
3261015a57dSChristopher Smith
3271015a57dSChristopher Smith/**
3280c39d46cSMichael Große * Initialize and/or fill global $JSINFO with some basic info to be given to javascript
3290c39d46cSMichael Große */
330*d868eb89SAndreas Gohrfunction jsinfo()
331*d868eb89SAndreas Gohr{
3320c39d46cSMichael Große    global $JSINFO, $ID, $INFO, $ACT;
3330c39d46cSMichael Große
3340c39d46cSMichael Große    if (!is_array($JSINFO)) {
3350c39d46cSMichael Große        $JSINFO = [];
3360c39d46cSMichael Große    }
3370c39d46cSMichael Große    //export minimal info to JS, plugins can add more
3380c39d46cSMichael Große    $JSINFO['id']                    = $ID;
33968491db9SPhy    $JSINFO['namespace']             = isset($INFO) ? (string) $INFO['namespace'] : '';
3400c39d46cSMichael Große    $JSINFO['ACT']                   = act_clean($ACT);
3410c39d46cSMichael Große    $JSINFO['useHeadingNavigation']  = (int) useHeading('navigation');
3420c39d46cSMichael Große    $JSINFO['useHeadingContent']     = (int) useHeading('content');
3430c39d46cSMichael Große}
3440c39d46cSMichael Große
3450c39d46cSMichael Große/**
3461015a57dSChristopher Smith * Return information about the current media item as an associative array.
347140cfbcdSGerrit Uitslag *
348140cfbcdSGerrit Uitslag * @return array with info about current media item
3491015a57dSChristopher Smith */
350*d868eb89SAndreas Gohrfunction mediainfo()
351*d868eb89SAndreas Gohr{
3521015a57dSChristopher Smith    global $NS;
3531015a57dSChristopher Smith    global $IMG;
3541015a57dSChristopher Smith
3551015a57dSChristopher Smith    $info = basicinfo("$NS:*");
3561015a57dSChristopher Smith    $info['image'] = $IMG;
3571c548ebeSAndreas Gohr
358f3f0262cSandi    return $info;
359f3f0262cSandi}
360f3f0262cSandi
361f3f0262cSandi/**
3622684e50aSAndreas Gohr * Build an string of URL parameters
3632684e50aSAndreas Gohr *
3642684e50aSAndreas Gohr * @author Andreas Gohr
365140cfbcdSGerrit Uitslag *
366140cfbcdSGerrit Uitslag * @param array  $params    array with key-value pairs
367140cfbcdSGerrit Uitslag * @param string $sep       series of pairs are separated by this character
368140cfbcdSGerrit Uitslag * @return string query string
3692684e50aSAndreas Gohr */
370*d868eb89SAndreas Gohrfunction buildURLparams($params, $sep = '&amp;')
371*d868eb89SAndreas Gohr{
3722684e50aSAndreas Gohr    $url = '';
3732684e50aSAndreas Gohr    $amp = false;
3742684e50aSAndreas Gohr    foreach($params as $key => $val) {
375b174aeaeSchris        if($amp) $url .= $sep;
3762684e50aSAndreas Gohr
37785e6871fSAdrian Lang        $url .= rawurlencode($key).'=';
3783a50618cSgweissbach        $url .= rawurlencode((string) $val);
3792684e50aSAndreas Gohr        $amp = true;
3802684e50aSAndreas Gohr    }
3812684e50aSAndreas Gohr    return $url;
3822684e50aSAndreas Gohr}
3832684e50aSAndreas Gohr
3842684e50aSAndreas Gohr/**
3852684e50aSAndreas Gohr * Build an string of html tag attributes
3862684e50aSAndreas Gohr *
3877bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
3887bff22c0SAndreas Gohr *
3892684e50aSAndreas Gohr * @author Andreas Gohr
390140cfbcdSGerrit Uitslag *
391140cfbcdSGerrit Uitslag * @param array $params           array with (attribute name-attribute value) pairs
392246d3337SMichael Große * @param bool  $skipEmptyStrings skip empty string values?
393140cfbcdSGerrit Uitslag * @return string
3942684e50aSAndreas Gohr */
395*d868eb89SAndreas Gohrfunction buildAttributes($params, $skipEmptyStrings = false)
396*d868eb89SAndreas Gohr{
3972684e50aSAndreas Gohr    $url   = '';
3989063ec14SAdrian Lang    $white = false;
3992684e50aSAndreas Gohr    foreach($params as $key => $val) {
4002401f18dSSyntaxseed        if($key[0] == '_') continue;
401246d3337SMichael Große        if($val === '' && $skipEmptyStrings) continue;
4029063ec14SAdrian Lang        if($white) $url .= ' ';
4037bff22c0SAndreas Gohr
4042684e50aSAndreas Gohr        $url .= $key.'="';
405f7711f2bSAndreas Gohr        $url .= hsc($val);
4062684e50aSAndreas Gohr        $url .= '"';
4079063ec14SAdrian Lang        $white = true;
4082684e50aSAndreas Gohr    }
4092684e50aSAndreas Gohr    return $url;
4102684e50aSAndreas Gohr}
4112684e50aSAndreas Gohr
4122684e50aSAndreas Gohr/**
41315fae107Sandi * This builds the breadcrumb trail and returns it as array
41415fae107Sandi *
41515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
416140cfbcdSGerrit Uitslag *
417e3710957SGerrit Uitslag * @return string[] with the data: array(pageid=>name, ... )
418f3f0262cSandi */
419*d868eb89SAndreas Gohrfunction breadcrumbs()
420*d868eb89SAndreas Gohr{
4218746e727Sandi    // we prepare the breadcrumbs early for quick session closing
4228746e727Sandi    static $crumbs = null;
4238746e727Sandi    if($crumbs != null) return $crumbs;
4248746e727Sandi
425f3f0262cSandi    global $ID;
426f3f0262cSandi    global $ACT;
427f3f0262cSandi    global $conf;
4280ea5ebb4SB_S666    global $INFO;
429f3f0262cSandi
430f3f0262cSandi    //first visit?
43124870174SAndreas Gohr    $crumbs = $_SESSION[DOKU_COOKIE]['bc'] ?? [];
4325603d3c1SHenry Pan    //we only save on show and existing visible readable wiki documents
433a77f5846Sjan    $file = wikiFN($ID);
4345603d3c1SHenry Pan    if($ACT != 'show' || $INFO['perm'] < AUTH_READ || isHiddenPage($ID) || !file_exists($file)) {
435e71ce681SAndreas Gohr        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
436f3f0262cSandi        return $crumbs;
437f3f0262cSandi    }
438a77f5846Sjan
439a77f5846Sjan    // page names
4401a84a0f3SAnika Henke    $name = noNSorNS($ID);
441fe9ec250SChris Smith    if(useHeading('navigation')) {
442a77f5846Sjan        // get page title
44367c15eceSMichael Hamann        $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
444a77f5846Sjan        if($title) {
445a77f5846Sjan            $name = $title;
446a77f5846Sjan        }
447a77f5846Sjan    }
448a77f5846Sjan
449f3f0262cSandi    //remove ID from array
450a77f5846Sjan    if(isset($crumbs[$ID])) {
451a77f5846Sjan        unset($crumbs[$ID]);
452f3f0262cSandi    }
453f3f0262cSandi
454f3f0262cSandi    //add to array
455a77f5846Sjan    $crumbs[$ID] = $name;
456f3f0262cSandi    //reduce size
457f3f0262cSandi    while(count($crumbs) > $conf['breadcrumbs']) {
458f3f0262cSandi        array_shift($crumbs);
459f3f0262cSandi    }
460f3f0262cSandi    //save to session
461e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
462f3f0262cSandi    return $crumbs;
463f3f0262cSandi}
464f3f0262cSandi
465f3f0262cSandi/**
46615fae107Sandi * Filter for page IDs
46715fae107Sandi *
468f3f0262cSandi * This is run on a ID before it is outputted somewhere
469f3f0262cSandi * currently used to replace the colon with something else
470907f24f7SAndreas Gohr * on Windows (non-IIS) systems and to have proper URL encoding
471907f24f7SAndreas Gohr *
472977aa967SAndreas Gohr * See discussions at https://github.com/dokuwiki/dokuwiki/pull/84 and
473977aa967SAndreas Gohr * https://github.com/dokuwiki/dokuwiki/pull/173 why we use a whitelist of
474907f24f7SAndreas Gohr * unaffected servers instead of blacklisting affected servers here.
47515fae107Sandi *
47649c713a3Sandi * Urlencoding is ommitted when the second parameter is false
47749c713a3Sandi *
47815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
479140cfbcdSGerrit Uitslag *
480140cfbcdSGerrit Uitslag * @param string $id pageid being filtered
481140cfbcdSGerrit Uitslag * @param bool   $ue apply urlencoding?
482140cfbcdSGerrit Uitslag * @return string
483f3f0262cSandi */
484*d868eb89SAndreas Gohrfunction idfilter($id, $ue = true)
485*d868eb89SAndreas Gohr{
486f3f0262cSandi    global $conf;
487585bf44eSChristopher Smith    /* @var Input $INPUT */
488585bf44eSChristopher Smith    global $INPUT;
489585bf44eSChristopher Smith
490bf8f8509SAndreas Gohr    $id = (string) $id;
491bf8f8509SAndreas Gohr
492f3f0262cSandi    if($conf['useslash'] && $conf['userewrite']) {
493f3f0262cSandi        $id = strtr($id, ':', '/');
494f3f0262cSandi    } elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
49558bedc8aSborekb        $conf['userewrite'] &&
496585bf44eSChristopher Smith        strpos($INPUT->server->str('SERVER_SOFTWARE'), 'Microsoft-IIS') === false
4973272d797SAndreas Gohr    ) {
498f3f0262cSandi        $id = strtr($id, ':', ';');
499f3f0262cSandi    }
50049c713a3Sandi    if($ue) {
501b6c6979fSAndreas Gohr        $id = rawurlencode($id);
502f3f0262cSandi        $id = str_replace('%3A', ':', $id); //keep as colon
503edd95259SGerrit Uitslag        $id = str_replace('%3B', ';', $id); //keep as semicolon
504f3f0262cSandi        $id = str_replace('%2F', '/', $id); //keep as slash
50549c713a3Sandi    }
506f3f0262cSandi    return $id;
507f3f0262cSandi}
508f3f0262cSandi
509f3f0262cSandi/**
510ed7b5f09Sandi * This builds a link to a wikipage
51115fae107Sandi *
5124bc480e5SAndreas Gohr * It handles URL rewriting and adds additional parameters
5136c7843b5Sandi *
51415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
5154bc480e5SAndreas Gohr *
5164bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
5174bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
5184bc480e5SAndreas Gohr * @param bool         $absolute       request an absolute URL instead of relative
5194bc480e5SAndreas Gohr * @param string       $separator      parameter separator
5204bc480e5SAndreas Gohr * @return string
521f3f0262cSandi */
522*d868eb89SAndreas Gohrfunction wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;')
523*d868eb89SAndreas Gohr{
524f3f0262cSandi    global $conf;
52516f15a81SDominik Eckelmann    if(is_array($urlParameters)) {
5264bde2196Slisps        if(isset($urlParameters['rev']) && !$urlParameters['rev']) unset($urlParameters['rev']);
52764159a61SAndreas Gohr        if(isset($urlParameters['at']) && $conf['date_at_format']) {
52864159a61SAndreas Gohr            $urlParameters['at'] = date($conf['date_at_format'], $urlParameters['at']);
52964159a61SAndreas Gohr        }
53016f15a81SDominik Eckelmann        $urlParameters = buildURLparams($urlParameters, $separator);
5316de3759aSAndreas Gohr    } else {
53216f15a81SDominik Eckelmann        $urlParameters = str_replace(',', $separator, $urlParameters);
5336de3759aSAndreas Gohr    }
53416f15a81SDominik Eckelmann    if($id === '') {
53516f15a81SDominik Eckelmann        $id = $conf['start'];
53616f15a81SDominik Eckelmann    }
537f3f0262cSandi    $id = idfilter($id);
53816f15a81SDominik Eckelmann    if($absolute) {
539ed7b5f09Sandi        $xlink = DOKU_URL;
540ed7b5f09Sandi    } else {
541ed7b5f09Sandi        $xlink = DOKU_BASE;
542ed7b5f09Sandi    }
543f3f0262cSandi
5446c7843b5Sandi    if($conf['userewrite'] == 2) {
5456c7843b5Sandi        $xlink .= DOKU_SCRIPT.'/'.$id;
54616f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
5476c7843b5Sandi    } elseif($conf['userewrite']) {
548f3f0262cSandi        $xlink .= $id;
54916f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
55040b5fb5bSPhy    } elseif($id !== '') {
5516c7843b5Sandi        $xlink .= DOKU_SCRIPT.'?id='.$id;
55216f15a81SDominik Eckelmann        if($urlParameters) $xlink .= $separator.$urlParameters;
553bce3726dSAndreas Gohr    } else {
554bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
55516f15a81SDominik Eckelmann        if($urlParameters) $xlink .= '?'.$urlParameters;
556f3f0262cSandi    }
557f3f0262cSandi
558f3f0262cSandi    return $xlink;
559f3f0262cSandi}
560f3f0262cSandi
561f3f0262cSandi/**
562f5c2808fSBen Coburn * This builds a link to an alternate page format
563f5c2808fSBen Coburn *
564f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
565f5c2808fSBen Coburn *
566f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
5674bc480e5SAndreas Gohr * @param string       $id             page id, defaults to start page
5684bc480e5SAndreas Gohr * @param string       $format         the export renderer to use
5694bc480e5SAndreas Gohr * @param string|array $urlParameters  URL parameters, associative array recommended
5704bc480e5SAndreas Gohr * @param bool         $abs            request an absolute URL instead of relative
5714bc480e5SAndreas Gohr * @param string       $sep            parameter separator
5724bc480e5SAndreas Gohr * @return string
573f5c2808fSBen Coburn */
574*d868eb89SAndreas Gohrfunction exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;')
575*d868eb89SAndreas Gohr{
576f5c2808fSBen Coburn    global $conf;
5774bc480e5SAndreas Gohr    if(is_array($urlParameters)) {
5784bc480e5SAndreas Gohr        $urlParameters = buildURLparams($urlParameters, $sep);
579f5c2808fSBen Coburn    } else {
5804bc480e5SAndreas Gohr        $urlParameters = str_replace(',', $sep, $urlParameters);
581f5c2808fSBen Coburn    }
582f5c2808fSBen Coburn
583f5c2808fSBen Coburn    $format = rawurlencode($format);
584f5c2808fSBen Coburn    $id     = idfilter($id);
585f5c2808fSBen Coburn    if($abs) {
586f5c2808fSBen Coburn        $xlink = DOKU_URL;
587f5c2808fSBen Coburn    } else {
588f5c2808fSBen Coburn        $xlink = DOKU_BASE;
589f5c2808fSBen Coburn    }
590f5c2808fSBen Coburn
591f5c2808fSBen Coburn    if($conf['userewrite'] == 2) {
592f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
5934bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
594f5c2808fSBen Coburn    } elseif($conf['userewrite'] == 1) {
595f5c2808fSBen Coburn        $xlink .= '_export/'.$format.'/'.$id;
5964bc480e5SAndreas Gohr        if($urlParameters) $xlink .= '?'.$urlParameters;
597f5c2808fSBen Coburn    } else {
598f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
5994bc480e5SAndreas Gohr        if($urlParameters) $xlink .= $sep.$urlParameters;
600f5c2808fSBen Coburn    }
601f5c2808fSBen Coburn
602f5c2808fSBen Coburn    return $xlink;
603f5c2808fSBen Coburn}
604f5c2808fSBen Coburn
605f5c2808fSBen Coburn/**
6066de3759aSAndreas Gohr * Build a link to a media file
6076de3759aSAndreas Gohr *
6086de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
6098c08db0aSAndreas Gohr *
6108c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
6118c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
6128c08db0aSAndreas Gohr *
6133272d797SAndreas Gohr * @param string  $id     the media file id or URL
6143272d797SAndreas Gohr * @param mixed   $more   string or array with additional parameters
6153272d797SAndreas Gohr * @param bool    $direct link to detail page if false
6163272d797SAndreas Gohr * @param string  $sep    URL parameter separator
6173272d797SAndreas Gohr * @param bool    $abs    Create an absolute URL
6183272d797SAndreas Gohr * @return string
6196de3759aSAndreas Gohr */
620*d868eb89SAndreas Gohrfunction ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false)
621*d868eb89SAndreas Gohr{
6226de3759aSAndreas Gohr    global $conf;
623b9ee6a44SKlap-in    $isexternalimage = media_isexternal($id);
624826d2766SKlap-in    if(!$isexternalimage) {
625826d2766SKlap-in        $id = cleanID($id);
626826d2766SKlap-in    }
627826d2766SKlap-in
6286de3759aSAndreas Gohr    if(is_array($more)) {
6290f4e0092SChristopher Smith        // add token for resized images
63024870174SAndreas Gohr        $w = $more['w'] ?? null;
63124870174SAndreas Gohr        $h = $more['h'] ?? null;
63298fe1ac9SDamien Regad        if($w || $h || $isexternalimage){
633357c9a39SDamien Regad            $more['tok'] = media_get_token($id, $w, $h);
6340f4e0092SChristopher Smith        }
6358c08db0aSAndreas Gohr        // strip defaults for shorter URLs
6368c08db0aSAndreas Gohr        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
637443e135dSChristopher Smith        if(empty($more['w'])) unset($more['w']);
638443e135dSChristopher Smith        if(empty($more['h'])) unset($more['h']);
6398c08db0aSAndreas Gohr        if(isset($more['id']) && $direct) unset($more['id']);
64078b874e6Slisps        if(isset($more['rev']) && !$more['rev']) unset($more['rev']);
641b174aeaeSchris        $more = buildURLparams($more, $sep);
6426de3759aSAndreas Gohr    } else {
64324870174SAndreas Gohr        $matches = [];
644cc036f74SKlap-in        if (preg_match_all('/\b(w|h)=(\d*)\b/', $more, $matches, PREG_SET_ORDER) || $isexternalimage){
64524870174SAndreas Gohr            $resize = ['w'=>0, 'h'=>0];
6465e7db1e2SChristopher Smith            foreach ($matches as $match){
6475e7db1e2SChristopher Smith                $resize[$match[1]] = $match[2];
6485e7db1e2SChristopher Smith            }
649cc036f74SKlap-in            $more .= $more === '' ? '' : $sep;
650cc036f74SKlap-in            $more .= 'tok='.media_get_token($id, $resize['w'], $resize['h']);
6515e7db1e2SChristopher Smith        }
6528c08db0aSAndreas Gohr        $more = str_replace('cache=cache', '', $more); //skip default
6538c08db0aSAndreas Gohr        $more = str_replace(',,', ',', $more);
654b174aeaeSchris        $more = str_replace(',', $sep, $more);
6556de3759aSAndreas Gohr    }
6566de3759aSAndreas Gohr
65755b2b31bSAndreas Gohr    if($abs) {
65855b2b31bSAndreas Gohr        $xlink = DOKU_URL;
65955b2b31bSAndreas Gohr    } else {
6606de3759aSAndreas Gohr        $xlink = DOKU_BASE;
66155b2b31bSAndreas Gohr    }
6626de3759aSAndreas Gohr
6636de3759aSAndreas Gohr    // external URLs are always direct without rewriting
664826d2766SKlap-in    if($isexternalimage) {
6656de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
666cc036f74SKlap-in        $xlink .= '?'.$more;
667b174aeaeSchris        $xlink .= $sep.'media='.rawurlencode($id);
6686de3759aSAndreas Gohr        return $xlink;
6696de3759aSAndreas Gohr    }
6706de3759aSAndreas Gohr
6716de3759aSAndreas Gohr    $id = idfilter($id);
6726de3759aSAndreas Gohr
6736de3759aSAndreas Gohr    // decide on scriptname
6746de3759aSAndreas Gohr    if ($direct) {
6756de3759aSAndreas Gohr        if($conf['userewrite'] == 1) {
6766de3759aSAndreas Gohr            $script = '_media';
6776de3759aSAndreas Gohr        } else {
6786de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
6796de3759aSAndreas Gohr        }
68024870174SAndreas Gohr    } elseif ($conf['userewrite'] == 1) {
6816de3759aSAndreas Gohr        $script = '_detail';
6826de3759aSAndreas Gohr    } else {
6836de3759aSAndreas Gohr        $script = 'lib/exe/detail.php';
6846de3759aSAndreas Gohr    }
6856de3759aSAndreas Gohr
6866de3759aSAndreas Gohr    // build URL based on rewrite mode
6876de3759aSAndreas Gohr    if ($conf['userewrite']) {
6886de3759aSAndreas Gohr        $xlink .= $script.'/'.$id;
6896de3759aSAndreas Gohr        if($more) $xlink .= '?'.$more;
69024870174SAndreas Gohr    } elseif ($more) {
691a99d3236SEsther Brunner        $xlink .= $script.'?'.$more;
692b174aeaeSchris        $xlink .= $sep.'media='.$id;
6936de3759aSAndreas Gohr    } else {
694a99d3236SEsther Brunner        $xlink .= $script.'?media='.$id;
6956de3759aSAndreas Gohr    }
6966de3759aSAndreas Gohr
6976de3759aSAndreas Gohr    return $xlink;
6986de3759aSAndreas Gohr}
6996de3759aSAndreas Gohr
7006de3759aSAndreas Gohr/**
70125ca5b17SAndreas Gohr * Returns the URL to the DokuWiki base script
70215fae107Sandi *
70325ca5b17SAndreas Gohr * Consider using wl() instead, unless you absoutely need the doku.php endpoint
70425ca5b17SAndreas Gohr *
70515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
706140cfbcdSGerrit Uitslag *
707140cfbcdSGerrit Uitslag * @return string
708f3f0262cSandi */
709*d868eb89SAndreas Gohrfunction script()
710*d868eb89SAndreas Gohr{
711ed7b5f09Sandi    return DOKU_BASE.DOKU_SCRIPT;
712f3f0262cSandi}
713f3f0262cSandi
714f3f0262cSandi/**
71515fae107Sandi * Spamcheck against wordlist
71615fae107Sandi *
717f3f0262cSandi * Checks the wikitext against a list of blocked expressions
718f3f0262cSandi * returns true if the text contains any bad words
71915fae107Sandi *
720e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
721e403cc58SMichael Klier *
722e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
723e403cc58SMichael Klier *  and gain information about the user who was blocked.
724e403cc58SMichael Klier *
725e403cc58SMichael Klier *  Event data:
726e403cc58SMichael Klier *    data['matches']  - array of matches
727e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
728e403cc58SMichael Klier *      [ip]           - ip address
729e403cc58SMichael Klier *      [user]         - username (if logged in)
730e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
731e403cc58SMichael Klier *      [name]         - real name (if logged in)
732e403cc58SMichael Klier *
73315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
7346dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
735140cfbcdSGerrit Uitslag *
7366dffa0e0SAndreas Gohr * @param  string $text - optional text to check, if not given the globals are used
7376dffa0e0SAndreas Gohr * @return bool         - true if a spam word was found
738f3f0262cSandi */
739*d868eb89SAndreas Gohrfunction checkwordblock($text = '')
740*d868eb89SAndreas Gohr{
741f3f0262cSandi    global $TEXT;
7426dffa0e0SAndreas Gohr    global $PRE;
7436dffa0e0SAndreas Gohr    global $SUF;
744e0086ca2SAndreas Gohr    global $SUM;
745f3f0262cSandi    global $conf;
746e403cc58SMichael Klier    global $INFO;
747585bf44eSChristopher Smith    /* @var Input $INPUT */
748585bf44eSChristopher Smith    global $INPUT;
749f3f0262cSandi
750f3f0262cSandi    if(!$conf['usewordblock']) return false;
751f3f0262cSandi
752e0086ca2SAndreas Gohr    if(!$text) $text = "$PRE $TEXT $SUF $SUM";
7536dffa0e0SAndreas Gohr
754041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
75564159a61SAndreas Gohr    // phpcs:disable Generic.Files.LineLength.TooLong
75664159a61SAndreas Gohr    $text = preg_replace(
75764159a61SAndreas Gohr        '!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i',
75864159a61SAndreas Gohr        '\1http://\2 \2\3',
75964159a61SAndreas Gohr        $text
76064159a61SAndreas Gohr    );
76164159a61SAndreas Gohr    // phpcs:enable
762041d1964SAndreas Gohr
763b9ac8716Schris    $wordblocks = getWordblocks();
764a51d08efSAndreas Gohr    // read file in chunks of 200 - this should work around the
7653e2965d7Sandi    // MAX_PATTERN_SIZE in modern PCRE
766a51d08efSAndreas Gohr    $chunksize = 200;
76764259528SAndreas Gohr
768b9ac8716Schris    while($blocks = array_splice($wordblocks, 0, $chunksize)) {
76924870174SAndreas Gohr        $re = [];
77049eb6e38SAndreas Gohr        // build regexp from blocks
771f3f0262cSandi        foreach($blocks as $block) {
772f3f0262cSandi            $block = preg_replace('/#.*$/', '', $block);
773f3f0262cSandi            $block = trim($block);
774f3f0262cSandi            if(empty($block)) continue;
775f3f0262cSandi            $re[] = $block;
776f3f0262cSandi        }
77724870174SAndreas Gohr        if(count($re) && preg_match('#('.implode('|', $re).')#si', $text, $matches)) {
778e403cc58SMichael Klier            // prepare event data
77924870174SAndreas Gohr            $data = [];
780e403cc58SMichael Klier            $data['matches']        = $matches;
781585bf44eSChristopher Smith            $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
782585bf44eSChristopher Smith            if($INPUT->server->str('REMOTE_USER')) {
783585bf44eSChristopher Smith                $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
784e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
785e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
786e403cc58SMichael Klier            }
78724870174SAndreas Gohr            $callback = static fn() => true;
788cbb44eabSAndreas Gohr            return Event::createAndTrigger('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
789b9ac8716Schris        }
790703f6fdeSandi    }
791f3f0262cSandi    return false;
792f3f0262cSandi}
793f3f0262cSandi
794f3f0262cSandi/**
79515fae107Sandi * Return the IP of the client
79615fae107Sandi *
7976d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
79815fae107Sandi *
7996d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
8006d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
8016d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
8026d8affe6SAndreas Gohr * headers
8036d8affe6SAndreas Gohr *
80415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
805140cfbcdSGerrit Uitslag *
8063272d797SAndreas Gohr * @param  boolean $single If set only a single IP is returned
8073272d797SAndreas Gohr * @return string
808f3f0262cSandi */
809*d868eb89SAndreas Gohrfunction clientIP($single = false)
810*d868eb89SAndreas Gohr{
811585bf44eSChristopher Smith    /* @var Input $INPUT */
812925105e8SPhy    global $INPUT, $conf;
813585bf44eSChristopher Smith
81424870174SAndreas Gohr    $ip   = [];
815585bf44eSChristopher Smith    $ip[] = $INPUT->server->str('REMOTE_ADDR');
816585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_FORWARDED_FOR')) {
817585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_FORWARDED_FOR'))));
818585bf44eSChristopher Smith    }
819585bf44eSChristopher Smith    if($INPUT->server->str('HTTP_X_REAL_IP')) {
820585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_REAL_IP'))));
821585bf44eSChristopher Smith    }
8226d8affe6SAndreas Gohr
8236d8affe6SAndreas Gohr    // remove any non-IP stuff
8246d8affe6SAndreas Gohr    $cnt   = count($ip);
8256d8affe6SAndreas Gohr    for($i = 0; $i < $cnt; $i++) {
8260a5f08e5SAdaKaleh        if(filter_var($ip[$i], FILTER_VALIDATE_IP) === false) {
8270a5f08e5SAdaKaleh            unset($ip[$i]);
8284ff28443Schris        }
829f3f0262cSandi    }
8306d8affe6SAndreas Gohr    $ip = array_values(array_unique($ip));
83124870174SAndreas Gohr    if($ip === [] || !$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
8326d8affe6SAndreas Gohr
83324870174SAndreas Gohr    if(!$single) return implode(',', $ip);
8346d8affe6SAndreas Gohr
835925105e8SPhy    // skip trusted local addresses
8366d8affe6SAndreas Gohr    foreach($ip as $i) {
837925105e8SPhy        if(!empty($conf['trustedproxy']) && preg_match('/'.$conf['trustedproxy'].'/', $i)) {
8386d8affe6SAndreas Gohr            continue;
8396d8affe6SAndreas Gohr        } else {
8406d8affe6SAndreas Gohr            return $i;
8416d8affe6SAndreas Gohr        }
8426d8affe6SAndreas Gohr    }
843925105e8SPhy
844925105e8SPhy    // still here? just use the last address
845925105e8SPhy    // this case all ips in the list are trusted
846925105e8SPhy    return $ip[count($ip)-1];
847f3f0262cSandi}
848f3f0262cSandi
849f3f0262cSandi/**
8501c548ebeSAndreas Gohr * Check if the browser is on a mobile device
8511c548ebeSAndreas Gohr *
8521c548ebeSAndreas Gohr * Adapted from the example code at url below
8531c548ebeSAndreas Gohr *
8541c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
855140cfbcdSGerrit Uitslag *
85664159a61SAndreas Gohr * @deprecated 2018-04-27 you probably want media queries instead anyway
857140cfbcdSGerrit Uitslag * @return bool if true, client is mobile browser; otherwise false
8581c548ebeSAndreas Gohr */
859*d868eb89SAndreas Gohrfunction clientismobile()
860*d868eb89SAndreas Gohr{
861585bf44eSChristopher Smith    /* @var Input $INPUT */
862585bf44eSChristopher Smith    global $INPUT;
8631c548ebeSAndreas Gohr
864585bf44eSChristopher Smith    if($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
8651c548ebeSAndreas Gohr
866585bf44eSChristopher Smith    if(preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
8671c548ebeSAndreas Gohr
868585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_USER_AGENT')) return false;
8691c548ebeSAndreas Gohr
87024870174SAndreas Gohr    $uamatches = implode(
87164159a61SAndreas Gohr        '|',
87264159a61SAndreas Gohr        [
87364159a61SAndreas Gohr            'midp', 'j2me', 'avantg', 'docomo', 'novarra', 'palmos', 'palmsource', '240x320', 'opwv',
87464159a61SAndreas Gohr            'chtml', 'pda', 'windows ce', 'mmp\/', 'blackberry', 'mib\/', 'symbian', 'wireless', 'nokia',
87564159a61SAndreas Gohr            'hand', 'mobi', 'phone', 'cdm', 'up\.b', 'audio', 'SIE\-', 'SEC\-', 'samsung', 'HTC', 'mot\-',
87664159a61SAndreas Gohr            'mitsu', 'sagem', 'sony', 'alcatel', 'lg', 'erics', 'vx', 'NEC', 'philips', 'mmm', 'xx',
87764159a61SAndreas Gohr            'panasonic', 'sharp', 'wap', 'sch', 'rover', 'pocket', 'benq', 'java', 'pt', 'pg', 'vox',
87864159a61SAndreas Gohr            'amoi', 'bird', 'compal', 'kg', 'voda', 'sany', 'kdd', 'dbt', 'sendo', 'sgh', 'gradi', 'jb',
87964159a61SAndreas Gohr            '\d\d\di', 'moto'
88064159a61SAndreas Gohr        ]
88164159a61SAndreas Gohr    );
8821c548ebeSAndreas Gohr
883585bf44eSChristopher Smith    if(preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
8841c548ebeSAndreas Gohr
8851c548ebeSAndreas Gohr    return false;
8861c548ebeSAndreas Gohr}
8871c548ebeSAndreas Gohr
8881c548ebeSAndreas Gohr/**
8896efc45a2SDmitry Katsubo * check if a given link is interwiki link
8906efc45a2SDmitry Katsubo *
8916efc45a2SDmitry Katsubo * @param string $link the link, e.g. "wiki>page"
8926efc45a2SDmitry Katsubo * @return bool
8936efc45a2SDmitry Katsubo */
894*d868eb89SAndreas Gohrfunction link_isinterwiki($link)
895*d868eb89SAndreas Gohr{
8966efc45a2SDmitry Katsubo    if (preg_match('/^[a-zA-Z0-9\.]+>/u', $link)) return true;
8976efc45a2SDmitry Katsubo    return false;
8986efc45a2SDmitry Katsubo}
8996efc45a2SDmitry Katsubo
9006efc45a2SDmitry Katsubo/**
90163211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
90263211f61SGlen Harris *
90322ef1e32SAndreas Gohr * If $conf['dnslookups'] is disabled it simply returns the input string
90422ef1e32SAndreas Gohr *
90563211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
906140cfbcdSGerrit Uitslag *
9073272d797SAndreas Gohr * @param  string $ips comma separated list of IP addresses
9083272d797SAndreas Gohr * @return string a comma separated list of hostnames
90963211f61SGlen Harris */
910*d868eb89SAndreas Gohrfunction gethostsbyaddrs($ips)
911*d868eb89SAndreas Gohr{
91222ef1e32SAndreas Gohr    global $conf;
91322ef1e32SAndreas Gohr    if(!$conf['dnslookups']) return $ips;
91422ef1e32SAndreas Gohr
91524870174SAndreas Gohr    $hosts = [];
91663211f61SGlen Harris    $ips   = explode(',', $ips);
917551a720fSMichael Klier
918551a720fSMichael Klier    if(is_array($ips)) {
9193886270dSAndreas Gohr        foreach($ips as $ip) {
920551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
92163211f61SGlen Harris        }
92224870174SAndreas Gohr        return implode(',', $hosts);
923551a720fSMichael Klier    } else {
924551a720fSMichael Klier        return gethostbyaddr(trim($ips));
925551a720fSMichael Klier    }
92663211f61SGlen Harris}
92763211f61SGlen Harris
92863211f61SGlen Harris/**
92915fae107Sandi * Checks if a given page is currently locked.
93015fae107Sandi *
931f3f0262cSandi * removes stale lockfiles
93215fae107Sandi *
93315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
934140cfbcdSGerrit Uitslag *
935140cfbcdSGerrit Uitslag * @param string $id page id
936140cfbcdSGerrit Uitslag * @return bool page is locked?
937f3f0262cSandi */
938*d868eb89SAndreas Gohrfunction checklock($id)
939*d868eb89SAndreas Gohr{
940f3f0262cSandi    global $conf;
941585bf44eSChristopher Smith    /* @var Input $INPUT */
942585bf44eSChristopher Smith    global $INPUT;
943585bf44eSChristopher Smith
944c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
945f3f0262cSandi
946f3f0262cSandi    //no lockfile
94779e79377SAndreas Gohr    if(!file_exists($lock)) return false;
948f3f0262cSandi
949f3f0262cSandi    //lockfile expired
950f3f0262cSandi    if((time() - filemtime($lock)) > $conf['locktime']) {
951d8186216SBen Coburn        @unlink($lock);
952f3f0262cSandi        return false;
953f3f0262cSandi    }
954f3f0262cSandi
955f3f0262cSandi    //my own lock
95624870174SAndreas Gohr    @[$ip, $session] = explode("\n", io_readFile($lock));
95724870174SAndreas Gohr    if($ip == $INPUT->server->str('REMOTE_USER') || (session_id() && $session === session_id())) {
958f3f0262cSandi        return false;
959f3f0262cSandi    }
960f3f0262cSandi
961f3f0262cSandi    return $ip;
962f3f0262cSandi}
963f3f0262cSandi
964f3f0262cSandi/**
96515fae107Sandi * Lock a page for editing
96615fae107Sandi *
96715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
968140cfbcdSGerrit Uitslag *
969140cfbcdSGerrit Uitslag * @param string $id page id to lock
970f3f0262cSandi */
971*d868eb89SAndreas Gohrfunction lock($id)
972*d868eb89SAndreas Gohr{
973544ed901SDaniel Calviño Sánchez    global $conf;
974585bf44eSChristopher Smith    /* @var Input $INPUT */
975585bf44eSChristopher Smith    global $INPUT;
976544ed901SDaniel Calviño Sánchez
977544ed901SDaniel Calviño Sánchez    if($conf['locktime'] == 0) {
978544ed901SDaniel Calviño Sánchez        return;
979544ed901SDaniel Calviño Sánchez    }
980544ed901SDaniel Calviño Sánchez
981c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
982585bf44eSChristopher Smith    if($INPUT->server->str('REMOTE_USER')) {
983585bf44eSChristopher Smith        io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
984f3f0262cSandi    } else {
98585fef7e2SAndreas Gohr        io_saveFile($lock, clientIP()."\n".session_id());
986f3f0262cSandi    }
987f3f0262cSandi}
988f3f0262cSandi
989f3f0262cSandi/**
99015fae107Sandi * Unlock a page if it was locked by the user
991f3f0262cSandi *
99215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
993140cfbcdSGerrit Uitslag *
9943272d797SAndreas Gohr * @param string $id page id to unlock
99515fae107Sandi * @return bool true if a lock was removed
996f3f0262cSandi */
997*d868eb89SAndreas Gohrfunction unlock($id)
998*d868eb89SAndreas Gohr{
999585bf44eSChristopher Smith    /* @var Input $INPUT */
1000585bf44eSChristopher Smith    global $INPUT;
1001585bf44eSChristopher Smith
1002c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
100379e79377SAndreas Gohr    if(file_exists($lock)) {
100424870174SAndreas Gohr        @[$ip, $session] = explode("\n", io_readFile($lock));
1005c0dd3914SAdaKaleh        if($ip == $INPUT->server->str('REMOTE_USER') || $session == session_id()) {
1006f3f0262cSandi            @unlink($lock);
1007f3f0262cSandi            return true;
1008f3f0262cSandi        }
1009f3f0262cSandi    }
1010f3f0262cSandi    return false;
1011f3f0262cSandi}
1012f3f0262cSandi
1013f3f0262cSandi/**
1014f3f0262cSandi * convert line ending to unix format
1015f3f0262cSandi *
10166db7468bSAndreas Gohr * also makes sure the given text is valid UTF-8
10176db7468bSAndreas Gohr *
101815fae107Sandi * @see    formText() for 2crlf conversion
101915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1020140cfbcdSGerrit Uitslag *
1021140cfbcdSGerrit Uitslag * @param string $text
1022140cfbcdSGerrit Uitslag * @return string
1023f3f0262cSandi */
1024*d868eb89SAndreas Gohrfunction cleanText($text)
1025*d868eb89SAndreas Gohr{
1026f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
10276db7468bSAndreas Gohr
10286db7468bSAndreas Gohr    // if the text is not valid UTF-8 we simply assume latin1
10296db7468bSAndreas Gohr    // this won't break any worse than it breaks with the wrong encoding
10306db7468bSAndreas Gohr    // but might actually fix the problem in many cases
103124870174SAndreas Gohr    if(!Clean::isUtf8($text)) $text = utf8_encode($text);
10326db7468bSAndreas Gohr
1033f3f0262cSandi    return $text;
1034f3f0262cSandi}
1035f3f0262cSandi
1036f3f0262cSandi/**
1037f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
1038f3f0262cSandi * It also converts line endings to Windows format which is
1039f3f0262cSandi * pseudo standard for webforms.
1040f3f0262cSandi *
104115fae107Sandi * @see    cleanText() for 2unix conversion
104215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1043140cfbcdSGerrit Uitslag *
1044140cfbcdSGerrit Uitslag * @param string $text
1045140cfbcdSGerrit Uitslag * @return string
1046f3f0262cSandi */
1047*d868eb89SAndreas Gohrfunction formText($text)
1048*d868eb89SAndreas Gohr{
1049a46a37efSAndreas Gohr    $text = str_replace("\012", "\015\012", $text ?? '');
1050f3f0262cSandi    return htmlspecialchars($text);
1051f3f0262cSandi}
1052f3f0262cSandi
1053f3f0262cSandi/**
105415fae107Sandi * Returns the specified local text in raw format
105515fae107Sandi *
105615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1057140cfbcdSGerrit Uitslag *
1058140cfbcdSGerrit Uitslag * @param string $id   page id
1059140cfbcdSGerrit Uitslag * @param string $ext  extension of file being read, default 'txt'
1060140cfbcdSGerrit Uitslag * @return string
1061f3f0262cSandi */
1062*d868eb89SAndreas Gohrfunction rawLocale($id, $ext = 'txt')
1063*d868eb89SAndreas Gohr{
10642adaf2b8SAndreas Gohr    return io_readFile(localeFN($id, $ext));
1065f3f0262cSandi}
1066f3f0262cSandi
1067f3f0262cSandi/**
1068f3f0262cSandi * Returns the raw WikiText
106915fae107Sandi *
107015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1071140cfbcdSGerrit Uitslag *
1072140cfbcdSGerrit Uitslag * @param string $id   page id
1073e0c26282SGerrit Uitslag * @param string|int $rev  timestamp when a revision of wikitext is desired
1074140cfbcdSGerrit Uitslag * @return string
1075f3f0262cSandi */
1076*d868eb89SAndreas Gohrfunction rawWiki($id, $rev = '')
1077*d868eb89SAndreas Gohr{
1078cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1079f3f0262cSandi}
1080f3f0262cSandi
1081f3f0262cSandi/**
10827146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
10837146cee2SAndreas Gohr *
10847b84afa2SAndreas Gohr * @triggers COMMON_PAGETPL_LOAD
10857146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1086140cfbcdSGerrit Uitslag *
1087140cfbcdSGerrit Uitslag * @param string $id the id of the page to be created
1088140cfbcdSGerrit Uitslag * @return string parsed pagetemplate content
10897146cee2SAndreas Gohr */
1090*d868eb89SAndreas Gohrfunction pageTemplate($id)
1091*d868eb89SAndreas Gohr{
1092a15ce62dSEsther Brunner    global $conf;
1093e29549feSAndreas Gohr
1094fe17917eSAdrian Lang    if(is_array($id)) $id = $id[0];
1095e29549feSAndreas Gohr
10967b84afa2SAndreas Gohr    // prepare initial event data
109724870174SAndreas Gohr    $data = [
10987b84afa2SAndreas Gohr        'id'        => $id, // the id of the page to be created
10997b84afa2SAndreas Gohr        'tpl'       => '', // the text used as template
11007b84afa2SAndreas Gohr        'tplfile'   => '', // the file above text was/should be loaded from
110124870174SAndreas Gohr        'doreplace' => true,
110224870174SAndreas Gohr    ];
11037b84afa2SAndreas Gohr
1104e1d9dcc8SAndreas Gohr    $evt = new Event('COMMON_PAGETPL_LOAD', $data);
11057b84afa2SAndreas Gohr    if($evt->advise_before(true)) {
11067b84afa2SAndreas Gohr        // the before event might have loaded the content already
11077b84afa2SAndreas Gohr        if(empty($data['tpl'])) {
11087b84afa2SAndreas Gohr            // if the before event did not set a template file, try to find one
11097b84afa2SAndreas Gohr            if(empty($data['tplfile'])) {
1110fe17917eSAdrian Lang                $path = dirname(wikiFN($id));
111179e79377SAndreas Gohr                if(file_exists($path.'/_template.txt')) {
11127b84afa2SAndreas Gohr                    $data['tplfile'] = $path.'/_template.txt';
1113e29549feSAndreas Gohr                } else {
1114e29549feSAndreas Gohr                    // search upper namespaces for templates
1115e29549feSAndreas Gohr                    $len = strlen(rtrim($conf['datadir'], '/'));
1116e29549feSAndreas Gohr                    while(strlen($path) >= $len) {
111779e79377SAndreas Gohr                        if(file_exists($path.'/__template.txt')) {
11187b84afa2SAndreas Gohr                            $data['tplfile'] = $path.'/__template.txt';
1119e29549feSAndreas Gohr                            break;
1120e29549feSAndreas Gohr                        }
1121e29549feSAndreas Gohr                        $path = substr($path, 0, strrpos($path, '/'));
1122e29549feSAndreas Gohr                    }
1123e29549feSAndreas Gohr                }
11247b84afa2SAndreas Gohr            }
11257b84afa2SAndreas Gohr            // load the content
11263d7ac595SMichael Hamann            $data['tpl'] = io_readFile($data['tplfile']);
11277b84afa2SAndreas Gohr        }
1128a1bbd05bSMichael Hamann        if($data['doreplace']) parsePageTemplate($data);
11297b84afa2SAndreas Gohr    }
11307b84afa2SAndreas Gohr    $evt->advise_after();
11317b84afa2SAndreas Gohr    unset($evt);
11327b84afa2SAndreas Gohr
1133fe17917eSAdrian Lang    return $data['tpl'];
11342b1223ecSAdrian Lang}
11352b1223ecSAdrian Lang
11362b1223ecSAdrian Lang/**
11372b1223ecSAdrian Lang * Performs common page template replacements
11387b84afa2SAndreas Gohr * This works on data from COMMON_PAGETPL_LOAD
11392b1223ecSAdrian Lang *
11402b1223ecSAdrian Lang * @author Andreas Gohr <andi@splitbrain.org>
1141140cfbcdSGerrit Uitslag *
1142140cfbcdSGerrit Uitslag * @param array $data array with event data
1143140cfbcdSGerrit Uitslag * @return string
11442b1223ecSAdrian Lang */
1145*d868eb89SAndreas Gohrfunction parsePageTemplate(&$data)
1146*d868eb89SAndreas Gohr{
11473272d797SAndreas Gohr    /**
11483272d797SAndreas Gohr     * @var string $id        the id of the page to be created
11493272d797SAndreas Gohr     * @var string $tpl       the text used as template
11503272d797SAndreas Gohr     * @var string $tplfile   the file above text was/should be loaded from
11513272d797SAndreas Gohr     * @var bool   $doreplace should wildcard replacements be done on the text?
11523272d797SAndreas Gohr     */
1153fe17917eSAdrian Lang    extract($data);
1154fe17917eSAdrian Lang
1155b856f7dfSAdrian Lang    global $USERINFO;
1156bce53b1fSAdrian Lang    global $conf;
1157585bf44eSChristopher Smith    /* @var Input $INPUT */
1158585bf44eSChristopher Smith    global $INPUT;
1159e29549feSAndreas Gohr
1160e29549feSAndreas Gohr    // replace placeholders
116126ece5a7SAndreas Gohr    $file = noNS($id);
116237c1acbdSAdrian Lang    $page = strtr($file, $conf['sepchar'], ' ');
116326ece5a7SAndreas Gohr
11643272d797SAndreas Gohr    $tpl = str_replace(
116524870174SAndreas Gohr        [
116626ece5a7SAndreas Gohr            '@ID@',
116726ece5a7SAndreas Gohr            '@NS@',
11688a7bcf66SShota Miyazaki            '@CURNS@',
1169a3db0ab0SSimon Lees            '@!CURNS@',
1170a3db0ab0SSimon Lees            '@!!CURNS@',
1171a3db0ab0SSimon Lees            '@!CURNS!@',
117226ece5a7SAndreas Gohr            '@FILE@',
117326ece5a7SAndreas Gohr            '@!FILE@',
117426ece5a7SAndreas Gohr            '@!FILE!@',
117526ece5a7SAndreas Gohr            '@PAGE@',
117626ece5a7SAndreas Gohr            '@!PAGE@',
117726ece5a7SAndreas Gohr            '@!!PAGE@',
117826ece5a7SAndreas Gohr            '@!PAGE!@',
117926ece5a7SAndreas Gohr            '@USER@',
118026ece5a7SAndreas Gohr            '@NAME@',
118126ece5a7SAndreas Gohr            '@MAIL@',
118224870174SAndreas Gohr            '@DATE@'
118324870174SAndreas Gohr        ],
118424870174SAndreas Gohr        [
118526ece5a7SAndreas Gohr            $id,
118626ece5a7SAndreas Gohr            getNS($id),
11878a7bcf66SShota Miyazaki            curNS($id),
118824870174SAndreas Gohr            PhpString::ucfirst(curNS($id)),
118924870174SAndreas Gohr            PhpString::ucwords(curNS($id)),
119024870174SAndreas Gohr            PhpString::strtoupper(curNS($id)),
119126ece5a7SAndreas Gohr            $file,
119224870174SAndreas Gohr            PhpString::ucfirst($file),
119324870174SAndreas Gohr            PhpString::strtoupper($file),
119426ece5a7SAndreas Gohr            $page,
119524870174SAndreas Gohr            PhpString::ucfirst($page),
119624870174SAndreas Gohr            PhpString::ucwords($page),
119724870174SAndreas Gohr            PhpString::strtoupper($page),
1198585bf44eSChristopher Smith            $INPUT->server->str('REMOTE_USER'),
11993e9ae63dSPhy            $USERINFO ? $USERINFO['name'] : '',
12003e9ae63dSPhy            $USERINFO ? $USERINFO['mail'] : '',
120124870174SAndreas Gohr            $conf['dformat']
120224870174SAndreas Gohr        ],
120324870174SAndreas Gohr        $tpl
12043272d797SAndreas Gohr    );
120526ece5a7SAndreas Gohr
12067d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
1207bad6fc0dSAndreas Gohr    $tpl = preg_replace_callback(
1208bad6fc0dSAndreas Gohr        '/%./',
120924870174SAndreas Gohr        static fn($m) => dformat(null, $m[0]),
1210bad6fc0dSAndreas Gohr        $tpl
1211bad6fc0dSAndreas Gohr    );
1212d535a2e9Sstretchyboy    $data['tpl'] = $tpl;
1213a15ce62dSEsther Brunner    return $tpl;
12147146cee2SAndreas Gohr}
12157146cee2SAndreas Gohr
12167146cee2SAndreas Gohr/**
121715fae107Sandi * Returns the raw Wiki Text in three slices.
121815fae107Sandi *
121915fae107Sandi * The range parameter needs to have the form "from-to"
122015cfe303Sandi * and gives the range of the section in bytes - no
122115cfe303Sandi * UTF-8 awareness is needed.
1222f3f0262cSandi * The returned order is prefix, section and suffix.
122315fae107Sandi *
122415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1225140cfbcdSGerrit Uitslag *
1226140cfbcdSGerrit Uitslag * @param string $range in form "from-to"
1227140cfbcdSGerrit Uitslag * @param string $id    page id
1228140cfbcdSGerrit Uitslag * @param string $rev   optional, the revision timestamp
122942ea7f44SGerrit Uitslag * @return string[] with three slices
1230f3f0262cSandi */
1231*d868eb89SAndreas Gohrfunction rawWikiSlices($range, $id, $rev = '')
1232*d868eb89SAndreas Gohr{
1233cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1234f3f0262cSandi
123580fcb268SAdrian Lang    // Parse range
123624870174SAndreas Gohr    [$from, $to] = sexplode('-', $range, 2);
123780fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
123824870174SAndreas Gohr    $from = $from ? $from - 1 : (0);
123924870174SAndreas Gohr    $to   = $to ? $to - 1 : (strlen($text));
124080fcb268SAdrian Lang
124124870174SAndreas Gohr    $slices = [];
124280fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
124380fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to - $from);
124415cfe303Sandi    $slices[2] = substr($text, $to);
1245f3f0262cSandi    return $slices;
1246f3f0262cSandi}
1247f3f0262cSandi
1248f3f0262cSandi/**
124915fae107Sandi * Joins wiki text slices
125015fae107Sandi *
125180fcb268SAdrian Lang * function to join the text slices.
1252f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
1253f3f0262cSandi * lines between sections if needed (used on saving).
125415fae107Sandi *
125515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1256140cfbcdSGerrit Uitslag *
1257140cfbcdSGerrit Uitslag * @param string $pre   prefix
1258140cfbcdSGerrit Uitslag * @param string $text  text in the middle
1259140cfbcdSGerrit Uitslag * @param string $suf   suffix
1260140cfbcdSGerrit Uitslag * @param bool $pretty add additional empty lines between sections
1261140cfbcdSGerrit Uitslag * @return string
1262f3f0262cSandi */
1263*d868eb89SAndreas Gohrfunction con($pre, $text, $suf, $pretty = false)
1264*d868eb89SAndreas Gohr{
1265f3f0262cSandi    if($pretty) {
126680fcb268SAdrian Lang        if($pre !== '' && substr($pre, -1) !== "\n" &&
12673272d797SAndreas Gohr            substr($text, 0, 1) !== "\n"
12683272d797SAndreas Gohr        ) {
126980fcb268SAdrian Lang            $pre .= "\n";
127080fcb268SAdrian Lang        }
127180fcb268SAdrian Lang        if($suf !== '' && substr($text, -1) !== "\n" &&
12723272d797SAndreas Gohr            substr($suf, 0, 1) !== "\n"
12733272d797SAndreas Gohr        ) {
127480fcb268SAdrian Lang            $text .= "\n";
127580fcb268SAdrian Lang        }
1276f3f0262cSandi    }
1277f3f0262cSandi
1278f3f0262cSandi    return $pre.$text.$suf;
1279f3f0262cSandi}
1280f3f0262cSandi
1281f3f0262cSandi/**
1282b24d9195SAndreas Gohr * Checks if the current page version is newer than the last entry in the page's
1283b24d9195SAndreas Gohr * changelog. If so, we assume it has been an external edit and we create an
1284b24d9195SAndreas Gohr * attic copy and add a proper changelog line.
1285b24d9195SAndreas Gohr *
1286b24d9195SAndreas Gohr * This check is only executed when the page is about to be saved again from the
1287b24d9195SAndreas Gohr * wiki, triggered in @see saveWikiText()
1288b24d9195SAndreas Gohr *
1289b24d9195SAndreas Gohr * @param string $id the page ID
129069f9b481SSatoshi Sahara * @deprecated 2021-11-28
1291b24d9195SAndreas Gohr */
1292*d868eb89SAndreas Gohrfunction detectExternalEdit($id)
1293*d868eb89SAndreas Gohr{
129479a2d784SGerrit Uitslag    dbg_deprecated(PageFile::class .'::detectExternalEdit()');
1295b24e9c4aSSatoshi Sahara    (new PageFile($id))->detectExternalEdit();
1296b24d9195SAndreas Gohr}
1297b24d9195SAndreas Gohr
1298b24d9195SAndreas Gohr/**
1299a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
1300a701424fSBen Coburn * Also directs changelog and attic updates.
130115fae107Sandi *
130215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
130371726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
1304140cfbcdSGerrit Uitslag *
1305140cfbcdSGerrit Uitslag * @param string $id       page id
1306140cfbcdSGerrit Uitslag * @param string $text     wikitext being saved
1307140cfbcdSGerrit Uitslag * @param string $summary  summary of text update
1308140cfbcdSGerrit Uitslag * @param bool   $minor    mark this saved version as minor update
1309f3f0262cSandi */
1310*d868eb89SAndreas Gohrfunction saveWikiText($id, $text, $summary, $minor = false)
1311*d868eb89SAndreas Gohr{
1312585bf44eSChristopher Smith
1313b24e9c4aSSatoshi Sahara    // get COMMON_WIKIPAGE_SAVE event data
1314b24e9c4aSSatoshi Sahara    $data = (new PageFile($id))->saveWikiText($text, $summary, $minor);
1315a577fbc2SAndreas Gohr    if(!$data) return; // save was cancelled (for no changes or by a plugin)
1316ac3ed4afSGerrit Uitslag
131726a0801fSAndreas Gohr    // send notify mails
131824870174SAndreas Gohr    ['oldRevision' => $rev, 'newRevision' => $new_rev, 'summary' => $summary] = $data;
13193b813d43SSatoshi Sahara    notify($id, 'admin', $rev, $summary, $minor, $new_rev);
13203b813d43SSatoshi Sahara    notify($id, 'subscribers', $rev, $summary, $minor, $new_rev);
1321f3f0262cSandi
13222eccbdaaSGina Haeussge    // if useheading is enabled, purge the cache of all linking pages
1323fe9ec250SChris Smith    if (useHeading('content')) {
132407ff0babSMichael Hamann        $pages = ft_backlinks($id, true);
13252eccbdaaSGina Haeussge        foreach ($pages as $page) {
13260db5771eSMichael Große            $cache = new CacheRenderer($page, wikiFN($page), 'xhtml');
13272eccbdaaSGina Haeussge            $cache->removeCache();
13282eccbdaaSGina Haeussge        }
13292eccbdaaSGina Haeussge    }
1330f3f0262cSandi}
1331f3f0262cSandi
1332f3f0262cSandi/**
1333d5824ab9SSatoshi Sahara * moves the current version to the attic and returns its revision date
133415fae107Sandi *
133515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1336140cfbcdSGerrit Uitslag *
1337140cfbcdSGerrit Uitslag * @param string $id page id
1338140cfbcdSGerrit Uitslag * @return int|string revision timestamp
133969f9b481SSatoshi Sahara * @deprecated 2021-11-28
1340f3f0262cSandi */
1341*d868eb89SAndreas Gohrfunction saveOldRevision($id)
1342*d868eb89SAndreas Gohr{
134379a2d784SGerrit Uitslag    dbg_deprecated(PageFile::class .'::saveOldRevision()');
1344b24e9c4aSSatoshi Sahara    return (new PageFile($id))->saveOldRevision();
1345f3f0262cSandi}
1346f3f0262cSandi
1347f3f0262cSandi/**
1348fde10de4SAdrian Lang * Sends a notify mail on page change or registration
134926a0801fSAndreas Gohr *
135026a0801fSAndreas Gohr * @param string     $id       The changed page
1351fde10de4SAdrian Lang * @param string     $who      Who to notify (admin|subscribers|register)
13523272d797SAndreas Gohr * @param int|string $rev      Old page revision
135326a0801fSAndreas Gohr * @param string     $summary  What changed
135490033e9dSAndreas Gohr * @param boolean    $minor    Is this a minor edit?
135542ea7f44SGerrit Uitslag * @param string[]   $replace  Additional string substitutions, @KEY@ to be replaced by value
135683734cddSPhy * @param int|string $current_rev  New page revision
13573272d797SAndreas Gohr * @return bool
1358140cfbcdSGerrit Uitslag *
135915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1360f3f0262cSandi */
1361*d868eb89SAndreas Gohrfunction notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = [], $current_rev = false)
1362*d868eb89SAndreas Gohr{
1363f3f0262cSandi    global $conf;
1364585bf44eSChristopher Smith    /* @var Input $INPUT */
1365585bf44eSChristopher Smith    global $INPUT;
1366b158d625SSteven Danz
13676df843eeSAndreas Gohr    // decide if there is something to do, eg. whom to mail
136826a0801fSAndreas Gohr    if ($who == 'admin') {
13693272d797SAndreas Gohr        if (empty($conf['notify'])) return false; //notify enabled?
13702ed38036SAndreas Gohr        $tpl = 'mailtext';
137126a0801fSAndreas Gohr        $to  = $conf['notify'];
137226a0801fSAndreas Gohr    } elseif ($who == 'subscribers') {
137384c1127cSAndreas Gohr        if (!actionOK('subscribe')) return false; //subscribers enabled?
1374585bf44eSChristopher Smith        if ($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
137524870174SAndreas Gohr        $data = ['id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace];
1376cbb44eabSAndreas Gohr        Event::createAndTrigger(
13773272d797SAndreas Gohr            'COMMON_NOTIFY_ADDRESSLIST', $data,
137824870174SAndreas Gohr            [new SubscriberManager(), 'notifyAddresses']
13793272d797SAndreas Gohr        );
13802ed38036SAndreas Gohr        $to = $data['addresslist'];
13812ed38036SAndreas Gohr        if (empty($to)) return false;
13822ed38036SAndreas Gohr        $tpl = 'subscr_single';
138326a0801fSAndreas Gohr    } else {
13843272d797SAndreas Gohr        return false; //just to be safe
138526a0801fSAndreas Gohr    }
138626a0801fSAndreas Gohr
13876df843eeSAndreas Gohr    // prepare content
1388704a815fSMichael Große    $subscription = new PageSubscriptionSender();
138983734cddSPhy    return $subscription->sendPageDiff($to, $tpl, $id, $rev, $summary, $current_rev);
1390f3f0262cSandi}
13912ed38036SAndreas Gohr
139215fae107Sandi/**
139371f7bde7SAndreas Gohr * extracts the query from a search engine referrer
139415fae107Sandi *
139515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
139671f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1397140cfbcdSGerrit Uitslag *
1398140cfbcdSGerrit Uitslag * @return array|string
1399f3f0262cSandi */
1400*d868eb89SAndreas Gohrfunction getGoogleQuery()
1401*d868eb89SAndreas Gohr{
1402585bf44eSChristopher Smith    /* @var Input $INPUT */
1403585bf44eSChristopher Smith    global $INPUT;
1404585bf44eSChristopher Smith
1405585bf44eSChristopher Smith    if(!$INPUT->server->has('HTTP_REFERER')) {
1406c66972f2SAdrian Lang        return '';
1407c66972f2SAdrian Lang    }
1408585bf44eSChristopher Smith    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1409f3f0262cSandi
1410079b3ac1SAndreas Gohr    // only handle common SEs
1411c7875401SJyoti S    if(!array_key_exists('host', $url)) return '';
1412079b3ac1SAndreas Gohr    if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/', $url['host'])) return '';
1413e4d8a516SKazutaka Miyasaka
141424870174SAndreas Gohr    $query = [];
1415181adffeSJulian Jeggle    if(!array_key_exists('query', $url)) return '';
1416f3f0262cSandi    parse_str($url['query'], $query);
1417e4d8a516SKazutaka Miyasaka
1418c66972f2SAdrian Lang    $q = '';
1419079b3ac1SAndreas Gohr    if(isset($query['q'])){
1420079b3ac1SAndreas Gohr        $q = $query['q'];
1421079b3ac1SAndreas Gohr    }elseif(isset($query['p'])){
1422079b3ac1SAndreas Gohr        $q = $query['p'];
1423079b3ac1SAndreas Gohr    }elseif(isset($query['query'])){
1424079b3ac1SAndreas Gohr        $q = $query['query'];
1425079b3ac1SAndreas Gohr    }
1426079b3ac1SAndreas Gohr    $q = trim($q);
1427f3f0262cSandi
1428079b3ac1SAndreas Gohr    if(!$q) return '';
1429c7dc833bSPhy    // ignore if query includes a full URL
1430c7dc833bSPhy    if(strpos($q, '//') !== false) return '';
14316531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1432f93b3b50SAndreas Gohr    return $q;
1433f3f0262cSandi}
1434f3f0262cSandi
1435f3f0262cSandi/**
1436f3f0262cSandi * Return the human readable size of a file
1437f3f0262cSandi *
1438f3f0262cSandi * @param int $size A file size
1439f3f0262cSandi * @param int $dec A number of decimal places
144074160ca1SGerrit Uitslag * @return string human readable size
1441140cfbcdSGerrit Uitslag *
1442f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1443f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1444f3f0262cSandi * @version     1.0.0
1445f3f0262cSandi */
1446*d868eb89SAndreas Gohrfunction filesize_h($size, $dec = 1)
1447*d868eb89SAndreas Gohr{
144824870174SAndreas Gohr    $sizes = ['B', 'KB', 'MB', 'GB'];
1449f3f0262cSandi    $count = count($sizes);
1450f3f0262cSandi    $i     = 0;
1451f3f0262cSandi
1452f3f0262cSandi    while($size >= 1024 && ($i < $count - 1)) {
1453f3f0262cSandi        $size /= 1024;
1454f3f0262cSandi        $i++;
1455f3f0262cSandi    }
1456f3f0262cSandi
1457ef08383eSAndreas Gohr    return round($size, $dec)."\xC2\xA0".$sizes[$i]; //non-breaking space
1458f3f0262cSandi}
1459f3f0262cSandi
146015fae107Sandi/**
1461c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1462c57e365eSAndreas Gohr *
1463c57e365eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1464140cfbcdSGerrit Uitslag *
1465140cfbcdSGerrit Uitslag * @param int $dt timestamp
1466140cfbcdSGerrit Uitslag * @return string
1467c57e365eSAndreas Gohr */
1468*d868eb89SAndreas Gohrfunction datetime_h($dt)
1469*d868eb89SAndreas Gohr{
1470c57e365eSAndreas Gohr    global $lang;
1471c57e365eSAndreas Gohr
1472c57e365eSAndreas Gohr    $ago = time() - $dt;
1473c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1474c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1475c57e365eSAndreas Gohr    }
1476c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 30 * 2) {
1477c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1478c57e365eSAndreas Gohr    }
1479c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 7 * 2) {
1480c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1481c57e365eSAndreas Gohr    }
1482c57e365eSAndreas Gohr    if($ago > 24 * 60 * 60 * 2) {
1483c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1484c57e365eSAndreas Gohr    }
1485c57e365eSAndreas Gohr    if($ago > 60 * 60 * 2) {
1486c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago / (60 * 60)));
1487c57e365eSAndreas Gohr    }
1488c57e365eSAndreas Gohr    if($ago > 60 * 2) {
1489c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago / (60)));
1490c57e365eSAndreas Gohr    }
1491c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1492c57e365eSAndreas Gohr}
1493c57e365eSAndreas Gohr
1494c57e365eSAndreas Gohr/**
1495f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1496f2263577SAndreas Gohr *
1497f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1498f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1499f2263577SAndreas Gohr *
1500f2263577SAndreas Gohr * @see datetime_h
1501f2263577SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1502140cfbcdSGerrit Uitslag *
1503140cfbcdSGerrit Uitslag * @param int|null $dt      timestamp when given, null will take current timestamp
1504140cfbcdSGerrit Uitslag * @param string   $format  empty default to $conf['dformat'], or provide format as recognized by strftime()
1505140cfbcdSGerrit Uitslag * @return string
1506f2263577SAndreas Gohr */
1507*d868eb89SAndreas Gohrfunction dformat($dt = null, $format = '')
1508*d868eb89SAndreas Gohr{
1509f2263577SAndreas Gohr    global $conf;
1510f2263577SAndreas Gohr
1511f2263577SAndreas Gohr    if(is_null($dt)) $dt = time();
1512f2263577SAndreas Gohr    $dt = (int) $dt;
1513f2263577SAndreas Gohr    if(!$format) $format = $conf['dformat'];
1514f2263577SAndreas Gohr
1515f2263577SAndreas Gohr    $format = str_replace('%f', datetime_h($dt), $format);
1516f2263577SAndreas Gohr    return strftime($format, $dt);
1517f2263577SAndreas Gohr}
1518f2263577SAndreas Gohr
1519f2263577SAndreas Gohr/**
1520c4f79b71SMichael Hamann * Formats a timestamp as ISO 8601 date
1521c4f79b71SMichael Hamann *
1522c4f79b71SMichael Hamann * @author <ungu at terong dot com>
152359752844SAnders Sandblad * @link http://php.net/manual/en/function.date.php#54072
1524140cfbcdSGerrit Uitslag *
15257e8500eeSGerrit Uitslag * @param int $int_date current date in UNIX timestamp
15263272d797SAndreas Gohr * @return string
1527c4f79b71SMichael Hamann */
1528*d868eb89SAndreas Gohrfunction date_iso8601($int_date)
1529*d868eb89SAndreas Gohr{
1530c4f79b71SMichael Hamann    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1531c4f79b71SMichael Hamann    $pre_timezone = date('O', $int_date);
1532c4f79b71SMichael Hamann    $time_zone    = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1533c4f79b71SMichael Hamann    $date_mod .= $time_zone;
1534c4f79b71SMichael Hamann    return $date_mod;
1535c4f79b71SMichael Hamann}
1536c4f79b71SMichael Hamann
1537c4f79b71SMichael Hamann/**
153800a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
153900a7b5adSEsther Brunner *
154000a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
154100a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
1542140cfbcdSGerrit Uitslag *
1543140cfbcdSGerrit Uitslag * @param string $email email address
1544140cfbcdSGerrit Uitslag * @return string
154500a7b5adSEsther Brunner */
1546*d868eb89SAndreas Gohrfunction obfuscate($email)
1547*d868eb89SAndreas Gohr{
154800a7b5adSEsther Brunner    global $conf;
154900a7b5adSEsther Brunner
155000a7b5adSEsther Brunner    switch($conf['mailguard']) {
155100a7b5adSEsther Brunner        case 'visible' :
155224870174SAndreas Gohr            $obfuscate = ['@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] '];
155300a7b5adSEsther Brunner            return strtr($email, $obfuscate);
155400a7b5adSEsther Brunner
155500a7b5adSEsther Brunner        case 'hex' :
155624870174SAndreas Gohr            return Conversion::toHtml($email, true);
155700a7b5adSEsther Brunner
155800a7b5adSEsther Brunner        case 'none' :
155900a7b5adSEsther Brunner        default :
156000a7b5adSEsther Brunner            return $email;
156100a7b5adSEsther Brunner    }
156200a7b5adSEsther Brunner}
156300a7b5adSEsther Brunner
156400a7b5adSEsther Brunner/**
156589541d4bSAndreas Gohr * Removes quoting backslashes
156689541d4bSAndreas Gohr *
156789541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1568140cfbcdSGerrit Uitslag *
1569140cfbcdSGerrit Uitslag * @param string $string
1570140cfbcdSGerrit Uitslag * @param string $char backslashed character
1571140cfbcdSGerrit Uitslag * @return string
157289541d4bSAndreas Gohr */
1573*d868eb89SAndreas Gohrfunction unslash($string, $char = "'")
1574*d868eb89SAndreas Gohr{
157589541d4bSAndreas Gohr    return str_replace('\\'.$char, $char, $string);
157689541d4bSAndreas Gohr}
157789541d4bSAndreas Gohr
157873038c47SAndreas Gohr/**
157973038c47SAndreas Gohr * Convert php.ini shorthands to byte
158073038c47SAndreas Gohr *
1581a81f3d99SAndreas Gohr * On 32 bit systems values >= 2GB will fail!
1582140cfbcdSGerrit Uitslag *
1583a81f3d99SAndreas Gohr * -1 (infinite size) will be reported as -1
1584a81f3d99SAndreas Gohr *
1585a81f3d99SAndreas Gohr * @link   https://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
1586a81f3d99SAndreas Gohr * @param string $value PHP size shorthand
1587a81f3d99SAndreas Gohr * @return int
158873038c47SAndreas Gohr */
1589*d868eb89SAndreas Gohrfunction php_to_byte($value)
1590*d868eb89SAndreas Gohr{
1591f5c0c80bSAndreas Gohr    switch (strtoupper(substr($value, -1))) {
159273038c47SAndreas Gohr        case 'G':
159324870174SAndreas Gohr            $ret = (int) substr($value, 0, -1) * 1024 * 1024 * 1024;
159473038c47SAndreas Gohr            break;
159573038c47SAndreas Gohr        case 'M':
159624870174SAndreas Gohr            $ret = (int) substr($value, 0, -1) * 1024 * 1024;
1597a81f3d99SAndreas Gohr            break;
159873038c47SAndreas Gohr        case 'K':
159924870174SAndreas Gohr            $ret = (int) substr($value, 0, -1) * 1024;
160073038c47SAndreas Gohr            break;
16019eeeb775SAndreas Gohr        default:
160224870174SAndreas Gohr            $ret = (int) $value;
160349cbd23eSOtto Vainio            break;
160473038c47SAndreas Gohr    }
160573038c47SAndreas Gohr    return $ret;
160673038c47SAndreas Gohr}
160773038c47SAndreas Gohr
1608546d3a99SAndreas Gohr/**
1609546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1610140cfbcdSGerrit Uitslag *
1611140cfbcdSGerrit Uitslag * @param string $string
1612140cfbcdSGerrit Uitslag * @return string
1613546d3a99SAndreas Gohr */
1614*d868eb89SAndreas Gohrfunction preg_quote_cb($string)
1615*d868eb89SAndreas Gohr{
1616546d3a99SAndreas Gohr    return preg_quote($string, '/');
1617546d3a99SAndreas Gohr}
161873038c47SAndreas Gohr
1619bd2f6c2fSAndreas Gohr/**
1620bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1621bd2f6c2fSAndreas Gohr *
1622c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1623bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1624bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1625bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1626bd2f6c2fSAndreas Gohr *
1627bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1628bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1629bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1630bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1631bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
16323272d797SAndreas Gohr * @return string
1633bd2f6c2fSAndreas Gohr */
1634*d868eb89SAndreas Gohrfunction shorten($keep, $short, $max, $min = 9, $char = '…')
1635*d868eb89SAndreas Gohr{
163624870174SAndreas Gohr    $max -= PhpString::strlen($keep);
1637bd2f6c2fSAndreas Gohr    if($max < $min) return $keep;
163824870174SAndreas Gohr    $len = PhpString::strlen($short);
1639bd2f6c2fSAndreas Gohr    if($len <= $max) return $keep.$short;
1640bd2f6c2fSAndreas Gohr    $half = floor($max / 2);
16416ce3e5f8SAndreas Gohr    return $keep .
164224870174SAndreas Gohr        PhpString::substr($short, 0, $half - 1) .
16436ce3e5f8SAndreas Gohr        $char .
164424870174SAndreas Gohr        PhpString::substr($short, $len - $half);
1645bd2f6c2fSAndreas Gohr}
1646bd2f6c2fSAndreas Gohr
1647dc58b6f4SAndy Webber/**
1648dc58b6f4SAndy Webber * Return the users real name or e-mail address for use
1649dc58b6f4SAndy Webber * in page footer and recent changes pages
1650dc58b6f4SAndy Webber *
1651b4b6c9a1SGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
165215f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1653c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
165415f3bc49SGerrit Uitslag *
1655dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1656dc58b6f4SAndy Webber */
1657*d868eb89SAndreas Gohrfunction editorinfo($username, $textonly = false)
1658*d868eb89SAndreas Gohr{
1659cd4635eeSGerrit Uitslag    return userlink($username, $textonly);
1660dc58b6f4SAndy Webber}
1661dc58b6f4SAndy Webber
166260a396c8SGerrit Uitslag/**
166360a396c8SGerrit Uitslag * Returns users realname w/o link
166460a396c8SGerrit Uitslag *
1665f168548cSGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
166615f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1667c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
166860a396c8SGerrit Uitslag *
166960a396c8SGerrit Uitslag * @triggers COMMON_USER_LINK
167060a396c8SGerrit Uitslag */
1671*d868eb89SAndreas Gohrfunction userlink($username = null, $textonly = false)
1672*d868eb89SAndreas Gohr{
167360a396c8SGerrit Uitslag    global $conf, $INFO;
1674e1d9dcc8SAndreas Gohr    /** @var AuthPlugin $auth */
167560a396c8SGerrit Uitslag    global $auth;
167630f6ec4bSGerrit Uitslag    /** @var Input $INPUT */
167730f6ec4bSGerrit Uitslag    global $INPUT;
167860a396c8SGerrit Uitslag
167960a396c8SGerrit Uitslag    // prepare initial event data
168024870174SAndreas Gohr    $data = [
168160a396c8SGerrit Uitslag        'username' => $username, // the unique user name
168260a396c8SGerrit Uitslag        'name' => '',
168324870174SAndreas Gohr        'link' => [
168424870174SAndreas Gohr            //setting 'link' to false disables linking
168560a396c8SGerrit Uitslag            'target' => '',
168660a396c8SGerrit Uitslag            'pre' => '',
168760a396c8SGerrit Uitslag            'suf' => '',
168860a396c8SGerrit Uitslag            'style' => '',
168960a396c8SGerrit Uitslag            'more' => '',
169060a396c8SGerrit Uitslag            'url' => '',
169160a396c8SGerrit Uitslag            'title' => '',
169224870174SAndreas Gohr            'class' => '',
169324870174SAndreas Gohr        ],
16944d5fc927SGerrit Uitslag        'userlink' => '', // formatted user name as will be returned
169524870174SAndreas Gohr        'textonly' => $textonly,
169624870174SAndreas Gohr    ];
169762c8004eSGerrit Uitslag    if($username === null) {
169830f6ec4bSGerrit Uitslag        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
169915f3bc49SGerrit Uitslag        if($textonly){
170015f3bc49SGerrit Uitslag            $data['name'] = $INFO['userinfo']['name']. ' (' . $INPUT->server->str('REMOTE_USER') . ')';
170115f3bc49SGerrit Uitslag        }else {
170264159a61SAndreas Gohr            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> '.
170364159a61SAndreas Gohr                '(<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
170460a396c8SGerrit Uitslag        }
170515f3bc49SGerrit Uitslag    }
170660a396c8SGerrit Uitslag
1707e1d9dcc8SAndreas Gohr    $evt = new Event('COMMON_USER_LINK', $data);
170860a396c8SGerrit Uitslag    if($evt->advise_before(true)) {
170960a396c8SGerrit Uitslag        if(empty($data['name'])) {
171060a396c8SGerrit Uitslag            if($auth) $info = $auth->getUserData($username);
171165833968SGerrit Uitslag            if($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1712dc58b6f4SAndy Webber                switch($conf['showuseras']) {
1713dc58b6f4SAndy Webber                    case 'username':
17147f081821SGerrit Uitslag                    case 'username_link':
171515f3bc49SGerrit Uitslag                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
171660a396c8SGerrit Uitslag                        break;
1717dc58b6f4SAndy Webber                    case 'email':
1718dc58b6f4SAndy Webber                    case 'email_link':
171960a396c8SGerrit Uitslag                        $data['name'] = obfuscate($info['mail']);
172060a396c8SGerrit Uitslag                        break;
1721dc58b6f4SAndy Webber                }
172265833968SGerrit Uitslag            } else {
172365833968SGerrit Uitslag                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
172460a396c8SGerrit Uitslag            }
172560a396c8SGerrit Uitslag        }
17267f081821SGerrit Uitslag
17277f081821SGerrit Uitslag        /** @var Doku_Renderer_xhtml $xhtml_renderer */
17287f081821SGerrit Uitslag        static $xhtml_renderer = null;
17297f081821SGerrit Uitslag
173015f3bc49SGerrit Uitslag        if(!$data['textonly'] && empty($data['link']['url'])) {
17317f081821SGerrit Uitslag
173224870174SAndreas Gohr            if(in_array($conf['showuseras'], ['email_link', 'username_link'])) {
173360a396c8SGerrit Uitslag                if(!isset($info)) {
173460a396c8SGerrit Uitslag                    if($auth) $info = $auth->getUserData($username);
173560a396c8SGerrit Uitslag                }
173660a396c8SGerrit Uitslag                if(isset($info) && $info) {
17377f081821SGerrit Uitslag                    if($conf['showuseras'] == 'email_link') {
173860a396c8SGerrit Uitslag                        $data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
1739dc58b6f4SAndy Webber                    } else {
17407f081821SGerrit Uitslag                        if(is_null($xhtml_renderer)) {
17417f081821SGerrit Uitslag                            $xhtml_renderer = p_get_renderer('xhtml');
17427f081821SGerrit Uitslag                        }
17437f081821SGerrit Uitslag                        if(empty($xhtml_renderer->interwiki)) {
17447f081821SGerrit Uitslag                            $xhtml_renderer->interwiki = getInterwiki();
17457f081821SGerrit Uitslag                        }
17467f081821SGerrit Uitslag                        $shortcut = 'user';
1747533772e1SGerrit Uitslag                        $exists = null;
17486496c33fSGerrit Uitslag                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
17492a2a43c4SGerrit Uitslag                        $data['link']['class'] .= ' interwiki iw_user';
17506496c33fSGerrit Uitslag                        if($exists !== null) {
17516496c33fSGerrit Uitslag                            if($exists) {
17526496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink1';
17536496c33fSGerrit Uitslag                            } else {
17546496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink2';
17556496c33fSGerrit Uitslag                                $data['link']['rel'] = 'nofollow';
17566496c33fSGerrit Uitslag                            }
17576496c33fSGerrit Uitslag                        }
1758dc58b6f4SAndy Webber                    }
1759dc58b6f4SAndy Webber                } else {
176015f3bc49SGerrit Uitslag                    $data['textonly'] = true;
1761dc58b6f4SAndy Webber                }
176260a396c8SGerrit Uitslag
176360a396c8SGerrit Uitslag            } else {
176415f3bc49SGerrit Uitslag                $data['textonly'] = true;
176560a396c8SGerrit Uitslag            }
176660a396c8SGerrit Uitslag        }
176760a396c8SGerrit Uitslag
176815f3bc49SGerrit Uitslag        if($data['textonly']) {
17694d5fc927SGerrit Uitslag            $data['userlink'] = $data['name'];
177060a396c8SGerrit Uitslag        } else {
177160a396c8SGerrit Uitslag            $data['link']['name'] = $data['name'];
177260a396c8SGerrit Uitslag            if(is_null($xhtml_renderer)) {
177360a396c8SGerrit Uitslag                $xhtml_renderer = p_get_renderer('xhtml');
177460a396c8SGerrit Uitslag            }
17754d5fc927SGerrit Uitslag            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
177660a396c8SGerrit Uitslag        }
177760a396c8SGerrit Uitslag    }
177860a396c8SGerrit Uitslag    $evt->advise_after();
177960a396c8SGerrit Uitslag    unset($evt);
178060a396c8SGerrit Uitslag
17814d5fc927SGerrit Uitslag    return $data['userlink'];
1782066fee30SAndreas Gohr}
1783066fee30SAndreas Gohr
1784066fee30SAndreas Gohr/**
1785066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1786066fee30SAndreas Gohr * When no image exists, returns an empty string
1787066fee30SAndreas Gohr *
1788066fee30SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1789140cfbcdSGerrit Uitslag *
1790066fee30SAndreas Gohr * @param  string $type - type of image 'badge' or 'button'
17913272d797SAndreas Gohr * @return string
1792066fee30SAndreas Gohr */
1793*d868eb89SAndreas Gohrfunction license_img($type)
1794*d868eb89SAndreas Gohr{
1795066fee30SAndreas Gohr    global $license;
1796066fee30SAndreas Gohr    global $conf;
1797066fee30SAndreas Gohr    if(!$conf['license']) return '';
1798066fee30SAndreas Gohr    if(!is_array($license[$conf['license']])) return '';
179924870174SAndreas Gohr    $try   = [];
1800066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1801066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1802066fee30SAndreas Gohr    if(substr($conf['license'], 0, 3) == 'cc-') {
1803066fee30SAndreas Gohr        $try[] = 'lib/images/license/'.$type.'/cc.png';
1804066fee30SAndreas Gohr    }
1805066fee30SAndreas Gohr    foreach($try as $src) {
180679e79377SAndreas Gohr        if(file_exists(DOKU_INC.$src)) return $src;
1807066fee30SAndreas Gohr    }
1808066fee30SAndreas Gohr    return '';
1809dc58b6f4SAndy Webber}
1810dc58b6f4SAndy Webber
181113c08e2fSMichael Klier/**
181213c08e2fSMichael Klier * Checks if the given amount of memory is available
181313c08e2fSMichael Klier *
181413c08e2fSMichael Klier * If the memory_get_usage() function is not available the
181513c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
181613c08e2fSMichael Klier *
181713c08e2fSMichael Klier * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
181813c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
18193272d797SAndreas Gohr *
18203272d797SAndreas Gohr * @param int  $mem    Size of memory you want to allocate in bytes
1821140cfbcdSGerrit Uitslag * @param int  $bytes  already allocated memory (see above)
18223272d797SAndreas Gohr * @return bool
182313c08e2fSMichael Klier */
1824*d868eb89SAndreas Gohrfunction is_mem_available($mem, $bytes = 1_048_576)
1825*d868eb89SAndreas Gohr{
182613c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
182713c08e2fSMichael Klier    if(empty($limit)) return true; // no limit set!
1828985d6187SElenchus    if($limit == -1) return true; // unlimited
182913c08e2fSMichael Klier
183013c08e2fSMichael Klier    // parse limit to bytes
183113c08e2fSMichael Klier    $limit = php_to_byte($limit);
183213c08e2fSMichael Klier
183313c08e2fSMichael Klier    // get used memory if possible
183413c08e2fSMichael Klier    if(function_exists('memory_get_usage')) {
183513c08e2fSMichael Klier        $used = memory_get_usage();
183649eb6e38SAndreas Gohr    } else {
183749eb6e38SAndreas Gohr        $used = $bytes;
183813c08e2fSMichael Klier    }
183913c08e2fSMichael Klier
184013c08e2fSMichael Klier    if($used + $mem > $limit) {
184113c08e2fSMichael Klier        return false;
184213c08e2fSMichael Klier    }
184313c08e2fSMichael Klier
184413c08e2fSMichael Klier    return true;
184513c08e2fSMichael Klier}
184613c08e2fSMichael Klier
1847af2408d5SAndreas Gohr/**
1848af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1849af2408d5SAndreas Gohr *
1850af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1851af2408d5SAndreas Gohr *
1852af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1853af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1854140cfbcdSGerrit Uitslag *
1855140cfbcdSGerrit Uitslag * @param string $url url being directed to
1856af2408d5SAndreas Gohr */
1857*d868eb89SAndreas Gohrfunction send_redirect($url)
1858*d868eb89SAndreas Gohr{
185998ca30d2SAndreas Gohr    $url = stripctl($url); // defend against HTTP Response Splitting
186098ca30d2SAndreas Gohr
1861585bf44eSChristopher Smith    /* @var Input $INPUT */
1862585bf44eSChristopher Smith    global $INPUT;
1863585bf44eSChristopher Smith
18640181f021SAndreas Gohr    //are there any undisplayed messages? keep them in session for display
18650181f021SAndreas Gohr    global $MSG;
18660181f021SAndreas Gohr    if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
18670181f021SAndreas Gohr        //reopen session, store data and close session again
18680181f021SAndreas Gohr        @session_start();
18690181f021SAndreas Gohr        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
18700181f021SAndreas Gohr    }
18710181f021SAndreas Gohr
1872d4869846SAndreas Gohr    // always close the session
1873d4869846SAndreas Gohr    session_write_close();
1874d4869846SAndreas Gohr
1875af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
1876585bf44eSChristopher Smith    if($INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1877585bf44eSChristopher Smith        (strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) &&
1878585bf44eSChristopher Smith        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
18793272d797SAndreas Gohr        $matches[1] < 6
18803272d797SAndreas Gohr    ) {
1881af2408d5SAndreas Gohr        header('Refresh: 0;url='.$url);
1882af2408d5SAndreas Gohr    } else {
1883af2408d5SAndreas Gohr        header('Location: '.$url);
1884af2408d5SAndreas Gohr    }
188581781cb6SAndreas Gohr
1886572dc222SLarsDW223    // no exits during unit tests
188727c0c399SAndreas Gohr    if(defined('DOKU_UNITTEST')) {
188827c0c399SAndreas Gohr        // pass info about the redirect back to the test suite
188927c0c399SAndreas Gohr        $testRequest = TestRequest::getRunning();
189027c0c399SAndreas Gohr        if($testRequest !== null) {
189127c0c399SAndreas Gohr            $testRequest->addData('send_redirect', $url);
189227c0c399SAndreas Gohr        }
1893572dc222SLarsDW223        return;
1894572dc222SLarsDW223    }
189527c0c399SAndreas Gohr
1896af2408d5SAndreas Gohr    exit;
1897af2408d5SAndreas Gohr}
1898af2408d5SAndreas Gohr
18995b75cd1fSAdrian Lang/**
19005b75cd1fSAdrian Lang * Validate a value using a set of valid values
19015b75cd1fSAdrian Lang *
19025b75cd1fSAdrian Lang * This function checks whether a specified value is set and in the array
19035b75cd1fSAdrian Lang * $valid_values. If not, the function returns a default value or, if no
19045b75cd1fSAdrian Lang * default is specified, throws an exception.
19055b75cd1fSAdrian Lang *
19065b75cd1fSAdrian Lang * @param string $param        The name of the parameter
19075b75cd1fSAdrian Lang * @param array  $valid_values A set of valid values; Optionally a default may
19085b75cd1fSAdrian Lang *                             be marked by the key “default”.
19095b75cd1fSAdrian Lang * @param array  $array        The array containing the value (typically $_POST
19105b75cd1fSAdrian Lang *                             or $_GET)
19115b75cd1fSAdrian Lang * @param string $exc          The text of the raised exception
19125b75cd1fSAdrian Lang *
19133272d797SAndreas Gohr * @throws Exception
19143272d797SAndreas Gohr * @return mixed
19155b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
19165b75cd1fSAdrian Lang */
1917*d868eb89SAndreas Gohrfunction valid_input_set($param, $valid_values, $array, $exc = '')
1918*d868eb89SAndreas Gohr{
19195b75cd1fSAdrian Lang    if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
19205b75cd1fSAdrian Lang        return $array[$param];
19215b75cd1fSAdrian Lang    } elseif(isset($valid_values['default'])) {
19225b75cd1fSAdrian Lang        return $valid_values['default'];
19235b75cd1fSAdrian Lang    } else {
19245b75cd1fSAdrian Lang        throw new Exception($exc);
19255b75cd1fSAdrian Lang    }
19265b75cd1fSAdrian Lang}
19275b75cd1fSAdrian Lang
192863703ba5SAndreas Gohr/**
192963703ba5SAndreas Gohr * Read a preference from the DokuWiki cookie
1930646a531aSChristopher Smith * (remembering both keys & values are urlencoded)
1931140cfbcdSGerrit Uitslag *
1932140cfbcdSGerrit Uitslag * @param string $pref     preference key
1933b4b6c9a1SGerrit Uitslag * @param mixed  $default  value returned when preference not found
1934140cfbcdSGerrit Uitslag * @return string preference value
193563703ba5SAndreas Gohr */
1936*d868eb89SAndreas Gohrfunction get_doku_pref($pref, $default)
1937*d868eb89SAndreas Gohr{
1938646a531aSChristopher Smith    $enc_pref = urlencode($pref);
193906c9ee33SMarius van Witzenburg    if(isset($_COOKIE['DOKU_PREFS']) && strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
1940554a8c9fSAdrian Lang        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
194163703ba5SAndreas Gohr        $cnt   = count($parts);
19421c3eca7dSPhy
19431c3eca7dSPhy        // due to #2721 there might be duplicate entries,
19441c3eca7dSPhy        // so we read from the end
19451c3eca7dSPhy        for($i = $cnt-2; $i >= 0; $i -= 2) {
194624870174SAndreas Gohr            if($parts[$i] === $enc_pref) {
1947646a531aSChristopher Smith                return urldecode($parts[$i + 1]);
1948554a8c9fSAdrian Lang            }
1949554a8c9fSAdrian Lang        }
1950554a8c9fSAdrian Lang    }
1951554a8c9fSAdrian Lang    return $default;
1952554a8c9fSAdrian Lang}
1953554a8c9fSAdrian Lang
19543c94d07bSAnika Henke/**
19553c94d07bSAnika Henke * Add a preference to the DokuWiki cookie
195636ec377eSChristopher Smith * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
19573a970889SAnika Henke * Remove it by setting $val to false
1958140cfbcdSGerrit Uitslag *
1959140cfbcdSGerrit Uitslag * @param string $pref  preference key
1960140cfbcdSGerrit Uitslag * @param string $val   preference value
19613c94d07bSAnika Henke */
1962*d868eb89SAndreas Gohrfunction set_doku_pref($pref, $val)
1963*d868eb89SAndreas Gohr{
19643c94d07bSAnika Henke    global $conf;
19653c94d07bSAnika Henke    $orig = get_doku_pref($pref, false);
19663c94d07bSAnika Henke    $cookieVal = '';
19673c94d07bSAnika Henke
19681c3eca7dSPhy    if ($orig !== false && ($orig !== $val)) {
19693c94d07bSAnika Henke        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
19703c94d07bSAnika Henke        $cnt   = count($parts);
197136ec377eSChristopher Smith        // urlencode $pref for the comparison
197236ec377eSChristopher Smith        $enc_pref = rawurlencode($pref);
19731c3eca7dSPhy        $seen = false;
19743c94d07bSAnika Henke        for ($i = 0; $i < $cnt; $i += 2) {
197524870174SAndreas Gohr            if ($parts[$i] === $enc_pref) {
19761c3eca7dSPhy                if (!$seen){
19773a970889SAnika Henke                    if ($val !== false) {
1978bf8f8509SAndreas Gohr                        $parts[$i + 1] = rawurlencode($val ?? '');
19793a970889SAnika Henke                    } else {
19803a970889SAnika Henke                        unset($parts[$i]);
19813a970889SAnika Henke                        unset($parts[$i + 1]);
19823a970889SAnika Henke                    }
19831c3eca7dSPhy                    $seen = true;
19841c3eca7dSPhy                } else {
19851c3eca7dSPhy                    // no break because we want to remove duplicate entries
19861c3eca7dSPhy                    unset($parts[$i]);
19871c3eca7dSPhy                    unset($parts[$i + 1]);
19881c3eca7dSPhy                }
19893c94d07bSAnika Henke            }
19903c94d07bSAnika Henke        }
19913c94d07bSAnika Henke        $cookieVal = implode('#', $parts);
19921c3eca7dSPhy    } elseif ($orig === false && $val !== false) {
1993c10f256aSDamien Regad        $cookieVal = (isset($_COOKIE['DOKU_PREFS']) ? $_COOKIE['DOKU_PREFS'] . '#' : '') .
199464159a61SAndreas Gohr            rawurlencode($pref) . '#' . rawurlencode($val);
19953c94d07bSAnika Henke    }
19963c94d07bSAnika Henke
199775e4dd8aSGerrit Uitslag    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
19985833995aSPhy    if(defined('DOKU_UNITTEST')) {
19995833995aSPhy        $_COOKIE['DOKU_PREFS'] = $cookieVal;
20005833995aSPhy    }else{
2001bf8392ebSAndreas Gohr        setcookie('DOKU_PREFS', $cookieVal, [
2002bf8392ebSAndreas Gohr            'expires' => time() + 365 * 24 * 3600,
2003bf8392ebSAndreas Gohr            'path' => $cookieDir,
2004bf8392ebSAndreas Gohr            'secure' => ($conf['securecookie'] && is_ssl()),
2005bf8392ebSAndreas Gohr            'samesite' => 'Lax'
2006bf8392ebSAndreas Gohr        ]);
20073c94d07bSAnika Henke    }
20083c94d07bSAnika Henke}
20093c94d07bSAnika Henke
2010f8fb2d18SAndreas Gohr/**
2011f8fb2d18SAndreas Gohr * Strips source mapping declarations from given text #601
2012f8fb2d18SAndreas Gohr *
201342ea7f44SGerrit Uitslag * @param string &$text reference to the CSS or JavaScript code to clean
2014f8fb2d18SAndreas Gohr */
2015*d868eb89SAndreas Gohrfunction stripsourcemaps(&$text)
2016*d868eb89SAndreas Gohr{
2017f8fb2d18SAndreas Gohr    $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text);
2018f8fb2d18SAndreas Gohr}
2019f8fb2d18SAndreas Gohr
20203c27983bSAndreas Gohr/**
202171de5572SAndreas Gohr * Returns the contents of a given SVG file for embedding
20223c27983bSAndreas Gohr *
20233c27983bSAndreas Gohr * Inlining SVGs saves on HTTP requests and more importantly allows for styling them through
20243c27983bSAndreas Gohr * CSS. However it should used with small SVGs only. The $maxsize setting ensures only small
20253c27983bSAndreas Gohr * files are embedded.
20263c27983bSAndreas Gohr *
202771de5572SAndreas Gohr * This strips unneeded headers, comments and newline. The result is not a vaild standalone SVG!
202871de5572SAndreas Gohr *
20293c27983bSAndreas Gohr * @param string $file full path to the SVG file
20303c27983bSAndreas Gohr * @param int $maxsize maximum allowed size for the SVG to be embedded
203171de5572SAndreas Gohr * @return string|false the SVG content, false if the file couldn't be loaded
20323c27983bSAndreas Gohr */
2033*d868eb89SAndreas Gohrfunction inlineSVG($file, $maxsize = 2048)
2034*d868eb89SAndreas Gohr{
20353c27983bSAndreas Gohr    $file = trim($file);
20363c27983bSAndreas Gohr    if($file === '') return false;
20373c27983bSAndreas Gohr    if(!file_exists($file)) return false;
20383c27983bSAndreas Gohr    if(filesize($file) > $maxsize) return false;
20393c27983bSAndreas Gohr    if(!is_readable($file)) return false;
20403c27983bSAndreas Gohr    $content = file_get_contents($file);
20410849fa88SAndreas Gohr    $content = preg_replace('/<!--.*?(-->)/s', '', $content); // comments
20420849fa88SAndreas Gohr    $content = preg_replace('/<\?xml .*?\?>/i', '', $content); // xml header
20430849fa88SAndreas Gohr    $content = preg_replace('/<!DOCTYPE .*?>/i', '', $content); // doc type
20440849fa88SAndreas Gohr    $content = preg_replace('/>\s+</s', '><', $content); // newlines between tags
20453c27983bSAndreas Gohr    $content = trim($content);
20463c27983bSAndreas Gohr    if(substr($content, 0, 5) !== '<svg ') return false;
204771de5572SAndreas Gohr    return $content;
20483c27983bSAndreas Gohr}
20493c27983bSAndreas Gohr
2050e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
2051