xref: /dokuwiki/inc/common.php (revision 6cc6a0d2d8cfd4379f05b92c2dd838275d7f1edd)
1ed7b5f09Sandi<?php
2d4f83172SAndreas Gohr
315fae107Sandi/**
415fae107Sandi * Common DokuWiki functions
515fae107Sandi *
615fae107Sandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
715fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
815fae107Sandi */
9d4f83172SAndreas Gohr
1024870174SAndreas Gohruse dokuwiki\PassHash;
1124870174SAndreas Gohruse dokuwiki\Draft;
1224870174SAndreas Gohruse dokuwiki\Utf8\Clean;
1324870174SAndreas Gohruse dokuwiki\Utf8\PhpString;
1424870174SAndreas Gohruse dokuwiki\Utf8\Conversion;
150db5771eSMichael Großeuse dokuwiki\Cache\CacheRenderer;
160c3a5702SAndreas Gohruse dokuwiki\ChangeLog\PageChangeLog;
17b24e9c4aSSatoshi Saharause dokuwiki\File\PageFile;
18704a815fSMichael Großeuse dokuwiki\Subscriptions\PageSubscriptionSender;
1975d66495SMichael Großeuse dokuwiki\Subscriptions\SubscriberManager;
20e1d9dcc8SAndreas Gohruse dokuwiki\Extension\AuthPlugin;
21e1d9dcc8SAndreas Gohruse dokuwiki\Extension\Event;
220c3a5702SAndreas Gohr
238b19906eSAndreas Gohruse function PHP81_BC\strftime;
248b19906eSAndreas Gohr
25f3f0262cSandi/**
26d5197206Schris * Wrapper around htmlspecialchars()
27d5197206Schris *
288b19906eSAndreas Gohr * @param string $string the string being converted
298b19906eSAndreas Gohr * @return string converted string
30d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
31d5197206Schris * @see    htmlspecialchars()
32140cfbcdSGerrit Uitslag *
33d5197206Schris */
34d868eb89SAndreas Gohrfunction hsc($string)
35d868eb89SAndreas Gohr{
36f7711f2bSAndreas Gohr    return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, 'UTF-8');
37d5197206Schris}
38d5197206Schris
39d5197206Schris/**
4012dd3cbcSAndreas Gohr * A safer explode for fixed length lists
4112dd3cbcSAndreas Gohr *
4212dd3cbcSAndreas Gohr * This works just like explode(), but will always return the wanted number of elements.
4312dd3cbcSAndreas Gohr * If the $input string does not contain enough elements, the missing elements will be
4412dd3cbcSAndreas Gohr * filled up with the $default value. If the input string contains more elements, the last
4512dd3cbcSAndreas Gohr * one will NOT be split up and will still contain $separator
4612dd3cbcSAndreas Gohr *
4712dd3cbcSAndreas Gohr * @param string $separator The boundary string
4812dd3cbcSAndreas Gohr * @param string $string The input string
4912dd3cbcSAndreas Gohr * @param int $limit The number of expected elements
5012dd3cbcSAndreas Gohr * @param mixed $default The value to use when filling up missing elements
5112dd3cbcSAndreas Gohr * @return array
528b19906eSAndreas Gohr * @see explode
5312dd3cbcSAndreas Gohr */
5412dd3cbcSAndreas Gohrfunction sexplode($separator, $string, $limit, $default = null)
5512dd3cbcSAndreas Gohr{
5612dd3cbcSAndreas Gohr    return array_pad(explode($separator, $string, $limit), $limit, $default);
5712dd3cbcSAndreas Gohr}
5812dd3cbcSAndreas Gohr
5912dd3cbcSAndreas Gohr/**
605b571377SAndreas Gohr * Checks if the given input is blank
615b571377SAndreas Gohr *
625b571377SAndreas Gohr * This is similar to empty() but will return false for "0".
635b571377SAndreas Gohr *
6467234204SAndreas Gohr * Please note: when you pass uninitialized variables, they will implicitly be created
6567234204SAndreas Gohr * with a NULL value without warning.
6667234204SAndreas Gohr *
6767234204SAndreas Gohr * To avoid this it's recommended to guard the call with isset like this:
6867234204SAndreas Gohr *
6967234204SAndreas Gohr * (isset($foo) && !blank($foo))
7067234204SAndreas Gohr * (!isset($foo) || blank($foo))
7167234204SAndreas Gohr *
725b571377SAndreas Gohr * @param $in
735b571377SAndreas Gohr * @param bool $trim Consider a string of whitespace to be blank
745b571377SAndreas Gohr * @return bool
755b571377SAndreas Gohr */
76d868eb89SAndreas Gohrfunction blank(&$in, $trim = false)
77d868eb89SAndreas Gohr{
785b571377SAndreas Gohr    if (is_null($in)) return true;
7924870174SAndreas Gohr    if (is_array($in)) return $in === [];
805b571377SAndreas Gohr    if ($in === "\0") return true;
815b571377SAndreas Gohr    if ($trim && trim($in) === '') return true;
825b571377SAndreas Gohr    if (strlen($in) > 0) return false;
835b571377SAndreas Gohr    return empty($in);
845b571377SAndreas Gohr}
855b571377SAndreas Gohr
865b571377SAndreas Gohr/**
8702b0b681SAndreas Gohr * strips control characters (<32) from the given string
8802b0b681SAndreas Gohr *
8942ea7f44SGerrit Uitslag * @param string $string being stripped
90140cfbcdSGerrit Uitslag * @return string
918b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
928b19906eSAndreas Gohr *
9302b0b681SAndreas Gohr */
94d868eb89SAndreas Gohrfunction stripctl($string)
95d868eb89SAndreas Gohr{
9602b0b681SAndreas Gohr    return preg_replace('/[\x00-\x1F]+/s', '', $string);
97d5197206Schris}
98d5197206Schris
99d5197206Schris/**
100634d7150SAndreas Gohr * Return a secret token to be used for CSRF attack prevention
101634d7150SAndreas Gohr *
1028b19906eSAndreas Gohr * @return  string
103634d7150SAndreas Gohr * @link    http://en.wikipedia.org/wiki/Cross-site_request_forgery
104634d7150SAndreas Gohr * @link    http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
10542ea7f44SGerrit Uitslag *
1068b19906eSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
107634d7150SAndreas Gohr */
108d868eb89SAndreas Gohrfunction getSecurityToken()
109d868eb89SAndreas Gohr{
110585bf44eSChristopher Smith    /** @var Input $INPUT */
111585bf44eSChristopher Smith    global $INPUT;
1123680e2cdSAndreas Gohr
1133680e2cdSAndreas Gohr    $user = $INPUT->server->str('REMOTE_USER');
1143680e2cdSAndreas Gohr    $session = session_id();
1153680e2cdSAndreas Gohr
1163680e2cdSAndreas Gohr    // CSRF checks are only for logged in users - do not generate for anonymous
1173680e2cdSAndreas Gohr    if (trim($user) == '' || trim($session) == '') return '';
11824870174SAndreas Gohr    return PassHash::hmac('md5', $session . $user, auth_cookiesalt());
119634d7150SAndreas Gohr}
120634d7150SAndreas Gohr
121634d7150SAndreas Gohr/**
122634d7150SAndreas Gohr * Check the secret CSRF token
123140cfbcdSGerrit Uitslag *
124140cfbcdSGerrit Uitslag * @param null|string $token security token or null to read it from request variable
125140cfbcdSGerrit Uitslag * @return bool success if the token matched
126634d7150SAndreas Gohr */
127d868eb89SAndreas Gohrfunction checkSecurityToken($token = null)
128d868eb89SAndreas Gohr{
129585bf44eSChristopher Smith    /** @var Input $INPUT */
1307d01a0eaSTom N Harris    global $INPUT;
131585bf44eSChristopher Smith    if (!$INPUT->server->str('REMOTE_USER')) return true; // no logged in user, no need for a check
132df97eaacSAndreas Gohr
1337d01a0eaSTom N Harris    if (is_null($token)) $token = $INPUT->str('sectok');
134634d7150SAndreas Gohr    if (getSecurityToken() != $token) {
135634d7150SAndreas Gohr        msg('Security Token did not match. Possible CSRF attack.', -1);
136634d7150SAndreas Gohr        return false;
137634d7150SAndreas Gohr    }
138634d7150SAndreas Gohr    return true;
139634d7150SAndreas Gohr}
140634d7150SAndreas Gohr
141634d7150SAndreas Gohr/**
142634d7150SAndreas Gohr * Print a hidden form field with a secret CSRF token
143634d7150SAndreas Gohr *
144140cfbcdSGerrit Uitslag * @param bool $print if true print the field, otherwise html of the field is returned
14542ea7f44SGerrit Uitslag * @return string html of hidden form field
1468b19906eSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
1478b19906eSAndreas Gohr *
148634d7150SAndreas Gohr */
149d868eb89SAndreas Gohrfunction formSecurityToken($print = true)
150d868eb89SAndreas Gohr{
1512404d0edSAnika Henke    $ret = '<div class="no"><input type="hidden" name="sectok" value="' . getSecurityToken() . '" /></div>' . "\n";
1523272d797SAndreas Gohr    if ($print) echo $ret;
153634d7150SAndreas Gohr    return $ret;
154634d7150SAndreas Gohr}
155634d7150SAndreas Gohr
156634d7150SAndreas Gohr/**
1571015a57dSChristopher Smith * Determine basic information for a request of $id
15815fae107Sandi *
159140cfbcdSGerrit Uitslag * @param string $id pageid
160140cfbcdSGerrit Uitslag * @param bool $htmlClient add info about whether is mobile browser
161140cfbcdSGerrit Uitslag * @return array with info for a request of $id
162140cfbcdSGerrit Uitslag *
1638b19906eSAndreas Gohr * @author Chris Smith <chris@jalakai.co.uk>
1648b19906eSAndreas Gohr *
1658b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
166f3f0262cSandi */
167d868eb89SAndreas Gohrfunction basicinfo($id, $htmlClient = true)
168d868eb89SAndreas Gohr{
169f3f0262cSandi    global $USERINFO;
170585bf44eSChristopher Smith    /* @var Input $INPUT */
171585bf44eSChristopher Smith    global $INPUT;
1726afe8dcaSchris
173c66972f2SAdrian Lang    // set info about manager/admin status.
17424870174SAndreas Gohr    $info = [];
175c66972f2SAdrian Lang    $info['isadmin'] = false;
176c66972f2SAdrian Lang    $info['ismanager'] = false;
177585bf44eSChristopher Smith    if ($INPUT->server->has('REMOTE_USER')) {
178f3f0262cSandi        $info['userinfo'] = $USERINFO;
1791015a57dSChristopher Smith        $info['perm'] = auth_quickaclcheck($id);
180585bf44eSChristopher Smith        $info['client'] = $INPUT->server->str('REMOTE_USER');
18117ee7f66SAndreas Gohr
182f8cc712eSAndreas Gohr        if ($info['perm'] == AUTH_ADMIN) {
183f8cc712eSAndreas Gohr            $info['isadmin'] = true;
184f8cc712eSAndreas Gohr            $info['ismanager'] = true;
185f8cc712eSAndreas Gohr        } elseif (auth_ismanager()) {
186f8cc712eSAndreas Gohr            $info['ismanager'] = true;
187f8cc712eSAndreas Gohr        }
188f8cc712eSAndreas Gohr
18917ee7f66SAndreas Gohr        // if some outside auth were used only REMOTE_USER is set
190a58fcbbcSAndreas Gohr        if (empty($info['userinfo']['name'])) {
191585bf44eSChristopher Smith            $info['userinfo']['name'] = $INPUT->server->str('REMOTE_USER');
19217ee7f66SAndreas Gohr        }
193f3f0262cSandi    } else {
1941015a57dSChristopher Smith        $info['perm'] = auth_aclcheck($id, '', null);
195ee4c4a1bSAndreas Gohr        $info['client'] = clientIP(true);
196f3f0262cSandi    }
197f3f0262cSandi
1981015a57dSChristopher Smith    $info['namespace'] = getNS($id);
1991015a57dSChristopher Smith
2001015a57dSChristopher Smith    // mobile detection
2011015a57dSChristopher Smith    if ($htmlClient) {
2021015a57dSChristopher Smith        $info['ismobile'] = clientismobile();
2031015a57dSChristopher Smith    }
2041015a57dSChristopher Smith
2051015a57dSChristopher Smith    return $info;
2061015a57dSChristopher Smith}
2071015a57dSChristopher Smith
2081015a57dSChristopher Smith/**
2091015a57dSChristopher Smith * Return info about the current document as associative
2101015a57dSChristopher Smith * array.
2111015a57dSChristopher Smith *
212140cfbcdSGerrit Uitslag * @return array with info about current document
2134dc42f7fSGerrit Uitslag * @throws Exception
2144dc42f7fSGerrit Uitslag *
2154dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
2161015a57dSChristopher Smith */
217d868eb89SAndreas Gohrfunction pageinfo()
218d868eb89SAndreas Gohr{
2191015a57dSChristopher Smith    global $ID;
2201015a57dSChristopher Smith    global $REV;
2211015a57dSChristopher Smith    global $RANGE;
2221015a57dSChristopher Smith    global $lang;
2231015a57dSChristopher Smith
2241015a57dSChristopher Smith    $info = basicinfo($ID);
2251015a57dSChristopher Smith
2261015a57dSChristopher Smith    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
2271015a57dSChristopher Smith    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
2281015a57dSChristopher Smith    $info['id'] = $ID;
2291015a57dSChristopher Smith    $info['rev'] = $REV;
2301015a57dSChristopher Smith
23175d66495SMichael Große    $subManager = new SubscriberManager();
23275d66495SMichael Große    $info['subscribed'] = $subManager->userSubscription();
2337e87a794SChristopher Smith
234f3f0262cSandi    $info['locked'] = checklock($ID);
235317a04c4SSatoshi Sahara    $info['filepath'] = wikiFN($ID);
23679e79377SAndreas Gohr    $info['exists'] = file_exists($info['filepath']);
23701c9a118SAndreas Gohr    $info['currentrev'] = @filemtime($info['filepath']);
2385ec96136SSatoshi Sahara
2392ca9d91cSBen Coburn    if ($REV) {
2402ca9d91cSBen Coburn        //check if current revision was meant
24101c9a118SAndreas Gohr        if ($info['exists'] && ($info['currentrev'] == $REV)) {
2422ca9d91cSBen Coburn            $REV = '';
2437b3a6803SAndreas Gohr        } elseif ($RANGE) {
2447b3a6803SAndreas Gohr            //section editing does not work with old revisions!
2457b3a6803SAndreas Gohr            $REV = '';
2467b3a6803SAndreas Gohr            $RANGE = '';
2477b3a6803SAndreas Gohr            msg($lang['nosecedit'], 0);
2482ca9d91cSBen Coburn        } else {
2492ca9d91cSBen Coburn            //really use old revision
250317a04c4SSatoshi Sahara            $info['filepath'] = wikiFN($ID, $REV);
25179e79377SAndreas Gohr            $info['exists'] = file_exists($info['filepath']);
252f3f0262cSandi        }
253f3f0262cSandi    }
254c112d578Sandi    $info['rev'] = $REV;
255f3f0262cSandi    if ($info['exists']) {
256252acce3SSatoshi Sahara        $info['writable'] = (is_writable($info['filepath']) && $info['perm'] >= AUTH_EDIT);
257f3f0262cSandi    } else {
258f3f0262cSandi        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
259f3f0262cSandi    }
26050e988b1SAndreas Gohr    $info['editable'] = ($info['writable'] && empty($info['locked']));
261f3f0262cSandi    $info['lastmod'] = @filemtime($info['filepath']);
262f3f0262cSandi
26371726d78SBen Coburn    //load page meta data
26471726d78SBen Coburn    $info['meta'] = p_get_metadata($ID);
26571726d78SBen Coburn
266652610a2Sandi    //who's the editor
267047bad06SGerrit Uitslag    $pagelog = new PageChangeLog($ID, 1024);
268652610a2Sandi    if ($REV) {
269f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($REV);
27024870174SAndreas Gohr    } elseif (!empty($info['meta']['last_change']) && is_array($info['meta']['last_change'])) {
271aa27cf05SAndreas Gohr        $revinfo = $info['meta']['last_change'];
272aa27cf05SAndreas Gohr    } else {
273f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($info['lastmod']);
274cd00a034SBen Coburn        // cache most recent changelog line in metadata if missing and still valid
275cd00a034SBen Coburn        if ($revinfo !== false) {
276cd00a034SBen Coburn            $info['meta']['last_change'] = $revinfo;
27724870174SAndreas Gohr            p_set_metadata($ID, ['last_change' => $revinfo]);
278cd00a034SBen Coburn        }
279cd00a034SBen Coburn    }
280cd00a034SBen Coburn    //and check for an external edit
281cd00a034SBen Coburn    if ($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
282cd00a034SBen Coburn        // cached changelog line no longer valid
283cd00a034SBen Coburn        $revinfo = false;
284cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
28524870174SAndreas Gohr        p_set_metadata($ID, ['last_change' => $revinfo]);
286652610a2Sandi    }
287bb4866bdSchris
2880a444b5aSPhy    if ($revinfo !== false) {
289652610a2Sandi        $info['ip'] = $revinfo['ip'];
290652610a2Sandi        $info['user'] = $revinfo['user'];
291652610a2Sandi        $info['sum'] = $revinfo['sum'];
29271726d78SBen Coburn        // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
293ebf1501fSBen Coburn        // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
29459f257aeSchris
295252acce3SSatoshi Sahara        $info['editor'] = $revinfo['user'] ?: $revinfo['ip'];
2960a444b5aSPhy    } else {
2970a444b5aSPhy        $info['ip'] = null;
2980a444b5aSPhy        $info['user'] = null;
2990a444b5aSPhy        $info['sum'] = null;
3000a444b5aSPhy        $info['editor'] = null;
3010a444b5aSPhy    }
302652610a2Sandi
303ee4c4a1bSAndreas Gohr    // draft
30424870174SAndreas Gohr    $draft = new Draft($ID, $info['client']);
3050aabe6f8SMichael Große    if ($draft->isDraftAvailable()) {
3060aabe6f8SMichael Große        $info['draft'] = $draft->getDraftFilename();
307ee4c4a1bSAndreas Gohr    }
308ee4c4a1bSAndreas Gohr
3091015a57dSChristopher Smith    return $info;
3101015a57dSChristopher Smith}
3111015a57dSChristopher Smith
3121015a57dSChristopher Smith/**
3130c39d46cSMichael Große * Initialize and/or fill global $JSINFO with some basic info to be given to javascript
3140c39d46cSMichael Große */
315d868eb89SAndreas Gohrfunction jsinfo()
316d868eb89SAndreas Gohr{
3170c39d46cSMichael Große    global $JSINFO, $ID, $INFO, $ACT;
3180c39d46cSMichael Große
3190c39d46cSMichael Große    if (!is_array($JSINFO)) {
3200c39d46cSMichael Große        $JSINFO = [];
3210c39d46cSMichael Große    }
3220c39d46cSMichael Große    //export minimal info to JS, plugins can add more
3230c39d46cSMichael Große    $JSINFO['id'] = $ID;
32468491db9SPhy    $JSINFO['namespace'] = isset($INFO) ? (string)$INFO['namespace'] : '';
3250c39d46cSMichael Große    $JSINFO['ACT'] = act_clean($ACT);
3260c39d46cSMichael Große    $JSINFO['useHeadingNavigation'] = (int)useHeading('navigation');
3270c39d46cSMichael Große    $JSINFO['useHeadingContent'] = (int)useHeading('content');
3280c39d46cSMichael Große}
3290c39d46cSMichael Große
3300c39d46cSMichael Große/**
3311015a57dSChristopher Smith * Return information about the current media item as an associative array.
332140cfbcdSGerrit Uitslag *
333140cfbcdSGerrit Uitslag * @return array with info about current media item
3341015a57dSChristopher Smith */
335d868eb89SAndreas Gohrfunction mediainfo()
336d868eb89SAndreas Gohr{
3371015a57dSChristopher Smith    global $NS;
3381015a57dSChristopher Smith    global $IMG;
3391015a57dSChristopher Smith
3401015a57dSChristopher Smith    $info = basicinfo("$NS:*");
3411015a57dSChristopher Smith    $info['image'] = $IMG;
3421c548ebeSAndreas Gohr
343f3f0262cSandi    return $info;
344f3f0262cSandi}
345f3f0262cSandi
346f3f0262cSandi/**
3472684e50aSAndreas Gohr * Build an string of URL parameters
3482684e50aSAndreas Gohr *
349*6cc6a0d2SAndreas Gohr * @see http_build_query()
350*6cc6a0d2SAndreas Gohr * @param array|object $params the data to encode
351140cfbcdSGerrit Uitslag * @param string $sep series of pairs are separated by this character
352140cfbcdSGerrit Uitslag * @return string query string
3538b19906eSAndreas Gohr *
3542684e50aSAndreas Gohr */
355d868eb89SAndreas Gohrfunction buildURLparams($params, $sep = '&amp;')
356d868eb89SAndreas Gohr{
357*6cc6a0d2SAndreas Gohr    return http_build_query($params, '', $sep, PHP_QUERY_RFC3986);
3582684e50aSAndreas Gohr}
3592684e50aSAndreas Gohr
3602684e50aSAndreas Gohr/**
3612684e50aSAndreas Gohr * Build an string of html tag attributes
3622684e50aSAndreas Gohr *
3637bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
3647bff22c0SAndreas Gohr *
365140cfbcdSGerrit Uitslag * @param array $params array with (attribute name-attribute value) pairs
366246d3337SMichael Große * @param bool $skipEmptyStrings skip empty string values?
367140cfbcdSGerrit Uitslag * @return string
3688b19906eSAndreas Gohr * @author Andreas Gohr
3698b19906eSAndreas Gohr *
3702684e50aSAndreas Gohr */
371d868eb89SAndreas Gohrfunction buildAttributes($params, $skipEmptyStrings = false)
372d868eb89SAndreas Gohr{
3732684e50aSAndreas Gohr    $url = '';
3749063ec14SAdrian Lang    $white = false;
3752684e50aSAndreas Gohr    foreach ($params as $key => $val) {
3762401f18dSSyntaxseed        if ($key[0] == '_') continue;
377246d3337SMichael Große        if ($val === '' && $skipEmptyStrings) continue;
3789063ec14SAdrian Lang        if ($white) $url .= ' ';
3797bff22c0SAndreas Gohr
3802684e50aSAndreas Gohr        $url .= $key . '="';
381f7711f2bSAndreas Gohr        $url .= hsc($val);
3822684e50aSAndreas Gohr        $url .= '"';
3839063ec14SAdrian Lang        $white = true;
3842684e50aSAndreas Gohr    }
3852684e50aSAndreas Gohr    return $url;
3862684e50aSAndreas Gohr}
3872684e50aSAndreas Gohr
3882684e50aSAndreas Gohr/**
38915fae107Sandi * This builds the breadcrumb trail and returns it as array
39015fae107Sandi *
3918b19906eSAndreas Gohr * @return string[] with the data: array(pageid=>name, ... )
39215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
393140cfbcdSGerrit Uitslag *
394f3f0262cSandi */
395d868eb89SAndreas Gohrfunction breadcrumbs()
396d868eb89SAndreas Gohr{
3978746e727Sandi    // we prepare the breadcrumbs early for quick session closing
3988746e727Sandi    static $crumbs = null;
3998746e727Sandi    if ($crumbs != null) return $crumbs;
4008746e727Sandi
401f3f0262cSandi    global $ID;
402f3f0262cSandi    global $ACT;
403f3f0262cSandi    global $conf;
4040ea5ebb4SB_S666    global $INFO;
405f3f0262cSandi
406f3f0262cSandi    //first visit?
40724870174SAndreas Gohr    $crumbs = $_SESSION[DOKU_COOKIE]['bc'] ?? [];
4085603d3c1SHenry Pan    //we only save on show and existing visible readable wiki documents
409a77f5846Sjan    $file = wikiFN($ID);
4105603d3c1SHenry Pan    if ($ACT != 'show' || $INFO['perm'] < AUTH_READ || isHiddenPage($ID) || !file_exists($file)) {
411e71ce681SAndreas Gohr        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
412f3f0262cSandi        return $crumbs;
413f3f0262cSandi    }
414a77f5846Sjan
415a77f5846Sjan    // page names
4161a84a0f3SAnika Henke    $name = noNSorNS($ID);
417fe9ec250SChris Smith    if (useHeading('navigation')) {
418a77f5846Sjan        // get page title
41967c15eceSMichael Hamann        $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
420a77f5846Sjan        if ($title) {
421a77f5846Sjan            $name = $title;
422a77f5846Sjan        }
423a77f5846Sjan    }
424a77f5846Sjan
425f3f0262cSandi    //remove ID from array
426a77f5846Sjan    if (isset($crumbs[$ID])) {
427a77f5846Sjan        unset($crumbs[$ID]);
428f3f0262cSandi    }
429f3f0262cSandi
430f3f0262cSandi    //add to array
431a77f5846Sjan    $crumbs[$ID] = $name;
432f3f0262cSandi    //reduce size
433f3f0262cSandi    while (count($crumbs) > $conf['breadcrumbs']) {
434f3f0262cSandi        array_shift($crumbs);
435f3f0262cSandi    }
436f3f0262cSandi    //save to session
437e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
438f3f0262cSandi    return $crumbs;
439f3f0262cSandi}
440f3f0262cSandi
441f3f0262cSandi/**
44215fae107Sandi * Filter for page IDs
44315fae107Sandi *
444f3f0262cSandi * This is run on a ID before it is outputted somewhere
445f3f0262cSandi * currently used to replace the colon with something else
446907f24f7SAndreas Gohr * on Windows (non-IIS) systems and to have proper URL encoding
447907f24f7SAndreas Gohr *
448977aa967SAndreas Gohr * See discussions at https://github.com/dokuwiki/dokuwiki/pull/84 and
449977aa967SAndreas Gohr * https://github.com/dokuwiki/dokuwiki/pull/173 why we use a whitelist of
450907f24f7SAndreas Gohr * unaffected servers instead of blacklisting affected servers here.
45115fae107Sandi *
45249c713a3Sandi * Urlencoding is ommitted when the second parameter is false
45349c713a3Sandi *
454140cfbcdSGerrit Uitslag * @param string $id pageid being filtered
455140cfbcdSGerrit Uitslag * @param bool $ue apply urlencoding?
456140cfbcdSGerrit Uitslag * @return string
4578b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
4588b19906eSAndreas Gohr *
459f3f0262cSandi */
460d868eb89SAndreas Gohrfunction idfilter($id, $ue = true)
461d868eb89SAndreas Gohr{
462f3f0262cSandi    global $conf;
463585bf44eSChristopher Smith    /* @var Input $INPUT */
464585bf44eSChristopher Smith    global $INPUT;
465585bf44eSChristopher Smith
466bf8f8509SAndreas Gohr    $id = (string)$id;
467bf8f8509SAndreas Gohr
468f3f0262cSandi    if ($conf['useslash'] && $conf['userewrite']) {
469f3f0262cSandi        $id = strtr($id, ':', '/');
4707d34963bSAndreas Gohr    } elseif (
4716c16a3a9Sfiwswe        str_starts_with(strtoupper(PHP_OS), 'WIN') &&
47258bedc8aSborekb        $conf['userewrite'] &&
473585bf44eSChristopher Smith        strpos($INPUT->server->str('SERVER_SOFTWARE'), 'Microsoft-IIS') === false
4743272d797SAndreas Gohr    ) {
475f3f0262cSandi        $id = strtr($id, ':', ';');
476f3f0262cSandi    }
47749c713a3Sandi    if ($ue) {
478b6c6979fSAndreas Gohr        $id = rawurlencode($id);
479f3f0262cSandi        $id = str_replace('%3A', ':', $id); //keep as colon
480edd95259SGerrit Uitslag        $id = str_replace('%3B', ';', $id); //keep as semicolon
481f3f0262cSandi        $id = str_replace('%2F', '/', $id); //keep as slash
48249c713a3Sandi    }
483f3f0262cSandi    return $id;
484f3f0262cSandi}
485f3f0262cSandi
486f3f0262cSandi/**
487ed7b5f09Sandi * This builds a link to a wikipage
48815fae107Sandi *
4894bc480e5SAndreas Gohr * It handles URL rewriting and adds additional parameters
4906c7843b5Sandi *
4914bc480e5SAndreas Gohr * @param string $id page id, defaults to start page
4924bc480e5SAndreas Gohr * @param string|array $urlParameters URL parameters, associative array recommended
4934bc480e5SAndreas Gohr * @param bool $absolute request an absolute URL instead of relative
4944bc480e5SAndreas Gohr * @param string $separator parameter separator
4954bc480e5SAndreas Gohr * @return string
4968b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
4978b19906eSAndreas Gohr *
498f3f0262cSandi */
499d868eb89SAndreas Gohrfunction wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;')
500d868eb89SAndreas Gohr{
501f3f0262cSandi    global $conf;
50216f15a81SDominik Eckelmann    if (is_array($urlParameters)) {
5034bde2196Slisps        if (isset($urlParameters['rev']) && !$urlParameters['rev']) unset($urlParameters['rev']);
50464159a61SAndreas Gohr        if (isset($urlParameters['at']) && $conf['date_at_format']) {
50564159a61SAndreas Gohr            $urlParameters['at'] = date($conf['date_at_format'], $urlParameters['at']);
50664159a61SAndreas Gohr        }
50716f15a81SDominik Eckelmann        $urlParameters = buildURLparams($urlParameters, $separator);
5086de3759aSAndreas Gohr    } else {
50916f15a81SDominik Eckelmann        $urlParameters = str_replace(',', $separator, $urlParameters);
5106de3759aSAndreas Gohr    }
51116f15a81SDominik Eckelmann    if ($id === '') {
51216f15a81SDominik Eckelmann        $id = $conf['start'];
51316f15a81SDominik Eckelmann    }
514f3f0262cSandi    $id = idfilter($id);
51516f15a81SDominik Eckelmann    if ($absolute) {
516ed7b5f09Sandi        $xlink = DOKU_URL;
517ed7b5f09Sandi    } else {
518ed7b5f09Sandi        $xlink = DOKU_BASE;
519ed7b5f09Sandi    }
520f3f0262cSandi
5216c7843b5Sandi    if ($conf['userewrite'] == 2) {
5226c7843b5Sandi        $xlink .= DOKU_SCRIPT . '/' . $id;
52316f15a81SDominik Eckelmann        if ($urlParameters) $xlink .= '?' . $urlParameters;
5246c7843b5Sandi    } elseif ($conf['userewrite']) {
525f3f0262cSandi        $xlink .= $id;
52616f15a81SDominik Eckelmann        if ($urlParameters) $xlink .= '?' . $urlParameters;
52740b5fb5bSPhy    } elseif ($id !== '') {
5286c7843b5Sandi        $xlink .= DOKU_SCRIPT . '?id=' . $id;
52916f15a81SDominik Eckelmann        if ($urlParameters) $xlink .= $separator . $urlParameters;
530bce3726dSAndreas Gohr    } else {
531bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
53216f15a81SDominik Eckelmann        if ($urlParameters) $xlink .= '?' . $urlParameters;
533f3f0262cSandi    }
534f3f0262cSandi
535f3f0262cSandi    return $xlink;
536f3f0262cSandi}
537f3f0262cSandi
538f3f0262cSandi/**
539f5c2808fSBen Coburn * This builds a link to an alternate page format
540f5c2808fSBen Coburn *
541f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
542f5c2808fSBen Coburn *
5434bc480e5SAndreas Gohr * @param string $id page id, defaults to start page
5444bc480e5SAndreas Gohr * @param string $format the export renderer to use
5454bc480e5SAndreas Gohr * @param string|array $urlParameters URL parameters, associative array recommended
5464bc480e5SAndreas Gohr * @param bool $abs request an absolute URL instead of relative
5474bc480e5SAndreas Gohr * @param string $sep parameter separator
5484bc480e5SAndreas Gohr * @return string
5498b19906eSAndreas Gohr * @author Ben Coburn <btcoburn@silicodon.net>
550f5c2808fSBen Coburn */
551d868eb89SAndreas Gohrfunction exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;')
552d868eb89SAndreas Gohr{
553f5c2808fSBen Coburn    global $conf;
5544bc480e5SAndreas Gohr    if (is_array($urlParameters)) {
5554bc480e5SAndreas Gohr        $urlParameters = buildURLparams($urlParameters, $sep);
556f5c2808fSBen Coburn    } else {
5574bc480e5SAndreas Gohr        $urlParameters = str_replace(',', $sep, $urlParameters);
558f5c2808fSBen Coburn    }
559f5c2808fSBen Coburn
560f5c2808fSBen Coburn    $format = rawurlencode($format);
561f5c2808fSBen Coburn    $id = idfilter($id);
562f5c2808fSBen Coburn    if ($abs) {
563f5c2808fSBen Coburn        $xlink = DOKU_URL;
564f5c2808fSBen Coburn    } else {
565f5c2808fSBen Coburn        $xlink = DOKU_BASE;
566f5c2808fSBen Coburn    }
567f5c2808fSBen Coburn
568f5c2808fSBen Coburn    if ($conf['userewrite'] == 2) {
569f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT . '/' . $id . '?do=export_' . $format;
5704bc480e5SAndreas Gohr        if ($urlParameters) $xlink .= $sep . $urlParameters;
571f5c2808fSBen Coburn    } elseif ($conf['userewrite'] == 1) {
572f5c2808fSBen Coburn        $xlink .= '_export/' . $format . '/' . $id;
5734bc480e5SAndreas Gohr        if ($urlParameters) $xlink .= '?' . $urlParameters;
574f5c2808fSBen Coburn    } else {
575f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT . '?do=export_' . $format . $sep . 'id=' . $id;
5764bc480e5SAndreas Gohr        if ($urlParameters) $xlink .= $sep . $urlParameters;
577f5c2808fSBen Coburn    }
578f5c2808fSBen Coburn
579f5c2808fSBen Coburn    return $xlink;
580f5c2808fSBen Coburn}
581f5c2808fSBen Coburn
582f5c2808fSBen Coburn/**
5836de3759aSAndreas Gohr * Build a link to a media file
5846de3759aSAndreas Gohr *
5856de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
5868c08db0aSAndreas Gohr *
5878c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
5888c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
5898c08db0aSAndreas Gohr *
5903272d797SAndreas Gohr * @param string $id the media file id or URL
5913272d797SAndreas Gohr * @param mixed $more string or array with additional parameters
5923272d797SAndreas Gohr * @param bool $direct link to detail page if false
5933272d797SAndreas Gohr * @param string $sep URL parameter separator
5943272d797SAndreas Gohr * @param bool $abs Create an absolute URL
5953272d797SAndreas Gohr * @return string
5966de3759aSAndreas Gohr */
597d868eb89SAndreas Gohrfunction ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false)
598d868eb89SAndreas Gohr{
5996de3759aSAndreas Gohr    global $conf;
600b9ee6a44SKlap-in    $isexternalimage = media_isexternal($id);
601826d2766SKlap-in    if (!$isexternalimage) {
602826d2766SKlap-in        $id = cleanID($id);
603826d2766SKlap-in    }
604826d2766SKlap-in
6056de3759aSAndreas Gohr    if (is_array($more)) {
6060f4e0092SChristopher Smith        // add token for resized images
60724870174SAndreas Gohr        $w = $more['w'] ?? null;
60824870174SAndreas Gohr        $h = $more['h'] ?? null;
60998fe1ac9SDamien Regad        if ($w || $h || $isexternalimage) {
610357c9a39SDamien Regad            $more['tok'] = media_get_token($id, $w, $h);
6110f4e0092SChristopher Smith        }
6128c08db0aSAndreas Gohr        // strip defaults for shorter URLs
6138c08db0aSAndreas Gohr        if (isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
614443e135dSChristopher Smith        if (empty($more['w'])) unset($more['w']);
615443e135dSChristopher Smith        if (empty($more['h'])) unset($more['h']);
6168c08db0aSAndreas Gohr        if (isset($more['id']) && $direct) unset($more['id']);
61778b874e6Slisps        if (isset($more['rev']) && !$more['rev']) unset($more['rev']);
618b174aeaeSchris        $more = buildURLparams($more, $sep);
6196de3759aSAndreas Gohr    } else {
62024870174SAndreas Gohr        $matches = [];
621cc036f74SKlap-in        if (preg_match_all('/\b(w|h)=(\d*)\b/', $more, $matches, PREG_SET_ORDER) || $isexternalimage) {
62224870174SAndreas Gohr            $resize = ['w' => 0, 'h' => 0];
6235e7db1e2SChristopher Smith            foreach ($matches as $match) {
6245e7db1e2SChristopher Smith                $resize[$match[1]] = $match[2];
6255e7db1e2SChristopher Smith            }
626cc036f74SKlap-in            $more .= $more === '' ? '' : $sep;
627cc036f74SKlap-in            $more .= 'tok=' . media_get_token($id, $resize['w'], $resize['h']);
6285e7db1e2SChristopher Smith        }
6298c08db0aSAndreas Gohr        $more = str_replace('cache=cache', '', $more); //skip default
6308c08db0aSAndreas Gohr        $more = str_replace(',,', ',', $more);
631b174aeaeSchris        $more = str_replace(',', $sep, $more);
6326de3759aSAndreas Gohr    }
6336de3759aSAndreas Gohr
63455b2b31bSAndreas Gohr    if ($abs) {
63555b2b31bSAndreas Gohr        $xlink = DOKU_URL;
63655b2b31bSAndreas Gohr    } else {
6376de3759aSAndreas Gohr        $xlink = DOKU_BASE;
63855b2b31bSAndreas Gohr    }
6396de3759aSAndreas Gohr
6406de3759aSAndreas Gohr    // external URLs are always direct without rewriting
641826d2766SKlap-in    if ($isexternalimage) {
6426de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
643cc036f74SKlap-in        $xlink .= '?' . $more;
644b174aeaeSchris        $xlink .= $sep . 'media=' . rawurlencode($id);
6456de3759aSAndreas Gohr        return $xlink;
6466de3759aSAndreas Gohr    }
6476de3759aSAndreas Gohr
6486de3759aSAndreas Gohr    $id = idfilter($id);
6496de3759aSAndreas Gohr
6506de3759aSAndreas Gohr    // decide on scriptname
6516de3759aSAndreas Gohr    if ($direct) {
6526de3759aSAndreas Gohr        if ($conf['userewrite'] == 1) {
6536de3759aSAndreas Gohr            $script = '_media';
6546de3759aSAndreas Gohr        } else {
6556de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
6566de3759aSAndreas Gohr        }
65724870174SAndreas Gohr    } elseif ($conf['userewrite'] == 1) {
6586de3759aSAndreas Gohr        $script = '_detail';
6596de3759aSAndreas Gohr    } else {
6606de3759aSAndreas Gohr        $script = 'lib/exe/detail.php';
6616de3759aSAndreas Gohr    }
6626de3759aSAndreas Gohr
6636de3759aSAndreas Gohr    // build URL based on rewrite mode
6646de3759aSAndreas Gohr    if ($conf['userewrite']) {
6656de3759aSAndreas Gohr        $xlink .= $script . '/' . $id;
6666de3759aSAndreas Gohr        if ($more) $xlink .= '?' . $more;
66724870174SAndreas Gohr    } elseif ($more) {
668a99d3236SEsther Brunner        $xlink .= $script . '?' . $more;
669b174aeaeSchris        $xlink .= $sep . 'media=' . $id;
6706de3759aSAndreas Gohr    } else {
671a99d3236SEsther Brunner        $xlink .= $script . '?media=' . $id;
6726de3759aSAndreas Gohr    }
6736de3759aSAndreas Gohr
6746de3759aSAndreas Gohr    return $xlink;
6756de3759aSAndreas Gohr}
6766de3759aSAndreas Gohr
6776de3759aSAndreas Gohr/**
67825ca5b17SAndreas Gohr * Returns the URL to the DokuWiki base script
67915fae107Sandi *
68025ca5b17SAndreas Gohr * Consider using wl() instead, unless you absoutely need the doku.php endpoint
68125ca5b17SAndreas Gohr *
6828b19906eSAndreas Gohr * @return string
68315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
684140cfbcdSGerrit Uitslag *
685f3f0262cSandi */
686d868eb89SAndreas Gohrfunction script()
687d868eb89SAndreas Gohr{
688ed7b5f09Sandi    return DOKU_BASE . DOKU_SCRIPT;
689f3f0262cSandi}
690f3f0262cSandi
691f3f0262cSandi/**
69215fae107Sandi * Spamcheck against wordlist
69315fae107Sandi *
694f3f0262cSandi * Checks the wikitext against a list of blocked expressions
695f3f0262cSandi * returns true if the text contains any bad words
69615fae107Sandi *
697e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
698e403cc58SMichael Klier *
699e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
700e403cc58SMichael Klier *  and gain information about the user who was blocked.
701e403cc58SMichael Klier *
702e403cc58SMichael Klier *  Event data:
703e403cc58SMichael Klier *    data['matches']  - array of matches
704e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
705e403cc58SMichael Klier *      [ip]           - ip address
706e403cc58SMichael Klier *      [user]         - username (if logged in)
707e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
708e403cc58SMichael Klier *      [name]         - real name (if logged in)
709e403cc58SMichael Klier *
7108b19906eSAndreas Gohr * @param string $text - optional text to check, if not given the globals are used
7118b19906eSAndreas Gohr * @return bool         - true if a spam word was found
71215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
7136dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
714140cfbcdSGerrit Uitslag *
715f3f0262cSandi */
716d868eb89SAndreas Gohrfunction checkwordblock($text = '')
717d868eb89SAndreas Gohr{
718f3f0262cSandi    global $TEXT;
7196dffa0e0SAndreas Gohr    global $PRE;
7206dffa0e0SAndreas Gohr    global $SUF;
721e0086ca2SAndreas Gohr    global $SUM;
722f3f0262cSandi    global $conf;
723e403cc58SMichael Klier    global $INFO;
724585bf44eSChristopher Smith    /* @var Input $INPUT */
725585bf44eSChristopher Smith    global $INPUT;
726f3f0262cSandi
727f3f0262cSandi    if (!$conf['usewordblock']) return false;
728f3f0262cSandi
729e0086ca2SAndreas Gohr    if (!$text) $text = "$PRE $TEXT $SUF $SUM";
7306dffa0e0SAndreas Gohr
731041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
73264159a61SAndreas Gohr    // phpcs:disable Generic.Files.LineLength.TooLong
73364159a61SAndreas Gohr    $text = preg_replace(
73464159a61SAndreas Gohr        '!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i',
73564159a61SAndreas Gohr        '\1http://\2 \2\3',
73664159a61SAndreas Gohr        $text
73764159a61SAndreas Gohr    );
73864159a61SAndreas Gohr    // phpcs:enable
739041d1964SAndreas Gohr
740b9ac8716Schris    $wordblocks = getWordblocks();
741a51d08efSAndreas Gohr    // read file in chunks of 200 - this should work around the
7423e2965d7Sandi    // MAX_PATTERN_SIZE in modern PCRE
743a51d08efSAndreas Gohr    $chunksize = 200;
74464259528SAndreas Gohr
745b9ac8716Schris    while ($blocks = array_splice($wordblocks, 0, $chunksize)) {
74624870174SAndreas Gohr        $re = [];
74749eb6e38SAndreas Gohr        // build regexp from blocks
748f3f0262cSandi        foreach ($blocks as $block) {
749f3f0262cSandi            $block = preg_replace('/#.*$/', '', $block);
750f3f0262cSandi            $block = trim($block);
751f3f0262cSandi            if (empty($block)) continue;
752f3f0262cSandi            $re[] = $block;
753f3f0262cSandi        }
75424870174SAndreas Gohr        if (count($re) && preg_match('#(' . implode('|', $re) . ')#si', $text, $matches)) {
755e403cc58SMichael Klier            // prepare event data
75624870174SAndreas Gohr            $data = [];
757e403cc58SMichael Klier            $data['matches'] = $matches;
758585bf44eSChristopher Smith            $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
759585bf44eSChristopher Smith            if ($INPUT->server->str('REMOTE_USER')) {
760585bf44eSChristopher Smith                $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
761e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
762e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
763e403cc58SMichael Klier            }
76424870174SAndreas Gohr            $callback = static fn() => true;
765cbb44eabSAndreas Gohr            return Event::createAndTrigger('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
766b9ac8716Schris        }
767703f6fdeSandi    }
768f3f0262cSandi    return false;
769f3f0262cSandi}
770f3f0262cSandi
771f3f0262cSandi/**
77215fae107Sandi * Return the IP of the client
77315fae107Sandi *
7746d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
77515fae107Sandi *
7766d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
7776d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
7786d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
7796d8affe6SAndreas Gohr * headers
7806d8affe6SAndreas Gohr *
7813272d797SAndreas Gohr * @param boolean $single If set only a single IP is returned
7823272d797SAndreas Gohr * @return string
7838b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
7848b19906eSAndreas Gohr *
785f3f0262cSandi */
786d868eb89SAndreas Gohrfunction clientIP($single = false)
787d868eb89SAndreas Gohr{
788585bf44eSChristopher Smith    /* @var Input $INPUT */
789925105e8SPhy    global $INPUT, $conf;
790585bf44eSChristopher Smith
79124870174SAndreas Gohr    $ip = [];
792585bf44eSChristopher Smith    $ip[] = $INPUT->server->str('REMOTE_ADDR');
793585bf44eSChristopher Smith    if ($INPUT->server->str('HTTP_X_FORWARDED_FOR')) {
794585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_FORWARDED_FOR'))));
795585bf44eSChristopher Smith    }
796585bf44eSChristopher Smith    if ($INPUT->server->str('HTTP_X_REAL_IP')) {
797585bf44eSChristopher Smith        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_REAL_IP'))));
798585bf44eSChristopher Smith    }
7996d8affe6SAndreas Gohr
8006d8affe6SAndreas Gohr    // remove any non-IP stuff
8016d8affe6SAndreas Gohr    $cnt = count($ip);
8026d8affe6SAndreas Gohr    for ($i = 0; $i < $cnt; $i++) {
8030a5f08e5SAdaKaleh        if (filter_var($ip[$i], FILTER_VALIDATE_IP) === false) {
8040a5f08e5SAdaKaleh            unset($ip[$i]);
8054ff28443Schris        }
806f3f0262cSandi    }
8076d8affe6SAndreas Gohr    $ip = array_values(array_unique($ip));
80824870174SAndreas Gohr    if ($ip === [] || !$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
8096d8affe6SAndreas Gohr
81024870174SAndreas Gohr    if (!$single) return implode(',', $ip);
8116d8affe6SAndreas Gohr
812925105e8SPhy    // skip trusted local addresses
8136d8affe6SAndreas Gohr    foreach ($ip as $i) {
814925105e8SPhy        if (!empty($conf['trustedproxy']) && preg_match('/' . $conf['trustedproxy'] . '/', $i)) {
8156d8affe6SAndreas Gohr            continue;
8166d8affe6SAndreas Gohr        } else {
8176d8affe6SAndreas Gohr            return $i;
8186d8affe6SAndreas Gohr        }
8196d8affe6SAndreas Gohr    }
820925105e8SPhy
821925105e8SPhy    // still here? just use the last address
822925105e8SPhy    // this case all ips in the list are trusted
823925105e8SPhy    return $ip[count($ip) - 1];
824f3f0262cSandi}
825f3f0262cSandi
826f3f0262cSandi/**
8271c548ebeSAndreas Gohr * Check if the browser is on a mobile device
8281c548ebeSAndreas Gohr *
8291c548ebeSAndreas Gohr * Adapted from the example code at url below
8301c548ebeSAndreas Gohr *
8311c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
832140cfbcdSGerrit Uitslag *
83364159a61SAndreas Gohr * @deprecated 2018-04-27 you probably want media queries instead anyway
834140cfbcdSGerrit Uitslag * @return bool if true, client is mobile browser; otherwise false
8351c548ebeSAndreas Gohr */
836d868eb89SAndreas Gohrfunction clientismobile()
837d868eb89SAndreas Gohr{
838585bf44eSChristopher Smith    /* @var Input $INPUT */
839585bf44eSChristopher Smith    global $INPUT;
8401c548ebeSAndreas Gohr
841585bf44eSChristopher Smith    if ($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
8421c548ebeSAndreas Gohr
843585bf44eSChristopher Smith    if (preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
8441c548ebeSAndreas Gohr
845585bf44eSChristopher Smith    if (!$INPUT->server->has('HTTP_USER_AGENT')) return false;
8461c548ebeSAndreas Gohr
84724870174SAndreas Gohr    $uamatches = implode(
84864159a61SAndreas Gohr        '|',
84964159a61SAndreas Gohr        [
85064159a61SAndreas Gohr            'midp', 'j2me', 'avantg', 'docomo', 'novarra', 'palmos', 'palmsource', '240x320', 'opwv',
85164159a61SAndreas Gohr            'chtml', 'pda', 'windows ce', 'mmp\/', 'blackberry', 'mib\/', 'symbian', 'wireless', 'nokia',
85264159a61SAndreas Gohr            'hand', 'mobi', 'phone', 'cdm', 'up\.b', 'audio', 'SIE\-', 'SEC\-', 'samsung', 'HTC', 'mot\-',
85364159a61SAndreas Gohr            'mitsu', 'sagem', 'sony', 'alcatel', 'lg', 'erics', 'vx', 'NEC', 'philips', 'mmm', 'xx',
85464159a61SAndreas Gohr            'panasonic', 'sharp', 'wap', 'sch', 'rover', 'pocket', 'benq', 'java', 'pt', 'pg', 'vox',
85564159a61SAndreas Gohr            'amoi', 'bird', 'compal', 'kg', 'voda', 'sany', 'kdd', 'dbt', 'sendo', 'sgh', 'gradi', 'jb',
85664159a61SAndreas Gohr            '\d\d\di', 'moto'
85764159a61SAndreas Gohr        ]
85864159a61SAndreas Gohr    );
8591c548ebeSAndreas Gohr
860585bf44eSChristopher Smith    if (preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
8611c548ebeSAndreas Gohr
8621c548ebeSAndreas Gohr    return false;
8631c548ebeSAndreas Gohr}
8641c548ebeSAndreas Gohr
8651c548ebeSAndreas Gohr/**
8666efc45a2SDmitry Katsubo * check if a given link is interwiki link
8676efc45a2SDmitry Katsubo *
8686efc45a2SDmitry Katsubo * @param string $link the link, e.g. "wiki>page"
8696efc45a2SDmitry Katsubo * @return bool
8706efc45a2SDmitry Katsubo */
871d868eb89SAndreas Gohrfunction link_isinterwiki($link)
872d868eb89SAndreas Gohr{
8736efc45a2SDmitry Katsubo    if (preg_match('/^[a-zA-Z0-9\.]+>/u', $link)) return true;
8746efc45a2SDmitry Katsubo    return false;
8756efc45a2SDmitry Katsubo}
8766efc45a2SDmitry Katsubo
8776efc45a2SDmitry Katsubo/**
87863211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
87963211f61SGlen Harris *
88022ef1e32SAndreas Gohr * If $conf['dnslookups'] is disabled it simply returns the input string
88122ef1e32SAndreas Gohr *
8823272d797SAndreas Gohr * @param string $ips comma separated list of IP addresses
8833272d797SAndreas Gohr * @return string a comma separated list of hostnames
8848b19906eSAndreas Gohr * @author Glen Harris <astfgl@iamnota.org>
8858b19906eSAndreas Gohr *
88663211f61SGlen Harris */
887d868eb89SAndreas Gohrfunction gethostsbyaddrs($ips)
888d868eb89SAndreas Gohr{
88922ef1e32SAndreas Gohr    global $conf;
89022ef1e32SAndreas Gohr    if (!$conf['dnslookups']) return $ips;
89122ef1e32SAndreas Gohr
89224870174SAndreas Gohr    $hosts = [];
89363211f61SGlen Harris    $ips = explode(',', $ips);
894551a720fSMichael Klier
895551a720fSMichael Klier    if (is_array($ips)) {
8963886270dSAndreas Gohr        foreach ($ips as $ip) {
897551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
89863211f61SGlen Harris        }
89924870174SAndreas Gohr        return implode(',', $hosts);
900551a720fSMichael Klier    } else {
901551a720fSMichael Klier        return gethostbyaddr(trim($ips));
902551a720fSMichael Klier    }
90363211f61SGlen Harris}
90463211f61SGlen Harris
90563211f61SGlen Harris/**
90615fae107Sandi * Checks if a given page is currently locked.
90715fae107Sandi *
908f3f0262cSandi * removes stale lockfiles
90915fae107Sandi *
910140cfbcdSGerrit Uitslag * @param string $id page id
911140cfbcdSGerrit Uitslag * @return bool page is locked?
9128b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
9138b19906eSAndreas Gohr *
914f3f0262cSandi */
915d868eb89SAndreas Gohrfunction checklock($id)
916d868eb89SAndreas Gohr{
917f3f0262cSandi    global $conf;
918585bf44eSChristopher Smith    /* @var Input $INPUT */
919585bf44eSChristopher Smith    global $INPUT;
920585bf44eSChristopher Smith
921c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
922f3f0262cSandi
923f3f0262cSandi    //no lockfile
92479e79377SAndreas Gohr    if (!file_exists($lock)) return false;
925f3f0262cSandi
926f3f0262cSandi    //lockfile expired
927f3f0262cSandi    if ((time() - filemtime($lock)) > $conf['locktime']) {
928d8186216SBen Coburn        @unlink($lock);
929f3f0262cSandi        return false;
930f3f0262cSandi    }
931f3f0262cSandi
932f3f0262cSandi    //my own lock
9335f21556dSDamien Regad    [$ip, $session] = sexplode("\n", io_readFile($lock), 2);
93424870174SAndreas Gohr    if ($ip == $INPUT->server->str('REMOTE_USER') || (session_id() && $session === session_id())) {
935f3f0262cSandi        return false;
936f3f0262cSandi    }
937f3f0262cSandi
938f3f0262cSandi    return $ip;
939f3f0262cSandi}
940f3f0262cSandi
941f3f0262cSandi/**
94215fae107Sandi * Lock a page for editing
94315fae107Sandi *
9448b19906eSAndreas Gohr * @param string $id page id to lock
94515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
946140cfbcdSGerrit Uitslag *
947f3f0262cSandi */
948d868eb89SAndreas Gohrfunction lock($id)
949d868eb89SAndreas Gohr{
950544ed901SDaniel Calviño Sánchez    global $conf;
951585bf44eSChristopher Smith    /* @var Input $INPUT */
952585bf44eSChristopher Smith    global $INPUT;
953544ed901SDaniel Calviño Sánchez
954544ed901SDaniel Calviño Sánchez    if ($conf['locktime'] == 0) {
955544ed901SDaniel Calviño Sánchez        return;
956544ed901SDaniel Calviño Sánchez    }
957544ed901SDaniel Calviño Sánchez
958c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
959585bf44eSChristopher Smith    if ($INPUT->server->str('REMOTE_USER')) {
960585bf44eSChristopher Smith        io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
961f3f0262cSandi    } else {
96285fef7e2SAndreas Gohr        io_saveFile($lock, clientIP() . "\n" . session_id());
963f3f0262cSandi    }
964f3f0262cSandi}
965f3f0262cSandi
966f3f0262cSandi/**
96715fae107Sandi * Unlock a page if it was locked by the user
968f3f0262cSandi *
9693272d797SAndreas Gohr * @param string $id page id to unlock
97015fae107Sandi * @return bool true if a lock was removed
9718b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
9728b19906eSAndreas Gohr *
973f3f0262cSandi */
974d868eb89SAndreas Gohrfunction unlock($id)
975d868eb89SAndreas Gohr{
976585bf44eSChristopher Smith    /* @var Input $INPUT */
977585bf44eSChristopher Smith    global $INPUT;
978585bf44eSChristopher Smith
979c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
98079e79377SAndreas Gohr    if (file_exists($lock)) {
98124870174SAndreas Gohr        @[$ip, $session] = explode("\n", io_readFile($lock));
982c0dd3914SAdaKaleh        if ($ip == $INPUT->server->str('REMOTE_USER') || $session == session_id()) {
983f3f0262cSandi            @unlink($lock);
984f3f0262cSandi            return true;
985f3f0262cSandi        }
986f3f0262cSandi    }
987f3f0262cSandi    return false;
988f3f0262cSandi}
989f3f0262cSandi
990f3f0262cSandi/**
991f3f0262cSandi * convert line ending to unix format
992f3f0262cSandi *
9936db7468bSAndreas Gohr * also makes sure the given text is valid UTF-8
9946db7468bSAndreas Gohr *
9958b19906eSAndreas Gohr * @param string $text
9968b19906eSAndreas Gohr * @return string
99715fae107Sandi * @see    formText() for 2crlf conversion
99815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
999140cfbcdSGerrit Uitslag *
1000f3f0262cSandi */
1001d868eb89SAndreas Gohrfunction cleanText($text)
1002d868eb89SAndreas Gohr{
1003f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
10046db7468bSAndreas Gohr
10056db7468bSAndreas Gohr    // if the text is not valid UTF-8 we simply assume latin1
10066db7468bSAndreas Gohr    // this won't break any worse than it breaks with the wrong encoding
10076db7468bSAndreas Gohr    // but might actually fix the problem in many cases
100853c68e5cSAndreas Gohr    if (!Clean::isUtf8($text)) $text = Conversion::fromLatin1($text);
10096db7468bSAndreas Gohr
1010f3f0262cSandi    return $text;
1011f3f0262cSandi}
1012f3f0262cSandi
1013f3f0262cSandi/**
1014f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
1015f3f0262cSandi * It also converts line endings to Windows format which is
1016f3f0262cSandi * pseudo standard for webforms.
1017f3f0262cSandi *
10188b19906eSAndreas Gohr * @param string $text
10198b19906eSAndreas Gohr * @return string
102015fae107Sandi * @see    cleanText() for 2unix conversion
102115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1022140cfbcdSGerrit Uitslag *
1023f3f0262cSandi */
1024d868eb89SAndreas Gohrfunction formText($text)
1025d868eb89SAndreas Gohr{
1026a46a37efSAndreas Gohr    $text = str_replace("\012", "\015\012", $text ?? '');
1027f3f0262cSandi    return htmlspecialchars($text);
1028f3f0262cSandi}
1029f3f0262cSandi
1030f3f0262cSandi/**
103115fae107Sandi * Returns the specified local text in raw format
103215fae107Sandi *
1033140cfbcdSGerrit Uitslag * @param string $id page id
1034140cfbcdSGerrit Uitslag * @param string $ext extension of file being read, default 'txt'
1035140cfbcdSGerrit Uitslag * @return string
10368b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10378b19906eSAndreas Gohr *
1038f3f0262cSandi */
1039d868eb89SAndreas Gohrfunction rawLocale($id, $ext = 'txt')
1040d868eb89SAndreas Gohr{
10412adaf2b8SAndreas Gohr    return io_readFile(localeFN($id, $ext));
1042f3f0262cSandi}
1043f3f0262cSandi
1044f3f0262cSandi/**
1045f3f0262cSandi * Returns the raw WikiText
104615fae107Sandi *
1047140cfbcdSGerrit Uitslag * @param string $id page id
1048e0c26282SGerrit Uitslag * @param string|int $rev timestamp when a revision of wikitext is desired
1049140cfbcdSGerrit Uitslag * @return string
10508b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10518b19906eSAndreas Gohr *
1052f3f0262cSandi */
1053d868eb89SAndreas Gohrfunction rawWiki($id, $rev = '')
1054d868eb89SAndreas Gohr{
1055cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1056f3f0262cSandi}
1057f3f0262cSandi
1058f3f0262cSandi/**
10597146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
10607146cee2SAndreas Gohr *
10617b84afa2SAndreas Gohr * @triggers COMMON_PAGETPL_LOAD
1062140cfbcdSGerrit Uitslag * @param string $id the id of the page to be created
1063140cfbcdSGerrit Uitslag * @return string parsed pagetemplate content
10648b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10658b19906eSAndreas Gohr *
10667146cee2SAndreas Gohr */
1067d868eb89SAndreas Gohrfunction pageTemplate($id)
1068d868eb89SAndreas Gohr{
1069a15ce62dSEsther Brunner    global $conf;
1070e29549feSAndreas Gohr
1071fe17917eSAdrian Lang    if (is_array($id)) $id = $id[0];
1072e29549feSAndreas Gohr
10737b84afa2SAndreas Gohr    // prepare initial event data
107424870174SAndreas Gohr    $data = [
10757b84afa2SAndreas Gohr        'id' => $id, // the id of the page to be created
10767b84afa2SAndreas Gohr        'tpl' => '', // the text used as template
10777b84afa2SAndreas Gohr        'tplfile' => '', // the file above text was/should be loaded from
107824870174SAndreas Gohr        'doreplace' => true,
107924870174SAndreas Gohr    ];
10807b84afa2SAndreas Gohr
1081e1d9dcc8SAndreas Gohr    $evt = new Event('COMMON_PAGETPL_LOAD', $data);
10827b84afa2SAndreas Gohr    if ($evt->advise_before(true)) {
10837b84afa2SAndreas Gohr        // the before event might have loaded the content already
10847b84afa2SAndreas Gohr        if (empty($data['tpl'])) {
10857b84afa2SAndreas Gohr            // if the before event did not set a template file, try to find one
10867b84afa2SAndreas Gohr            if (empty($data['tplfile'])) {
1087fe17917eSAdrian Lang                $path = dirname(wikiFN($id));
108879e79377SAndreas Gohr                if (file_exists($path . '/_template.txt')) {
10897b84afa2SAndreas Gohr                    $data['tplfile'] = $path . '/_template.txt';
1090e29549feSAndreas Gohr                } else {
1091e29549feSAndreas Gohr                    // search upper namespaces for templates
1092e29549feSAndreas Gohr                    $len = strlen(rtrim($conf['datadir'], '/'));
1093e29549feSAndreas Gohr                    while (strlen($path) >= $len) {
109479e79377SAndreas Gohr                        if (file_exists($path . '/__template.txt')) {
10957b84afa2SAndreas Gohr                            $data['tplfile'] = $path . '/__template.txt';
1096e29549feSAndreas Gohr                            break;
1097e29549feSAndreas Gohr                        }
1098e29549feSAndreas Gohr                        $path = substr($path, 0, strrpos($path, '/'));
1099e29549feSAndreas Gohr                    }
1100e29549feSAndreas Gohr                }
11017b84afa2SAndreas Gohr            }
11027b84afa2SAndreas Gohr            // load the content
11033d7ac595SMichael Hamann            $data['tpl'] = io_readFile($data['tplfile']);
11047b84afa2SAndreas Gohr        }
1105a1bbd05bSMichael Hamann        if ($data['doreplace']) parsePageTemplate($data);
11067b84afa2SAndreas Gohr    }
11077b84afa2SAndreas Gohr    $evt->advise_after();
11087b84afa2SAndreas Gohr    unset($evt);
11097b84afa2SAndreas Gohr
1110fe17917eSAdrian Lang    return $data['tpl'];
11112b1223ecSAdrian Lang}
11122b1223ecSAdrian Lang
11132b1223ecSAdrian Lang/**
11142b1223ecSAdrian Lang * Performs common page template replacements
11157b84afa2SAndreas Gohr * This works on data from COMMON_PAGETPL_LOAD
11162b1223ecSAdrian Lang *
1117140cfbcdSGerrit Uitslag * @param array $data array with event data
1118140cfbcdSGerrit Uitslag * @return string
11198b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
11208b19906eSAndreas Gohr *
11212b1223ecSAdrian Lang */
1122d868eb89SAndreas Gohrfunction parsePageTemplate(&$data)
1123d868eb89SAndreas Gohr{
11243272d797SAndreas Gohr    /**
11253272d797SAndreas Gohr     * @var string $id the id of the page to be created
11263272d797SAndreas Gohr     * @var string $tpl the text used as template
11273272d797SAndreas Gohr     * @var string $tplfile the file above text was/should be loaded from
11283272d797SAndreas Gohr     * @var bool $doreplace should wildcard replacements be done on the text?
11293272d797SAndreas Gohr     */
1130fe17917eSAdrian Lang    extract($data);
1131fe17917eSAdrian Lang
1132b856f7dfSAdrian Lang    global $USERINFO;
1133bce53b1fSAdrian Lang    global $conf;
1134585bf44eSChristopher Smith    /* @var Input $INPUT */
1135585bf44eSChristopher Smith    global $INPUT;
1136e29549feSAndreas Gohr
1137e29549feSAndreas Gohr    // replace placeholders
113826ece5a7SAndreas Gohr    $file = noNS($id);
113937c1acbdSAdrian Lang    $page = strtr($file, $conf['sepchar'], ' ');
114026ece5a7SAndreas Gohr
11413272d797SAndreas Gohr    $tpl = str_replace(
114224870174SAndreas Gohr        [
114326ece5a7SAndreas Gohr            '@ID@',
114426ece5a7SAndreas Gohr            '@NS@',
11458a7bcf66SShota Miyazaki            '@CURNS@',
1146a3db0ab0SSimon Lees            '@!CURNS@',
1147a3db0ab0SSimon Lees            '@!!CURNS@',
1148a3db0ab0SSimon Lees            '@!CURNS!@',
114926ece5a7SAndreas Gohr            '@FILE@',
115026ece5a7SAndreas Gohr            '@!FILE@',
115126ece5a7SAndreas Gohr            '@!FILE!@',
115226ece5a7SAndreas Gohr            '@PAGE@',
115326ece5a7SAndreas Gohr            '@!PAGE@',
115426ece5a7SAndreas Gohr            '@!!PAGE@',
115526ece5a7SAndreas Gohr            '@!PAGE!@',
115626ece5a7SAndreas Gohr            '@USER@',
115726ece5a7SAndreas Gohr            '@NAME@',
115826ece5a7SAndreas Gohr            '@MAIL@',
115924870174SAndreas Gohr            '@DATE@'
116024870174SAndreas Gohr        ],
116124870174SAndreas Gohr        [
116226ece5a7SAndreas Gohr            $id,
116326ece5a7SAndreas Gohr            getNS($id),
11648a7bcf66SShota Miyazaki            curNS($id),
116524870174SAndreas Gohr            PhpString::ucfirst(curNS($id)),
116624870174SAndreas Gohr            PhpString::ucwords(curNS($id)),
116724870174SAndreas Gohr            PhpString::strtoupper(curNS($id)),
116826ece5a7SAndreas Gohr            $file,
116924870174SAndreas Gohr            PhpString::ucfirst($file),
117024870174SAndreas Gohr            PhpString::strtoupper($file),
117126ece5a7SAndreas Gohr            $page,
117224870174SAndreas Gohr            PhpString::ucfirst($page),
117324870174SAndreas Gohr            PhpString::ucwords($page),
117424870174SAndreas Gohr            PhpString::strtoupper($page),
1175585bf44eSChristopher Smith            $INPUT->server->str('REMOTE_USER'),
11763e9ae63dSPhy            $USERINFO ? $USERINFO['name'] : '',
11773e9ae63dSPhy            $USERINFO ? $USERINFO['mail'] : '',
117824870174SAndreas Gohr            $conf['dformat']
117924870174SAndreas Gohr        ],
118024870174SAndreas Gohr        $tpl
11813272d797SAndreas Gohr    );
118226ece5a7SAndreas Gohr
11837d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
1184bad6fc0dSAndreas Gohr    $tpl = preg_replace_callback(
1185bad6fc0dSAndreas Gohr        '/%./',
118624870174SAndreas Gohr        static fn($m) => dformat(null, $m[0]),
1187bad6fc0dSAndreas Gohr        $tpl
1188bad6fc0dSAndreas Gohr    );
1189d535a2e9Sstretchyboy    $data['tpl'] = $tpl;
1190a15ce62dSEsther Brunner    return $tpl;
11917146cee2SAndreas Gohr}
11927146cee2SAndreas Gohr
11937146cee2SAndreas Gohr/**
119415fae107Sandi * Returns the raw Wiki Text in three slices.
119515fae107Sandi *
119615fae107Sandi * The range parameter needs to have the form "from-to"
119715cfe303Sandi * and gives the range of the section in bytes - no
119815cfe303Sandi * UTF-8 awareness is needed.
1199f3f0262cSandi * The returned order is prefix, section and suffix.
120015fae107Sandi *
1201140cfbcdSGerrit Uitslag * @param string $range in form "from-to"
1202140cfbcdSGerrit Uitslag * @param string $id page id
1203140cfbcdSGerrit Uitslag * @param string $rev optional, the revision timestamp
120442ea7f44SGerrit Uitslag * @return string[] with three slices
12058b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
12068b19906eSAndreas Gohr *
1207f3f0262cSandi */
1208d868eb89SAndreas Gohrfunction rawWikiSlices($range, $id, $rev = '')
1209d868eb89SAndreas Gohr{
1210cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1211f3f0262cSandi
121280fcb268SAdrian Lang    // Parse range
121324870174SAndreas Gohr    [$from, $to] = sexplode('-', $range, 2);
121480fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
121524870174SAndreas Gohr    $from = $from ? $from - 1 : (0);
121624870174SAndreas Gohr    $to = $to ? $to - 1 : (strlen($text));
121780fcb268SAdrian Lang
121824870174SAndreas Gohr    $slices = [];
121980fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
122080fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to - $from);
122115cfe303Sandi    $slices[2] = substr($text, $to);
1222f3f0262cSandi    return $slices;
1223f3f0262cSandi}
1224f3f0262cSandi
1225f3f0262cSandi/**
122615fae107Sandi * Joins wiki text slices
122715fae107Sandi *
122880fcb268SAdrian Lang * function to join the text slices.
1229f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
1230f3f0262cSandi * lines between sections if needed (used on saving).
123115fae107Sandi *
1232140cfbcdSGerrit Uitslag * @param string $pre prefix
1233140cfbcdSGerrit Uitslag * @param string $text text in the middle
1234140cfbcdSGerrit Uitslag * @param string $suf suffix
1235140cfbcdSGerrit Uitslag * @param bool $pretty add additional empty lines between sections
1236140cfbcdSGerrit Uitslag * @return string
12378b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
12388b19906eSAndreas Gohr *
1239f3f0262cSandi */
1240d868eb89SAndreas Gohrfunction con($pre, $text, $suf, $pretty = false)
1241d868eb89SAndreas Gohr{
1242f3f0262cSandi    if ($pretty) {
12437d34963bSAndreas Gohr        if (
12446c16a3a9Sfiwswe            $pre !== '' && !str_ends_with($pre, "\n") &&
12456c16a3a9Sfiwswe            !str_starts_with($text, "\n")
12463272d797SAndreas Gohr        ) {
124780fcb268SAdrian Lang            $pre .= "\n";
124880fcb268SAdrian Lang        }
12497d34963bSAndreas Gohr        if (
12506c16a3a9Sfiwswe            $suf !== '' && !str_ends_with($text, "\n") &&
12516c16a3a9Sfiwswe            !str_starts_with($suf, "\n")
12523272d797SAndreas Gohr        ) {
125380fcb268SAdrian Lang            $text .= "\n";
125480fcb268SAdrian Lang        }
1255f3f0262cSandi    }
1256f3f0262cSandi
1257f3f0262cSandi    return $pre . $text . $suf;
1258f3f0262cSandi}
1259f3f0262cSandi
1260f3f0262cSandi/**
1261b24d9195SAndreas Gohr * Checks if the current page version is newer than the last entry in the page's
1262b24d9195SAndreas Gohr * changelog. If so, we assume it has been an external edit and we create an
1263b24d9195SAndreas Gohr * attic copy and add a proper changelog line.
1264b24d9195SAndreas Gohr *
1265b24d9195SAndreas Gohr * This check is only executed when the page is about to be saved again from the
12668b19906eSAndreas Gohr * wiki, triggered in @param string $id the page ID
12678b19906eSAndreas Gohr * @see saveWikiText()
1268b24d9195SAndreas Gohr *
126969f9b481SSatoshi Sahara * @deprecated 2021-11-28
1270b24d9195SAndreas Gohr */
1271d868eb89SAndreas Gohrfunction detectExternalEdit($id)
1272d868eb89SAndreas Gohr{
127379a2d784SGerrit Uitslag    dbg_deprecated(PageFile::class . '::detectExternalEdit()');
1274b24e9c4aSSatoshi Sahara    (new PageFile($id))->detectExternalEdit();
1275b24d9195SAndreas Gohr}
1276b24d9195SAndreas Gohr
1277b24d9195SAndreas Gohr/**
1278a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
1279a701424fSBen Coburn * Also directs changelog and attic updates.
128015fae107Sandi *
1281140cfbcdSGerrit Uitslag * @param string $id page id
1282140cfbcdSGerrit Uitslag * @param string $text wikitext being saved
1283140cfbcdSGerrit Uitslag * @param string $summary summary of text update
1284140cfbcdSGerrit Uitslag * @param bool $minor mark this saved version as minor update
12858b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
12868b19906eSAndreas Gohr * @author Ben Coburn <btcoburn@silicodon.net>
12878b19906eSAndreas Gohr *
1288f3f0262cSandi */
1289d868eb89SAndreas Gohrfunction saveWikiText($id, $text, $summary, $minor = false)
1290d868eb89SAndreas Gohr{
1291585bf44eSChristopher Smith
1292b24e9c4aSSatoshi Sahara    // get COMMON_WIKIPAGE_SAVE event data
1293b24e9c4aSSatoshi Sahara    $data = (new PageFile($id))->saveWikiText($text, $summary, $minor);
1294a577fbc2SAndreas Gohr    if (!$data) return; // save was cancelled (for no changes or by a plugin)
1295ac3ed4afSGerrit Uitslag
129626a0801fSAndreas Gohr    // send notify mails
129724870174SAndreas Gohr    ['oldRevision' => $rev, 'newRevision' => $new_rev, 'summary' => $summary] = $data;
12983b813d43SSatoshi Sahara    notify($id, 'admin', $rev, $summary, $minor, $new_rev);
12993b813d43SSatoshi Sahara    notify($id, 'subscribers', $rev, $summary, $minor, $new_rev);
1300f3f0262cSandi
13012eccbdaaSGina Haeussge    // if useheading is enabled, purge the cache of all linking pages
1302fe9ec250SChris Smith    if (useHeading('content')) {
130307ff0babSMichael Hamann        $pages = ft_backlinks($id, true);
13042eccbdaaSGina Haeussge        foreach ($pages as $page) {
13050db5771eSMichael Große            $cache = new CacheRenderer($page, wikiFN($page), 'xhtml');
13062eccbdaaSGina Haeussge            $cache->removeCache();
13072eccbdaaSGina Haeussge        }
13082eccbdaaSGina Haeussge    }
1309f3f0262cSandi}
1310f3f0262cSandi
1311f3f0262cSandi/**
1312d5824ab9SSatoshi Sahara * moves the current version to the attic and returns its revision date
131315fae107Sandi *
1314140cfbcdSGerrit Uitslag * @param string $id page id
1315140cfbcdSGerrit Uitslag * @return int|string revision timestamp
13168b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
13178b19906eSAndreas Gohr *
131869f9b481SSatoshi Sahara * @deprecated 2021-11-28
1319f3f0262cSandi */
1320d868eb89SAndreas Gohrfunction saveOldRevision($id)
1321d868eb89SAndreas Gohr{
132279a2d784SGerrit Uitslag    dbg_deprecated(PageFile::class . '::saveOldRevision()');
1323b24e9c4aSSatoshi Sahara    return (new PageFile($id))->saveOldRevision();
1324f3f0262cSandi}
1325f3f0262cSandi
1326f3f0262cSandi/**
1327fde10de4SAdrian Lang * Sends a notify mail on page change or registration
132826a0801fSAndreas Gohr *
132926a0801fSAndreas Gohr * @param string $id The changed page
1330fde10de4SAdrian Lang * @param string $who Who to notify (admin|subscribers|register)
13313272d797SAndreas Gohr * @param int|string $rev Old page revision
133226a0801fSAndreas Gohr * @param string $summary What changed
133390033e9dSAndreas Gohr * @param boolean $minor Is this a minor edit?
133442ea7f44SGerrit Uitslag * @param string[] $replace Additional string substitutions, @KEY@ to be replaced by value
133583734cddSPhy * @param int|string $current_rev New page revision
13363272d797SAndreas Gohr * @return bool
1337140cfbcdSGerrit Uitslag *
133815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1339f3f0262cSandi */
1340d868eb89SAndreas Gohrfunction notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = [], $current_rev = false)
1341d868eb89SAndreas Gohr{
1342f3f0262cSandi    global $conf;
1343585bf44eSChristopher Smith    /* @var Input $INPUT */
1344585bf44eSChristopher Smith    global $INPUT;
1345b158d625SSteven Danz
13466df843eeSAndreas Gohr    // decide if there is something to do, eg. whom to mail
134726a0801fSAndreas Gohr    if ($who == 'admin') {
13483272d797SAndreas Gohr        if (empty($conf['notify'])) return false; //notify enabled?
13492ed38036SAndreas Gohr        $tpl = 'mailtext';
135026a0801fSAndreas Gohr        $to = $conf['notify'];
135126a0801fSAndreas Gohr    } elseif ($who == 'subscribers') {
135284c1127cSAndreas Gohr        if (!actionOK('subscribe')) return false; //subscribers enabled?
1353585bf44eSChristopher Smith        if ($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
135424870174SAndreas Gohr        $data = ['id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace];
1355cbb44eabSAndreas Gohr        Event::createAndTrigger(
1356dccd6b2bSAndreas Gohr            'COMMON_NOTIFY_ADDRESSLIST',
1357dccd6b2bSAndreas Gohr            $data,
135824870174SAndreas Gohr            [new SubscriberManager(), 'notifyAddresses']
13593272d797SAndreas Gohr        );
13602ed38036SAndreas Gohr        $to = $data['addresslist'];
13612ed38036SAndreas Gohr        if (empty($to)) return false;
13622ed38036SAndreas Gohr        $tpl = 'subscr_single';
136326a0801fSAndreas Gohr    } else {
13643272d797SAndreas Gohr        return false; //just to be safe
136526a0801fSAndreas Gohr    }
136626a0801fSAndreas Gohr
13676df843eeSAndreas Gohr    // prepare content
1368704a815fSMichael Große    $subscription = new PageSubscriptionSender();
136983734cddSPhy    return $subscription->sendPageDiff($to, $tpl, $id, $rev, $summary, $current_rev);
1370f3f0262cSandi}
13712ed38036SAndreas Gohr
137215fae107Sandi/**
137371f7bde7SAndreas Gohr * extracts the query from a search engine referrer
137415fae107Sandi *
13758b19906eSAndreas Gohr * @return array|string
137671f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1377140cfbcdSGerrit Uitslag *
13788b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1379f3f0262cSandi */
1380d868eb89SAndreas Gohrfunction getGoogleQuery()
1381d868eb89SAndreas Gohr{
1382585bf44eSChristopher Smith    /* @var Input $INPUT */
1383585bf44eSChristopher Smith    global $INPUT;
1384585bf44eSChristopher Smith
1385585bf44eSChristopher Smith    if (!$INPUT->server->has('HTTP_REFERER')) {
1386c66972f2SAdrian Lang        return '';
1387c66972f2SAdrian Lang    }
1388585bf44eSChristopher Smith    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1389f3f0262cSandi
1390079b3ac1SAndreas Gohr    // only handle common SEs
1391c7875401SJyoti S    if (!array_key_exists('host', $url)) return '';
1392079b3ac1SAndreas Gohr    if (!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/', $url['host'])) return '';
1393e4d8a516SKazutaka Miyasaka
139424870174SAndreas Gohr    $query = [];
1395181adffeSJulian Jeggle    if (!array_key_exists('query', $url)) return '';
1396f3f0262cSandi    parse_str($url['query'], $query);
1397e4d8a516SKazutaka Miyasaka
1398c66972f2SAdrian Lang    $q = '';
1399079b3ac1SAndreas Gohr    if (isset($query['q'])) {
1400079b3ac1SAndreas Gohr        $q = $query['q'];
1401079b3ac1SAndreas Gohr    } elseif (isset($query['p'])) {
1402079b3ac1SAndreas Gohr        $q = $query['p'];
1403079b3ac1SAndreas Gohr    } elseif (isset($query['query'])) {
1404079b3ac1SAndreas Gohr        $q = $query['query'];
1405079b3ac1SAndreas Gohr    }
1406079b3ac1SAndreas Gohr    $q = trim($q);
1407f3f0262cSandi
1408079b3ac1SAndreas Gohr    if (!$q) return '';
1409c7dc833bSPhy    // ignore if query includes a full URL
1410c7dc833bSPhy    if (strpos($q, '//') !== false) return '';
14116531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1412f93b3b50SAndreas Gohr    return $q;
1413f3f0262cSandi}
1414f3f0262cSandi
1415f3f0262cSandi/**
1416f3f0262cSandi * Return the human readable size of a file
1417f3f0262cSandi *
1418f3f0262cSandi * @param int $size A file size
1419f3f0262cSandi * @param int $dec A number of decimal places
142074160ca1SGerrit Uitslag * @return string human readable size
1421140cfbcdSGerrit Uitslag *
1422f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1423f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1424f3f0262cSandi * @version     1.0.0
1425f3f0262cSandi */
1426d868eb89SAndreas Gohrfunction filesize_h($size, $dec = 1)
1427d868eb89SAndreas Gohr{
142824870174SAndreas Gohr    $sizes = ['B', 'KB', 'MB', 'GB'];
1429f3f0262cSandi    $count = count($sizes);
1430f3f0262cSandi    $i = 0;
1431f3f0262cSandi
1432f3f0262cSandi    while ($size >= 1024 && ($i < $count - 1)) {
1433f3f0262cSandi        $size /= 1024;
1434f3f0262cSandi        $i++;
1435f3f0262cSandi    }
1436f3f0262cSandi
1437ef08383eSAndreas Gohr    return round($size, $dec) . "\xC2\xA0" . $sizes[$i]; //non-breaking space
1438f3f0262cSandi}
1439f3f0262cSandi
144015fae107Sandi/**
1441c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1442c57e365eSAndreas Gohr *
1443140cfbcdSGerrit Uitslag * @param int $dt timestamp
1444140cfbcdSGerrit Uitslag * @return string
14458b19906eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
14468b19906eSAndreas Gohr *
1447c57e365eSAndreas Gohr */
1448d868eb89SAndreas Gohrfunction datetime_h($dt)
1449d868eb89SAndreas Gohr{
1450c57e365eSAndreas Gohr    global $lang;
1451c57e365eSAndreas Gohr
1452c57e365eSAndreas Gohr    $ago = time() - $dt;
1453c57e365eSAndreas Gohr    if ($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1454c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1455c57e365eSAndreas Gohr    }
1456c57e365eSAndreas Gohr    if ($ago > 24 * 60 * 60 * 30 * 2) {
1457c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1458c57e365eSAndreas Gohr    }
1459c57e365eSAndreas Gohr    if ($ago > 24 * 60 * 60 * 7 * 2) {
1460c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1461c57e365eSAndreas Gohr    }
1462c57e365eSAndreas Gohr    if ($ago > 24 * 60 * 60 * 2) {
1463c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1464c57e365eSAndreas Gohr    }
1465c57e365eSAndreas Gohr    if ($ago > 60 * 60 * 2) {
1466c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago / (60 * 60)));
1467c57e365eSAndreas Gohr    }
1468c57e365eSAndreas Gohr    if ($ago > 60 * 2) {
1469c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago / (60)));
1470c57e365eSAndreas Gohr    }
1471c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1472c57e365eSAndreas Gohr}
1473c57e365eSAndreas Gohr
1474c57e365eSAndreas Gohr/**
1475f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1476f2263577SAndreas Gohr *
1477f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1478f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1479f2263577SAndreas Gohr *
1480140cfbcdSGerrit Uitslag * @param int|null $dt timestamp when given, null will take current timestamp
1481140cfbcdSGerrit Uitslag * @param string $format empty default to $conf['dformat'], or provide format as recognized by strftime()
1482140cfbcdSGerrit Uitslag * @return string
14838b19906eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
14848b19906eSAndreas Gohr *
14858b19906eSAndreas Gohr * @see datetime_h
1486f2263577SAndreas Gohr */
1487d868eb89SAndreas Gohrfunction dformat($dt = null, $format = '')
1488d868eb89SAndreas Gohr{
1489f2263577SAndreas Gohr    global $conf;
1490f2263577SAndreas Gohr
1491f2263577SAndreas Gohr    if (is_null($dt)) $dt = time();
1492f2263577SAndreas Gohr    $dt = (int)$dt;
1493f2263577SAndreas Gohr    if (!$format) $format = $conf['dformat'];
1494f2263577SAndreas Gohr
1495f2263577SAndreas Gohr    $format = str_replace('%f', datetime_h($dt), $format);
1496b3894732Ssplitbrain    return strftime($format, $dt);
1497f2263577SAndreas Gohr}
1498f2263577SAndreas Gohr
1499f2263577SAndreas Gohr/**
1500c4f79b71SMichael Hamann * Formats a timestamp as ISO 8601 date
1501c4f79b71SMichael Hamann *
15028b19906eSAndreas Gohr * @param int $int_date current date in UNIX timestamp
15038b19906eSAndreas Gohr * @return string
1504c4f79b71SMichael Hamann * @author <ungu at terong dot com>
150559752844SAnders Sandblad * @link http://php.net/manual/en/function.date.php#54072
1506140cfbcdSGerrit Uitslag *
1507c4f79b71SMichael Hamann */
1508d868eb89SAndreas Gohrfunction date_iso8601($int_date)
1509d868eb89SAndreas Gohr{
1510c4f79b71SMichael Hamann    $date_mod = date('Y-m-d\TH:i:s', $int_date);
1511c4f79b71SMichael Hamann    $pre_timezone = date('O', $int_date);
1512c4f79b71SMichael Hamann    $time_zone = substr($pre_timezone, 0, 3) . ":" . substr($pre_timezone, 3, 2);
1513c4f79b71SMichael Hamann    $date_mod .= $time_zone;
1514c4f79b71SMichael Hamann    return $date_mod;
1515c4f79b71SMichael Hamann}
1516c4f79b71SMichael Hamann
1517c4f79b71SMichael Hamann/**
151800a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
151900a7b5adSEsther Brunner *
15208b19906eSAndreas Gohr * @param string $email email address
15218b19906eSAndreas Gohr * @return string
152200a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
152300a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
1524140cfbcdSGerrit Uitslag *
152500a7b5adSEsther Brunner */
1526d868eb89SAndreas Gohrfunction obfuscate($email)
1527d868eb89SAndreas Gohr{
152800a7b5adSEsther Brunner    global $conf;
152900a7b5adSEsther Brunner
153000a7b5adSEsther Brunner    switch ($conf['mailguard']) {
153100a7b5adSEsther Brunner        case 'visible':
153224870174SAndreas Gohr            $obfuscate = ['@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] '];
153300a7b5adSEsther Brunner            return strtr($email, $obfuscate);
153400a7b5adSEsther Brunner
153500a7b5adSEsther Brunner        case 'hex':
153624870174SAndreas Gohr            return Conversion::toHtml($email, true);
153700a7b5adSEsther Brunner
153800a7b5adSEsther Brunner        case 'none':
153900a7b5adSEsther Brunner        default:
154000a7b5adSEsther Brunner            return $email;
154100a7b5adSEsther Brunner    }
154200a7b5adSEsther Brunner}
154300a7b5adSEsther Brunner
154400a7b5adSEsther Brunner/**
154589541d4bSAndreas Gohr * Removes quoting backslashes
154689541d4bSAndreas Gohr *
1547140cfbcdSGerrit Uitslag * @param string $string
1548140cfbcdSGerrit Uitslag * @param string $char backslashed character
1549140cfbcdSGerrit Uitslag * @return string
15508b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
15518b19906eSAndreas Gohr *
155289541d4bSAndreas Gohr */
1553d868eb89SAndreas Gohrfunction unslash($string, $char = "'")
1554d868eb89SAndreas Gohr{
155589541d4bSAndreas Gohr    return str_replace('\\' . $char, $char, $string);
155689541d4bSAndreas Gohr}
155789541d4bSAndreas Gohr
155873038c47SAndreas Gohr/**
155973038c47SAndreas Gohr * Convert php.ini shorthands to byte
156073038c47SAndreas Gohr *
1561a81f3d99SAndreas Gohr * On 32 bit systems values >= 2GB will fail!
1562140cfbcdSGerrit Uitslag *
1563a81f3d99SAndreas Gohr * -1 (infinite size) will be reported as -1
1564a81f3d99SAndreas Gohr *
1565a81f3d99SAndreas Gohr * @link   https://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
1566a81f3d99SAndreas Gohr * @param string $value PHP size shorthand
1567a81f3d99SAndreas Gohr * @return int
156873038c47SAndreas Gohr */
1569d868eb89SAndreas Gohrfunction php_to_byte($value)
1570d868eb89SAndreas Gohr{
1571f5c0c80bSAndreas Gohr    switch (strtoupper(substr($value, -1))) {
157273038c47SAndreas Gohr        case 'G':
157324870174SAndreas Gohr            $ret = (int)substr($value, 0, -1) * 1024 * 1024 * 1024;
157473038c47SAndreas Gohr            break;
157573038c47SAndreas Gohr        case 'M':
157624870174SAndreas Gohr            $ret = (int)substr($value, 0, -1) * 1024 * 1024;
1577a81f3d99SAndreas Gohr            break;
157873038c47SAndreas Gohr        case 'K':
157924870174SAndreas Gohr            $ret = (int)substr($value, 0, -1) * 1024;
158073038c47SAndreas Gohr            break;
15819eeeb775SAndreas Gohr        default:
158224870174SAndreas Gohr            $ret = (int)$value;
158349cbd23eSOtto Vainio            break;
158473038c47SAndreas Gohr    }
158573038c47SAndreas Gohr    return $ret;
158673038c47SAndreas Gohr}
158773038c47SAndreas Gohr
1588546d3a99SAndreas Gohr/**
1589546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1590140cfbcdSGerrit Uitslag *
1591140cfbcdSGerrit Uitslag * @param string $string
1592140cfbcdSGerrit Uitslag * @return string
1593546d3a99SAndreas Gohr */
1594d868eb89SAndreas Gohrfunction preg_quote_cb($string)
1595d868eb89SAndreas Gohr{
1596546d3a99SAndreas Gohr    return preg_quote($string, '/');
1597546d3a99SAndreas Gohr}
159873038c47SAndreas Gohr
1599bd2f6c2fSAndreas Gohr/**
1600bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1601bd2f6c2fSAndreas Gohr *
1602c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1603bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1604bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1605bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1606bd2f6c2fSAndreas Gohr *
1607bd2f6c2fSAndreas Gohr * @param string $keep the part to keep
1608bd2f6c2fSAndreas Gohr * @param string $short the part to shorten
1609bd2f6c2fSAndreas Gohr * @param int $max maximum chars you want for the whole string
1610bd2f6c2fSAndreas Gohr * @param int $min minimum number of chars to have left for middle shortening
1611bd2f6c2fSAndreas Gohr * @param string $char the shortening character to use
16123272d797SAndreas Gohr * @return string
1613bd2f6c2fSAndreas Gohr */
1614d868eb89SAndreas Gohrfunction shorten($keep, $short, $max, $min = 9, $char = '…')
1615d868eb89SAndreas Gohr{
161624870174SAndreas Gohr    $max -= PhpString::strlen($keep);
1617bd2f6c2fSAndreas Gohr    if ($max < $min) return $keep;
161824870174SAndreas Gohr    $len = PhpString::strlen($short);
1619bd2f6c2fSAndreas Gohr    if ($len <= $max) return $keep . $short;
1620bd2f6c2fSAndreas Gohr    $half = floor($max / 2);
16216ce3e5f8SAndreas Gohr    return $keep .
162224870174SAndreas Gohr        PhpString::substr($short, 0, $half - 1) .
16236ce3e5f8SAndreas Gohr        $char .
162424870174SAndreas Gohr        PhpString::substr($short, $len - $half);
1625bd2f6c2fSAndreas Gohr}
1626bd2f6c2fSAndreas Gohr
1627dc58b6f4SAndy Webber/**
1628dc58b6f4SAndy Webber * Return the users real name or e-mail address for use
1629dc58b6f4SAndy Webber * in page footer and recent changes pages
1630dc58b6f4SAndy Webber *
1631b4b6c9a1SGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
163215f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1633c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
163415f3bc49SGerrit Uitslag *
1635dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1636dc58b6f4SAndy Webber */
1637d868eb89SAndreas Gohrfunction editorinfo($username, $textonly = false)
1638d868eb89SAndreas Gohr{
1639cd4635eeSGerrit Uitslag    return userlink($username, $textonly);
1640dc58b6f4SAndy Webber}
1641dc58b6f4SAndy Webber
164260a396c8SGerrit Uitslag/**
164360a396c8SGerrit Uitslag * Returns users realname w/o link
164460a396c8SGerrit Uitslag *
1645f168548cSGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
164615f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1647c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
164860a396c8SGerrit Uitslag *
164960a396c8SGerrit Uitslag * @triggers COMMON_USER_LINK
165060a396c8SGerrit Uitslag */
1651d868eb89SAndreas Gohrfunction userlink($username = null, $textonly = false)
1652d868eb89SAndreas Gohr{
165360a396c8SGerrit Uitslag    global $conf, $INFO;
1654e1d9dcc8SAndreas Gohr    /** @var AuthPlugin $auth */
165560a396c8SGerrit Uitslag    global $auth;
165630f6ec4bSGerrit Uitslag    /** @var Input $INPUT */
165730f6ec4bSGerrit Uitslag    global $INPUT;
165860a396c8SGerrit Uitslag
165960a396c8SGerrit Uitslag    // prepare initial event data
166024870174SAndreas Gohr    $data = [
166160a396c8SGerrit Uitslag        'username' => $username, // the unique user name
166260a396c8SGerrit Uitslag        'name' => '',
166324870174SAndreas Gohr        'link' => [
166424870174SAndreas Gohr            //setting 'link' to false disables linking
166560a396c8SGerrit Uitslag            'target' => '',
166660a396c8SGerrit Uitslag            'pre' => '',
166760a396c8SGerrit Uitslag            'suf' => '',
166860a396c8SGerrit Uitslag            'style' => '',
166960a396c8SGerrit Uitslag            'more' => '',
167060a396c8SGerrit Uitslag            'url' => '',
167160a396c8SGerrit Uitslag            'title' => '',
167224870174SAndreas Gohr            'class' => '',
167324870174SAndreas Gohr        ],
16744d5fc927SGerrit Uitslag        'userlink' => '', // formatted user name as will be returned
167524870174SAndreas Gohr        'textonly' => $textonly,
167624870174SAndreas Gohr    ];
167762c8004eSGerrit Uitslag    if ($username === null) {
167830f6ec4bSGerrit Uitslag        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
167915f3bc49SGerrit Uitslag        if ($textonly) {
168015f3bc49SGerrit Uitslag            $data['name'] = $INFO['userinfo']['name'] . ' (' . $INPUT->server->str('REMOTE_USER') . ')';
168115f3bc49SGerrit Uitslag        } else {
168264159a61SAndreas Gohr            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> ' .
168364159a61SAndreas Gohr                '(<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
168460a396c8SGerrit Uitslag        }
168515f3bc49SGerrit Uitslag    }
168660a396c8SGerrit Uitslag
1687e1d9dcc8SAndreas Gohr    $evt = new Event('COMMON_USER_LINK', $data);
168860a396c8SGerrit Uitslag    if ($evt->advise_before(true)) {
168960a396c8SGerrit Uitslag        if (empty($data['name'])) {
16906547cfc7SGerrit Uitslag            if ($auth instanceof AuthPlugin) {
16916547cfc7SGerrit Uitslag                $info = $auth->getUserData($username);
16926547cfc7SGerrit Uitslag            }
169365833968SGerrit Uitslag            if ($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1694dc58b6f4SAndy Webber                switch ($conf['showuseras']) {
1695dc58b6f4SAndy Webber                    case 'username':
16967f081821SGerrit Uitslag                    case 'username_link':
169715f3bc49SGerrit Uitslag                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
169860a396c8SGerrit Uitslag                        break;
1699dc58b6f4SAndy Webber                    case 'email':
1700dc58b6f4SAndy Webber                    case 'email_link':
170160a396c8SGerrit Uitslag                        $data['name'] = obfuscate($info['mail']);
170260a396c8SGerrit Uitslag                        break;
1703dc58b6f4SAndy Webber                }
170465833968SGerrit Uitslag            } else {
170565833968SGerrit Uitslag                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
170660a396c8SGerrit Uitslag            }
170760a396c8SGerrit Uitslag        }
17087f081821SGerrit Uitslag
17097f081821SGerrit Uitslag        /** @var Doku_Renderer_xhtml $xhtml_renderer */
17107f081821SGerrit Uitslag        static $xhtml_renderer = null;
17117f081821SGerrit Uitslag
171215f3bc49SGerrit Uitslag        if (!$data['textonly'] && empty($data['link']['url'])) {
171324870174SAndreas Gohr            if (in_array($conf['showuseras'], ['email_link', 'username_link'])) {
17146547cfc7SGerrit Uitslag                if (!isset($info) && $auth instanceof AuthPlugin) {
17156547cfc7SGerrit Uitslag                    $info = $auth->getUserData($username);
171660a396c8SGerrit Uitslag                }
171760a396c8SGerrit Uitslag                if (isset($info) && $info) {
17187f081821SGerrit Uitslag                    if ($conf['showuseras'] == 'email_link') {
171960a396c8SGerrit Uitslag                        $data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
1720dc58b6f4SAndy Webber                    } else {
17217f081821SGerrit Uitslag                        if (is_null($xhtml_renderer)) {
17227f081821SGerrit Uitslag                            $xhtml_renderer = p_get_renderer('xhtml');
17237f081821SGerrit Uitslag                        }
17248407f251Ssplitbrain                        if ($xhtml_renderer->interwiki === []) {
17257f081821SGerrit Uitslag                            $xhtml_renderer->interwiki = getInterwiki();
17267f081821SGerrit Uitslag                        }
17277f081821SGerrit Uitslag                        $shortcut = 'user';
1728533772e1SGerrit Uitslag                        $exists = null;
17296496c33fSGerrit Uitslag                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
17302a2a43c4SGerrit Uitslag                        $data['link']['class'] .= ' interwiki iw_user';
17316496c33fSGerrit Uitslag                        if ($exists !== null) {
17326496c33fSGerrit Uitslag                            if ($exists) {
17336496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink1';
17346496c33fSGerrit Uitslag                            } else {
17356496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink2';
17366496c33fSGerrit Uitslag                                $data['link']['rel'] = 'nofollow';
17376496c33fSGerrit Uitslag                            }
17386496c33fSGerrit Uitslag                        }
1739dc58b6f4SAndy Webber                    }
1740dc58b6f4SAndy Webber                } else {
174115f3bc49SGerrit Uitslag                    $data['textonly'] = true;
1742dc58b6f4SAndy Webber                }
174360a396c8SGerrit Uitslag            } else {
174415f3bc49SGerrit Uitslag                $data['textonly'] = true;
174560a396c8SGerrit Uitslag            }
174660a396c8SGerrit Uitslag        }
174760a396c8SGerrit Uitslag
174815f3bc49SGerrit Uitslag        if ($data['textonly']) {
17494d5fc927SGerrit Uitslag            $data['userlink'] = $data['name'];
175060a396c8SGerrit Uitslag        } else {
175160a396c8SGerrit Uitslag            $data['link']['name'] = $data['name'];
175260a396c8SGerrit Uitslag            if (is_null($xhtml_renderer)) {
175360a396c8SGerrit Uitslag                $xhtml_renderer = p_get_renderer('xhtml');
175460a396c8SGerrit Uitslag            }
17554d5fc927SGerrit Uitslag            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
175660a396c8SGerrit Uitslag        }
175760a396c8SGerrit Uitslag    }
175860a396c8SGerrit Uitslag    $evt->advise_after();
175960a396c8SGerrit Uitslag    unset($evt);
176060a396c8SGerrit Uitslag
17614d5fc927SGerrit Uitslag    return $data['userlink'];
1762066fee30SAndreas Gohr}
1763066fee30SAndreas Gohr
1764066fee30SAndreas Gohr/**
1765066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1766066fee30SAndreas Gohr * When no image exists, returns an empty string
1767066fee30SAndreas Gohr *
1768066fee30SAndreas Gohr * @param string $type - type of image 'badge' or 'button'
17693272d797SAndreas Gohr * @return string
17708b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
17718b19906eSAndreas Gohr *
1772066fee30SAndreas Gohr */
1773d868eb89SAndreas Gohrfunction license_img($type)
1774d868eb89SAndreas Gohr{
1775066fee30SAndreas Gohr    global $license;
1776066fee30SAndreas Gohr    global $conf;
1777066fee30SAndreas Gohr    if (!$conf['license']) return '';
1778066fee30SAndreas Gohr    if (!is_array($license[$conf['license']])) return '';
177924870174SAndreas Gohr    $try = [];
1780066fee30SAndreas Gohr    $try[] = 'lib/images/license/' . $type . '/' . $conf['license'] . '.png';
1781066fee30SAndreas Gohr    $try[] = 'lib/images/license/' . $type . '/' . $conf['license'] . '.gif';
17826c16a3a9Sfiwswe    if (str_starts_with($conf['license'], 'cc-')) {
1783066fee30SAndreas Gohr        $try[] = 'lib/images/license/' . $type . '/cc.png';
1784066fee30SAndreas Gohr    }
1785066fee30SAndreas Gohr    foreach ($try as $src) {
178679e79377SAndreas Gohr        if (file_exists(DOKU_INC . $src)) return $src;
1787066fee30SAndreas Gohr    }
1788066fee30SAndreas Gohr    return '';
1789dc58b6f4SAndy Webber}
1790dc58b6f4SAndy Webber
179113c08e2fSMichael Klier/**
179213c08e2fSMichael Klier * Checks if the given amount of memory is available
179313c08e2fSMichael Klier *
179413c08e2fSMichael Klier * If the memory_get_usage() function is not available the
179513c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
179613c08e2fSMichael Klier *
17973272d797SAndreas Gohr * @param int $mem Size of memory you want to allocate in bytes
1798140cfbcdSGerrit Uitslag * @param int $bytes already allocated memory (see above)
17993272d797SAndreas Gohr * @return bool
18008b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
18018b19906eSAndreas Gohr *
18028b19906eSAndreas Gohr * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
180313c08e2fSMichael Klier */
1804d868eb89SAndreas Gohrfunction is_mem_available($mem, $bytes = 1_048_576)
1805d868eb89SAndreas Gohr{
180613c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
180713c08e2fSMichael Klier    if (empty($limit)) return true; // no limit set!
1808985d6187SElenchus    if ($limit == -1) return true; // unlimited
180913c08e2fSMichael Klier
181013c08e2fSMichael Klier    // parse limit to bytes
181113c08e2fSMichael Klier    $limit = php_to_byte($limit);
181213c08e2fSMichael Klier
181313c08e2fSMichael Klier    // get used memory if possible
181413c08e2fSMichael Klier    if (function_exists('memory_get_usage')) {
181513c08e2fSMichael Klier        $used = memory_get_usage();
181649eb6e38SAndreas Gohr    } else {
181749eb6e38SAndreas Gohr        $used = $bytes;
181813c08e2fSMichael Klier    }
181913c08e2fSMichael Klier
182013c08e2fSMichael Klier    if ($used + $mem > $limit) {
182113c08e2fSMichael Klier        return false;
182213c08e2fSMichael Klier    }
182313c08e2fSMichael Klier
182413c08e2fSMichael Klier    return true;
182513c08e2fSMichael Klier}
182613c08e2fSMichael Klier
1827af2408d5SAndreas Gohr/**
1828af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1829af2408d5SAndreas Gohr *
1830af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1831af2408d5SAndreas Gohr *
1832af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1833af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1834140cfbcdSGerrit Uitslag *
1835140cfbcdSGerrit Uitslag * @param string $url url being directed to
1836af2408d5SAndreas Gohr */
1837d868eb89SAndreas Gohrfunction send_redirect($url)
1838d868eb89SAndreas Gohr{
183998ca30d2SAndreas Gohr    $url = stripctl($url); // defend against HTTP Response Splitting
184098ca30d2SAndreas Gohr
1841585bf44eSChristopher Smith    /* @var Input $INPUT */
1842585bf44eSChristopher Smith    global $INPUT;
1843585bf44eSChristopher Smith
18440181f021SAndreas Gohr    //are there any undisplayed messages? keep them in session for display
18450181f021SAndreas Gohr    global $MSG;
18460181f021SAndreas Gohr    if (isset($MSG) && count($MSG) && !defined('NOSESSION')) {
18470181f021SAndreas Gohr        //reopen session, store data and close session again
18480181f021SAndreas Gohr        @session_start();
18490181f021SAndreas Gohr        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
18500181f021SAndreas Gohr    }
18510181f021SAndreas Gohr
1852d4869846SAndreas Gohr    // always close the session
1853d4869846SAndreas Gohr    session_write_close();
1854d4869846SAndreas Gohr
1855af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
18567d34963bSAndreas Gohr    if (
18577d34963bSAndreas Gohr        $INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1858585bf44eSChristopher Smith        (strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) &&
1859585bf44eSChristopher Smith        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
18603272d797SAndreas Gohr        $matches[1] < 6
18613272d797SAndreas Gohr    ) {
1862af2408d5SAndreas Gohr        header('Refresh: 0;url=' . $url);
1863af2408d5SAndreas Gohr    } else {
1864af2408d5SAndreas Gohr        header('Location: ' . $url);
1865af2408d5SAndreas Gohr    }
186681781cb6SAndreas Gohr
1867572dc222SLarsDW223    // no exits during unit tests
186827c0c399SAndreas Gohr    if (defined('DOKU_UNITTEST')) {
186927c0c399SAndreas Gohr        // pass info about the redirect back to the test suite
187027c0c399SAndreas Gohr        $testRequest = TestRequest::getRunning();
187127c0c399SAndreas Gohr        if ($testRequest !== null) {
187227c0c399SAndreas Gohr            $testRequest->addData('send_redirect', $url);
187327c0c399SAndreas Gohr        }
1874572dc222SLarsDW223        return;
1875572dc222SLarsDW223    }
187627c0c399SAndreas Gohr
1877af2408d5SAndreas Gohr    exit;
1878af2408d5SAndreas Gohr}
1879af2408d5SAndreas Gohr
18805b75cd1fSAdrian Lang/**
18815b75cd1fSAdrian Lang * Validate a value using a set of valid values
18825b75cd1fSAdrian Lang *
18835b75cd1fSAdrian Lang * This function checks whether a specified value is set and in the array
18845b75cd1fSAdrian Lang * $valid_values. If not, the function returns a default value or, if no
18855b75cd1fSAdrian Lang * default is specified, throws an exception.
18865b75cd1fSAdrian Lang *
18875b75cd1fSAdrian Lang * @param string $param The name of the parameter
18885b75cd1fSAdrian Lang * @param array $valid_values A set of valid values; Optionally a default may
18895b75cd1fSAdrian Lang *                             be marked by the key “default”.
18905b75cd1fSAdrian Lang * @param array $array The array containing the value (typically $_POST
18915b75cd1fSAdrian Lang *                             or $_GET)
18925b75cd1fSAdrian Lang * @param string $exc The text of the raised exception
18935b75cd1fSAdrian Lang *
18943272d797SAndreas Gohr * @return mixed
18958b19906eSAndreas Gohr * @throws Exception
18965b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
18975b75cd1fSAdrian Lang */
1898d868eb89SAndreas Gohrfunction valid_input_set($param, $valid_values, $array, $exc = '')
1899d868eb89SAndreas Gohr{
19005b75cd1fSAdrian Lang    if (isset($array[$param]) && in_array($array[$param], $valid_values)) {
19015b75cd1fSAdrian Lang        return $array[$param];
19025b75cd1fSAdrian Lang    } elseif (isset($valid_values['default'])) {
19035b75cd1fSAdrian Lang        return $valid_values['default'];
19045b75cd1fSAdrian Lang    } else {
19055b75cd1fSAdrian Lang        throw new Exception($exc);
19065b75cd1fSAdrian Lang    }
19075b75cd1fSAdrian Lang}
19085b75cd1fSAdrian Lang
190963703ba5SAndreas Gohr/**
191063703ba5SAndreas Gohr * Read a preference from the DokuWiki cookie
1911646a531aSChristopher Smith * (remembering both keys & values are urlencoded)
1912140cfbcdSGerrit Uitslag *
1913140cfbcdSGerrit Uitslag * @param string $pref preference key
1914b4b6c9a1SGerrit Uitslag * @param mixed $default value returned when preference not found
1915140cfbcdSGerrit Uitslag * @return string preference value
191663703ba5SAndreas Gohr */
1917d868eb89SAndreas Gohrfunction get_doku_pref($pref, $default)
1918d868eb89SAndreas Gohr{
1919646a531aSChristopher Smith    $enc_pref = urlencode($pref);
192006c9ee33SMarius van Witzenburg    if (isset($_COOKIE['DOKU_PREFS']) && strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
1921554a8c9fSAdrian Lang        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
192263703ba5SAndreas Gohr        $cnt = count($parts);
19231c3eca7dSPhy
19241c3eca7dSPhy        // due to #2721 there might be duplicate entries,
19251c3eca7dSPhy        // so we read from the end
19261c3eca7dSPhy        for ($i = $cnt - 2; $i >= 0; $i -= 2) {
192724870174SAndreas Gohr            if ($parts[$i] === $enc_pref) {
1928646a531aSChristopher Smith                return urldecode($parts[$i + 1]);
1929554a8c9fSAdrian Lang            }
1930554a8c9fSAdrian Lang        }
1931554a8c9fSAdrian Lang    }
1932554a8c9fSAdrian Lang    return $default;
1933554a8c9fSAdrian Lang}
1934554a8c9fSAdrian Lang
19353c94d07bSAnika Henke/**
19363c94d07bSAnika Henke * Add a preference to the DokuWiki cookie
193736ec377eSChristopher Smith * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
19383a970889SAnika Henke * Remove it by setting $val to false
1939140cfbcdSGerrit Uitslag *
1940140cfbcdSGerrit Uitslag * @param string $pref preference key
1941140cfbcdSGerrit Uitslag * @param string $val preference value
19423c94d07bSAnika Henke */
1943d868eb89SAndreas Gohrfunction set_doku_pref($pref, $val)
1944d868eb89SAndreas Gohr{
19453c94d07bSAnika Henke    global $conf;
19463c94d07bSAnika Henke    $orig = get_doku_pref($pref, false);
19473c94d07bSAnika Henke    $cookieVal = '';
19483c94d07bSAnika Henke
19491c3eca7dSPhy    if ($orig !== false && ($orig !== $val)) {
19503c94d07bSAnika Henke        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
19513c94d07bSAnika Henke        $cnt = count($parts);
195236ec377eSChristopher Smith        // urlencode $pref for the comparison
195336ec377eSChristopher Smith        $enc_pref = rawurlencode($pref);
19541c3eca7dSPhy        $seen = false;
19553c94d07bSAnika Henke        for ($i = 0; $i < $cnt; $i += 2) {
195624870174SAndreas Gohr            if ($parts[$i] === $enc_pref) {
19571c3eca7dSPhy                if (!$seen) {
19583a970889SAnika Henke                    if ($val !== false) {
1959bf8f8509SAndreas Gohr                        $parts[$i + 1] = rawurlencode($val ?? '');
19603a970889SAnika Henke                    } else {
19613a970889SAnika Henke                        unset($parts[$i]);
19623a970889SAnika Henke                        unset($parts[$i + 1]);
19633a970889SAnika Henke                    }
19641c3eca7dSPhy                    $seen = true;
19651c3eca7dSPhy                } else {
19661c3eca7dSPhy                    // no break because we want to remove duplicate entries
19671c3eca7dSPhy                    unset($parts[$i]);
19681c3eca7dSPhy                    unset($parts[$i + 1]);
19691c3eca7dSPhy                }
19703c94d07bSAnika Henke            }
19713c94d07bSAnika Henke        }
19723c94d07bSAnika Henke        $cookieVal = implode('#', $parts);
19731c3eca7dSPhy    } elseif ($orig === false && $val !== false) {
1974c10f256aSDamien Regad        $cookieVal = (isset($_COOKIE['DOKU_PREFS']) ? $_COOKIE['DOKU_PREFS'] . '#' : '') .
197564159a61SAndreas Gohr            rawurlencode($pref) . '#' . rawurlencode($val);
19763c94d07bSAnika Henke    }
19773c94d07bSAnika Henke
197875e4dd8aSGerrit Uitslag    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
19795833995aSPhy    if (defined('DOKU_UNITTEST')) {
19805833995aSPhy        $_COOKIE['DOKU_PREFS'] = $cookieVal;
19815833995aSPhy    } else {
1982bf8392ebSAndreas Gohr        setcookie('DOKU_PREFS', $cookieVal, [
1983bf8392ebSAndreas Gohr            'expires' => time() + 365 * 24 * 3600,
1984bf8392ebSAndreas Gohr            'path' => $cookieDir,
1985bf8392ebSAndreas Gohr            'secure' => ($conf['securecookie'] && is_ssl()),
1986bf8392ebSAndreas Gohr            'samesite' => 'Lax'
1987bf8392ebSAndreas Gohr        ]);
19883c94d07bSAnika Henke    }
19893c94d07bSAnika Henke}
19903c94d07bSAnika Henke
1991f8fb2d18SAndreas Gohr/**
1992f8fb2d18SAndreas Gohr * Strips source mapping declarations from given text #601
1993f8fb2d18SAndreas Gohr *
199442ea7f44SGerrit Uitslag * @param string &$text reference to the CSS or JavaScript code to clean
1995f8fb2d18SAndreas Gohr */
1996d868eb89SAndreas Gohrfunction stripsourcemaps(&$text)
1997d868eb89SAndreas Gohr{
1998f8fb2d18SAndreas Gohr    $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text);
1999f8fb2d18SAndreas Gohr}
2000f8fb2d18SAndreas Gohr
20013c27983bSAndreas Gohr/**
200271de5572SAndreas Gohr * Returns the contents of a given SVG file for embedding
20033c27983bSAndreas Gohr *
20043c27983bSAndreas Gohr * Inlining SVGs saves on HTTP requests and more importantly allows for styling them through
20053c27983bSAndreas Gohr * CSS. However it should used with small SVGs only. The $maxsize setting ensures only small
20063c27983bSAndreas Gohr * files are embedded.
20073c27983bSAndreas Gohr *
200871de5572SAndreas Gohr * This strips unneeded headers, comments and newline. The result is not a vaild standalone SVG!
200971de5572SAndreas Gohr *
20103c27983bSAndreas Gohr * @param string $file full path to the SVG file
20113c27983bSAndreas Gohr * @param int $maxsize maximum allowed size for the SVG to be embedded
201271de5572SAndreas Gohr * @return string|false the SVG content, false if the file couldn't be loaded
20133c27983bSAndreas Gohr */
2014d868eb89SAndreas Gohrfunction inlineSVG($file, $maxsize = 2048)
2015d868eb89SAndreas Gohr{
20163c27983bSAndreas Gohr    $file = trim($file);
20173c27983bSAndreas Gohr    if ($file === '') return false;
20183c27983bSAndreas Gohr    if (!file_exists($file)) return false;
20193c27983bSAndreas Gohr    if (filesize($file) > $maxsize) return false;
20203c27983bSAndreas Gohr    if (!is_readable($file)) return false;
20213c27983bSAndreas Gohr    $content = file_get_contents($file);
20220849fa88SAndreas Gohr    $content = preg_replace('/<!--.*?(-->)/s', '', $content); // comments
20230849fa88SAndreas Gohr    $content = preg_replace('/<\?xml .*?\?>/i', '', $content); // xml header
20240849fa88SAndreas Gohr    $content = preg_replace('/<!DOCTYPE .*?>/i', '', $content); // doc type
20250849fa88SAndreas Gohr    $content = preg_replace('/>\s+</s', '><', $content); // newlines between tags
20263c27983bSAndreas Gohr    $content = trim($content);
20276c16a3a9Sfiwswe    if (!str_starts_with($content, '<svg ')) return false;
202871de5572SAndreas Gohr    return $content;
20293c27983bSAndreas Gohr}
20303c27983bSAndreas Gohr
2031e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
2032