xref: /dokuwiki/inc/common.php (revision 75aef198cdc7307a75ab63c9403e704e2194959a)
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;
123f108b37SAndreas Gohruse dokuwiki\PrefCookie;
1324870174SAndreas Gohruse dokuwiki\Utf8\Clean;
1424870174SAndreas Gohruse dokuwiki\Utf8\PhpString;
1524870174SAndreas Gohruse dokuwiki\Utf8\Conversion;
160db5771eSMichael Großeuse dokuwiki\Cache\CacheRenderer;
170c3a5702SAndreas Gohruse dokuwiki\ChangeLog\PageChangeLog;
18b24e9c4aSSatoshi Saharause dokuwiki\File\PageFile;
19704a815fSMichael Großeuse dokuwiki\Subscriptions\PageSubscriptionSender;
2075d66495SMichael Großeuse dokuwiki\Subscriptions\SubscriberManager;
21e1d9dcc8SAndreas Gohruse dokuwiki\Extension\AuthPlugin;
22e1d9dcc8SAndreas Gohruse dokuwiki\Extension\Event;
232aba9aedSAndreas Gohruse dokuwiki\Ip;
24*73dc0a89SAndreas Gohruse dokuwiki\MailUtils;
256734bb8cSAndreas Gohruse dokuwiki\Search\MetadataSearch;
260c3a5702SAndreas Gohr
278b19906eSAndreas Gohruse function PHP81_BC\strftime;
288b19906eSAndreas Gohr
29f3f0262cSandi/**
30d5197206Schris * Wrapper around htmlspecialchars()
31d5197206Schris *
328b19906eSAndreas Gohr * @param string $string the string being converted
338b19906eSAndreas Gohr * @return string converted string
34d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
35d5197206Schris * @see    htmlspecialchars()
36140cfbcdSGerrit Uitslag *
37d5197206Schris */
38d868eb89SAndreas Gohrfunction hsc($string)
39d868eb89SAndreas Gohr{
40f7711f2bSAndreas Gohr    return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, 'UTF-8');
41d5197206Schris}
42d5197206Schris
43d5197206Schris/**
4412dd3cbcSAndreas Gohr * A safer explode for fixed length lists
4512dd3cbcSAndreas Gohr *
4612dd3cbcSAndreas Gohr * This works just like explode(), but will always return the wanted number of elements.
4712dd3cbcSAndreas Gohr * If the $input string does not contain enough elements, the missing elements will be
4812dd3cbcSAndreas Gohr * filled up with the $default value. If the input string contains more elements, the last
4912dd3cbcSAndreas Gohr * one will NOT be split up and will still contain $separator
5012dd3cbcSAndreas Gohr *
5112dd3cbcSAndreas Gohr * @param string $separator The boundary string
5212dd3cbcSAndreas Gohr * @param string $string The input string
5312dd3cbcSAndreas Gohr * @param int $limit The number of expected elements
5412dd3cbcSAndreas Gohr * @param mixed $default The value to use when filling up missing elements
5512dd3cbcSAndreas Gohr * @return array
568b19906eSAndreas Gohr * @see explode
5712dd3cbcSAndreas Gohr */
5812dd3cbcSAndreas Gohrfunction sexplode($separator, $string, $limit, $default = null)
5912dd3cbcSAndreas Gohr{
6012dd3cbcSAndreas Gohr    return array_pad(explode($separator, $string, $limit), $limit, $default);
6112dd3cbcSAndreas Gohr}
6212dd3cbcSAndreas Gohr
6312dd3cbcSAndreas Gohr/**
645b571377SAndreas Gohr * Checks if the given input is blank
655b571377SAndreas Gohr *
665b571377SAndreas Gohr * This is similar to empty() but will return false for "0".
675b571377SAndreas Gohr *
6867234204SAndreas Gohr * Please note: when you pass uninitialized variables, they will implicitly be created
6967234204SAndreas Gohr * with a NULL value without warning.
7067234204SAndreas Gohr *
7167234204SAndreas Gohr * To avoid this it's recommended to guard the call with isset like this:
7267234204SAndreas Gohr *
7367234204SAndreas Gohr * (isset($foo) && !blank($foo))
7467234204SAndreas Gohr * (!isset($foo) || blank($foo))
7567234204SAndreas Gohr *
765b571377SAndreas Gohr * @param $in
775b571377SAndreas Gohr * @param bool $trim Consider a string of whitespace to be blank
785b571377SAndreas Gohr * @return bool
795b571377SAndreas Gohr */
80d868eb89SAndreas Gohrfunction blank(&$in, $trim = false)
81d868eb89SAndreas Gohr{
825b571377SAndreas Gohr    if (is_null($in)) return true;
8324870174SAndreas Gohr    if (is_array($in)) return $in === [];
845b571377SAndreas Gohr    if ($in === "\0") return true;
855b571377SAndreas Gohr    if ($trim && trim($in) === '') return true;
86093fe67eSAndreas Gohr    if ((string) $in !== '') return false;
875b571377SAndreas Gohr    return empty($in);
885b571377SAndreas Gohr}
895b571377SAndreas Gohr
905b571377SAndreas Gohr/**
9102b0b681SAndreas Gohr * strips control characters (<32) from the given string
9202b0b681SAndreas Gohr *
9342ea7f44SGerrit Uitslag * @param string $string being stripped
94140cfbcdSGerrit Uitslag * @return string
958b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
968b19906eSAndreas Gohr *
9702b0b681SAndreas Gohr */
98d868eb89SAndreas Gohrfunction stripctl($string)
99d868eb89SAndreas Gohr{
10002b0b681SAndreas Gohr    return preg_replace('/[\x00-\x1F]+/s', '', $string);
101d5197206Schris}
102d5197206Schris
103d5197206Schris/**
104634d7150SAndreas Gohr * Return a secret token to be used for CSRF attack prevention
105634d7150SAndreas Gohr *
1068b19906eSAndreas Gohr * @return  string
107634d7150SAndreas Gohr * @link    http://en.wikipedia.org/wiki/Cross-site_request_forgery
108634d7150SAndreas Gohr * @link    http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
10942ea7f44SGerrit Uitslag *
1108b19906eSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
111634d7150SAndreas Gohr */
112d868eb89SAndreas Gohrfunction getSecurityToken()
113d868eb89SAndreas Gohr{
114585bf44eSChristopher Smith    /** @var Input $INPUT */
115585bf44eSChristopher Smith    global $INPUT;
1163680e2cdSAndreas Gohr
1173680e2cdSAndreas Gohr    $user = $INPUT->server->str('REMOTE_USER');
1183680e2cdSAndreas Gohr    $session = session_id();
1193680e2cdSAndreas Gohr
1203680e2cdSAndreas Gohr    // CSRF checks are only for logged in users - do not generate for anonymous
1213680e2cdSAndreas Gohr    if (trim($user) == '' || trim($session) == '') return '';
12224870174SAndreas Gohr    return PassHash::hmac('md5', $session . $user, auth_cookiesalt());
123634d7150SAndreas Gohr}
124634d7150SAndreas Gohr
125634d7150SAndreas Gohr/**
126634d7150SAndreas Gohr * Check the secret CSRF token
127140cfbcdSGerrit Uitslag *
128140cfbcdSGerrit Uitslag * @param null|string $token security token or null to read it from request variable
129140cfbcdSGerrit Uitslag * @return bool success if the token matched
130634d7150SAndreas Gohr */
131d868eb89SAndreas Gohrfunction checkSecurityToken($token = null)
132d868eb89SAndreas Gohr{
133585bf44eSChristopher Smith    /** @var Input $INPUT */
1347d01a0eaSTom N Harris    global $INPUT;
135585bf44eSChristopher Smith    if (!$INPUT->server->str('REMOTE_USER')) return true; // no logged in user, no need for a check
136df97eaacSAndreas Gohr
1377d01a0eaSTom N Harris    if (is_null($token)) $token = $INPUT->str('sectok');
138634d7150SAndreas Gohr    if (getSecurityToken() != $token) {
139634d7150SAndreas Gohr        msg('Security Token did not match. Possible CSRF attack.', -1);
140634d7150SAndreas Gohr        return false;
141634d7150SAndreas Gohr    }
142634d7150SAndreas Gohr    return true;
143634d7150SAndreas Gohr}
144634d7150SAndreas Gohr
145634d7150SAndreas Gohr/**
146634d7150SAndreas Gohr * Print a hidden form field with a secret CSRF token
147634d7150SAndreas Gohr *
148140cfbcdSGerrit Uitslag * @param bool $print if true print the field, otherwise html of the field is returned
14942ea7f44SGerrit Uitslag * @return string html of hidden form field
1508b19906eSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
1518b19906eSAndreas Gohr *
152634d7150SAndreas Gohr */
153d868eb89SAndreas Gohrfunction formSecurityToken($print = true)
154d868eb89SAndreas Gohr{
1552404d0edSAnika Henke    $ret = '<div class="no"><input type="hidden" name="sectok" value="' . getSecurityToken() . '" /></div>' . "\n";
1563272d797SAndreas Gohr    if ($print) echo $ret;
157634d7150SAndreas Gohr    return $ret;
158634d7150SAndreas Gohr}
159634d7150SAndreas Gohr
160634d7150SAndreas Gohr/**
1611015a57dSChristopher Smith * Determine basic information for a request of $id
16215fae107Sandi *
163140cfbcdSGerrit Uitslag * @param string $id pageid
164140cfbcdSGerrit Uitslag * @param bool $htmlClient add info about whether is mobile browser
165140cfbcdSGerrit Uitslag * @return array with info for a request of $id
166140cfbcdSGerrit Uitslag *
1678b19906eSAndreas Gohr * @author Chris Smith <chris@jalakai.co.uk>
1688b19906eSAndreas Gohr *
1698b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
170f3f0262cSandi */
171d868eb89SAndreas Gohrfunction basicinfo($id, $htmlClient = true)
172d868eb89SAndreas Gohr{
173f3f0262cSandi    global $USERINFO;
174585bf44eSChristopher Smith    /* @var Input $INPUT */
175585bf44eSChristopher Smith    global $INPUT;
1766afe8dcaSchris
177c66972f2SAdrian Lang    // set info about manager/admin status.
17824870174SAndreas Gohr    $info = [];
179c66972f2SAdrian Lang    $info['isadmin'] = false;
180c66972f2SAdrian Lang    $info['ismanager'] = false;
181585bf44eSChristopher Smith    if ($INPUT->server->has('REMOTE_USER')) {
182f3f0262cSandi        $info['userinfo'] = $USERINFO;
1831015a57dSChristopher Smith        $info['perm'] = auth_quickaclcheck($id);
184585bf44eSChristopher Smith        $info['client'] = $INPUT->server->str('REMOTE_USER');
18517ee7f66SAndreas Gohr
186f8cc712eSAndreas Gohr        if ($info['perm'] == AUTH_ADMIN) {
187f8cc712eSAndreas Gohr            $info['isadmin'] = true;
188f8cc712eSAndreas Gohr            $info['ismanager'] = true;
189f8cc712eSAndreas Gohr        } elseif (auth_ismanager()) {
190f8cc712eSAndreas Gohr            $info['ismanager'] = true;
191f8cc712eSAndreas Gohr        }
192f8cc712eSAndreas Gohr
19317ee7f66SAndreas Gohr        // if some outside auth were used only REMOTE_USER is set
194a58fcbbcSAndreas Gohr        if (empty($info['userinfo']['name'])) {
195585bf44eSChristopher Smith            $info['userinfo']['name'] = $INPUT->server->str('REMOTE_USER');
19617ee7f66SAndreas Gohr        }
197f3f0262cSandi    } else {
1981015a57dSChristopher Smith        $info['perm'] = auth_aclcheck($id, '', null);
199ee4c4a1bSAndreas Gohr        $info['client'] = clientIP(true);
200f3f0262cSandi    }
201f3f0262cSandi
2021015a57dSChristopher Smith    $info['namespace'] = getNS($id);
2031015a57dSChristopher Smith
2041015a57dSChristopher Smith    // mobile detection
2051015a57dSChristopher Smith    if ($htmlClient) {
2061015a57dSChristopher Smith        $info['ismobile'] = clientismobile();
2071015a57dSChristopher Smith    }
2081015a57dSChristopher Smith
2091015a57dSChristopher Smith    return $info;
2101015a57dSChristopher Smith}
2111015a57dSChristopher Smith
2121015a57dSChristopher Smith/**
2131015a57dSChristopher Smith * Return info about the current document as associative
2141015a57dSChristopher Smith * array.
2151015a57dSChristopher Smith *
216140cfbcdSGerrit Uitslag * @return array with info about current document
2174dc42f7fSGerrit Uitslag * @throws Exception
2184dc42f7fSGerrit Uitslag *
2194dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
2201015a57dSChristopher Smith */
221d868eb89SAndreas Gohrfunction pageinfo()
222d868eb89SAndreas Gohr{
2231015a57dSChristopher Smith    global $ID;
2241015a57dSChristopher Smith    global $REV;
2251015a57dSChristopher Smith    global $RANGE;
2261015a57dSChristopher Smith    global $lang;
2271015a57dSChristopher Smith
2281015a57dSChristopher Smith    $info = basicinfo($ID);
2291015a57dSChristopher Smith
2301015a57dSChristopher Smith    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
2311015a57dSChristopher Smith    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
2321015a57dSChristopher Smith    $info['id'] = $ID;
2331015a57dSChristopher Smith    $info['rev'] = $REV;
2341015a57dSChristopher Smith
23575d66495SMichael Große    $subManager = new SubscriberManager();
23675d66495SMichael Große    $info['subscribed'] = $subManager->userSubscription();
2377e87a794SChristopher Smith
238f3f0262cSandi    $info['locked'] = checklock($ID);
239317a04c4SSatoshi Sahara    $info['filepath'] = wikiFN($ID);
24079e79377SAndreas Gohr    $info['exists'] = file_exists($info['filepath']);
24101c9a118SAndreas Gohr    $info['currentrev'] = @filemtime($info['filepath']);
2425ec96136SSatoshi Sahara
2432ca9d91cSBen Coburn    if ($REV) {
2442ca9d91cSBen Coburn        //check if current revision was meant
24501c9a118SAndreas Gohr        if ($info['exists'] && ($info['currentrev'] == $REV)) {
2462ca9d91cSBen Coburn            $REV = '';
2477b3a6803SAndreas Gohr        } elseif ($RANGE) {
2487b3a6803SAndreas Gohr            //section editing does not work with old revisions!
2497b3a6803SAndreas Gohr            $REV = '';
2507b3a6803SAndreas Gohr            $RANGE = '';
2517b3a6803SAndreas Gohr            msg($lang['nosecedit'], 0);
2522ca9d91cSBen Coburn        } else {
2532ca9d91cSBen Coburn            //really use old revision
254317a04c4SSatoshi Sahara            $info['filepath'] = wikiFN($ID, $REV);
25579e79377SAndreas Gohr            $info['exists'] = file_exists($info['filepath']);
256f3f0262cSandi        }
257f3f0262cSandi    }
258c112d578Sandi    $info['rev'] = $REV;
259f3f0262cSandi    if ($info['exists']) {
260252acce3SSatoshi Sahara        $info['writable'] = (is_writable($info['filepath']) && $info['perm'] >= AUTH_EDIT);
261f3f0262cSandi    } else {
262f3f0262cSandi        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
263f3f0262cSandi    }
26450e988b1SAndreas Gohr    $info['editable'] = ($info['writable'] && empty($info['locked']));
265f3f0262cSandi    $info['lastmod'] = @filemtime($info['filepath']);
266f3f0262cSandi
26771726d78SBen Coburn    //load page meta data
26871726d78SBen Coburn    $info['meta'] = p_get_metadata($ID);
26971726d78SBen Coburn
270652610a2Sandi    //who's the editor
271047bad06SGerrit Uitslag    $pagelog = new PageChangeLog($ID, 1024);
272652610a2Sandi    if ($REV) {
273f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($REV);
27424870174SAndreas Gohr    } elseif (!empty($info['meta']['last_change']) && is_array($info['meta']['last_change'])) {
275aa27cf05SAndreas Gohr        $revinfo = $info['meta']['last_change'];
276aa27cf05SAndreas Gohr    } else {
277f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($info['lastmod']);
278cd00a034SBen Coburn        // cache most recent changelog line in metadata if missing and still valid
279cd00a034SBen Coburn        if ($revinfo !== false) {
280cd00a034SBen Coburn            $info['meta']['last_change'] = $revinfo;
28124870174SAndreas Gohr            p_set_metadata($ID, ['last_change' => $revinfo]);
282cd00a034SBen Coburn        }
283cd00a034SBen Coburn    }
284cd00a034SBen Coburn    //and check for an external edit
285cd00a034SBen Coburn    if ($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
286cd00a034SBen Coburn        // cached changelog line no longer valid
287cd00a034SBen Coburn        $revinfo = false;
288cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
28924870174SAndreas Gohr        p_set_metadata($ID, ['last_change' => $revinfo]);
290652610a2Sandi    }
291bb4866bdSchris
2920a444b5aSPhy    if ($revinfo !== false) {
293652610a2Sandi        $info['ip'] = $revinfo['ip'];
294652610a2Sandi        $info['user'] = $revinfo['user'];
295652610a2Sandi        $info['sum'] = $revinfo['sum'];
29671726d78SBen Coburn        // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
297ebf1501fSBen Coburn        // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
29859f257aeSchris
299252acce3SSatoshi Sahara        $info['editor'] = $revinfo['user'] ?: $revinfo['ip'];
3000a444b5aSPhy    } else {
3010a444b5aSPhy        $info['ip'] = null;
3020a444b5aSPhy        $info['user'] = null;
3030a444b5aSPhy        $info['sum'] = null;
3040a444b5aSPhy        $info['editor'] = null;
3050a444b5aSPhy    }
306652610a2Sandi
307ee4c4a1bSAndreas Gohr    // draft
30824870174SAndreas Gohr    $draft = new Draft($ID, $info['client']);
3090aabe6f8SMichael Große    if ($draft->isDraftAvailable()) {
3100aabe6f8SMichael Große        $info['draft'] = $draft->getDraftFilename();
311ee4c4a1bSAndreas Gohr    }
312ee4c4a1bSAndreas Gohr
3131015a57dSChristopher Smith    return $info;
3141015a57dSChristopher Smith}
3151015a57dSChristopher Smith
3161015a57dSChristopher Smith/**
3170c39d46cSMichael Große * Initialize and/or fill global $JSINFO with some basic info to be given to javascript
3180c39d46cSMichael Große */
319d868eb89SAndreas Gohrfunction jsinfo()
320d868eb89SAndreas Gohr{
3210c39d46cSMichael Große    global $JSINFO, $ID, $INFO, $ACT;
3220c39d46cSMichael Große
3230c39d46cSMichael Große    if (!is_array($JSINFO)) {
3240c39d46cSMichael Große        $JSINFO = [];
3250c39d46cSMichael Große    }
3260c39d46cSMichael Große    //export minimal info to JS, plugins can add more
3270c39d46cSMichael Große    $JSINFO['id'] = $ID;
32868491db9SPhy    $JSINFO['namespace'] = isset($INFO) ? (string)$INFO['namespace'] : '';
3290c39d46cSMichael Große    $JSINFO['ACT'] = act_clean($ACT);
3300c39d46cSMichael Große    $JSINFO['useHeadingNavigation'] = (int)useHeading('navigation');
3310c39d46cSMichael Große    $JSINFO['useHeadingContent'] = (int)useHeading('content');
3320c39d46cSMichael Große}
3330c39d46cSMichael Große
3340c39d46cSMichael Große/**
3351015a57dSChristopher Smith * Return information about the current media item as an associative array.
336140cfbcdSGerrit Uitslag *
337140cfbcdSGerrit Uitslag * @return array with info about current media item
3381015a57dSChristopher Smith */
339d868eb89SAndreas Gohrfunction mediainfo()
340d868eb89SAndreas Gohr{
3411015a57dSChristopher Smith    global $NS;
3421015a57dSChristopher Smith    global $IMG;
3431015a57dSChristopher Smith
3441015a57dSChristopher Smith    $info = basicinfo("$NS:*");
3451015a57dSChristopher Smith    $info['image'] = $IMG;
3461c548ebeSAndreas Gohr
347f3f0262cSandi    return $info;
348f3f0262cSandi}
349f3f0262cSandi
350f3f0262cSandi/**
3512684e50aSAndreas Gohr * Build an string of URL parameters
3522684e50aSAndreas Gohr *
3536cc6a0d2SAndreas Gohr * @see http_build_query()
3546cc6a0d2SAndreas Gohr * @param array|object $params the data to encode
355140cfbcdSGerrit Uitslag * @param string $sep series of pairs are separated by this character
356140cfbcdSGerrit Uitslag * @return string query string
3578b19906eSAndreas Gohr *
3582684e50aSAndreas Gohr */
359d868eb89SAndreas Gohrfunction buildURLparams($params, $sep = '&amp;')
360d868eb89SAndreas Gohr{
3616cc6a0d2SAndreas Gohr    return http_build_query($params, '', $sep, PHP_QUERY_RFC3986);
3622684e50aSAndreas Gohr}
3632684e50aSAndreas Gohr
3642684e50aSAndreas Gohr/**
3652684e50aSAndreas Gohr * Build an string of html tag attributes
3662684e50aSAndreas Gohr *
3677bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
3687bff22c0SAndreas Gohr *
369140cfbcdSGerrit Uitslag * @param array $params array with (attribute name-attribute value) pairs
370246d3337SMichael Große * @param bool $skipEmptyStrings skip empty string values?
371140cfbcdSGerrit Uitslag * @return string
3728b19906eSAndreas Gohr * @author Andreas Gohr
3738b19906eSAndreas Gohr *
3742684e50aSAndreas Gohr */
375d868eb89SAndreas Gohrfunction buildAttributes($params, $skipEmptyStrings = false)
376d868eb89SAndreas Gohr{
3772684e50aSAndreas Gohr    $url = '';
3789063ec14SAdrian Lang    $white = false;
3792684e50aSAndreas Gohr    foreach ($params as $key => $val) {
3802401f18dSSyntaxseed        if ($key[0] == '_') continue;
381246d3337SMichael Große        if ($val === '' && $skipEmptyStrings) continue;
3829063ec14SAdrian Lang        if ($white) $url .= ' ';
3837bff22c0SAndreas Gohr
3842684e50aSAndreas Gohr        $url .= $key . '="';
385f7711f2bSAndreas Gohr        $url .= hsc($val);
3862684e50aSAndreas Gohr        $url .= '"';
3879063ec14SAdrian Lang        $white = true;
3882684e50aSAndreas Gohr    }
3892684e50aSAndreas Gohr    return $url;
3902684e50aSAndreas Gohr}
3912684e50aSAndreas Gohr
3922684e50aSAndreas Gohr/**
39315fae107Sandi * This builds the breadcrumb trail and returns it as array
39415fae107Sandi *
3958b19906eSAndreas Gohr * @return string[] with the data: array(pageid=>name, ... )
39615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
397140cfbcdSGerrit Uitslag *
398f3f0262cSandi */
399d868eb89SAndreas Gohrfunction breadcrumbs()
400d868eb89SAndreas Gohr{
4018746e727Sandi    // we prepare the breadcrumbs early for quick session closing
4028746e727Sandi    static $crumbs = null;
4038746e727Sandi    if ($crumbs != null) return $crumbs;
4048746e727Sandi
405f3f0262cSandi    global $ID;
406f3f0262cSandi    global $ACT;
407f3f0262cSandi    global $conf;
4080ea5ebb4SB_S666    global $INFO;
409f3f0262cSandi
410f3f0262cSandi    //first visit?
41124870174SAndreas Gohr    $crumbs = $_SESSION[DOKU_COOKIE]['bc'] ?? [];
4125603d3c1SHenry Pan    //we only save on show and existing visible readable wiki documents
413a77f5846Sjan    $file = wikiFN($ID);
4145603d3c1SHenry Pan    if ($ACT != 'show' || $INFO['perm'] < AUTH_READ || isHiddenPage($ID) || !file_exists($file)) {
415e71ce681SAndreas Gohr        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
416f3f0262cSandi        return $crumbs;
417f3f0262cSandi    }
418a77f5846Sjan
419a77f5846Sjan    // page names
4201a84a0f3SAnika Henke    $name = noNSorNS($ID);
421fe9ec250SChris Smith    if (useHeading('navigation')) {
422a77f5846Sjan        // get page title
42367c15eceSMichael Hamann        $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
424a77f5846Sjan        if ($title) {
425a77f5846Sjan            $name = $title;
426a77f5846Sjan        }
427a77f5846Sjan    }
428a77f5846Sjan
429f3f0262cSandi    //remove ID from array
430a77f5846Sjan    if (isset($crumbs[$ID])) {
431a77f5846Sjan        unset($crumbs[$ID]);
432f3f0262cSandi    }
433f3f0262cSandi
434f3f0262cSandi    //add to array
435a77f5846Sjan    $crumbs[$ID] = $name;
436f3f0262cSandi    //reduce size
437f3f0262cSandi    while (count($crumbs) > $conf['breadcrumbs']) {
438f3f0262cSandi        array_shift($crumbs);
439f3f0262cSandi    }
440f3f0262cSandi    //save to session
441e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
442f3f0262cSandi    return $crumbs;
443f3f0262cSandi}
444f3f0262cSandi
445f3f0262cSandi/**
44615fae107Sandi * Filter for page IDs
44715fae107Sandi *
448f3f0262cSandi * This is run on a ID before it is outputted somewhere
449f3f0262cSandi * currently used to replace the colon with something else
450907f24f7SAndreas Gohr * on Windows (non-IIS) systems and to have proper URL encoding
451907f24f7SAndreas Gohr *
452977aa967SAndreas Gohr * See discussions at https://github.com/dokuwiki/dokuwiki/pull/84 and
453977aa967SAndreas Gohr * https://github.com/dokuwiki/dokuwiki/pull/173 why we use a whitelist of
454907f24f7SAndreas Gohr * unaffected servers instead of blacklisting affected servers here.
45515fae107Sandi *
45649c713a3Sandi * Urlencoding is ommitted when the second parameter is false
45749c713a3Sandi *
458140cfbcdSGerrit Uitslag * @param string $id pageid being filtered
459140cfbcdSGerrit Uitslag * @param bool $ue apply urlencoding?
460140cfbcdSGerrit Uitslag * @return string
4618b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
4628b19906eSAndreas Gohr *
463f3f0262cSandi */
464d868eb89SAndreas Gohrfunction idfilter($id, $ue = true)
465d868eb89SAndreas Gohr{
466f3f0262cSandi    global $conf;
467585bf44eSChristopher Smith    /* @var Input $INPUT */
468585bf44eSChristopher Smith    global $INPUT;
469585bf44eSChristopher Smith
470bf8f8509SAndreas Gohr    $id = (string)$id;
471bf8f8509SAndreas Gohr
472f3f0262cSandi    if ($conf['useslash'] && $conf['userewrite']) {
473f3f0262cSandi        $id = strtr($id, ':', '/');
4747d34963bSAndreas Gohr    } elseif (
4756c16a3a9Sfiwswe        str_starts_with(strtoupper(PHP_OS), 'WIN') &&
47658bedc8aSborekb        $conf['userewrite'] &&
477093fe67eSAndreas Gohr        !str_contains($INPUT->server->str('SERVER_SOFTWARE'), 'Microsoft-IIS')
4783272d797SAndreas Gohr    ) {
479f3f0262cSandi        $id = strtr($id, ':', ';');
480f3f0262cSandi    }
48149c713a3Sandi    if ($ue) {
482b6c6979fSAndreas Gohr        $id = rawurlencode($id);
483f3f0262cSandi        $id = str_replace('%3A', ':', $id); //keep as colon
484edd95259SGerrit Uitslag        $id = str_replace('%3B', ';', $id); //keep as semicolon
485f3f0262cSandi        $id = str_replace('%2F', '/', $id); //keep as slash
48649c713a3Sandi    }
487f3f0262cSandi    return $id;
488f3f0262cSandi}
489f3f0262cSandi
490f3f0262cSandi/**
491ed7b5f09Sandi * This builds a link to a wikipage
49215fae107Sandi *
4934bc480e5SAndreas Gohr * It handles URL rewriting and adds additional parameters
4946c7843b5Sandi *
4954bc480e5SAndreas Gohr * @param string $id page id, defaults to start page
4964bc480e5SAndreas Gohr * @param string|array $urlParameters URL parameters, associative array recommended
4974bc480e5SAndreas Gohr * @param bool $absolute request an absolute URL instead of relative
4984bc480e5SAndreas Gohr * @param string $separator parameter separator
4994bc480e5SAndreas Gohr * @return string
5008b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
5018b19906eSAndreas Gohr *
502f3f0262cSandi */
503d868eb89SAndreas Gohrfunction wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;')
504d868eb89SAndreas Gohr{
505f3f0262cSandi    global $conf;
50616f15a81SDominik Eckelmann    if (is_array($urlParameters)) {
5074bde2196Slisps        if (isset($urlParameters['rev']) && !$urlParameters['rev']) unset($urlParameters['rev']);
50864159a61SAndreas Gohr        if (isset($urlParameters['at']) && $conf['date_at_format']) {
50964159a61SAndreas Gohr            $urlParameters['at'] = date($conf['date_at_format'], $urlParameters['at']);
51064159a61SAndreas Gohr        }
51116f15a81SDominik Eckelmann        $urlParameters = buildURLparams($urlParameters, $separator);
5126de3759aSAndreas Gohr    } else {
51316f15a81SDominik Eckelmann        $urlParameters = str_replace(',', $separator, $urlParameters);
5146de3759aSAndreas Gohr    }
51516f15a81SDominik Eckelmann    if ($id === '') {
51616f15a81SDominik Eckelmann        $id = $conf['start'];
51716f15a81SDominik Eckelmann    }
518f3f0262cSandi    $id = idfilter($id);
51916f15a81SDominik Eckelmann    if ($absolute) {
520ed7b5f09Sandi        $xlink = DOKU_URL;
521ed7b5f09Sandi    } else {
522ed7b5f09Sandi        $xlink = DOKU_BASE;
523ed7b5f09Sandi    }
524f3f0262cSandi
5256c7843b5Sandi    if ($conf['userewrite'] == 2) {
5266c7843b5Sandi        $xlink .= DOKU_SCRIPT . '/' . $id;
52716f15a81SDominik Eckelmann        if ($urlParameters) $xlink .= '?' . $urlParameters;
5286c7843b5Sandi    } elseif ($conf['userewrite']) {
529f3f0262cSandi        $xlink .= $id;
53016f15a81SDominik Eckelmann        if ($urlParameters) $xlink .= '?' . $urlParameters;
53140b5fb5bSPhy    } elseif ($id !== '') {
5326c7843b5Sandi        $xlink .= DOKU_SCRIPT . '?id=' . $id;
53316f15a81SDominik Eckelmann        if ($urlParameters) $xlink .= $separator . $urlParameters;
534bce3726dSAndreas Gohr    } else {
535bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
53616f15a81SDominik Eckelmann        if ($urlParameters) $xlink .= '?' . $urlParameters;
537f3f0262cSandi    }
538f3f0262cSandi
539f3f0262cSandi    return $xlink;
540f3f0262cSandi}
541f3f0262cSandi
542f3f0262cSandi/**
543f5c2808fSBen Coburn * This builds a link to an alternate page format
544f5c2808fSBen Coburn *
545f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
546f5c2808fSBen Coburn *
5474bc480e5SAndreas Gohr * @param string $id page id, defaults to start page
5484bc480e5SAndreas Gohr * @param string $format the export renderer to use
5494bc480e5SAndreas Gohr * @param string|array $urlParameters URL parameters, associative array recommended
5504bc480e5SAndreas Gohr * @param bool $abs request an absolute URL instead of relative
5514bc480e5SAndreas Gohr * @param string $sep parameter separator
5524bc480e5SAndreas Gohr * @return string
5538b19906eSAndreas Gohr * @author Ben Coburn <btcoburn@silicodon.net>
554f5c2808fSBen Coburn */
555d868eb89SAndreas Gohrfunction exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;')
556d868eb89SAndreas Gohr{
557f5c2808fSBen Coburn    global $conf;
5584bc480e5SAndreas Gohr    if (is_array($urlParameters)) {
5594bc480e5SAndreas Gohr        $urlParameters = buildURLparams($urlParameters, $sep);
560f5c2808fSBen Coburn    } else {
5614bc480e5SAndreas Gohr        $urlParameters = str_replace(',', $sep, $urlParameters);
562f5c2808fSBen Coburn    }
563f5c2808fSBen Coburn
564f5c2808fSBen Coburn    $format = rawurlencode($format);
565f5c2808fSBen Coburn    $id = idfilter($id);
566f5c2808fSBen Coburn    if ($abs) {
567f5c2808fSBen Coburn        $xlink = DOKU_URL;
568f5c2808fSBen Coburn    } else {
569f5c2808fSBen Coburn        $xlink = DOKU_BASE;
570f5c2808fSBen Coburn    }
571f5c2808fSBen Coburn
572f5c2808fSBen Coburn    if ($conf['userewrite'] == 2) {
573f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT . '/' . $id . '?do=export_' . $format;
5744bc480e5SAndreas Gohr        if ($urlParameters) $xlink .= $sep . $urlParameters;
575f5c2808fSBen Coburn    } elseif ($conf['userewrite'] == 1) {
576f5c2808fSBen Coburn        $xlink .= '_export/' . $format . '/' . $id;
5774bc480e5SAndreas Gohr        if ($urlParameters) $xlink .= '?' . $urlParameters;
578f5c2808fSBen Coburn    } else {
579f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT . '?do=export_' . $format . $sep . 'id=' . $id;
5804bc480e5SAndreas Gohr        if ($urlParameters) $xlink .= $sep . $urlParameters;
581f5c2808fSBen Coburn    }
582f5c2808fSBen Coburn
583f5c2808fSBen Coburn    return $xlink;
584f5c2808fSBen Coburn}
585f5c2808fSBen Coburn
586f5c2808fSBen Coburn/**
5876de3759aSAndreas Gohr * Build a link to a media file
5886de3759aSAndreas Gohr *
5896de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
5908c08db0aSAndreas Gohr *
5918c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
5928c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
5938c08db0aSAndreas Gohr *
5943272d797SAndreas Gohr * @param string $id the media file id or URL
5953272d797SAndreas Gohr * @param mixed $more string or array with additional parameters
5963272d797SAndreas Gohr * @param bool $direct link to detail page if false
5973272d797SAndreas Gohr * @param string $sep URL parameter separator
5983272d797SAndreas Gohr * @param bool $abs Create an absolute URL
5993272d797SAndreas Gohr * @return string
6006de3759aSAndreas Gohr */
601d868eb89SAndreas Gohrfunction ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false)
602d868eb89SAndreas Gohr{
6036de3759aSAndreas Gohr    global $conf;
604b9ee6a44SKlap-in    $isexternalimage = media_isexternal($id);
605826d2766SKlap-in    if (!$isexternalimage) {
606826d2766SKlap-in        $id = cleanID($id);
607826d2766SKlap-in    }
608826d2766SKlap-in
6096de3759aSAndreas Gohr    if (is_array($more)) {
6100f4e0092SChristopher Smith        // add token for resized images
61124870174SAndreas Gohr        $w = $more['w'] ?? null;
61224870174SAndreas Gohr        $h = $more['h'] ?? null;
61398fe1ac9SDamien Regad        if ($w || $h || $isexternalimage) {
614357c9a39SDamien Regad            $more['tok'] = media_get_token($id, $w, $h);
6150f4e0092SChristopher Smith        }
6168c08db0aSAndreas Gohr        // strip defaults for shorter URLs
6178c08db0aSAndreas Gohr        if (isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
618443e135dSChristopher Smith        if (empty($more['w'])) unset($more['w']);
619443e135dSChristopher Smith        if (empty($more['h'])) unset($more['h']);
6208c08db0aSAndreas Gohr        if (isset($more['id']) && $direct) unset($more['id']);
62178b874e6Slisps        if (isset($more['rev']) && !$more['rev']) unset($more['rev']);
622b174aeaeSchris        $more = buildURLparams($more, $sep);
6236de3759aSAndreas Gohr    } else {
62424870174SAndreas Gohr        $matches = [];
625cc036f74SKlap-in        if (preg_match_all('/\b(w|h)=(\d*)\b/', $more, $matches, PREG_SET_ORDER) || $isexternalimage) {
62624870174SAndreas Gohr            $resize = ['w' => 0, 'h' => 0];
6275e7db1e2SChristopher Smith            foreach ($matches as $match) {
6285e7db1e2SChristopher Smith                $resize[$match[1]] = $match[2];
6295e7db1e2SChristopher Smith            }
630cc036f74SKlap-in            $more .= $more === '' ? '' : $sep;
631cc036f74SKlap-in            $more .= 'tok=' . media_get_token($id, $resize['w'], $resize['h']);
6325e7db1e2SChristopher Smith        }
6338c08db0aSAndreas Gohr        $more = str_replace('cache=cache', '', $more); //skip default
6348c08db0aSAndreas Gohr        $more = str_replace(',,', ',', $more);
635b174aeaeSchris        $more = str_replace(',', $sep, $more);
6366de3759aSAndreas Gohr    }
6376de3759aSAndreas Gohr
63855b2b31bSAndreas Gohr    if ($abs) {
63955b2b31bSAndreas Gohr        $xlink = DOKU_URL;
64055b2b31bSAndreas Gohr    } else {
6416de3759aSAndreas Gohr        $xlink = DOKU_BASE;
64255b2b31bSAndreas Gohr    }
6436de3759aSAndreas Gohr
6446de3759aSAndreas Gohr    // external URLs are always direct without rewriting
645826d2766SKlap-in    if ($isexternalimage) {
6466de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
647cc036f74SKlap-in        $xlink .= '?' . $more;
648b174aeaeSchris        $xlink .= $sep . 'media=' . rawurlencode($id);
6496de3759aSAndreas Gohr        return $xlink;
6506de3759aSAndreas Gohr    }
6516de3759aSAndreas Gohr
6526de3759aSAndreas Gohr    $id = idfilter($id);
6536de3759aSAndreas Gohr
6546de3759aSAndreas Gohr    // decide on scriptname
6556de3759aSAndreas Gohr    if ($direct) {
6566de3759aSAndreas Gohr        if ($conf['userewrite'] == 1) {
6576de3759aSAndreas Gohr            $script = '_media';
6586de3759aSAndreas Gohr        } else {
6596de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
6606de3759aSAndreas Gohr        }
66124870174SAndreas Gohr    } elseif ($conf['userewrite'] == 1) {
6626de3759aSAndreas Gohr        $script = '_detail';
6636de3759aSAndreas Gohr    } else {
6646de3759aSAndreas Gohr        $script = 'lib/exe/detail.php';
6656de3759aSAndreas Gohr    }
6666de3759aSAndreas Gohr
6676de3759aSAndreas Gohr    // build URL based on rewrite mode
6686de3759aSAndreas Gohr    if ($conf['userewrite']) {
6696de3759aSAndreas Gohr        $xlink .= $script . '/' . $id;
6706de3759aSAndreas Gohr        if ($more) $xlink .= '?' . $more;
67124870174SAndreas Gohr    } elseif ($more) {
672a99d3236SEsther Brunner        $xlink .= $script . '?' . $more;
673b174aeaeSchris        $xlink .= $sep . 'media=' . $id;
6746de3759aSAndreas Gohr    } else {
675a99d3236SEsther Brunner        $xlink .= $script . '?media=' . $id;
6766de3759aSAndreas Gohr    }
6776de3759aSAndreas Gohr
6786de3759aSAndreas Gohr    return $xlink;
6796de3759aSAndreas Gohr}
6806de3759aSAndreas Gohr
6816de3759aSAndreas Gohr/**
68225ca5b17SAndreas Gohr * Returns the URL to the DokuWiki base script
68315fae107Sandi *
68425ca5b17SAndreas Gohr * Consider using wl() instead, unless you absoutely need the doku.php endpoint
68525ca5b17SAndreas Gohr *
6868b19906eSAndreas Gohr * @return string
68715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
688140cfbcdSGerrit Uitslag *
689f3f0262cSandi */
690d868eb89SAndreas Gohrfunction script()
691d868eb89SAndreas Gohr{
692ed7b5f09Sandi    return DOKU_BASE . DOKU_SCRIPT;
693f3f0262cSandi}
694f3f0262cSandi
695f3f0262cSandi/**
69615fae107Sandi * Spamcheck against wordlist
69715fae107Sandi *
698f3f0262cSandi * Checks the wikitext against a list of blocked expressions
699f3f0262cSandi * returns true if the text contains any bad words
70015fae107Sandi *
701e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
702e403cc58SMichael Klier *
703e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
704e403cc58SMichael Klier *  and gain information about the user who was blocked.
705e403cc58SMichael Klier *
706e403cc58SMichael Klier *  Event data:
707e403cc58SMichael Klier *    data['matches']  - array of matches
708e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
709e403cc58SMichael Klier *      [ip]           - ip address
710e403cc58SMichael Klier *      [user]         - username (if logged in)
711e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
712e403cc58SMichael Klier *      [name]         - real name (if logged in)
713e403cc58SMichael Klier *
7148b19906eSAndreas Gohr * @param string $text - optional text to check, if not given the globals are used
7158b19906eSAndreas Gohr * @return bool         - true if a spam word was found
71615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
7176dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
718140cfbcdSGerrit Uitslag *
719f3f0262cSandi */
720d868eb89SAndreas Gohrfunction checkwordblock($text = '')
721d868eb89SAndreas Gohr{
722f3f0262cSandi    global $TEXT;
7236dffa0e0SAndreas Gohr    global $PRE;
7246dffa0e0SAndreas Gohr    global $SUF;
725e0086ca2SAndreas Gohr    global $SUM;
726f3f0262cSandi    global $conf;
727e403cc58SMichael Klier    global $INFO;
728585bf44eSChristopher Smith    /* @var Input $INPUT */
729585bf44eSChristopher Smith    global $INPUT;
730f3f0262cSandi
731f3f0262cSandi    if (!$conf['usewordblock']) return false;
732f3f0262cSandi
733e0086ca2SAndreas Gohr    if (!$text) $text = "$PRE $TEXT $SUF $SUM";
7346dffa0e0SAndreas Gohr
735041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
73664159a61SAndreas Gohr    // phpcs:disable Generic.Files.LineLength.TooLong
73764159a61SAndreas Gohr    $text = preg_replace(
73864159a61SAndreas Gohr        '!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i',
73964159a61SAndreas Gohr        '\1http://\2 \2\3',
74064159a61SAndreas Gohr        $text
74164159a61SAndreas Gohr    );
74264159a61SAndreas Gohr    // phpcs:enable
743041d1964SAndreas Gohr
744b9ac8716Schris    $wordblocks = getWordblocks();
745a51d08efSAndreas Gohr    // read file in chunks of 200 - this should work around the
7463e2965d7Sandi    // MAX_PATTERN_SIZE in modern PCRE
747a51d08efSAndreas Gohr    $chunksize = 200;
74864259528SAndreas Gohr
749b9ac8716Schris    while ($blocks = array_splice($wordblocks, 0, $chunksize)) {
75024870174SAndreas Gohr        $re = [];
75149eb6e38SAndreas Gohr        // build regexp from blocks
752f3f0262cSandi        foreach ($blocks as $block) {
753f3f0262cSandi            $block = preg_replace('/#.*$/', '', $block);
754f3f0262cSandi            $block = trim($block);
755f3f0262cSandi            if (empty($block)) continue;
756f3f0262cSandi            $re[] = $block;
757f3f0262cSandi        }
75824870174SAndreas Gohr        if (count($re) && preg_match('#(' . implode('|', $re) . ')#si', $text, $matches)) {
759e403cc58SMichael Klier            // prepare event data
76024870174SAndreas Gohr            $data = [];
761e403cc58SMichael Klier            $data['matches'] = $matches;
762585bf44eSChristopher Smith            $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
763585bf44eSChristopher Smith            if ($INPUT->server->str('REMOTE_USER')) {
764585bf44eSChristopher Smith                $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
765e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
766e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
767e403cc58SMichael Klier            }
76824870174SAndreas Gohr            $callback = static fn() => true;
769cbb44eabSAndreas Gohr            return Event::createAndTrigger('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
770b9ac8716Schris        }
771703f6fdeSandi    }
772f3f0262cSandi    return false;
773f3f0262cSandi}
774f3f0262cSandi
775f3f0262cSandi/**
776a7580321SZebra North * Return the IP of the client.
77715fae107Sandi *
778a7580321SZebra North * The IP is sourced from, in order of preference:
77915fae107Sandi *
78090c2f6e3SAndreas Gohr *   - The custom IP header if $conf[client_ip_header] is set.
781d5dd5d1bSAndreas Gohr *   - The X-Forwarded-For header if all the proxies are trusted by $conf[trustedproxies].
782a7580321SZebra North *   - The TCP/IP connection remote address.
783a7580321SZebra North *   - 0.0.0.0 if all else fails.
7846d8affe6SAndreas Gohr *
78590c2f6e3SAndreas Gohr * The 'client_ip_header' config value should only be set if the header
786a7580321SZebra North * is being added by the web server, otherwise it may be spoofed by the client.
7878b19906eSAndreas Gohr *
788d5dd5d1bSAndreas Gohr * The 'trustedproxies' setting must not allow any IP, otherwise the X-Forwarded-For
789a7580321SZebra North * may be spoofed by the client.
790a7580321SZebra North *
791608cdefcSZebra North * @param bool $single If set only a single IP is returned.
792608cdefcSZebra North *
793a7580321SZebra North * @return string Returns an IP address if 'single' is true, or a comma-separated list
794a7580321SZebra North *                of IP addresses otherwise.
7952f828abfSAndreas Gohr * @author Zebra North <mrzebra@mrzebra.co.uk>
7962f828abfSAndreas Gohr *
797f3f0262cSandi */
7982f828abfSAndreas Gohrfunction clientIP($single = false)
7992f828abfSAndreas Gohr{
800a7580321SZebra North    // Return the first IP in single mode, or all the IPs.
80198b599a6Ssplitbrain    return $single ? Ip::clientIp() : implode(',', Ip::clientIps());
802f3f0262cSandi}
803f3f0262cSandi
804f3f0262cSandi/**
8051c548ebeSAndreas Gohr * Check if the browser is on a mobile device
8061c548ebeSAndreas Gohr *
8071c548ebeSAndreas Gohr * Adapted from the example code at url below
8081c548ebeSAndreas Gohr *
8091c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
810140cfbcdSGerrit Uitslag *
81164159a61SAndreas Gohr * @deprecated 2018-04-27 you probably want media queries instead anyway
812140cfbcdSGerrit Uitslag * @return bool if true, client is mobile browser; otherwise false
8131c548ebeSAndreas Gohr */
814d868eb89SAndreas Gohrfunction clientismobile()
815d868eb89SAndreas Gohr{
816585bf44eSChristopher Smith    /* @var Input $INPUT */
817585bf44eSChristopher Smith    global $INPUT;
8181c548ebeSAndreas Gohr
819585bf44eSChristopher Smith    if ($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
8201c548ebeSAndreas Gohr
821585bf44eSChristopher Smith    if (preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
8221c548ebeSAndreas Gohr
823585bf44eSChristopher Smith    if (!$INPUT->server->has('HTTP_USER_AGENT')) return false;
8241c548ebeSAndreas Gohr
82524870174SAndreas Gohr    $uamatches = implode(
82664159a61SAndreas Gohr        '|',
82764159a61SAndreas Gohr        [
82864159a61SAndreas Gohr            'midp', 'j2me', 'avantg', 'docomo', 'novarra', 'palmos', 'palmsource', '240x320', 'opwv',
82964159a61SAndreas Gohr            'chtml', 'pda', 'windows ce', 'mmp\/', 'blackberry', 'mib\/', 'symbian', 'wireless', 'nokia',
83064159a61SAndreas Gohr            'hand', 'mobi', 'phone', 'cdm', 'up\.b', 'audio', 'SIE\-', 'SEC\-', 'samsung', 'HTC', 'mot\-',
83164159a61SAndreas Gohr            'mitsu', 'sagem', 'sony', 'alcatel', 'lg', 'erics', 'vx', 'NEC', 'philips', 'mmm', 'xx',
83264159a61SAndreas Gohr            'panasonic', 'sharp', 'wap', 'sch', 'rover', 'pocket', 'benq', 'java', 'pt', 'pg', 'vox',
83364159a61SAndreas Gohr            'amoi', 'bird', 'compal', 'kg', 'voda', 'sany', 'kdd', 'dbt', 'sendo', 'sgh', 'gradi', 'jb',
83464159a61SAndreas Gohr            '\d\d\di', 'moto'
83564159a61SAndreas Gohr        ]
83664159a61SAndreas Gohr    );
8371c548ebeSAndreas Gohr
838585bf44eSChristopher Smith    if (preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
8391c548ebeSAndreas Gohr
8401c548ebeSAndreas Gohr    return false;
8411c548ebeSAndreas Gohr}
8421c548ebeSAndreas Gohr
8431c548ebeSAndreas Gohr/**
8446efc45a2SDmitry Katsubo * check if a given link is interwiki link
8456efc45a2SDmitry Katsubo *
8466efc45a2SDmitry Katsubo * @param string $link the link, e.g. "wiki>page"
8476efc45a2SDmitry Katsubo * @return bool
8486efc45a2SDmitry Katsubo */
849d868eb89SAndreas Gohrfunction link_isinterwiki($link)
850d868eb89SAndreas Gohr{
8516efc45a2SDmitry Katsubo    if (preg_match('/^[a-zA-Z0-9\.]+>/u', $link)) return true;
8526efc45a2SDmitry Katsubo    return false;
8536efc45a2SDmitry Katsubo}
8546efc45a2SDmitry Katsubo
8556efc45a2SDmitry Katsubo/**
85663211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
85763211f61SGlen Harris *
85822ef1e32SAndreas Gohr * If $conf['dnslookups'] is disabled it simply returns the input string
85922ef1e32SAndreas Gohr *
8603272d797SAndreas Gohr * @param string $ips comma separated list of IP addresses
8613272d797SAndreas Gohr * @return string a comma separated list of hostnames
8628b19906eSAndreas Gohr * @author Glen Harris <astfgl@iamnota.org>
8638b19906eSAndreas Gohr *
86463211f61SGlen Harris */
865d868eb89SAndreas Gohrfunction gethostsbyaddrs($ips)
866d868eb89SAndreas Gohr{
86722ef1e32SAndreas Gohr    global $conf;
86822ef1e32SAndreas Gohr    if (!$conf['dnslookups']) return $ips;
86922ef1e32SAndreas Gohr
87024870174SAndreas Gohr    $hosts = [];
87163211f61SGlen Harris    $ips = explode(',', $ips);
872551a720fSMichael Klier
873551a720fSMichael Klier    if (is_array($ips)) {
8743886270dSAndreas Gohr        foreach ($ips as $ip) {
875551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
87663211f61SGlen Harris        }
87724870174SAndreas Gohr        return implode(',', $hosts);
878551a720fSMichael Klier    } else {
879551a720fSMichael Klier        return gethostbyaddr(trim($ips));
880551a720fSMichael Klier    }
88163211f61SGlen Harris}
88263211f61SGlen Harris
88363211f61SGlen Harris/**
88415fae107Sandi * Checks if a given page is currently locked.
88515fae107Sandi *
886f3f0262cSandi * removes stale lockfiles
88715fae107Sandi *
888140cfbcdSGerrit Uitslag * @param string $id page id
889140cfbcdSGerrit Uitslag * @return bool page is locked?
8908b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
8918b19906eSAndreas Gohr *
892f3f0262cSandi */
893d868eb89SAndreas Gohrfunction checklock($id)
894d868eb89SAndreas Gohr{
895f3f0262cSandi    global $conf;
896585bf44eSChristopher Smith    /* @var Input $INPUT */
897585bf44eSChristopher Smith    global $INPUT;
898585bf44eSChristopher Smith
899c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
900f3f0262cSandi
901f3f0262cSandi    //no lockfile
90279e79377SAndreas Gohr    if (!file_exists($lock)) return false;
903f3f0262cSandi
904f3f0262cSandi    //lockfile expired
905f3f0262cSandi    if ((time() - filemtime($lock)) > $conf['locktime']) {
906d8186216SBen Coburn        @unlink($lock);
907f3f0262cSandi        return false;
908f3f0262cSandi    }
909f3f0262cSandi
910f3f0262cSandi    //my own lock
9115f21556dSDamien Regad    [$ip, $session] = sexplode("\n", io_readFile($lock), 2);
91224870174SAndreas Gohr    if ($ip == $INPUT->server->str('REMOTE_USER') || (session_id() && $session === session_id())) {
913f3f0262cSandi        return false;
914f3f0262cSandi    }
915f3f0262cSandi
916f3f0262cSandi    return $ip;
917f3f0262cSandi}
918f3f0262cSandi
919f3f0262cSandi/**
92015fae107Sandi * Lock a page for editing
92115fae107Sandi *
9228b19906eSAndreas Gohr * @param string $id page id to lock
92315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
924140cfbcdSGerrit Uitslag *
925f3f0262cSandi */
926d868eb89SAndreas Gohrfunction lock($id)
927d868eb89SAndreas Gohr{
928544ed901SDaniel Calviño Sánchez    global $conf;
929585bf44eSChristopher Smith    /* @var Input $INPUT */
930585bf44eSChristopher Smith    global $INPUT;
931544ed901SDaniel Calviño Sánchez
932544ed901SDaniel Calviño Sánchez    if ($conf['locktime'] == 0) {
933544ed901SDaniel Calviño Sánchez        return;
934544ed901SDaniel Calviño Sánchez    }
935544ed901SDaniel Calviño Sánchez
936c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
937585bf44eSChristopher Smith    if ($INPUT->server->str('REMOTE_USER')) {
938585bf44eSChristopher Smith        io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
939f3f0262cSandi    } else {
94085fef7e2SAndreas Gohr        io_saveFile($lock, clientIP() . "\n" . session_id());
941f3f0262cSandi    }
942f3f0262cSandi}
943f3f0262cSandi
944f3f0262cSandi/**
94515fae107Sandi * Unlock a page if it was locked by the user
946f3f0262cSandi *
9473272d797SAndreas Gohr * @param string $id page id to unlock
94815fae107Sandi * @return bool true if a lock was removed
9498b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
9508b19906eSAndreas Gohr *
951f3f0262cSandi */
952d868eb89SAndreas Gohrfunction unlock($id)
953d868eb89SAndreas Gohr{
954585bf44eSChristopher Smith    /* @var Input $INPUT */
955585bf44eSChristopher Smith    global $INPUT;
956585bf44eSChristopher Smith
957c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
95879e79377SAndreas Gohr    if (file_exists($lock)) {
95924870174SAndreas Gohr        @[$ip, $session] = explode("\n", io_readFile($lock));
960c0dd3914SAdaKaleh        if ($ip == $INPUT->server->str('REMOTE_USER') || $session == session_id()) {
961f3f0262cSandi            @unlink($lock);
962f3f0262cSandi            return true;
963f3f0262cSandi        }
964f3f0262cSandi    }
965f3f0262cSandi    return false;
966f3f0262cSandi}
967f3f0262cSandi
968f3f0262cSandi/**
969f3f0262cSandi * convert line ending to unix format
970f3f0262cSandi *
9716db7468bSAndreas Gohr * also makes sure the given text is valid UTF-8
9726db7468bSAndreas Gohr *
9738b19906eSAndreas Gohr * @param string $text
9748b19906eSAndreas Gohr * @return string
97515fae107Sandi * @see    formText() for 2crlf conversion
97615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
977140cfbcdSGerrit Uitslag *
978f3f0262cSandi */
979d868eb89SAndreas Gohrfunction cleanText($text)
980d868eb89SAndreas Gohr{
981f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
9826db7468bSAndreas Gohr
9836db7468bSAndreas Gohr    // if the text is not valid UTF-8 we simply assume latin1
9846db7468bSAndreas Gohr    // this won't break any worse than it breaks with the wrong encoding
9856db7468bSAndreas Gohr    // but might actually fix the problem in many cases
98653c68e5cSAndreas Gohr    if (!Clean::isUtf8($text)) $text = Conversion::fromLatin1($text);
9876db7468bSAndreas Gohr
988f3f0262cSandi    return $text;
989f3f0262cSandi}
990f3f0262cSandi
991f3f0262cSandi/**
992f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
993f3f0262cSandi * It also converts line endings to Windows format which is
994f3f0262cSandi * pseudo standard for webforms.
995f3f0262cSandi *
9968b19906eSAndreas Gohr * @param string $text
9978b19906eSAndreas Gohr * @return string
99815fae107Sandi * @see    cleanText() for 2unix conversion
99915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1000140cfbcdSGerrit Uitslag *
1001f3f0262cSandi */
1002d868eb89SAndreas Gohrfunction formText($text)
1003d868eb89SAndreas Gohr{
1004a46a37efSAndreas Gohr    $text = str_replace("\012", "\015\012", $text ?? '');
1005f3f0262cSandi    return htmlspecialchars($text);
1006f3f0262cSandi}
1007f3f0262cSandi
1008f3f0262cSandi/**
100915fae107Sandi * Returns the specified local text in raw format
101015fae107Sandi *
1011140cfbcdSGerrit Uitslag * @param string $id page id
1012140cfbcdSGerrit Uitslag * @param string $ext extension of file being read, default 'txt'
1013140cfbcdSGerrit Uitslag * @return string
10148b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10158b19906eSAndreas Gohr *
1016f3f0262cSandi */
1017d868eb89SAndreas Gohrfunction rawLocale($id, $ext = 'txt')
1018d868eb89SAndreas Gohr{
10192adaf2b8SAndreas Gohr    return io_readFile(localeFN($id, $ext));
1020f3f0262cSandi}
1021f3f0262cSandi
1022f3f0262cSandi/**
1023f3f0262cSandi * Returns the raw WikiText
102415fae107Sandi *
1025140cfbcdSGerrit Uitslag * @param string $id page id
1026e0c26282SGerrit Uitslag * @param string|int $rev timestamp when a revision of wikitext is desired
1027140cfbcdSGerrit Uitslag * @return string
10288b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10298b19906eSAndreas Gohr *
1030f3f0262cSandi */
1031d868eb89SAndreas Gohrfunction rawWiki($id, $rev = '')
1032d868eb89SAndreas Gohr{
1033cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1034f3f0262cSandi}
1035f3f0262cSandi
1036f3f0262cSandi/**
10377146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
10387146cee2SAndreas Gohr *
10397b84afa2SAndreas Gohr * @triggers COMMON_PAGETPL_LOAD
1040140cfbcdSGerrit Uitslag * @param string $id the id of the page to be created
1041140cfbcdSGerrit Uitslag * @return string parsed pagetemplate content
10428b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10438b19906eSAndreas Gohr *
10447146cee2SAndreas Gohr */
1045d868eb89SAndreas Gohrfunction pageTemplate($id)
1046d868eb89SAndreas Gohr{
1047a15ce62dSEsther Brunner    global $conf;
1048e29549feSAndreas Gohr
1049fe17917eSAdrian Lang    if (is_array($id)) $id = $id[0];
1050e29549feSAndreas Gohr
10517b84afa2SAndreas Gohr    // prepare initial event data
105224870174SAndreas Gohr    $data = [
10537b84afa2SAndreas Gohr        'id' => $id, // the id of the page to be created
10547b84afa2SAndreas Gohr        'tpl' => '', // the text used as template
10557b84afa2SAndreas Gohr        'tplfile' => '', // the file above text was/should be loaded from
105624870174SAndreas Gohr        'doreplace' => true,
105724870174SAndreas Gohr    ];
10587b84afa2SAndreas Gohr
1059e1d9dcc8SAndreas Gohr    $evt = new Event('COMMON_PAGETPL_LOAD', $data);
10607b84afa2SAndreas Gohr    if ($evt->advise_before(true)) {
10617b84afa2SAndreas Gohr        // the before event might have loaded the content already
10627b84afa2SAndreas Gohr        if (empty($data['tpl'])) {
10637b84afa2SAndreas Gohr            // if the before event did not set a template file, try to find one
10647b84afa2SAndreas Gohr            if (empty($data['tplfile'])) {
1065fe17917eSAdrian Lang                $path = dirname(wikiFN($id));
106679e79377SAndreas Gohr                if (file_exists($path . '/_template.txt')) {
10677b84afa2SAndreas Gohr                    $data['tplfile'] = $path . '/_template.txt';
1068e29549feSAndreas Gohr                } else {
1069e29549feSAndreas Gohr                    // search upper namespaces for templates
1070e29549feSAndreas Gohr                    $len = strlen(rtrim($conf['datadir'], '/'));
1071e29549feSAndreas Gohr                    while (strlen($path) >= $len) {
107279e79377SAndreas Gohr                        if (file_exists($path . '/__template.txt')) {
10737b84afa2SAndreas Gohr                            $data['tplfile'] = $path . '/__template.txt';
1074e29549feSAndreas Gohr                            break;
1075e29549feSAndreas Gohr                        }
1076e29549feSAndreas Gohr                        $path = substr($path, 0, strrpos($path, '/'));
1077e29549feSAndreas Gohr                    }
1078e29549feSAndreas Gohr                }
10797b84afa2SAndreas Gohr            }
10807b84afa2SAndreas Gohr            // load the content
10813d7ac595SMichael Hamann            $data['tpl'] = io_readFile($data['tplfile']);
10827b84afa2SAndreas Gohr        }
1083a1bbd05bSMichael Hamann        if ($data['doreplace']) parsePageTemplate($data);
10847b84afa2SAndreas Gohr    }
10857b84afa2SAndreas Gohr    $evt->advise_after();
10867b84afa2SAndreas Gohr    unset($evt);
10877b84afa2SAndreas Gohr
1088fe17917eSAdrian Lang    return $data['tpl'];
10892b1223ecSAdrian Lang}
10902b1223ecSAdrian Lang
10912b1223ecSAdrian Lang/**
10922b1223ecSAdrian Lang * Performs common page template replacements
10937b84afa2SAndreas Gohr * This works on data from COMMON_PAGETPL_LOAD
10942b1223ecSAdrian Lang *
1095140cfbcdSGerrit Uitslag * @param array $data array with event data
1096140cfbcdSGerrit Uitslag * @return string
10978b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10988b19906eSAndreas Gohr *
10992b1223ecSAdrian Lang */
1100d868eb89SAndreas Gohrfunction parsePageTemplate(&$data)
1101d868eb89SAndreas Gohr{
11023272d797SAndreas Gohr    /**
11033272d797SAndreas Gohr     * @var string $id the id of the page to be created
11043272d797SAndreas Gohr     * @var string $tpl the text used as template
11053272d797SAndreas Gohr     * @var string $tplfile the file above text was/should be loaded from
11063272d797SAndreas Gohr     * @var bool $doreplace should wildcard replacements be done on the text?
11073272d797SAndreas Gohr     */
1108fe17917eSAdrian Lang    extract($data);
1109fe17917eSAdrian Lang
1110b856f7dfSAdrian Lang    global $USERINFO;
1111bce53b1fSAdrian Lang    global $conf;
1112585bf44eSChristopher Smith    /* @var Input $INPUT */
1113585bf44eSChristopher Smith    global $INPUT;
1114e29549feSAndreas Gohr
1115e29549feSAndreas Gohr    // replace placeholders
111626ece5a7SAndreas Gohr    $file = noNS($id);
111737c1acbdSAdrian Lang    $page = strtr($file, $conf['sepchar'], ' ');
111826ece5a7SAndreas Gohr
11193272d797SAndreas Gohr    $tpl = str_replace(
112024870174SAndreas Gohr        [
112126ece5a7SAndreas Gohr            '@ID@',
112226ece5a7SAndreas Gohr            '@NS@',
11238a7bcf66SShota Miyazaki            '@CURNS@',
1124a3db0ab0SSimon Lees            '@!CURNS@',
1125a3db0ab0SSimon Lees            '@!!CURNS@',
1126a3db0ab0SSimon Lees            '@!CURNS!@',
112726ece5a7SAndreas Gohr            '@FILE@',
112826ece5a7SAndreas Gohr            '@!FILE@',
112926ece5a7SAndreas Gohr            '@!FILE!@',
113026ece5a7SAndreas Gohr            '@PAGE@',
113126ece5a7SAndreas Gohr            '@!PAGE@',
113226ece5a7SAndreas Gohr            '@!!PAGE@',
113326ece5a7SAndreas Gohr            '@!PAGE!@',
113426ece5a7SAndreas Gohr            '@USER@',
113526ece5a7SAndreas Gohr            '@NAME@',
113626ece5a7SAndreas Gohr            '@MAIL@',
113724870174SAndreas Gohr            '@DATE@'
113824870174SAndreas Gohr        ],
113924870174SAndreas Gohr        [
114026ece5a7SAndreas Gohr            $id,
114126ece5a7SAndreas Gohr            getNS($id),
11428a7bcf66SShota Miyazaki            curNS($id),
114324870174SAndreas Gohr            PhpString::ucfirst(curNS($id)),
114424870174SAndreas Gohr            PhpString::ucwords(curNS($id)),
114524870174SAndreas Gohr            PhpString::strtoupper(curNS($id)),
114626ece5a7SAndreas Gohr            $file,
114724870174SAndreas Gohr            PhpString::ucfirst($file),
114824870174SAndreas Gohr            PhpString::strtoupper($file),
114926ece5a7SAndreas Gohr            $page,
115024870174SAndreas Gohr            PhpString::ucfirst($page),
115124870174SAndreas Gohr            PhpString::ucwords($page),
115224870174SAndreas Gohr            PhpString::strtoupper($page),
1153585bf44eSChristopher Smith            $INPUT->server->str('REMOTE_USER'),
11543e9ae63dSPhy            $USERINFO ? $USERINFO['name'] : '',
11553e9ae63dSPhy            $USERINFO ? $USERINFO['mail'] : '',
115624870174SAndreas Gohr            $conf['dformat']
115724870174SAndreas Gohr        ],
115824870174SAndreas Gohr        $tpl
11593272d797SAndreas Gohr    );
116026ece5a7SAndreas Gohr
11617d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
1162bad6fc0dSAndreas Gohr    $tpl = preg_replace_callback(
1163bad6fc0dSAndreas Gohr        '/%./',
116424870174SAndreas Gohr        static fn($m) => dformat(null, $m[0]),
1165bad6fc0dSAndreas Gohr        $tpl
1166bad6fc0dSAndreas Gohr    );
1167d535a2e9Sstretchyboy    $data['tpl'] = $tpl;
1168a15ce62dSEsther Brunner    return $tpl;
11697146cee2SAndreas Gohr}
11707146cee2SAndreas Gohr
11717146cee2SAndreas Gohr/**
117215fae107Sandi * Returns the raw Wiki Text in three slices.
117315fae107Sandi *
117415fae107Sandi * The range parameter needs to have the form "from-to"
117515cfe303Sandi * and gives the range of the section in bytes - no
117615cfe303Sandi * UTF-8 awareness is needed.
1177f3f0262cSandi * The returned order is prefix, section and suffix.
117815fae107Sandi *
1179140cfbcdSGerrit Uitslag * @param string $range in form "from-to"
1180140cfbcdSGerrit Uitslag * @param string $id page id
1181140cfbcdSGerrit Uitslag * @param string $rev optional, the revision timestamp
118242ea7f44SGerrit Uitslag * @return string[] with three slices
11838b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
11848b19906eSAndreas Gohr *
1185f3f0262cSandi */
1186d868eb89SAndreas Gohrfunction rawWikiSlices($range, $id, $rev = '')
1187d868eb89SAndreas Gohr{
1188cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1189f3f0262cSandi
119080fcb268SAdrian Lang    // Parse range
119124870174SAndreas Gohr    [$from, $to] = sexplode('-', $range, 2);
119280fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
119324870174SAndreas Gohr    $from = $from ? $from - 1 : (0);
119424870174SAndreas Gohr    $to = $to ? $to - 1 : (strlen($text));
119580fcb268SAdrian Lang
119624870174SAndreas Gohr    $slices = [];
119780fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
119880fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to - $from);
119915cfe303Sandi    $slices[2] = substr($text, $to);
1200f3f0262cSandi    return $slices;
1201f3f0262cSandi}
1202f3f0262cSandi
1203f3f0262cSandi/**
120415fae107Sandi * Joins wiki text slices
120515fae107Sandi *
120680fcb268SAdrian Lang * function to join the text slices.
1207f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
1208f3f0262cSandi * lines between sections if needed (used on saving).
120915fae107Sandi *
1210140cfbcdSGerrit Uitslag * @param string $pre prefix
1211140cfbcdSGerrit Uitslag * @param string $text text in the middle
1212140cfbcdSGerrit Uitslag * @param string $suf suffix
1213140cfbcdSGerrit Uitslag * @param bool $pretty add additional empty lines between sections
1214140cfbcdSGerrit Uitslag * @return string
12158b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
12168b19906eSAndreas Gohr *
1217f3f0262cSandi */
1218d868eb89SAndreas Gohrfunction con($pre, $text, $suf, $pretty = false)
1219d868eb89SAndreas Gohr{
1220f3f0262cSandi    if ($pretty) {
12217d34963bSAndreas Gohr        if (
12226c16a3a9Sfiwswe            $pre !== '' && !str_ends_with($pre, "\n") &&
12236c16a3a9Sfiwswe            !str_starts_with($text, "\n")
12243272d797SAndreas Gohr        ) {
122580fcb268SAdrian Lang            $pre .= "\n";
122680fcb268SAdrian Lang        }
12277d34963bSAndreas Gohr        if (
12286c16a3a9Sfiwswe            $suf !== '' && !str_ends_with($text, "\n") &&
12296c16a3a9Sfiwswe            !str_starts_with($suf, "\n")
12303272d797SAndreas Gohr        ) {
123180fcb268SAdrian Lang            $text .= "\n";
123280fcb268SAdrian Lang        }
1233f3f0262cSandi    }
1234f3f0262cSandi
1235f3f0262cSandi    return $pre . $text . $suf;
1236f3f0262cSandi}
1237f3f0262cSandi
1238f3f0262cSandi/**
1239a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
1240a701424fSBen Coburn * Also directs changelog and attic updates.
124115fae107Sandi *
1242140cfbcdSGerrit Uitslag * @param string $id page id
1243140cfbcdSGerrit Uitslag * @param string $text wikitext being saved
1244140cfbcdSGerrit Uitslag * @param string $summary summary of text update
1245140cfbcdSGerrit Uitslag * @param bool $minor mark this saved version as minor update
12468b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
12478b19906eSAndreas Gohr * @author Ben Coburn <btcoburn@silicodon.net>
12488b19906eSAndreas Gohr *
1249f3f0262cSandi */
1250d868eb89SAndreas Gohrfunction saveWikiText($id, $text, $summary, $minor = false)
1251d868eb89SAndreas Gohr{
1252585bf44eSChristopher Smith
1253b24e9c4aSSatoshi Sahara    // get COMMON_WIKIPAGE_SAVE event data
1254b24e9c4aSSatoshi Sahara    $data = (new PageFile($id))->saveWikiText($text, $summary, $minor);
1255a577fbc2SAndreas Gohr    if (!$data) return; // save was cancelled (for no changes or by a plugin)
1256ac3ed4afSGerrit Uitslag
125726a0801fSAndreas Gohr    // send notify mails
125824870174SAndreas Gohr    ['oldRevision' => $rev, 'newRevision' => $new_rev, 'summary' => $summary] = $data;
12593b813d43SSatoshi Sahara    notify($id, 'admin', $rev, $summary, $minor, $new_rev);
12603b813d43SSatoshi Sahara    notify($id, 'subscribers', $rev, $summary, $minor, $new_rev);
1261f3f0262cSandi
12622eccbdaaSGina Haeussge    // if useheading is enabled, purge the cache of all linking pages
1263fe9ec250SChris Smith    if (useHeading('content')) {
12646734bb8cSAndreas Gohr        $pages = (new MetadataSearch())->backlinks($id, true);
12652eccbdaaSGina Haeussge        foreach ($pages as $page) {
12660db5771eSMichael Große            $cache = new CacheRenderer($page, wikiFN($page), 'xhtml');
12672eccbdaaSGina Haeussge            $cache->removeCache();
12682eccbdaaSGina Haeussge        }
12692eccbdaaSGina Haeussge    }
1270f3f0262cSandi}
1271f3f0262cSandi
1272f3f0262cSandi/**
1273d5824ab9SSatoshi Sahara * moves the current version to the attic and returns its revision date
127415fae107Sandi *
1275140cfbcdSGerrit Uitslag * @param string $id page id
1276140cfbcdSGerrit Uitslag * @return int|string revision timestamp
12778b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
12788b19906eSAndreas Gohr *
127969f9b481SSatoshi Sahara * @deprecated 2021-11-28
1280f3f0262cSandi */
1281d868eb89SAndreas Gohrfunction saveOldRevision($id)
1282d868eb89SAndreas Gohr{
128379a2d784SGerrit Uitslag    dbg_deprecated(PageFile::class . '::saveOldRevision()');
1284b24e9c4aSSatoshi Sahara    return (new PageFile($id))->saveOldRevision();
1285f3f0262cSandi}
1286f3f0262cSandi
1287f3f0262cSandi/**
1288fde10de4SAdrian Lang * Sends a notify mail on page change or registration
128926a0801fSAndreas Gohr *
129026a0801fSAndreas Gohr * @param string $id The changed page
1291fde10de4SAdrian Lang * @param string $who Who to notify (admin|subscribers|register)
12923272d797SAndreas Gohr * @param int|string $rev Old page revision
129326a0801fSAndreas Gohr * @param string $summary What changed
129490033e9dSAndreas Gohr * @param boolean $minor Is this a minor edit?
129542ea7f44SGerrit Uitslag * @param string[] $replace Additional string substitutions, @KEY@ to be replaced by value
129683734cddSPhy * @param int|string $current_rev New page revision
12973272d797SAndreas Gohr * @return bool
1298140cfbcdSGerrit Uitslag *
129915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1300f3f0262cSandi */
1301d868eb89SAndreas Gohrfunction notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = [], $current_rev = false)
1302d868eb89SAndreas Gohr{
1303f3f0262cSandi    global $conf;
1304585bf44eSChristopher Smith    /* @var Input $INPUT */
1305585bf44eSChristopher Smith    global $INPUT;
1306b158d625SSteven Danz
13076df843eeSAndreas Gohr    // decide if there is something to do, eg. whom to mail
130826a0801fSAndreas Gohr    if ($who == 'admin') {
13093272d797SAndreas Gohr        if (empty($conf['notify'])) return false; //notify enabled?
13102ed38036SAndreas Gohr        $tpl = 'mailtext';
131126a0801fSAndreas Gohr        $to = $conf['notify'];
131226a0801fSAndreas Gohr    } elseif ($who == 'subscribers') {
131384c1127cSAndreas Gohr        if (!actionOK('subscribe')) return false; //subscribers enabled?
1314585bf44eSChristopher Smith        if ($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
131524870174SAndreas Gohr        $data = ['id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace];
1316cbb44eabSAndreas Gohr        Event::createAndTrigger(
1317dccd6b2bSAndreas Gohr            'COMMON_NOTIFY_ADDRESSLIST',
1318dccd6b2bSAndreas Gohr            $data,
131924870174SAndreas Gohr            [new SubscriberManager(), 'notifyAddresses']
13203272d797SAndreas Gohr        );
13212ed38036SAndreas Gohr        $to = $data['addresslist'];
13222ed38036SAndreas Gohr        if (empty($to)) return false;
13232ed38036SAndreas Gohr        $tpl = 'subscr_single';
132426a0801fSAndreas Gohr    } else {
13253272d797SAndreas Gohr        return false; //just to be safe
132626a0801fSAndreas Gohr    }
132726a0801fSAndreas Gohr
13286df843eeSAndreas Gohr    // prepare content
1329704a815fSMichael Große    $subscription = new PageSubscriptionSender();
133083734cddSPhy    return $subscription->sendPageDiff($to, $tpl, $id, $rev, $summary, $current_rev);
1331f3f0262cSandi}
13322ed38036SAndreas Gohr
133315fae107Sandi/**
133471f7bde7SAndreas Gohr * extracts the query from a search engine referrer
133515fae107Sandi *
13368b19906eSAndreas Gohr * @return array|string
133771f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1338140cfbcdSGerrit Uitslag *
13398b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1340f3f0262cSandi */
1341d868eb89SAndreas Gohrfunction getGoogleQuery()
1342d868eb89SAndreas Gohr{
1343585bf44eSChristopher Smith    /* @var Input $INPUT */
1344585bf44eSChristopher Smith    global $INPUT;
1345585bf44eSChristopher Smith
1346585bf44eSChristopher Smith    if (!$INPUT->server->has('HTTP_REFERER')) {
1347c66972f2SAdrian Lang        return '';
1348c66972f2SAdrian Lang    }
1349585bf44eSChristopher Smith    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1350f3f0262cSandi
1351079b3ac1SAndreas Gohr    // only handle common SEs
1352c7875401SJyoti S    if (!array_key_exists('host', $url)) return '';
1353079b3ac1SAndreas Gohr    if (!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/', $url['host'])) return '';
1354e4d8a516SKazutaka Miyasaka
135524870174SAndreas Gohr    $query = [];
1356181adffeSJulian Jeggle    if (!array_key_exists('query', $url)) return '';
1357f3f0262cSandi    parse_str($url['query'], $query);
1358e4d8a516SKazutaka Miyasaka
1359c66972f2SAdrian Lang    $q = '';
1360079b3ac1SAndreas Gohr    if (isset($query['q'])) {
1361079b3ac1SAndreas Gohr        $q = $query['q'];
1362079b3ac1SAndreas Gohr    } elseif (isset($query['p'])) {
1363079b3ac1SAndreas Gohr        $q = $query['p'];
1364079b3ac1SAndreas Gohr    } elseif (isset($query['query'])) {
1365079b3ac1SAndreas Gohr        $q = $query['query'];
1366079b3ac1SAndreas Gohr    }
1367079b3ac1SAndreas Gohr    $q = trim($q);
1368f3f0262cSandi
1369079b3ac1SAndreas Gohr    if (!$q) return '';
1370c7dc833bSPhy    // ignore if query includes a full URL
1371093fe67eSAndreas Gohr    if (str_contains($q, '//')) return '';
13726531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1373f93b3b50SAndreas Gohr    return $q;
1374f3f0262cSandi}
1375f3f0262cSandi
1376f3f0262cSandi/**
1377f3f0262cSandi * Return the human readable size of a file
1378f3f0262cSandi *
1379f3f0262cSandi * @param int $size A file size
1380f3f0262cSandi * @param int $dec A number of decimal places
138174160ca1SGerrit Uitslag * @return string human readable size
1382140cfbcdSGerrit Uitslag *
1383f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1384f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1385f3f0262cSandi * @version     1.0.0
1386f3f0262cSandi */
1387d868eb89SAndreas Gohrfunction filesize_h($size, $dec = 1)
1388d868eb89SAndreas Gohr{
138924870174SAndreas Gohr    $sizes = ['B', 'KB', 'MB', 'GB'];
1390f3f0262cSandi    $count = count($sizes);
1391f3f0262cSandi    $i = 0;
1392f3f0262cSandi
1393f3f0262cSandi    while ($size >= 1024 && ($i < $count - 1)) {
1394f3f0262cSandi        $size /= 1024;
1395f3f0262cSandi        $i++;
1396f3f0262cSandi    }
1397f3f0262cSandi
1398ef08383eSAndreas Gohr    return round($size, $dec) . "\xC2\xA0" . $sizes[$i]; //non-breaking space
1399f3f0262cSandi}
1400f3f0262cSandi
140115fae107Sandi/**
1402c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1403c57e365eSAndreas Gohr *
1404140cfbcdSGerrit Uitslag * @param int $dt timestamp
1405140cfbcdSGerrit Uitslag * @return string
14068b19906eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
14078b19906eSAndreas Gohr *
1408c57e365eSAndreas Gohr */
1409d868eb89SAndreas Gohrfunction datetime_h($dt)
1410d868eb89SAndreas Gohr{
1411c57e365eSAndreas Gohr    global $lang;
1412c57e365eSAndreas Gohr
1413c57e365eSAndreas Gohr    $ago = time() - $dt;
1414c57e365eSAndreas Gohr    if ($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1415c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1416c57e365eSAndreas Gohr    }
1417c57e365eSAndreas Gohr    if ($ago > 24 * 60 * 60 * 30 * 2) {
1418c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1419c57e365eSAndreas Gohr    }
1420c57e365eSAndreas Gohr    if ($ago > 24 * 60 * 60 * 7 * 2) {
1421c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1422c57e365eSAndreas Gohr    }
1423c57e365eSAndreas Gohr    if ($ago > 24 * 60 * 60 * 2) {
1424c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1425c57e365eSAndreas Gohr    }
1426c57e365eSAndreas Gohr    if ($ago > 60 * 60 * 2) {
1427c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago / (60 * 60)));
1428c57e365eSAndreas Gohr    }
1429c57e365eSAndreas Gohr    if ($ago > 60 * 2) {
1430c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago / (60)));
1431c57e365eSAndreas Gohr    }
1432c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1433c57e365eSAndreas Gohr}
1434c57e365eSAndreas Gohr
1435c57e365eSAndreas Gohr/**
1436f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1437f2263577SAndreas Gohr *
1438f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1439f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1440f2263577SAndreas Gohr *
1441140cfbcdSGerrit Uitslag * @param int|null $dt timestamp when given, null will take current timestamp
1442140cfbcdSGerrit Uitslag * @param string $format empty default to $conf['dformat'], or provide format as recognized by strftime()
1443140cfbcdSGerrit Uitslag * @return string
14448b19906eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
14458b19906eSAndreas Gohr *
14468b19906eSAndreas Gohr * @see datetime_h
1447f2263577SAndreas Gohr */
1448d868eb89SAndreas Gohrfunction dformat($dt = null, $format = '')
1449d868eb89SAndreas Gohr{
1450f2263577SAndreas Gohr    global $conf;
1451f2263577SAndreas Gohr
1452f2263577SAndreas Gohr    if (is_null($dt)) $dt = time();
1453f2263577SAndreas Gohr    $dt = (int)$dt;
1454f2263577SAndreas Gohr    if (!$format) $format = $conf['dformat'];
1455f2263577SAndreas Gohr
1456f2263577SAndreas Gohr    $format = str_replace('%f', datetime_h($dt), $format);
1457b3894732Ssplitbrain    return strftime($format, $dt);
1458f2263577SAndreas Gohr}
1459f2263577SAndreas Gohr
1460f2263577SAndreas Gohr/**
1461c4f79b71SMichael Hamann * Formats a timestamp as ISO 8601 date
1462c4f79b71SMichael Hamann *
14638b19906eSAndreas Gohr * @param int $int_date current date in UNIX timestamp
14648b19906eSAndreas Gohr * @return string
1465c4f79b71SMichael Hamann * @author <ungu at terong dot com>
146659752844SAnders Sandblad * @link http://php.net/manual/en/function.date.php#54072
1467140cfbcdSGerrit Uitslag *
1468c4f79b71SMichael Hamann */
1469d868eb89SAndreas Gohrfunction date_iso8601($int_date)
1470d868eb89SAndreas Gohr{
1471c4f79b71SMichael Hamann    $date_mod = date('Y-m-d\TH:i:s', $int_date);
1472c4f79b71SMichael Hamann    $pre_timezone = date('O', $int_date);
1473c4f79b71SMichael Hamann    $time_zone = substr($pre_timezone, 0, 3) . ":" . substr($pre_timezone, 3, 2);
1474c4f79b71SMichael Hamann    $date_mod .= $time_zone;
1475c4f79b71SMichael Hamann    return $date_mod;
1476c4f79b71SMichael Hamann}
1477c4f79b71SMichael Hamann
1478c4f79b71SMichael Hamann/**
147989541d4bSAndreas Gohr * Removes quoting backslashes
148089541d4bSAndreas Gohr *
1481140cfbcdSGerrit Uitslag * @param string $string
1482140cfbcdSGerrit Uitslag * @param string $char backslashed character
1483140cfbcdSGerrit Uitslag * @return string
14848b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
14858b19906eSAndreas Gohr *
148689541d4bSAndreas Gohr */
1487d868eb89SAndreas Gohrfunction unslash($string, $char = "'")
1488d868eb89SAndreas Gohr{
148989541d4bSAndreas Gohr    return str_replace('\\' . $char, $char, $string);
149089541d4bSAndreas Gohr}
149189541d4bSAndreas Gohr
149273038c47SAndreas Gohr/**
149373038c47SAndreas Gohr * Convert php.ini shorthands to byte
149473038c47SAndreas Gohr *
1495a81f3d99SAndreas Gohr * On 32 bit systems values >= 2GB will fail!
1496140cfbcdSGerrit Uitslag *
1497a81f3d99SAndreas Gohr * -1 (infinite size) will be reported as -1
1498a81f3d99SAndreas Gohr *
1499a81f3d99SAndreas Gohr * @link   https://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
1500a81f3d99SAndreas Gohr * @param string $value PHP size shorthand
1501a81f3d99SAndreas Gohr * @return int
150273038c47SAndreas Gohr */
1503d868eb89SAndreas Gohrfunction php_to_byte($value)
1504d868eb89SAndreas Gohr{
1505093fe67eSAndreas Gohr    $ret = match (strtoupper(substr($value, -1))) {
1506093fe67eSAndreas Gohr        'G' => (int)substr($value, 0, -1) * 1024 * 1024 * 1024,
1507093fe67eSAndreas Gohr        'M' => (int)substr($value, 0, -1) * 1024 * 1024,
1508093fe67eSAndreas Gohr        'K' => (int)substr($value, 0, -1) * 1024,
1509093fe67eSAndreas Gohr        default => (int)$value,
1510093fe67eSAndreas Gohr    };
151173038c47SAndreas Gohr    return $ret;
151273038c47SAndreas Gohr}
151373038c47SAndreas Gohr
1514546d3a99SAndreas Gohr/**
1515546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1516140cfbcdSGerrit Uitslag *
1517140cfbcdSGerrit Uitslag * @param string $string
1518140cfbcdSGerrit Uitslag * @return string
1519546d3a99SAndreas Gohr */
1520d868eb89SAndreas Gohrfunction preg_quote_cb($string)
1521d868eb89SAndreas Gohr{
1522546d3a99SAndreas Gohr    return preg_quote($string, '/');
1523546d3a99SAndreas Gohr}
152473038c47SAndreas Gohr
1525bd2f6c2fSAndreas Gohr/**
1526bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1527bd2f6c2fSAndreas Gohr *
1528c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1529bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1530bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1531bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1532bd2f6c2fSAndreas Gohr *
1533bd2f6c2fSAndreas Gohr * @param string $keep the part to keep
1534bd2f6c2fSAndreas Gohr * @param string $short the part to shorten
1535bd2f6c2fSAndreas Gohr * @param int $max maximum chars you want for the whole string
1536bd2f6c2fSAndreas Gohr * @param int $min minimum number of chars to have left for middle shortening
1537bd2f6c2fSAndreas Gohr * @param string $char the shortening character to use
15383272d797SAndreas Gohr * @return string
1539bd2f6c2fSAndreas Gohr */
1540d868eb89SAndreas Gohrfunction shorten($keep, $short, $max, $min = 9, $char = '…')
1541d868eb89SAndreas Gohr{
154224870174SAndreas Gohr    $max -= PhpString::strlen($keep);
1543bd2f6c2fSAndreas Gohr    if ($max < $min) return $keep;
154424870174SAndreas Gohr    $len = PhpString::strlen($short);
1545bd2f6c2fSAndreas Gohr    if ($len <= $max) return $keep . $short;
1546bd2f6c2fSAndreas Gohr    $half = floor($max / 2);
15476ce3e5f8SAndreas Gohr    return $keep .
154824870174SAndreas Gohr        PhpString::substr($short, 0, $half - 1) .
15496ce3e5f8SAndreas Gohr        $char .
155024870174SAndreas Gohr        PhpString::substr($short, $len - $half);
1551bd2f6c2fSAndreas Gohr}
1552bd2f6c2fSAndreas Gohr
1553dc58b6f4SAndy Webber/**
1554dc58b6f4SAndy Webber * Return the users real name or e-mail address for use
1555dc58b6f4SAndy Webber * in page footer and recent changes pages
1556dc58b6f4SAndy Webber *
1557b4b6c9a1SGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
155815f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1559c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
156015f3bc49SGerrit Uitslag *
1561dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1562dc58b6f4SAndy Webber */
1563d868eb89SAndreas Gohrfunction editorinfo($username, $textonly = false)
1564d868eb89SAndreas Gohr{
1565cd4635eeSGerrit Uitslag    return userlink($username, $textonly);
1566dc58b6f4SAndy Webber}
1567dc58b6f4SAndy Webber
156860a396c8SGerrit Uitslag/**
156960a396c8SGerrit Uitslag * Returns users realname w/o link
157060a396c8SGerrit Uitslag *
1571f168548cSGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
157215f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1573c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
157460a396c8SGerrit Uitslag *
157560a396c8SGerrit Uitslag * @triggers COMMON_USER_LINK
157660a396c8SGerrit Uitslag */
1577d868eb89SAndreas Gohrfunction userlink($username = null, $textonly = false)
1578d868eb89SAndreas Gohr{
157960a396c8SGerrit Uitslag    global $conf, $INFO;
1580e1d9dcc8SAndreas Gohr    /** @var AuthPlugin $auth */
158160a396c8SGerrit Uitslag    global $auth;
158230f6ec4bSGerrit Uitslag    /** @var Input $INPUT */
158330f6ec4bSGerrit Uitslag    global $INPUT;
158460a396c8SGerrit Uitslag
158560a396c8SGerrit Uitslag    // prepare initial event data
158624870174SAndreas Gohr    $data = [
158760a396c8SGerrit Uitslag        'username' => $username, // the unique user name
158860a396c8SGerrit Uitslag        'name' => '',
158924870174SAndreas Gohr        'link' => [
159024870174SAndreas Gohr            //setting 'link' to false disables linking
159160a396c8SGerrit Uitslag            'target' => '',
159260a396c8SGerrit Uitslag            'pre' => '',
159360a396c8SGerrit Uitslag            'suf' => '',
159460a396c8SGerrit Uitslag            'style' => '',
159560a396c8SGerrit Uitslag            'more' => '',
159660a396c8SGerrit Uitslag            'url' => '',
159760a396c8SGerrit Uitslag            'title' => '',
159824870174SAndreas Gohr            'class' => '',
159924870174SAndreas Gohr        ],
16004d5fc927SGerrit Uitslag        'userlink' => '', // formatted user name as will be returned
160124870174SAndreas Gohr        'textonly' => $textonly,
160224870174SAndreas Gohr    ];
160362c8004eSGerrit Uitslag    if ($username === null) {
160430f6ec4bSGerrit Uitslag        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
160515f3bc49SGerrit Uitslag        if ($textonly) {
160615f3bc49SGerrit Uitslag            $data['name'] = $INFO['userinfo']['name'] . ' (' . $INPUT->server->str('REMOTE_USER') . ')';
160715f3bc49SGerrit Uitslag        } else {
160864159a61SAndreas Gohr            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> ' .
160964159a61SAndreas Gohr                '(<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
161060a396c8SGerrit Uitslag        }
161115f3bc49SGerrit Uitslag    }
161260a396c8SGerrit Uitslag
1613e1d9dcc8SAndreas Gohr    $evt = new Event('COMMON_USER_LINK', $data);
161460a396c8SGerrit Uitslag    if ($evt->advise_before(true)) {
161560a396c8SGerrit Uitslag        if (empty($data['name'])) {
16166547cfc7SGerrit Uitslag            if ($auth instanceof AuthPlugin) {
16176547cfc7SGerrit Uitslag                $info = $auth->getUserData($username);
16186547cfc7SGerrit Uitslag            }
161965833968SGerrit Uitslag            if ($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1620dc58b6f4SAndy Webber                switch ($conf['showuseras']) {
1621dc58b6f4SAndy Webber                    case 'username':
16227f081821SGerrit Uitslag                    case 'username_link':
162315f3bc49SGerrit Uitslag                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
162460a396c8SGerrit Uitslag                        break;
1625dc58b6f4SAndy Webber                    case 'email':
1626dc58b6f4SAndy Webber                    case 'email_link':
1627*73dc0a89SAndreas Gohr                        $data['name'] = MailUtils::obfuscate($info['mail']);
162860a396c8SGerrit Uitslag                        break;
1629dc58b6f4SAndy Webber                }
163065833968SGerrit Uitslag            } else {
163165833968SGerrit Uitslag                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
163260a396c8SGerrit Uitslag            }
163360a396c8SGerrit Uitslag        }
16347f081821SGerrit Uitslag
16357f081821SGerrit Uitslag        /** @var Doku_Renderer_xhtml $xhtml_renderer */
16367f081821SGerrit Uitslag        static $xhtml_renderer = null;
16377f081821SGerrit Uitslag
163815f3bc49SGerrit Uitslag        if (!$data['textonly'] && empty($data['link']['url'])) {
163924870174SAndreas Gohr            if (in_array($conf['showuseras'], ['email_link', 'username_link'])) {
16406547cfc7SGerrit Uitslag                if (!isset($info) && $auth instanceof AuthPlugin) {
16416547cfc7SGerrit Uitslag                    $info = $auth->getUserData($username);
164260a396c8SGerrit Uitslag                }
164360a396c8SGerrit Uitslag                if (isset($info) && $info) {
16447f081821SGerrit Uitslag                    if ($conf['showuseras'] == 'email_link') {
1645*73dc0a89SAndreas Gohr                        $data['link']['url'] = 'mailto:' . MailUtils::obfuscateUrl($info['mail']);
1646dc58b6f4SAndy Webber                    } else {
16477f081821SGerrit Uitslag                        if (is_null($xhtml_renderer)) {
16487f081821SGerrit Uitslag                            $xhtml_renderer = p_get_renderer('xhtml');
16497f081821SGerrit Uitslag                        }
16508407f251Ssplitbrain                        if ($xhtml_renderer->interwiki === []) {
16517f081821SGerrit Uitslag                            $xhtml_renderer->interwiki = getInterwiki();
16527f081821SGerrit Uitslag                        }
16537f081821SGerrit Uitslag                        $shortcut = 'user';
1654533772e1SGerrit Uitslag                        $exists = null;
16556496c33fSGerrit Uitslag                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
16562a2a43c4SGerrit Uitslag                        $data['link']['class'] .= ' interwiki iw_user';
16576496c33fSGerrit Uitslag                        if ($exists !== null) {
16586496c33fSGerrit Uitslag                            if ($exists) {
16596496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink1';
16606496c33fSGerrit Uitslag                            } else {
16616496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink2';
16626496c33fSGerrit Uitslag                                $data['link']['rel'] = 'nofollow';
16636496c33fSGerrit Uitslag                            }
16646496c33fSGerrit Uitslag                        }
1665dc58b6f4SAndy Webber                    }
1666dc58b6f4SAndy Webber                } else {
166715f3bc49SGerrit Uitslag                    $data['textonly'] = true;
1668dc58b6f4SAndy Webber                }
166960a396c8SGerrit Uitslag            } else {
167015f3bc49SGerrit Uitslag                $data['textonly'] = true;
167160a396c8SGerrit Uitslag            }
167260a396c8SGerrit Uitslag        }
167360a396c8SGerrit Uitslag
167415f3bc49SGerrit Uitslag        if ($data['textonly']) {
16754d5fc927SGerrit Uitslag            $data['userlink'] = $data['name'];
167660a396c8SGerrit Uitslag        } else {
167760a396c8SGerrit Uitslag            $data['link']['name'] = $data['name'];
167860a396c8SGerrit Uitslag            if (is_null($xhtml_renderer)) {
167960a396c8SGerrit Uitslag                $xhtml_renderer = p_get_renderer('xhtml');
168060a396c8SGerrit Uitslag            }
16814d5fc927SGerrit Uitslag            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
168260a396c8SGerrit Uitslag        }
168360a396c8SGerrit Uitslag    }
168460a396c8SGerrit Uitslag    $evt->advise_after();
168560a396c8SGerrit Uitslag    unset($evt);
168660a396c8SGerrit Uitslag
16874d5fc927SGerrit Uitslag    return $data['userlink'];
1688066fee30SAndreas Gohr}
1689066fee30SAndreas Gohr
1690066fee30SAndreas Gohr/**
1691066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1692066fee30SAndreas Gohr * When no image exists, returns an empty string
1693066fee30SAndreas Gohr *
1694066fee30SAndreas Gohr * @param string $type - type of image 'badge' or 'button'
16953272d797SAndreas Gohr * @return string
16968b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
16978b19906eSAndreas Gohr *
1698066fee30SAndreas Gohr */
1699d868eb89SAndreas Gohrfunction license_img($type)
1700d868eb89SAndreas Gohr{
1701066fee30SAndreas Gohr    global $license;
1702066fee30SAndreas Gohr    global $conf;
1703066fee30SAndreas Gohr    if (!$conf['license']) return '';
1704066fee30SAndreas Gohr    if (!is_array($license[$conf['license']])) return '';
170524870174SAndreas Gohr    $try = [];
1706066fee30SAndreas Gohr    $try[] = 'lib/images/license/' . $type . '/' . $conf['license'] . '.png';
1707066fee30SAndreas Gohr    $try[] = 'lib/images/license/' . $type . '/' . $conf['license'] . '.gif';
17086c16a3a9Sfiwswe    if (str_starts_with($conf['license'], 'cc-')) {
1709066fee30SAndreas Gohr        $try[] = 'lib/images/license/' . $type . '/cc.png';
1710066fee30SAndreas Gohr    }
1711066fee30SAndreas Gohr    foreach ($try as $src) {
171279e79377SAndreas Gohr        if (file_exists(DOKU_INC . $src)) return $src;
1713066fee30SAndreas Gohr    }
1714066fee30SAndreas Gohr    return '';
1715dc58b6f4SAndy Webber}
1716dc58b6f4SAndy Webber
171713c08e2fSMichael Klier/**
171813c08e2fSMichael Klier * Checks if the given amount of memory is available
171913c08e2fSMichael Klier *
172013c08e2fSMichael Klier * If the memory_get_usage() function is not available the
172113c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
172213c08e2fSMichael Klier *
17233272d797SAndreas Gohr * @param int $mem Size of memory you want to allocate in bytes
1724140cfbcdSGerrit Uitslag * @param int $bytes already allocated memory (see above)
17253272d797SAndreas Gohr * @return bool
17268b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
17278b19906eSAndreas Gohr *
17288b19906eSAndreas Gohr * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
172913c08e2fSMichael Klier */
1730d868eb89SAndreas Gohrfunction is_mem_available($mem, $bytes = 1_048_576)
1731d868eb89SAndreas Gohr{
173213c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
173313c08e2fSMichael Klier    if (empty($limit)) return true; // no limit set!
1734985d6187SElenchus    if ($limit == -1) return true; // unlimited
173513c08e2fSMichael Klier
173613c08e2fSMichael Klier    // parse limit to bytes
173713c08e2fSMichael Klier    $limit = php_to_byte($limit);
173813c08e2fSMichael Klier
173913c08e2fSMichael Klier    // get used memory if possible
174013c08e2fSMichael Klier    if (function_exists('memory_get_usage')) {
174113c08e2fSMichael Klier        $used = memory_get_usage();
174249eb6e38SAndreas Gohr    } else {
174349eb6e38SAndreas Gohr        $used = $bytes;
174413c08e2fSMichael Klier    }
174513c08e2fSMichael Klier
174613c08e2fSMichael Klier    if ($used + $mem > $limit) {
174713c08e2fSMichael Klier        return false;
174813c08e2fSMichael Klier    }
174913c08e2fSMichael Klier
175013c08e2fSMichael Klier    return true;
175113c08e2fSMichael Klier}
175213c08e2fSMichael Klier
1753af2408d5SAndreas Gohr/**
1754af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1755af2408d5SAndreas Gohr *
1756af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1757af2408d5SAndreas Gohr *
1758af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1759af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1760140cfbcdSGerrit Uitslag *
1761140cfbcdSGerrit Uitslag * @param string $url url being directed to
1762af2408d5SAndreas Gohr */
1763d868eb89SAndreas Gohrfunction send_redirect($url)
1764d868eb89SAndreas Gohr{
176598ca30d2SAndreas Gohr    $url = stripctl($url); // defend against HTTP Response Splitting
176698ca30d2SAndreas Gohr
1767585bf44eSChristopher Smith    /* @var Input $INPUT */
1768585bf44eSChristopher Smith    global $INPUT;
1769585bf44eSChristopher Smith
17700181f021SAndreas Gohr    //are there any undisplayed messages? keep them in session for display
17710181f021SAndreas Gohr    global $MSG;
17720181f021SAndreas Gohr    if (isset($MSG) && count($MSG) && !defined('NOSESSION')) {
17730181f021SAndreas Gohr        //reopen session, store data and close session again
17740181f021SAndreas Gohr        @session_start();
17750181f021SAndreas Gohr        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
17760181f021SAndreas Gohr    }
17770181f021SAndreas Gohr
1778d4869846SAndreas Gohr    // always close the session
1779d4869846SAndreas Gohr    session_write_close();
1780d4869846SAndreas Gohr
1781af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
17827d34963bSAndreas Gohr    if (
17837d34963bSAndreas Gohr        $INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1784093fe67eSAndreas Gohr        (str_contains($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI')) &&
1785585bf44eSChristopher Smith        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
17863272d797SAndreas Gohr        $matches[1] < 6
17873272d797SAndreas Gohr    ) {
1788af2408d5SAndreas Gohr        header('Refresh: 0;url=' . $url);
1789af2408d5SAndreas Gohr    } else {
1790af2408d5SAndreas Gohr        header('Location: ' . $url);
1791af2408d5SAndreas Gohr    }
179281781cb6SAndreas Gohr
1793572dc222SLarsDW223    // no exits during unit tests
179427c0c399SAndreas Gohr    if (defined('DOKU_UNITTEST')) {
179527c0c399SAndreas Gohr        // pass info about the redirect back to the test suite
179627c0c399SAndreas Gohr        $testRequest = TestRequest::getRunning();
179727c0c399SAndreas Gohr        if ($testRequest !== null) {
179827c0c399SAndreas Gohr            $testRequest->addData('send_redirect', $url);
179927c0c399SAndreas Gohr        }
1800572dc222SLarsDW223        return;
1801572dc222SLarsDW223    }
180227c0c399SAndreas Gohr
1803af2408d5SAndreas Gohr    exit;
1804af2408d5SAndreas Gohr}
1805af2408d5SAndreas Gohr
18065b75cd1fSAdrian Lang/**
180763703ba5SAndreas Gohr * Read a preference from the DokuWiki cookie
18083f108b37SAndreas Gohr *
18093f108b37SAndreas Gohr * Consider using PrefCookie directly
1810140cfbcdSGerrit Uitslag *
1811140cfbcdSGerrit Uitslag * @param string $pref preference key
1812b4b6c9a1SGerrit Uitslag * @param mixed $default value returned when preference not found
18133f108b37SAndreas Gohr * @return mixed preference value
181463703ba5SAndreas Gohr */
1815d868eb89SAndreas Gohrfunction get_doku_pref($pref, $default)
1816d868eb89SAndreas Gohr{
18173f108b37SAndreas Gohr    return (new PrefCookie())->get($pref, $default);
1818554a8c9fSAdrian Lang}
1819554a8c9fSAdrian Lang
18203c94d07bSAnika Henke/**
18213c94d07bSAnika Henke * Add a preference to the DokuWiki cookie
18223f108b37SAndreas Gohr *
18233f108b37SAndreas Gohr * Remove it by setting $val to false.
18243f108b37SAndreas Gohr * Consider using PrefCookie directly
1825140cfbcdSGerrit Uitslag *
1826140cfbcdSGerrit Uitslag * @param string $pref preference key
18273f108b37SAndreas Gohr * @param string|false $val preference value
18283c94d07bSAnika Henke */
1829d868eb89SAndreas Gohrfunction set_doku_pref($pref, $val)
1830d868eb89SAndreas Gohr{
18313f108b37SAndreas Gohr    if ($val === false) {
18323f108b37SAndreas Gohr        $val = null;
18333a970889SAnika Henke    } else {
18343f108b37SAndreas Gohr        $val = (string) $val;
18353c94d07bSAnika Henke    }
18363c94d07bSAnika Henke
18373f108b37SAndreas Gohr    (new PrefCookie())->set($pref, $val);
18383c94d07bSAnika Henke}
18393c94d07bSAnika Henke
1840f8fb2d18SAndreas Gohr/**
1841f8fb2d18SAndreas Gohr * Strips source mapping declarations from given text #601
1842f8fb2d18SAndreas Gohr *
184342ea7f44SGerrit Uitslag * @param string &$text reference to the CSS or JavaScript code to clean
1844f8fb2d18SAndreas Gohr */
1845d868eb89SAndreas Gohrfunction stripsourcemaps(&$text)
1846d868eb89SAndreas Gohr{
1847f8fb2d18SAndreas Gohr    $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text);
1848f8fb2d18SAndreas Gohr}
1849f8fb2d18SAndreas Gohr
18503c27983bSAndreas Gohr/**
185171de5572SAndreas Gohr * Returns the contents of a given SVG file for embedding
18523c27983bSAndreas Gohr *
18533c27983bSAndreas Gohr * Inlining SVGs saves on HTTP requests and more importantly allows for styling them through
18543c27983bSAndreas Gohr * CSS. However it should used with small SVGs only. The $maxsize setting ensures only small
18553c27983bSAndreas Gohr * files are embedded.
18563c27983bSAndreas Gohr *
185771de5572SAndreas Gohr * This strips unneeded headers, comments and newline. The result is not a vaild standalone SVG!
185871de5572SAndreas Gohr *
18593c27983bSAndreas Gohr * @param string $file full path to the SVG file
18603c27983bSAndreas Gohr * @param int $maxsize maximum allowed size for the SVG to be embedded
186171de5572SAndreas Gohr * @return string|false the SVG content, false if the file couldn't be loaded
18623c27983bSAndreas Gohr */
1863d868eb89SAndreas Gohrfunction inlineSVG($file, $maxsize = 2048)
1864d868eb89SAndreas Gohr{
18653c27983bSAndreas Gohr    $file = trim($file);
18663c27983bSAndreas Gohr    if ($file === '') return false;
18673c27983bSAndreas Gohr    if (!file_exists($file)) return false;
18683c27983bSAndreas Gohr    if (filesize($file) > $maxsize) return false;
18693c27983bSAndreas Gohr    if (!is_readable($file)) return false;
18703c27983bSAndreas Gohr    $content = file_get_contents($file);
18710849fa88SAndreas Gohr    $content = preg_replace('/<!--.*?(-->)/s', '', $content); // comments
18720849fa88SAndreas Gohr    $content = preg_replace('/<\?xml .*?\?>/i', '', $content); // xml header
18730849fa88SAndreas Gohr    $content = preg_replace('/<!DOCTYPE .*?>/i', '', $content); // doc type
18740849fa88SAndreas Gohr    $content = preg_replace('/>\s+</s', '><', $content); // newlines between tags
18753c27983bSAndreas Gohr    $content = trim($content);
18766c16a3a9Sfiwswe    if (!str_starts_with($content, '<svg ')) return false;
187771de5572SAndreas Gohr    return $content;
18783c27983bSAndreas Gohr}
18793c27983bSAndreas Gohr
1880e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1881