xref: /dokuwiki/inc/common.php (revision 85cddb538a58d7b2cfc0a3b41359a9310d6a6843)
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;
240c3a5702SAndreas Gohr
258b19906eSAndreas Gohruse function PHP81_BC\strftime;
268b19906eSAndreas Gohr
27f3f0262cSandi/**
28d5197206Schris * Wrapper around htmlspecialchars()
29d5197206Schris *
308b19906eSAndreas Gohr * @param string $string the string being converted
318b19906eSAndreas Gohr * @return string converted string
32d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
33d5197206Schris * @see    htmlspecialchars()
34140cfbcdSGerrit Uitslag *
35d5197206Schris */
36d868eb89SAndreas Gohrfunction hsc($string)
37d868eb89SAndreas Gohr{
38f7711f2bSAndreas Gohr    return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, 'UTF-8');
39d5197206Schris}
40d5197206Schris
41d5197206Schris/**
4212dd3cbcSAndreas Gohr * A safer explode for fixed length lists
4312dd3cbcSAndreas Gohr *
4412dd3cbcSAndreas Gohr * This works just like explode(), but will always return the wanted number of elements.
4512dd3cbcSAndreas Gohr * If the $input string does not contain enough elements, the missing elements will be
4612dd3cbcSAndreas Gohr * filled up with the $default value. If the input string contains more elements, the last
4712dd3cbcSAndreas Gohr * one will NOT be split up and will still contain $separator
4812dd3cbcSAndreas Gohr *
4912dd3cbcSAndreas Gohr * @param string $separator The boundary string
5012dd3cbcSAndreas Gohr * @param string $string The input string
5112dd3cbcSAndreas Gohr * @param int $limit The number of expected elements
5212dd3cbcSAndreas Gohr * @param mixed $default The value to use when filling up missing elements
5312dd3cbcSAndreas Gohr * @return array
548b19906eSAndreas Gohr * @see explode
5512dd3cbcSAndreas Gohr */
5612dd3cbcSAndreas Gohrfunction sexplode($separator, $string, $limit, $default = null)
5712dd3cbcSAndreas Gohr{
5812dd3cbcSAndreas Gohr    return array_pad(explode($separator, $string, $limit), $limit, $default);
5912dd3cbcSAndreas Gohr}
6012dd3cbcSAndreas Gohr
6112dd3cbcSAndreas Gohr/**
625b571377SAndreas Gohr * Checks if the given input is blank
635b571377SAndreas Gohr *
645b571377SAndreas Gohr * This is similar to empty() but will return false for "0".
655b571377SAndreas Gohr *
6667234204SAndreas Gohr * Please note: when you pass uninitialized variables, they will implicitly be created
6767234204SAndreas Gohr * with a NULL value without warning.
6867234204SAndreas Gohr *
6967234204SAndreas Gohr * To avoid this it's recommended to guard the call with isset like this:
7067234204SAndreas Gohr *
7167234204SAndreas Gohr * (isset($foo) && !blank($foo))
7267234204SAndreas Gohr * (!isset($foo) || blank($foo))
7367234204SAndreas Gohr *
745b571377SAndreas Gohr * @param $in
755b571377SAndreas Gohr * @param bool $trim Consider a string of whitespace to be blank
765b571377SAndreas Gohr * @return bool
775b571377SAndreas Gohr */
78d868eb89SAndreas Gohrfunction blank(&$in, $trim = false)
79d868eb89SAndreas Gohr{
805b571377SAndreas Gohr    if (is_null($in)) return true;
8124870174SAndreas Gohr    if (is_array($in)) return $in === [];
825b571377SAndreas Gohr    if ($in === "\0") return true;
835b571377SAndreas Gohr    if ($trim && trim($in) === '') return true;
84093fe67eSAndreas Gohr    if ((string) $in !== '') return false;
855b571377SAndreas Gohr    return empty($in);
865b571377SAndreas Gohr}
875b571377SAndreas Gohr
885b571377SAndreas Gohr/**
8902b0b681SAndreas Gohr * strips control characters (<32) from the given string
9002b0b681SAndreas Gohr *
9142ea7f44SGerrit Uitslag * @param string $string being stripped
92140cfbcdSGerrit Uitslag * @return string
938b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
948b19906eSAndreas Gohr *
9502b0b681SAndreas Gohr */
96d868eb89SAndreas Gohrfunction stripctl($string)
97d868eb89SAndreas Gohr{
9802b0b681SAndreas Gohr    return preg_replace('/[\x00-\x1F]+/s', '', $string);
99d5197206Schris}
100d5197206Schris
101d5197206Schris/**
102634d7150SAndreas Gohr * Return a secret token to be used for CSRF attack prevention
103634d7150SAndreas Gohr *
1048b19906eSAndreas Gohr * @return  string
105634d7150SAndreas Gohr * @link    http://en.wikipedia.org/wiki/Cross-site_request_forgery
106634d7150SAndreas Gohr * @link    http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
10742ea7f44SGerrit Uitslag *
1088b19906eSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
109634d7150SAndreas Gohr */
110d868eb89SAndreas Gohrfunction getSecurityToken()
111d868eb89SAndreas Gohr{
112585bf44eSChristopher Smith    /** @var Input $INPUT */
113585bf44eSChristopher Smith    global $INPUT;
1143680e2cdSAndreas Gohr
1153680e2cdSAndreas Gohr    $user = $INPUT->server->str('REMOTE_USER');
1163680e2cdSAndreas Gohr    $session = session_id();
1173680e2cdSAndreas Gohr
1183680e2cdSAndreas Gohr    // CSRF checks are only for logged in users - do not generate for anonymous
1193680e2cdSAndreas Gohr    if (trim($user) == '' || trim($session) == '') return '';
12024870174SAndreas Gohr    return PassHash::hmac('md5', $session . $user, auth_cookiesalt());
121634d7150SAndreas Gohr}
122634d7150SAndreas Gohr
123634d7150SAndreas Gohr/**
124634d7150SAndreas Gohr * Check the secret CSRF token
125140cfbcdSGerrit Uitslag *
126140cfbcdSGerrit Uitslag * @param null|string $token security token or null to read it from request variable
127140cfbcdSGerrit Uitslag * @return bool success if the token matched
128634d7150SAndreas Gohr */
129d868eb89SAndreas Gohrfunction checkSecurityToken($token = null)
130d868eb89SAndreas Gohr{
131585bf44eSChristopher Smith    /** @var Input $INPUT */
1327d01a0eaSTom N Harris    global $INPUT;
133585bf44eSChristopher Smith    if (!$INPUT->server->str('REMOTE_USER')) return true; // no logged in user, no need for a check
134df97eaacSAndreas Gohr
1357d01a0eaSTom N Harris    if (is_null($token)) $token = $INPUT->str('sectok');
136634d7150SAndreas Gohr    if (getSecurityToken() != $token) {
137634d7150SAndreas Gohr        msg('Security Token did not match. Possible CSRF attack.', -1);
138634d7150SAndreas Gohr        return false;
139634d7150SAndreas Gohr    }
140634d7150SAndreas Gohr    return true;
141634d7150SAndreas Gohr}
142634d7150SAndreas Gohr
143634d7150SAndreas Gohr/**
144634d7150SAndreas Gohr * Print a hidden form field with a secret CSRF token
145634d7150SAndreas Gohr *
146140cfbcdSGerrit Uitslag * @param bool $print if true print the field, otherwise html of the field is returned
14742ea7f44SGerrit Uitslag * @return string html of hidden form field
1488b19906eSAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
1498b19906eSAndreas Gohr *
150634d7150SAndreas Gohr */
151d868eb89SAndreas Gohrfunction formSecurityToken($print = true)
152d868eb89SAndreas Gohr{
1532404d0edSAnika Henke    $ret = '<div class="no"><input type="hidden" name="sectok" value="' . getSecurityToken() . '" /></div>' . "\n";
1543272d797SAndreas Gohr    if ($print) echo $ret;
155634d7150SAndreas Gohr    return $ret;
156634d7150SAndreas Gohr}
157634d7150SAndreas Gohr
158634d7150SAndreas Gohr/**
1591015a57dSChristopher Smith * Determine basic information for a request of $id
16015fae107Sandi *
161140cfbcdSGerrit Uitslag * @param string $id pageid
162140cfbcdSGerrit Uitslag * @param bool $htmlClient add info about whether is mobile browser
163140cfbcdSGerrit Uitslag * @return array with info for a request of $id
164140cfbcdSGerrit Uitslag *
1658b19906eSAndreas Gohr * @author Chris Smith <chris@jalakai.co.uk>
1668b19906eSAndreas Gohr *
1678b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
168f3f0262cSandi */
169d868eb89SAndreas Gohrfunction basicinfo($id, $htmlClient = true)
170d868eb89SAndreas Gohr{
171f3f0262cSandi    global $USERINFO;
172585bf44eSChristopher Smith    /* @var Input $INPUT */
173585bf44eSChristopher Smith    global $INPUT;
1746afe8dcaSchris
175c66972f2SAdrian Lang    // set info about manager/admin status.
17624870174SAndreas Gohr    $info = [];
177c66972f2SAdrian Lang    $info['isadmin'] = false;
178c66972f2SAdrian Lang    $info['ismanager'] = false;
179585bf44eSChristopher Smith    if ($INPUT->server->has('REMOTE_USER')) {
180f3f0262cSandi        $info['userinfo'] = $USERINFO;
1811015a57dSChristopher Smith        $info['perm'] = auth_quickaclcheck($id);
182585bf44eSChristopher Smith        $info['client'] = $INPUT->server->str('REMOTE_USER');
18317ee7f66SAndreas Gohr
184f8cc712eSAndreas Gohr        if ($info['perm'] == AUTH_ADMIN) {
185f8cc712eSAndreas Gohr            $info['isadmin'] = true;
186f8cc712eSAndreas Gohr            $info['ismanager'] = true;
187f8cc712eSAndreas Gohr        } elseif (auth_ismanager()) {
188f8cc712eSAndreas Gohr            $info['ismanager'] = true;
189f8cc712eSAndreas Gohr        }
190f8cc712eSAndreas Gohr
19117ee7f66SAndreas Gohr        // if some outside auth were used only REMOTE_USER is set
192a58fcbbcSAndreas Gohr        if (empty($info['userinfo']['name'])) {
193585bf44eSChristopher Smith            $info['userinfo']['name'] = $INPUT->server->str('REMOTE_USER');
19417ee7f66SAndreas Gohr        }
195f3f0262cSandi    } else {
1961015a57dSChristopher Smith        $info['perm'] = auth_aclcheck($id, '', null);
197ee4c4a1bSAndreas Gohr        $info['client'] = clientIP(true);
198f3f0262cSandi    }
199f3f0262cSandi
2001015a57dSChristopher Smith    $info['namespace'] = getNS($id);
2011015a57dSChristopher Smith
2021015a57dSChristopher Smith    // mobile detection
2031015a57dSChristopher Smith    if ($htmlClient) {
2041015a57dSChristopher Smith        $info['ismobile'] = clientismobile();
2051015a57dSChristopher Smith    }
2061015a57dSChristopher Smith
2071015a57dSChristopher Smith    return $info;
2081015a57dSChristopher Smith}
2091015a57dSChristopher Smith
2101015a57dSChristopher Smith/**
2111015a57dSChristopher Smith * Return info about the current document as associative
2121015a57dSChristopher Smith * array.
2131015a57dSChristopher Smith *
214140cfbcdSGerrit Uitslag * @return array with info about current document
2154dc42f7fSGerrit Uitslag * @throws Exception
2164dc42f7fSGerrit Uitslag *
2174dc42f7fSGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
2181015a57dSChristopher Smith */
219d868eb89SAndreas Gohrfunction pageinfo()
220d868eb89SAndreas Gohr{
2211015a57dSChristopher Smith    global $ID;
2221015a57dSChristopher Smith    global $REV;
2231015a57dSChristopher Smith    global $RANGE;
2241015a57dSChristopher Smith    global $lang;
2251015a57dSChristopher Smith
2261015a57dSChristopher Smith    $info = basicinfo($ID);
2271015a57dSChristopher Smith
2281015a57dSChristopher Smith    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
2291015a57dSChristopher Smith    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
2301015a57dSChristopher Smith    $info['id'] = $ID;
2311015a57dSChristopher Smith    $info['rev'] = $REV;
2321015a57dSChristopher Smith
23375d66495SMichael Große    $subManager = new SubscriberManager();
23475d66495SMichael Große    $info['subscribed'] = $subManager->userSubscription();
2357e87a794SChristopher Smith
236f3f0262cSandi    $info['locked'] = checklock($ID);
237317a04c4SSatoshi Sahara    $info['filepath'] = wikiFN($ID);
23879e79377SAndreas Gohr    $info['exists'] = file_exists($info['filepath']);
23901c9a118SAndreas Gohr    $info['currentrev'] = @filemtime($info['filepath']);
2405ec96136SSatoshi Sahara
2412ca9d91cSBen Coburn    if ($REV) {
2422ca9d91cSBen Coburn        //check if current revision was meant
24301c9a118SAndreas Gohr        if ($info['exists'] && ($info['currentrev'] == $REV)) {
2442ca9d91cSBen Coburn            $REV = '';
2457b3a6803SAndreas Gohr        } elseif ($RANGE) {
2467b3a6803SAndreas Gohr            //section editing does not work with old revisions!
2477b3a6803SAndreas Gohr            $REV = '';
2487b3a6803SAndreas Gohr            $RANGE = '';
2497b3a6803SAndreas Gohr            msg($lang['nosecedit'], 0);
2502ca9d91cSBen Coburn        } else {
2512ca9d91cSBen Coburn            //really use old revision
252317a04c4SSatoshi Sahara            $info['filepath'] = wikiFN($ID, $REV);
25379e79377SAndreas Gohr            $info['exists'] = file_exists($info['filepath']);
254f3f0262cSandi        }
255f3f0262cSandi    }
256c112d578Sandi    $info['rev'] = $REV;
257f3f0262cSandi    if ($info['exists']) {
258252acce3SSatoshi Sahara        $info['writable'] = (is_writable($info['filepath']) && $info['perm'] >= AUTH_EDIT);
259f3f0262cSandi    } else {
260f3f0262cSandi        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
261f3f0262cSandi    }
26250e988b1SAndreas Gohr    $info['editable'] = ($info['writable'] && empty($info['locked']));
263f3f0262cSandi    $info['lastmod'] = @filemtime($info['filepath']);
264f3f0262cSandi
26571726d78SBen Coburn    //load page meta data
26671726d78SBen Coburn    $info['meta'] = p_get_metadata($ID);
26771726d78SBen Coburn
268652610a2Sandi    //who's the editor
269047bad06SGerrit Uitslag    $pagelog = new PageChangeLog($ID, 1024);
270652610a2Sandi    if ($REV) {
271f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($REV);
27224870174SAndreas Gohr    } elseif (!empty($info['meta']['last_change']) && is_array($info['meta']['last_change'])) {
273aa27cf05SAndreas Gohr        $revinfo = $info['meta']['last_change'];
274aa27cf05SAndreas Gohr    } else {
275f523c971SGerrit Uitslag        $revinfo = $pagelog->getRevisionInfo($info['lastmod']);
276cd00a034SBen Coburn        // cache most recent changelog line in metadata if missing and still valid
277cd00a034SBen Coburn        if ($revinfo !== false) {
278cd00a034SBen Coburn            $info['meta']['last_change'] = $revinfo;
27924870174SAndreas Gohr            p_set_metadata($ID, ['last_change' => $revinfo]);
280cd00a034SBen Coburn        }
281cd00a034SBen Coburn    }
282cd00a034SBen Coburn    //and check for an external edit
283cd00a034SBen Coburn    if ($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
284cd00a034SBen Coburn        // cached changelog line no longer valid
285cd00a034SBen Coburn        $revinfo = false;
286cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
28724870174SAndreas Gohr        p_set_metadata($ID, ['last_change' => $revinfo]);
288652610a2Sandi    }
289bb4866bdSchris
2900a444b5aSPhy    if ($revinfo !== false) {
291652610a2Sandi        $info['ip'] = $revinfo['ip'];
292652610a2Sandi        $info['user'] = $revinfo['user'];
293652610a2Sandi        $info['sum'] = $revinfo['sum'];
29471726d78SBen Coburn        // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
295ebf1501fSBen Coburn        // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
29659f257aeSchris
297252acce3SSatoshi Sahara        $info['editor'] = $revinfo['user'] ?: $revinfo['ip'];
2980a444b5aSPhy    } else {
2990a444b5aSPhy        $info['ip'] = null;
3000a444b5aSPhy        $info['user'] = null;
3010a444b5aSPhy        $info['sum'] = null;
3020a444b5aSPhy        $info['editor'] = null;
3030a444b5aSPhy    }
304652610a2Sandi
305ee4c4a1bSAndreas Gohr    // draft
30624870174SAndreas Gohr    $draft = new Draft($ID, $info['client']);
3070aabe6f8SMichael Große    if ($draft->isDraftAvailable()) {
3080aabe6f8SMichael Große        $info['draft'] = $draft->getDraftFilename();
309ee4c4a1bSAndreas Gohr    }
310ee4c4a1bSAndreas Gohr
3111015a57dSChristopher Smith    return $info;
3121015a57dSChristopher Smith}
3131015a57dSChristopher Smith
3141015a57dSChristopher Smith/**
3150c39d46cSMichael Große * Initialize and/or fill global $JSINFO with some basic info to be given to javascript
3160c39d46cSMichael Große */
317d868eb89SAndreas Gohrfunction jsinfo()
318d868eb89SAndreas Gohr{
3190c39d46cSMichael Große    global $JSINFO, $ID, $INFO, $ACT;
3200c39d46cSMichael Große
3210c39d46cSMichael Große    if (!is_array($JSINFO)) {
3220c39d46cSMichael Große        $JSINFO = [];
3230c39d46cSMichael Große    }
3240c39d46cSMichael Große    //export minimal info to JS, plugins can add more
3250c39d46cSMichael Große    $JSINFO['id'] = $ID;
32668491db9SPhy    $JSINFO['namespace'] = isset($INFO) ? (string)$INFO['namespace'] : '';
3270c39d46cSMichael Große    $JSINFO['ACT'] = act_clean($ACT);
3280c39d46cSMichael Große    $JSINFO['useHeadingNavigation'] = (int)useHeading('navigation');
3290c39d46cSMichael Große    $JSINFO['useHeadingContent'] = (int)useHeading('content');
3300c39d46cSMichael Große}
3310c39d46cSMichael Große
3320c39d46cSMichael Große/**
3331015a57dSChristopher Smith * Return information about the current media item as an associative array.
334140cfbcdSGerrit Uitslag *
335140cfbcdSGerrit Uitslag * @return array with info about current media item
3361015a57dSChristopher Smith */
337d868eb89SAndreas Gohrfunction mediainfo()
338d868eb89SAndreas Gohr{
3391015a57dSChristopher Smith    global $NS;
3401015a57dSChristopher Smith    global $IMG;
3411015a57dSChristopher Smith
3421015a57dSChristopher Smith    $info = basicinfo("$NS:*");
3431015a57dSChristopher Smith    $info['image'] = $IMG;
3441c548ebeSAndreas Gohr
345f3f0262cSandi    return $info;
346f3f0262cSandi}
347f3f0262cSandi
348f3f0262cSandi/**
3492684e50aSAndreas Gohr * Build an string of URL parameters
3502684e50aSAndreas Gohr *
3516cc6a0d2SAndreas Gohr * @see http_build_query()
3526cc6a0d2SAndreas Gohr * @param array|object $params the data to encode
353140cfbcdSGerrit Uitslag * @param string $sep series of pairs are separated by this character
354140cfbcdSGerrit Uitslag * @return string query string
3558b19906eSAndreas Gohr *
3562684e50aSAndreas Gohr */
357d868eb89SAndreas Gohrfunction buildURLparams($params, $sep = '&amp;')
358d868eb89SAndreas Gohr{
3596cc6a0d2SAndreas Gohr    return http_build_query($params, '', $sep, PHP_QUERY_RFC3986);
3602684e50aSAndreas Gohr}
3612684e50aSAndreas Gohr
3622684e50aSAndreas Gohr/**
3632684e50aSAndreas Gohr * Build an string of html tag attributes
3642684e50aSAndreas Gohr *
3657bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
3667bff22c0SAndreas Gohr *
367140cfbcdSGerrit Uitslag * @param array $params array with (attribute name-attribute value) pairs
368246d3337SMichael Große * @param bool $skipEmptyStrings skip empty string values?
369140cfbcdSGerrit Uitslag * @return string
3708b19906eSAndreas Gohr * @author Andreas Gohr
3718b19906eSAndreas Gohr *
3722684e50aSAndreas Gohr */
373d868eb89SAndreas Gohrfunction buildAttributes($params, $skipEmptyStrings = false)
374d868eb89SAndreas Gohr{
3752684e50aSAndreas Gohr    $url = '';
3769063ec14SAdrian Lang    $white = false;
3772684e50aSAndreas Gohr    foreach ($params as $key => $val) {
3782401f18dSSyntaxseed        if ($key[0] == '_') continue;
379246d3337SMichael Große        if ($val === '' && $skipEmptyStrings) continue;
3809063ec14SAdrian Lang        if ($white) $url .= ' ';
3817bff22c0SAndreas Gohr
3822684e50aSAndreas Gohr        $url .= $key . '="';
383f7711f2bSAndreas Gohr        $url .= hsc($val);
3842684e50aSAndreas Gohr        $url .= '"';
3859063ec14SAdrian Lang        $white = true;
3862684e50aSAndreas Gohr    }
3872684e50aSAndreas Gohr    return $url;
3882684e50aSAndreas Gohr}
3892684e50aSAndreas Gohr
3902684e50aSAndreas Gohr/**
39115fae107Sandi * This builds the breadcrumb trail and returns it as array
39215fae107Sandi *
3938b19906eSAndreas Gohr * @return string[] with the data: array(pageid=>name, ... )
39415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
395140cfbcdSGerrit Uitslag *
396f3f0262cSandi */
397d868eb89SAndreas Gohrfunction breadcrumbs()
398d868eb89SAndreas Gohr{
3998746e727Sandi    // we prepare the breadcrumbs early for quick session closing
4008746e727Sandi    static $crumbs = null;
4018746e727Sandi    if ($crumbs != null) return $crumbs;
4028746e727Sandi
403f3f0262cSandi    global $ID;
404f3f0262cSandi    global $ACT;
405f3f0262cSandi    global $conf;
4060ea5ebb4SB_S666    global $INFO;
407f3f0262cSandi
408f3f0262cSandi    //first visit?
40924870174SAndreas Gohr    $crumbs = $_SESSION[DOKU_COOKIE]['bc'] ?? [];
4105603d3c1SHenry Pan    //we only save on show and existing visible readable wiki documents
411a77f5846Sjan    $file = wikiFN($ID);
4125603d3c1SHenry Pan    if ($ACT != 'show' || $INFO['perm'] < AUTH_READ || isHiddenPage($ID) || !file_exists($file)) {
413e71ce681SAndreas Gohr        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
414f3f0262cSandi        return $crumbs;
415f3f0262cSandi    }
416a77f5846Sjan
417a77f5846Sjan    // page names
4181a84a0f3SAnika Henke    $name = noNSorNS($ID);
419fe9ec250SChris Smith    if (useHeading('navigation')) {
420a77f5846Sjan        // get page title
42167c15eceSMichael Hamann        $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
422a77f5846Sjan        if ($title) {
423a77f5846Sjan            $name = $title;
424a77f5846Sjan        }
425a77f5846Sjan    }
426a77f5846Sjan
427f3f0262cSandi    //remove ID from array
428a77f5846Sjan    if (isset($crumbs[$ID])) {
429a77f5846Sjan        unset($crumbs[$ID]);
430f3f0262cSandi    }
431f3f0262cSandi
432f3f0262cSandi    //add to array
433a77f5846Sjan    $crumbs[$ID] = $name;
434f3f0262cSandi    //reduce size
435f3f0262cSandi    while (count($crumbs) > $conf['breadcrumbs']) {
436f3f0262cSandi        array_shift($crumbs);
437f3f0262cSandi    }
438f3f0262cSandi    //save to session
439e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
440f3f0262cSandi    return $crumbs;
441f3f0262cSandi}
442f3f0262cSandi
443f3f0262cSandi/**
44415fae107Sandi * Filter for page IDs
44515fae107Sandi *
446f3f0262cSandi * This is run on a ID before it is outputted somewhere
447f3f0262cSandi * currently used to replace the colon with something else
448907f24f7SAndreas Gohr * on Windows (non-IIS) systems and to have proper URL encoding
449907f24f7SAndreas Gohr *
450977aa967SAndreas Gohr * See discussions at https://github.com/dokuwiki/dokuwiki/pull/84 and
451977aa967SAndreas Gohr * https://github.com/dokuwiki/dokuwiki/pull/173 why we use a whitelist of
452907f24f7SAndreas Gohr * unaffected servers instead of blacklisting affected servers here.
45315fae107Sandi *
45449c713a3Sandi * Urlencoding is ommitted when the second parameter is false
45549c713a3Sandi *
456140cfbcdSGerrit Uitslag * @param string $id pageid being filtered
457140cfbcdSGerrit Uitslag * @param bool $ue apply urlencoding?
458140cfbcdSGerrit Uitslag * @return string
4598b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
4608b19906eSAndreas Gohr *
461f3f0262cSandi */
462d868eb89SAndreas Gohrfunction idfilter($id, $ue = true)
463d868eb89SAndreas Gohr{
464f3f0262cSandi    global $conf;
465585bf44eSChristopher Smith    /* @var Input $INPUT */
466585bf44eSChristopher Smith    global $INPUT;
467585bf44eSChristopher Smith
468bf8f8509SAndreas Gohr    $id = (string)$id;
469bf8f8509SAndreas Gohr
470f3f0262cSandi    if ($conf['useslash'] && $conf['userewrite']) {
471f3f0262cSandi        $id = strtr($id, ':', '/');
4727d34963bSAndreas Gohr    } elseif (
4736c16a3a9Sfiwswe        str_starts_with(strtoupper(PHP_OS), 'WIN') &&
47458bedc8aSborekb        $conf['userewrite'] &&
475093fe67eSAndreas Gohr        !str_contains($INPUT->server->str('SERVER_SOFTWARE'), 'Microsoft-IIS')
4763272d797SAndreas Gohr    ) {
477f3f0262cSandi        $id = strtr($id, ':', ';');
478f3f0262cSandi    }
47949c713a3Sandi    if ($ue) {
480b6c6979fSAndreas Gohr        $id = rawurlencode($id);
481f3f0262cSandi        $id = str_replace('%3A', ':', $id); //keep as colon
482edd95259SGerrit Uitslag        $id = str_replace('%3B', ';', $id); //keep as semicolon
483f3f0262cSandi        $id = str_replace('%2F', '/', $id); //keep as slash
48449c713a3Sandi    }
485f3f0262cSandi    return $id;
486f3f0262cSandi}
487f3f0262cSandi
488f3f0262cSandi/**
489ed7b5f09Sandi * This builds a link to a wikipage
49015fae107Sandi *
4914bc480e5SAndreas Gohr * It handles URL rewriting and adds additional parameters
4926c7843b5Sandi *
4934bc480e5SAndreas Gohr * @param string $id page id, defaults to start page
4944bc480e5SAndreas Gohr * @param string|array $urlParameters URL parameters, associative array recommended
4954bc480e5SAndreas Gohr * @param bool $absolute request an absolute URL instead of relative
4964bc480e5SAndreas Gohr * @param string $separator parameter separator
4974bc480e5SAndreas Gohr * @return string
4988b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
4998b19906eSAndreas Gohr *
500f3f0262cSandi */
501d868eb89SAndreas Gohrfunction wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;')
502d868eb89SAndreas Gohr{
503f3f0262cSandi    global $conf;
50416f15a81SDominik Eckelmann    if (is_array($urlParameters)) {
5054bde2196Slisps        if (isset($urlParameters['rev']) && !$urlParameters['rev']) unset($urlParameters['rev']);
50664159a61SAndreas Gohr        if (isset($urlParameters['at']) && $conf['date_at_format']) {
50764159a61SAndreas Gohr            $urlParameters['at'] = date($conf['date_at_format'], $urlParameters['at']);
50864159a61SAndreas Gohr        }
50916f15a81SDominik Eckelmann        $urlParameters = buildURLparams($urlParameters, $separator);
5106de3759aSAndreas Gohr    } else {
51116f15a81SDominik Eckelmann        $urlParameters = str_replace(',', $separator, $urlParameters);
5126de3759aSAndreas Gohr    }
51316f15a81SDominik Eckelmann    if ($id === '') {
51416f15a81SDominik Eckelmann        $id = $conf['start'];
51516f15a81SDominik Eckelmann    }
516f3f0262cSandi    $id = idfilter($id);
51716f15a81SDominik Eckelmann    if ($absolute) {
518ed7b5f09Sandi        $xlink = DOKU_URL;
519ed7b5f09Sandi    } else {
520ed7b5f09Sandi        $xlink = DOKU_BASE;
521ed7b5f09Sandi    }
522f3f0262cSandi
5236c7843b5Sandi    if ($conf['userewrite'] == 2) {
5246c7843b5Sandi        $xlink .= DOKU_SCRIPT . '/' . $id;
52516f15a81SDominik Eckelmann        if ($urlParameters) $xlink .= '?' . $urlParameters;
5266c7843b5Sandi    } elseif ($conf['userewrite']) {
527f3f0262cSandi        $xlink .= $id;
52816f15a81SDominik Eckelmann        if ($urlParameters) $xlink .= '?' . $urlParameters;
52940b5fb5bSPhy    } elseif ($id !== '') {
5306c7843b5Sandi        $xlink .= DOKU_SCRIPT . '?id=' . $id;
53116f15a81SDominik Eckelmann        if ($urlParameters) $xlink .= $separator . $urlParameters;
532bce3726dSAndreas Gohr    } else {
533bce3726dSAndreas Gohr        $xlink .= DOKU_SCRIPT;
53416f15a81SDominik Eckelmann        if ($urlParameters) $xlink .= '?' . $urlParameters;
535f3f0262cSandi    }
536f3f0262cSandi
537f3f0262cSandi    return $xlink;
538f3f0262cSandi}
539f3f0262cSandi
540f3f0262cSandi/**
541f5c2808fSBen Coburn * This builds a link to an alternate page format
542f5c2808fSBen Coburn *
543f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
544f5c2808fSBen Coburn *
5454bc480e5SAndreas Gohr * @param string $id page id, defaults to start page
5464bc480e5SAndreas Gohr * @param string $format the export renderer to use
5474bc480e5SAndreas Gohr * @param string|array $urlParameters URL parameters, associative array recommended
5484bc480e5SAndreas Gohr * @param bool $abs request an absolute URL instead of relative
5494bc480e5SAndreas Gohr * @param string $sep parameter separator
5504bc480e5SAndreas Gohr * @return string
5518b19906eSAndreas Gohr * @author Ben Coburn <btcoburn@silicodon.net>
552f5c2808fSBen Coburn */
553d868eb89SAndreas Gohrfunction exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;')
554d868eb89SAndreas Gohr{
555f5c2808fSBen Coburn    global $conf;
5564bc480e5SAndreas Gohr    if (is_array($urlParameters)) {
5574bc480e5SAndreas Gohr        $urlParameters = buildURLparams($urlParameters, $sep);
558f5c2808fSBen Coburn    } else {
5594bc480e5SAndreas Gohr        $urlParameters = str_replace(',', $sep, $urlParameters);
560f5c2808fSBen Coburn    }
561f5c2808fSBen Coburn
562f5c2808fSBen Coburn    $format = rawurlencode($format);
563f5c2808fSBen Coburn    $id = idfilter($id);
564f5c2808fSBen Coburn    if ($abs) {
565f5c2808fSBen Coburn        $xlink = DOKU_URL;
566f5c2808fSBen Coburn    } else {
567f5c2808fSBen Coburn        $xlink = DOKU_BASE;
568f5c2808fSBen Coburn    }
569f5c2808fSBen Coburn
570f5c2808fSBen Coburn    if ($conf['userewrite'] == 2) {
571f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT . '/' . $id . '?do=export_' . $format;
5724bc480e5SAndreas Gohr        if ($urlParameters) $xlink .= $sep . $urlParameters;
573f5c2808fSBen Coburn    } elseif ($conf['userewrite'] == 1) {
574f5c2808fSBen Coburn        $xlink .= '_export/' . $format . '/' . $id;
5754bc480e5SAndreas Gohr        if ($urlParameters) $xlink .= '?' . $urlParameters;
576f5c2808fSBen Coburn    } else {
577f5c2808fSBen Coburn        $xlink .= DOKU_SCRIPT . '?do=export_' . $format . $sep . 'id=' . $id;
5784bc480e5SAndreas Gohr        if ($urlParameters) $xlink .= $sep . $urlParameters;
579f5c2808fSBen Coburn    }
580f5c2808fSBen Coburn
581f5c2808fSBen Coburn    return $xlink;
582f5c2808fSBen Coburn}
583f5c2808fSBen Coburn
584f5c2808fSBen Coburn/**
5856de3759aSAndreas Gohr * Build a link to a media file
5866de3759aSAndreas Gohr *
5876de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
5888c08db0aSAndreas Gohr *
5898c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
5908c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
5918c08db0aSAndreas Gohr *
5923272d797SAndreas Gohr * @param string $id the media file id or URL
5933272d797SAndreas Gohr * @param mixed $more string or array with additional parameters
5943272d797SAndreas Gohr * @param bool $direct link to detail page if false
5953272d797SAndreas Gohr * @param string $sep URL parameter separator
5963272d797SAndreas Gohr * @param bool $abs Create an absolute URL
5973272d797SAndreas Gohr * @return string
5986de3759aSAndreas Gohr */
599d868eb89SAndreas Gohrfunction ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false)
600d868eb89SAndreas Gohr{
6016de3759aSAndreas Gohr    global $conf;
602b9ee6a44SKlap-in    $isexternalimage = media_isexternal($id);
603826d2766SKlap-in    if (!$isexternalimage) {
604826d2766SKlap-in        $id = cleanID($id);
605826d2766SKlap-in    }
606826d2766SKlap-in
6076de3759aSAndreas Gohr    if (is_array($more)) {
6080f4e0092SChristopher Smith        // add token for resized images
60924870174SAndreas Gohr        $w = $more['w'] ?? null;
61024870174SAndreas Gohr        $h = $more['h'] ?? null;
61198fe1ac9SDamien Regad        if ($w || $h || $isexternalimage) {
612357c9a39SDamien Regad            $more['tok'] = media_get_token($id, $w, $h);
6130f4e0092SChristopher Smith        }
6148c08db0aSAndreas Gohr        // strip defaults for shorter URLs
6158c08db0aSAndreas Gohr        if (isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
616443e135dSChristopher Smith        if (empty($more['w'])) unset($more['w']);
617443e135dSChristopher Smith        if (empty($more['h'])) unset($more['h']);
6188c08db0aSAndreas Gohr        if (isset($more['id']) && $direct) unset($more['id']);
61978b874e6Slisps        if (isset($more['rev']) && !$more['rev']) unset($more['rev']);
620b174aeaeSchris        $more = buildURLparams($more, $sep);
6216de3759aSAndreas Gohr    } else {
62224870174SAndreas Gohr        $matches = [];
623cc036f74SKlap-in        if (preg_match_all('/\b(w|h)=(\d*)\b/', $more, $matches, PREG_SET_ORDER) || $isexternalimage) {
62424870174SAndreas Gohr            $resize = ['w' => 0, 'h' => 0];
6255e7db1e2SChristopher Smith            foreach ($matches as $match) {
6265e7db1e2SChristopher Smith                $resize[$match[1]] = $match[2];
6275e7db1e2SChristopher Smith            }
628cc036f74SKlap-in            $more .= $more === '' ? '' : $sep;
629cc036f74SKlap-in            $more .= 'tok=' . media_get_token($id, $resize['w'], $resize['h']);
6305e7db1e2SChristopher Smith        }
6318c08db0aSAndreas Gohr        $more = str_replace('cache=cache', '', $more); //skip default
6328c08db0aSAndreas Gohr        $more = str_replace(',,', ',', $more);
633b174aeaeSchris        $more = str_replace(',', $sep, $more);
6346de3759aSAndreas Gohr    }
6356de3759aSAndreas Gohr
63655b2b31bSAndreas Gohr    if ($abs) {
63755b2b31bSAndreas Gohr        $xlink = DOKU_URL;
63855b2b31bSAndreas Gohr    } else {
6396de3759aSAndreas Gohr        $xlink = DOKU_BASE;
64055b2b31bSAndreas Gohr    }
6416de3759aSAndreas Gohr
6426de3759aSAndreas Gohr    // external URLs are always direct without rewriting
643826d2766SKlap-in    if ($isexternalimage) {
6446de3759aSAndreas Gohr        $xlink .= 'lib/exe/fetch.php';
645cc036f74SKlap-in        $xlink .= '?' . $more;
646b174aeaeSchris        $xlink .= $sep . 'media=' . rawurlencode($id);
6476de3759aSAndreas Gohr        return $xlink;
6486de3759aSAndreas Gohr    }
6496de3759aSAndreas Gohr
6506de3759aSAndreas Gohr    $id = idfilter($id);
6516de3759aSAndreas Gohr
6526de3759aSAndreas Gohr    // decide on scriptname
6536de3759aSAndreas Gohr    if ($direct) {
6546de3759aSAndreas Gohr        if ($conf['userewrite'] == 1) {
6556de3759aSAndreas Gohr            $script = '_media';
6566de3759aSAndreas Gohr        } else {
6576de3759aSAndreas Gohr            $script = 'lib/exe/fetch.php';
6586de3759aSAndreas Gohr        }
65924870174SAndreas Gohr    } elseif ($conf['userewrite'] == 1) {
6606de3759aSAndreas Gohr        $script = '_detail';
6616de3759aSAndreas Gohr    } else {
6626de3759aSAndreas Gohr        $script = 'lib/exe/detail.php';
6636de3759aSAndreas Gohr    }
6646de3759aSAndreas Gohr
6656de3759aSAndreas Gohr    // build URL based on rewrite mode
6666de3759aSAndreas Gohr    if ($conf['userewrite']) {
6676de3759aSAndreas Gohr        $xlink .= $script . '/' . $id;
6686de3759aSAndreas Gohr        if ($more) $xlink .= '?' . $more;
66924870174SAndreas Gohr    } elseif ($more) {
670a99d3236SEsther Brunner        $xlink .= $script . '?' . $more;
671b174aeaeSchris        $xlink .= $sep . 'media=' . $id;
6726de3759aSAndreas Gohr    } else {
673a99d3236SEsther Brunner        $xlink .= $script . '?media=' . $id;
6746de3759aSAndreas Gohr    }
6756de3759aSAndreas Gohr
6766de3759aSAndreas Gohr    return $xlink;
6776de3759aSAndreas Gohr}
6786de3759aSAndreas Gohr
6796de3759aSAndreas Gohr/**
68025ca5b17SAndreas Gohr * Returns the URL to the DokuWiki base script
68115fae107Sandi *
68225ca5b17SAndreas Gohr * Consider using wl() instead, unless you absoutely need the doku.php endpoint
68325ca5b17SAndreas Gohr *
6848b19906eSAndreas Gohr * @return string
68515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
686140cfbcdSGerrit Uitslag *
687f3f0262cSandi */
688d868eb89SAndreas Gohrfunction script()
689d868eb89SAndreas Gohr{
690ed7b5f09Sandi    return DOKU_BASE . DOKU_SCRIPT;
691f3f0262cSandi}
692f3f0262cSandi
693f3f0262cSandi/**
69415fae107Sandi * Spamcheck against wordlist
69515fae107Sandi *
696f3f0262cSandi * Checks the wikitext against a list of blocked expressions
697f3f0262cSandi * returns true if the text contains any bad words
69815fae107Sandi *
699e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
700e403cc58SMichael Klier *
701e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
702e403cc58SMichael Klier *  and gain information about the user who was blocked.
703e403cc58SMichael Klier *
704e403cc58SMichael Klier *  Event data:
705e403cc58SMichael Klier *    data['matches']  - array of matches
706e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
707e403cc58SMichael Klier *      [ip]           - ip address
708e403cc58SMichael Klier *      [user]         - username (if logged in)
709e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
710e403cc58SMichael Klier *      [name]         - real name (if logged in)
711e403cc58SMichael Klier *
7128b19906eSAndreas Gohr * @param string $text - optional text to check, if not given the globals are used
7138b19906eSAndreas Gohr * @return bool         - true if a spam word was found
71415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
7156dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
716140cfbcdSGerrit Uitslag *
717f3f0262cSandi */
718d868eb89SAndreas Gohrfunction checkwordblock($text = '')
719d868eb89SAndreas Gohr{
720f3f0262cSandi    global $TEXT;
7216dffa0e0SAndreas Gohr    global $PRE;
7226dffa0e0SAndreas Gohr    global $SUF;
723e0086ca2SAndreas Gohr    global $SUM;
724f3f0262cSandi    global $conf;
725e403cc58SMichael Klier    global $INFO;
726585bf44eSChristopher Smith    /* @var Input $INPUT */
727585bf44eSChristopher Smith    global $INPUT;
728f3f0262cSandi
729f3f0262cSandi    if (!$conf['usewordblock']) return false;
730f3f0262cSandi
731e0086ca2SAndreas Gohr    if (!$text) $text = "$PRE $TEXT $SUF $SUM";
7326dffa0e0SAndreas Gohr
733041d1964SAndreas Gohr    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
73464159a61SAndreas Gohr    // phpcs:disable Generic.Files.LineLength.TooLong
73564159a61SAndreas Gohr    $text = preg_replace(
73664159a61SAndreas Gohr        '!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i',
73764159a61SAndreas Gohr        '\1http://\2 \2\3',
73864159a61SAndreas Gohr        $text
73964159a61SAndreas Gohr    );
74064159a61SAndreas Gohr    // phpcs:enable
741041d1964SAndreas Gohr
742b9ac8716Schris    $wordblocks = getWordblocks();
743a51d08efSAndreas Gohr    // read file in chunks of 200 - this should work around the
7443e2965d7Sandi    // MAX_PATTERN_SIZE in modern PCRE
745a51d08efSAndreas Gohr    $chunksize = 200;
74664259528SAndreas Gohr
747b9ac8716Schris    while ($blocks = array_splice($wordblocks, 0, $chunksize)) {
74824870174SAndreas Gohr        $re = [];
74949eb6e38SAndreas Gohr        // build regexp from blocks
750f3f0262cSandi        foreach ($blocks as $block) {
751f3f0262cSandi            $block = preg_replace('/#.*$/', '', $block);
752f3f0262cSandi            $block = trim($block);
753f3f0262cSandi            if (empty($block)) continue;
754f3f0262cSandi            $re[] = $block;
755f3f0262cSandi        }
75624870174SAndreas Gohr        if (count($re) && preg_match('#(' . implode('|', $re) . ')#si', $text, $matches)) {
757e403cc58SMichael Klier            // prepare event data
75824870174SAndreas Gohr            $data = [];
759e403cc58SMichael Klier            $data['matches'] = $matches;
760585bf44eSChristopher Smith            $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
761585bf44eSChristopher Smith            if ($INPUT->server->str('REMOTE_USER')) {
762585bf44eSChristopher Smith                $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
763e403cc58SMichael Klier                $data['userinfo']['name'] = $INFO['userinfo']['name'];
764e403cc58SMichael Klier                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
765e403cc58SMichael Klier            }
76624870174SAndreas Gohr            $callback = static fn() => true;
767cbb44eabSAndreas Gohr            return Event::createAndTrigger('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
768b9ac8716Schris        }
769703f6fdeSandi    }
770f3f0262cSandi    return false;
771f3f0262cSandi}
772f3f0262cSandi
773f3f0262cSandi/**
774a7580321SZebra North * Return the IP of the client.
77515fae107Sandi *
776a7580321SZebra North * The IP is sourced from, in order of preference:
77715fae107Sandi *
778*90c2f6e3SAndreas Gohr *   - The custom IP header if $conf[client_ip_header] is set.
779d5dd5d1bSAndreas Gohr *   - The X-Forwarded-For header if all the proxies are trusted by $conf[trustedproxies].
780a7580321SZebra North *   - The TCP/IP connection remote address.
781a7580321SZebra North *   - 0.0.0.0 if all else fails.
7826d8affe6SAndreas Gohr *
783*90c2f6e3SAndreas Gohr * The 'client_ip_header' config value should only be set if the header
784a7580321SZebra North * is being added by the web server, otherwise it may be spoofed by the client.
7858b19906eSAndreas Gohr *
786d5dd5d1bSAndreas Gohr * The 'trustedproxies' setting must not allow any IP, otherwise the X-Forwarded-For
787a7580321SZebra North * may be spoofed by the client.
788a7580321SZebra North *
789608cdefcSZebra North * @param bool $single If set only a single IP is returned.
790608cdefcSZebra North *
791a7580321SZebra North * @return string Returns an IP address if 'single' is true, or a comma-separated list
792a7580321SZebra North *                of IP addresses otherwise.
7932f828abfSAndreas Gohr * @author Zebra North <mrzebra@mrzebra.co.uk>
7942f828abfSAndreas Gohr *
795f3f0262cSandi */
7962f828abfSAndreas Gohrfunction clientIP($single = false)
7972f828abfSAndreas Gohr{
798a7580321SZebra North    // Return the first IP in single mode, or all the IPs.
79998b599a6Ssplitbrain    return $single ? Ip::clientIp() : implode(',', Ip::clientIps());
800f3f0262cSandi}
801f3f0262cSandi
802f3f0262cSandi/**
8031c548ebeSAndreas Gohr * Check if the browser is on a mobile device
8041c548ebeSAndreas Gohr *
8051c548ebeSAndreas Gohr * Adapted from the example code at url below
8061c548ebeSAndreas Gohr *
8071c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
808140cfbcdSGerrit Uitslag *
80964159a61SAndreas Gohr * @deprecated 2018-04-27 you probably want media queries instead anyway
810140cfbcdSGerrit Uitslag * @return bool if true, client is mobile browser; otherwise false
8111c548ebeSAndreas Gohr */
812d868eb89SAndreas Gohrfunction clientismobile()
813d868eb89SAndreas Gohr{
814585bf44eSChristopher Smith    /* @var Input $INPUT */
815585bf44eSChristopher Smith    global $INPUT;
8161c548ebeSAndreas Gohr
817585bf44eSChristopher Smith    if ($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
8181c548ebeSAndreas Gohr
819585bf44eSChristopher Smith    if (preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
8201c548ebeSAndreas Gohr
821585bf44eSChristopher Smith    if (!$INPUT->server->has('HTTP_USER_AGENT')) return false;
8221c548ebeSAndreas Gohr
82324870174SAndreas Gohr    $uamatches = implode(
82464159a61SAndreas Gohr        '|',
82564159a61SAndreas Gohr        [
82664159a61SAndreas Gohr            'midp', 'j2me', 'avantg', 'docomo', 'novarra', 'palmos', 'palmsource', '240x320', 'opwv',
82764159a61SAndreas Gohr            'chtml', 'pda', 'windows ce', 'mmp\/', 'blackberry', 'mib\/', 'symbian', 'wireless', 'nokia',
82864159a61SAndreas Gohr            'hand', 'mobi', 'phone', 'cdm', 'up\.b', 'audio', 'SIE\-', 'SEC\-', 'samsung', 'HTC', 'mot\-',
82964159a61SAndreas Gohr            'mitsu', 'sagem', 'sony', 'alcatel', 'lg', 'erics', 'vx', 'NEC', 'philips', 'mmm', 'xx',
83064159a61SAndreas Gohr            'panasonic', 'sharp', 'wap', 'sch', 'rover', 'pocket', 'benq', 'java', 'pt', 'pg', 'vox',
83164159a61SAndreas Gohr            'amoi', 'bird', 'compal', 'kg', 'voda', 'sany', 'kdd', 'dbt', 'sendo', 'sgh', 'gradi', 'jb',
83264159a61SAndreas Gohr            '\d\d\di', 'moto'
83364159a61SAndreas Gohr        ]
83464159a61SAndreas Gohr    );
8351c548ebeSAndreas Gohr
836585bf44eSChristopher Smith    if (preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
8371c548ebeSAndreas Gohr
8381c548ebeSAndreas Gohr    return false;
8391c548ebeSAndreas Gohr}
8401c548ebeSAndreas Gohr
8411c548ebeSAndreas Gohr/**
8426efc45a2SDmitry Katsubo * check if a given link is interwiki link
8436efc45a2SDmitry Katsubo *
8446efc45a2SDmitry Katsubo * @param string $link the link, e.g. "wiki>page"
8456efc45a2SDmitry Katsubo * @return bool
8466efc45a2SDmitry Katsubo */
847d868eb89SAndreas Gohrfunction link_isinterwiki($link)
848d868eb89SAndreas Gohr{
8496efc45a2SDmitry Katsubo    if (preg_match('/^[a-zA-Z0-9\.]+>/u', $link)) return true;
8506efc45a2SDmitry Katsubo    return false;
8516efc45a2SDmitry Katsubo}
8526efc45a2SDmitry Katsubo
8536efc45a2SDmitry Katsubo/**
85463211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
85563211f61SGlen Harris *
85622ef1e32SAndreas Gohr * If $conf['dnslookups'] is disabled it simply returns the input string
85722ef1e32SAndreas Gohr *
8583272d797SAndreas Gohr * @param string $ips comma separated list of IP addresses
8593272d797SAndreas Gohr * @return string a comma separated list of hostnames
8608b19906eSAndreas Gohr * @author Glen Harris <astfgl@iamnota.org>
8618b19906eSAndreas Gohr *
86263211f61SGlen Harris */
863d868eb89SAndreas Gohrfunction gethostsbyaddrs($ips)
864d868eb89SAndreas Gohr{
86522ef1e32SAndreas Gohr    global $conf;
86622ef1e32SAndreas Gohr    if (!$conf['dnslookups']) return $ips;
86722ef1e32SAndreas Gohr
86824870174SAndreas Gohr    $hosts = [];
86963211f61SGlen Harris    $ips = explode(',', $ips);
870551a720fSMichael Klier
871551a720fSMichael Klier    if (is_array($ips)) {
8723886270dSAndreas Gohr        foreach ($ips as $ip) {
873551a720fSMichael Klier            $hosts[] = gethostbyaddr(trim($ip));
87463211f61SGlen Harris        }
87524870174SAndreas Gohr        return implode(',', $hosts);
876551a720fSMichael Klier    } else {
877551a720fSMichael Klier        return gethostbyaddr(trim($ips));
878551a720fSMichael Klier    }
87963211f61SGlen Harris}
88063211f61SGlen Harris
88163211f61SGlen Harris/**
88215fae107Sandi * Checks if a given page is currently locked.
88315fae107Sandi *
884f3f0262cSandi * removes stale lockfiles
88515fae107Sandi *
886140cfbcdSGerrit Uitslag * @param string $id page id
887140cfbcdSGerrit Uitslag * @return bool page is locked?
8888b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
8898b19906eSAndreas Gohr *
890f3f0262cSandi */
891d868eb89SAndreas Gohrfunction checklock($id)
892d868eb89SAndreas Gohr{
893f3f0262cSandi    global $conf;
894585bf44eSChristopher Smith    /* @var Input $INPUT */
895585bf44eSChristopher Smith    global $INPUT;
896585bf44eSChristopher Smith
897c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
898f3f0262cSandi
899f3f0262cSandi    //no lockfile
90079e79377SAndreas Gohr    if (!file_exists($lock)) return false;
901f3f0262cSandi
902f3f0262cSandi    //lockfile expired
903f3f0262cSandi    if ((time() - filemtime($lock)) > $conf['locktime']) {
904d8186216SBen Coburn        @unlink($lock);
905f3f0262cSandi        return false;
906f3f0262cSandi    }
907f3f0262cSandi
908f3f0262cSandi    //my own lock
9095f21556dSDamien Regad    [$ip, $session] = sexplode("\n", io_readFile($lock), 2);
91024870174SAndreas Gohr    if ($ip == $INPUT->server->str('REMOTE_USER') || (session_id() && $session === session_id())) {
911f3f0262cSandi        return false;
912f3f0262cSandi    }
913f3f0262cSandi
914f3f0262cSandi    return $ip;
915f3f0262cSandi}
916f3f0262cSandi
917f3f0262cSandi/**
91815fae107Sandi * Lock a page for editing
91915fae107Sandi *
9208b19906eSAndreas Gohr * @param string $id page id to lock
92115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
922140cfbcdSGerrit Uitslag *
923f3f0262cSandi */
924d868eb89SAndreas Gohrfunction lock($id)
925d868eb89SAndreas Gohr{
926544ed901SDaniel Calviño Sánchez    global $conf;
927585bf44eSChristopher Smith    /* @var Input $INPUT */
928585bf44eSChristopher Smith    global $INPUT;
929544ed901SDaniel Calviño Sánchez
930544ed901SDaniel Calviño Sánchez    if ($conf['locktime'] == 0) {
931544ed901SDaniel Calviño Sánchez        return;
932544ed901SDaniel Calviño Sánchez    }
933544ed901SDaniel Calviño Sánchez
934c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
935585bf44eSChristopher Smith    if ($INPUT->server->str('REMOTE_USER')) {
936585bf44eSChristopher Smith        io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
937f3f0262cSandi    } else {
93885fef7e2SAndreas Gohr        io_saveFile($lock, clientIP() . "\n" . session_id());
939f3f0262cSandi    }
940f3f0262cSandi}
941f3f0262cSandi
942f3f0262cSandi/**
94315fae107Sandi * Unlock a page if it was locked by the user
944f3f0262cSandi *
9453272d797SAndreas Gohr * @param string $id page id to unlock
94615fae107Sandi * @return bool true if a lock was removed
9478b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
9488b19906eSAndreas Gohr *
949f3f0262cSandi */
950d868eb89SAndreas Gohrfunction unlock($id)
951d868eb89SAndreas Gohr{
952585bf44eSChristopher Smith    /* @var Input $INPUT */
953585bf44eSChristopher Smith    global $INPUT;
954585bf44eSChristopher Smith
955c9b4bd1eSBen Coburn    $lock = wikiLockFN($id);
95679e79377SAndreas Gohr    if (file_exists($lock)) {
95724870174SAndreas Gohr        @[$ip, $session] = explode("\n", io_readFile($lock));
958c0dd3914SAdaKaleh        if ($ip == $INPUT->server->str('REMOTE_USER') || $session == session_id()) {
959f3f0262cSandi            @unlink($lock);
960f3f0262cSandi            return true;
961f3f0262cSandi        }
962f3f0262cSandi    }
963f3f0262cSandi    return false;
964f3f0262cSandi}
965f3f0262cSandi
966f3f0262cSandi/**
967f3f0262cSandi * convert line ending to unix format
968f3f0262cSandi *
9696db7468bSAndreas Gohr * also makes sure the given text is valid UTF-8
9706db7468bSAndreas Gohr *
9718b19906eSAndreas Gohr * @param string $text
9728b19906eSAndreas Gohr * @return string
97315fae107Sandi * @see    formText() for 2crlf conversion
97415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
975140cfbcdSGerrit Uitslag *
976f3f0262cSandi */
977d868eb89SAndreas Gohrfunction cleanText($text)
978d868eb89SAndreas Gohr{
979f3f0262cSandi    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
9806db7468bSAndreas Gohr
9816db7468bSAndreas Gohr    // if the text is not valid UTF-8 we simply assume latin1
9826db7468bSAndreas Gohr    // this won't break any worse than it breaks with the wrong encoding
9836db7468bSAndreas Gohr    // but might actually fix the problem in many cases
98453c68e5cSAndreas Gohr    if (!Clean::isUtf8($text)) $text = Conversion::fromLatin1($text);
9856db7468bSAndreas Gohr
986f3f0262cSandi    return $text;
987f3f0262cSandi}
988f3f0262cSandi
989f3f0262cSandi/**
990f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
991f3f0262cSandi * It also converts line endings to Windows format which is
992f3f0262cSandi * pseudo standard for webforms.
993f3f0262cSandi *
9948b19906eSAndreas Gohr * @param string $text
9958b19906eSAndreas Gohr * @return string
99615fae107Sandi * @see    cleanText() for 2unix conversion
99715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
998140cfbcdSGerrit Uitslag *
999f3f0262cSandi */
1000d868eb89SAndreas Gohrfunction formText($text)
1001d868eb89SAndreas Gohr{
1002a46a37efSAndreas Gohr    $text = str_replace("\012", "\015\012", $text ?? '');
1003f3f0262cSandi    return htmlspecialchars($text);
1004f3f0262cSandi}
1005f3f0262cSandi
1006f3f0262cSandi/**
100715fae107Sandi * Returns the specified local text in raw format
100815fae107Sandi *
1009140cfbcdSGerrit Uitslag * @param string $id page id
1010140cfbcdSGerrit Uitslag * @param string $ext extension of file being read, default 'txt'
1011140cfbcdSGerrit Uitslag * @return string
10128b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10138b19906eSAndreas Gohr *
1014f3f0262cSandi */
1015d868eb89SAndreas Gohrfunction rawLocale($id, $ext = 'txt')
1016d868eb89SAndreas Gohr{
10172adaf2b8SAndreas Gohr    return io_readFile(localeFN($id, $ext));
1018f3f0262cSandi}
1019f3f0262cSandi
1020f3f0262cSandi/**
1021f3f0262cSandi * Returns the raw WikiText
102215fae107Sandi *
1023140cfbcdSGerrit Uitslag * @param string $id page id
1024e0c26282SGerrit Uitslag * @param string|int $rev timestamp when a revision of wikitext is desired
1025140cfbcdSGerrit Uitslag * @return string
10268b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10278b19906eSAndreas Gohr *
1028f3f0262cSandi */
1029d868eb89SAndreas Gohrfunction rawWiki($id, $rev = '')
1030d868eb89SAndreas Gohr{
1031cc7d0c94SBen Coburn    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1032f3f0262cSandi}
1033f3f0262cSandi
1034f3f0262cSandi/**
10357146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
10367146cee2SAndreas Gohr *
10377b84afa2SAndreas Gohr * @triggers COMMON_PAGETPL_LOAD
1038140cfbcdSGerrit Uitslag * @param string $id the id of the page to be created
1039140cfbcdSGerrit Uitslag * @return string parsed pagetemplate content
10408b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10418b19906eSAndreas Gohr *
10427146cee2SAndreas Gohr */
1043d868eb89SAndreas Gohrfunction pageTemplate($id)
1044d868eb89SAndreas Gohr{
1045a15ce62dSEsther Brunner    global $conf;
1046e29549feSAndreas Gohr
1047fe17917eSAdrian Lang    if (is_array($id)) $id = $id[0];
1048e29549feSAndreas Gohr
10497b84afa2SAndreas Gohr    // prepare initial event data
105024870174SAndreas Gohr    $data = [
10517b84afa2SAndreas Gohr        'id' => $id, // the id of the page to be created
10527b84afa2SAndreas Gohr        'tpl' => '', // the text used as template
10537b84afa2SAndreas Gohr        'tplfile' => '', // the file above text was/should be loaded from
105424870174SAndreas Gohr        'doreplace' => true,
105524870174SAndreas Gohr    ];
10567b84afa2SAndreas Gohr
1057e1d9dcc8SAndreas Gohr    $evt = new Event('COMMON_PAGETPL_LOAD', $data);
10587b84afa2SAndreas Gohr    if ($evt->advise_before(true)) {
10597b84afa2SAndreas Gohr        // the before event might have loaded the content already
10607b84afa2SAndreas Gohr        if (empty($data['tpl'])) {
10617b84afa2SAndreas Gohr            // if the before event did not set a template file, try to find one
10627b84afa2SAndreas Gohr            if (empty($data['tplfile'])) {
1063fe17917eSAdrian Lang                $path = dirname(wikiFN($id));
106479e79377SAndreas Gohr                if (file_exists($path . '/_template.txt')) {
10657b84afa2SAndreas Gohr                    $data['tplfile'] = $path . '/_template.txt';
1066e29549feSAndreas Gohr                } else {
1067e29549feSAndreas Gohr                    // search upper namespaces for templates
1068e29549feSAndreas Gohr                    $len = strlen(rtrim($conf['datadir'], '/'));
1069e29549feSAndreas Gohr                    while (strlen($path) >= $len) {
107079e79377SAndreas Gohr                        if (file_exists($path . '/__template.txt')) {
10717b84afa2SAndreas Gohr                            $data['tplfile'] = $path . '/__template.txt';
1072e29549feSAndreas Gohr                            break;
1073e29549feSAndreas Gohr                        }
1074e29549feSAndreas Gohr                        $path = substr($path, 0, strrpos($path, '/'));
1075e29549feSAndreas Gohr                    }
1076e29549feSAndreas Gohr                }
10777b84afa2SAndreas Gohr            }
10787b84afa2SAndreas Gohr            // load the content
10793d7ac595SMichael Hamann            $data['tpl'] = io_readFile($data['tplfile']);
10807b84afa2SAndreas Gohr        }
1081a1bbd05bSMichael Hamann        if ($data['doreplace']) parsePageTemplate($data);
10827b84afa2SAndreas Gohr    }
10837b84afa2SAndreas Gohr    $evt->advise_after();
10847b84afa2SAndreas Gohr    unset($evt);
10857b84afa2SAndreas Gohr
1086fe17917eSAdrian Lang    return $data['tpl'];
10872b1223ecSAdrian Lang}
10882b1223ecSAdrian Lang
10892b1223ecSAdrian Lang/**
10902b1223ecSAdrian Lang * Performs common page template replacements
10917b84afa2SAndreas Gohr * This works on data from COMMON_PAGETPL_LOAD
10922b1223ecSAdrian Lang *
1093140cfbcdSGerrit Uitslag * @param array $data array with event data
1094140cfbcdSGerrit Uitslag * @return string
10958b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
10968b19906eSAndreas Gohr *
10972b1223ecSAdrian Lang */
1098d868eb89SAndreas Gohrfunction parsePageTemplate(&$data)
1099d868eb89SAndreas Gohr{
11003272d797SAndreas Gohr    /**
11013272d797SAndreas Gohr     * @var string $id the id of the page to be created
11023272d797SAndreas Gohr     * @var string $tpl the text used as template
11033272d797SAndreas Gohr     * @var string $tplfile the file above text was/should be loaded from
11043272d797SAndreas Gohr     * @var bool $doreplace should wildcard replacements be done on the text?
11053272d797SAndreas Gohr     */
1106fe17917eSAdrian Lang    extract($data);
1107fe17917eSAdrian Lang
1108b856f7dfSAdrian Lang    global $USERINFO;
1109bce53b1fSAdrian Lang    global $conf;
1110585bf44eSChristopher Smith    /* @var Input $INPUT */
1111585bf44eSChristopher Smith    global $INPUT;
1112e29549feSAndreas Gohr
1113e29549feSAndreas Gohr    // replace placeholders
111426ece5a7SAndreas Gohr    $file = noNS($id);
111537c1acbdSAdrian Lang    $page = strtr($file, $conf['sepchar'], ' ');
111626ece5a7SAndreas Gohr
11173272d797SAndreas Gohr    $tpl = str_replace(
111824870174SAndreas Gohr        [
111926ece5a7SAndreas Gohr            '@ID@',
112026ece5a7SAndreas Gohr            '@NS@',
11218a7bcf66SShota Miyazaki            '@CURNS@',
1122a3db0ab0SSimon Lees            '@!CURNS@',
1123a3db0ab0SSimon Lees            '@!!CURNS@',
1124a3db0ab0SSimon Lees            '@!CURNS!@',
112526ece5a7SAndreas Gohr            '@FILE@',
112626ece5a7SAndreas Gohr            '@!FILE@',
112726ece5a7SAndreas Gohr            '@!FILE!@',
112826ece5a7SAndreas Gohr            '@PAGE@',
112926ece5a7SAndreas Gohr            '@!PAGE@',
113026ece5a7SAndreas Gohr            '@!!PAGE@',
113126ece5a7SAndreas Gohr            '@!PAGE!@',
113226ece5a7SAndreas Gohr            '@USER@',
113326ece5a7SAndreas Gohr            '@NAME@',
113426ece5a7SAndreas Gohr            '@MAIL@',
113524870174SAndreas Gohr            '@DATE@'
113624870174SAndreas Gohr        ],
113724870174SAndreas Gohr        [
113826ece5a7SAndreas Gohr            $id,
113926ece5a7SAndreas Gohr            getNS($id),
11408a7bcf66SShota Miyazaki            curNS($id),
114124870174SAndreas Gohr            PhpString::ucfirst(curNS($id)),
114224870174SAndreas Gohr            PhpString::ucwords(curNS($id)),
114324870174SAndreas Gohr            PhpString::strtoupper(curNS($id)),
114426ece5a7SAndreas Gohr            $file,
114524870174SAndreas Gohr            PhpString::ucfirst($file),
114624870174SAndreas Gohr            PhpString::strtoupper($file),
114726ece5a7SAndreas Gohr            $page,
114824870174SAndreas Gohr            PhpString::ucfirst($page),
114924870174SAndreas Gohr            PhpString::ucwords($page),
115024870174SAndreas Gohr            PhpString::strtoupper($page),
1151585bf44eSChristopher Smith            $INPUT->server->str('REMOTE_USER'),
11523e9ae63dSPhy            $USERINFO ? $USERINFO['name'] : '',
11533e9ae63dSPhy            $USERINFO ? $USERINFO['mail'] : '',
115424870174SAndreas Gohr            $conf['dformat']
115524870174SAndreas Gohr        ],
115624870174SAndreas Gohr        $tpl
11573272d797SAndreas Gohr    );
115826ece5a7SAndreas Gohr
11597d644fc8SAndreas Gohr    // we need the callback to work around strftime's char limit
1160bad6fc0dSAndreas Gohr    $tpl = preg_replace_callback(
1161bad6fc0dSAndreas Gohr        '/%./',
116224870174SAndreas Gohr        static fn($m) => dformat(null, $m[0]),
1163bad6fc0dSAndreas Gohr        $tpl
1164bad6fc0dSAndreas Gohr    );
1165d535a2e9Sstretchyboy    $data['tpl'] = $tpl;
1166a15ce62dSEsther Brunner    return $tpl;
11677146cee2SAndreas Gohr}
11687146cee2SAndreas Gohr
11697146cee2SAndreas Gohr/**
117015fae107Sandi * Returns the raw Wiki Text in three slices.
117115fae107Sandi *
117215fae107Sandi * The range parameter needs to have the form "from-to"
117315cfe303Sandi * and gives the range of the section in bytes - no
117415cfe303Sandi * UTF-8 awareness is needed.
1175f3f0262cSandi * The returned order is prefix, section and suffix.
117615fae107Sandi *
1177140cfbcdSGerrit Uitslag * @param string $range in form "from-to"
1178140cfbcdSGerrit Uitslag * @param string $id page id
1179140cfbcdSGerrit Uitslag * @param string $rev optional, the revision timestamp
118042ea7f44SGerrit Uitslag * @return string[] with three slices
11818b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
11828b19906eSAndreas Gohr *
1183f3f0262cSandi */
1184d868eb89SAndreas Gohrfunction rawWikiSlices($range, $id, $rev = '')
1185d868eb89SAndreas Gohr{
1186cc7d0c94SBen Coburn    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1187f3f0262cSandi
118880fcb268SAdrian Lang    // Parse range
118924870174SAndreas Gohr    [$from, $to] = sexplode('-', $range, 2);
119080fcb268SAdrian Lang    // Make range zero-based, use defaults if marker is missing
119124870174SAndreas Gohr    $from = $from ? $from - 1 : (0);
119224870174SAndreas Gohr    $to = $to ? $to - 1 : (strlen($text));
119380fcb268SAdrian Lang
119424870174SAndreas Gohr    $slices = [];
119580fcb268SAdrian Lang    $slices[0] = substr($text, 0, $from);
119680fcb268SAdrian Lang    $slices[1] = substr($text, $from, $to - $from);
119715cfe303Sandi    $slices[2] = substr($text, $to);
1198f3f0262cSandi    return $slices;
1199f3f0262cSandi}
1200f3f0262cSandi
1201f3f0262cSandi/**
120215fae107Sandi * Joins wiki text slices
120315fae107Sandi *
120480fcb268SAdrian Lang * function to join the text slices.
1205f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
1206f3f0262cSandi * lines between sections if needed (used on saving).
120715fae107Sandi *
1208140cfbcdSGerrit Uitslag * @param string $pre prefix
1209140cfbcdSGerrit Uitslag * @param string $text text in the middle
1210140cfbcdSGerrit Uitslag * @param string $suf suffix
1211140cfbcdSGerrit Uitslag * @param bool $pretty add additional empty lines between sections
1212140cfbcdSGerrit Uitslag * @return string
12138b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
12148b19906eSAndreas Gohr *
1215f3f0262cSandi */
1216d868eb89SAndreas Gohrfunction con($pre, $text, $suf, $pretty = false)
1217d868eb89SAndreas Gohr{
1218f3f0262cSandi    if ($pretty) {
12197d34963bSAndreas Gohr        if (
12206c16a3a9Sfiwswe            $pre !== '' && !str_ends_with($pre, "\n") &&
12216c16a3a9Sfiwswe            !str_starts_with($text, "\n")
12223272d797SAndreas Gohr        ) {
122380fcb268SAdrian Lang            $pre .= "\n";
122480fcb268SAdrian Lang        }
12257d34963bSAndreas Gohr        if (
12266c16a3a9Sfiwswe            $suf !== '' && !str_ends_with($text, "\n") &&
12276c16a3a9Sfiwswe            !str_starts_with($suf, "\n")
12283272d797SAndreas Gohr        ) {
122980fcb268SAdrian Lang            $text .= "\n";
123080fcb268SAdrian Lang        }
1231f3f0262cSandi    }
1232f3f0262cSandi
1233f3f0262cSandi    return $pre . $text . $suf;
1234f3f0262cSandi}
1235f3f0262cSandi
1236f3f0262cSandi/**
1237b24d9195SAndreas Gohr * Checks if the current page version is newer than the last entry in the page's
1238b24d9195SAndreas Gohr * changelog. If so, we assume it has been an external edit and we create an
1239b24d9195SAndreas Gohr * attic copy and add a proper changelog line.
1240b24d9195SAndreas Gohr *
1241b24d9195SAndreas Gohr * This check is only executed when the page is about to be saved again from the
12428b19906eSAndreas Gohr * wiki, triggered in @param string $id the page ID
12438b19906eSAndreas Gohr * @see saveWikiText()
1244b24d9195SAndreas Gohr *
124569f9b481SSatoshi Sahara * @deprecated 2021-11-28
1246b24d9195SAndreas Gohr */
1247d868eb89SAndreas Gohrfunction detectExternalEdit($id)
1248d868eb89SAndreas Gohr{
124979a2d784SGerrit Uitslag    dbg_deprecated(PageFile::class . '::detectExternalEdit()');
1250b24e9c4aSSatoshi Sahara    (new PageFile($id))->detectExternalEdit();
1251b24d9195SAndreas Gohr}
1252b24d9195SAndreas Gohr
1253b24d9195SAndreas Gohr/**
1254a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
1255a701424fSBen Coburn * Also directs changelog and attic updates.
125615fae107Sandi *
1257140cfbcdSGerrit Uitslag * @param string $id page id
1258140cfbcdSGerrit Uitslag * @param string $text wikitext being saved
1259140cfbcdSGerrit Uitslag * @param string $summary summary of text update
1260140cfbcdSGerrit Uitslag * @param bool $minor mark this saved version as minor update
12618b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
12628b19906eSAndreas Gohr * @author Ben Coburn <btcoburn@silicodon.net>
12638b19906eSAndreas Gohr *
1264f3f0262cSandi */
1265d868eb89SAndreas Gohrfunction saveWikiText($id, $text, $summary, $minor = false)
1266d868eb89SAndreas Gohr{
1267585bf44eSChristopher Smith
1268b24e9c4aSSatoshi Sahara    // get COMMON_WIKIPAGE_SAVE event data
1269b24e9c4aSSatoshi Sahara    $data = (new PageFile($id))->saveWikiText($text, $summary, $minor);
1270a577fbc2SAndreas Gohr    if (!$data) return; // save was cancelled (for no changes or by a plugin)
1271ac3ed4afSGerrit Uitslag
127226a0801fSAndreas Gohr    // send notify mails
127324870174SAndreas Gohr    ['oldRevision' => $rev, 'newRevision' => $new_rev, 'summary' => $summary] = $data;
12743b813d43SSatoshi Sahara    notify($id, 'admin', $rev, $summary, $minor, $new_rev);
12753b813d43SSatoshi Sahara    notify($id, 'subscribers', $rev, $summary, $minor, $new_rev);
1276f3f0262cSandi
12772eccbdaaSGina Haeussge    // if useheading is enabled, purge the cache of all linking pages
1278fe9ec250SChris Smith    if (useHeading('content')) {
127907ff0babSMichael Hamann        $pages = ft_backlinks($id, true);
12802eccbdaaSGina Haeussge        foreach ($pages as $page) {
12810db5771eSMichael Große            $cache = new CacheRenderer($page, wikiFN($page), 'xhtml');
12822eccbdaaSGina Haeussge            $cache->removeCache();
12832eccbdaaSGina Haeussge        }
12842eccbdaaSGina Haeussge    }
1285f3f0262cSandi}
1286f3f0262cSandi
1287f3f0262cSandi/**
1288d5824ab9SSatoshi Sahara * moves the current version to the attic and returns its revision date
128915fae107Sandi *
1290140cfbcdSGerrit Uitslag * @param string $id page id
1291140cfbcdSGerrit Uitslag * @return int|string revision timestamp
12928b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
12938b19906eSAndreas Gohr *
129469f9b481SSatoshi Sahara * @deprecated 2021-11-28
1295f3f0262cSandi */
1296d868eb89SAndreas Gohrfunction saveOldRevision($id)
1297d868eb89SAndreas Gohr{
129879a2d784SGerrit Uitslag    dbg_deprecated(PageFile::class . '::saveOldRevision()');
1299b24e9c4aSSatoshi Sahara    return (new PageFile($id))->saveOldRevision();
1300f3f0262cSandi}
1301f3f0262cSandi
1302f3f0262cSandi/**
1303fde10de4SAdrian Lang * Sends a notify mail on page change or registration
130426a0801fSAndreas Gohr *
130526a0801fSAndreas Gohr * @param string $id The changed page
1306fde10de4SAdrian Lang * @param string $who Who to notify (admin|subscribers|register)
13073272d797SAndreas Gohr * @param int|string $rev Old page revision
130826a0801fSAndreas Gohr * @param string $summary What changed
130990033e9dSAndreas Gohr * @param boolean $minor Is this a minor edit?
131042ea7f44SGerrit Uitslag * @param string[] $replace Additional string substitutions, @KEY@ to be replaced by value
131183734cddSPhy * @param int|string $current_rev New page revision
13123272d797SAndreas Gohr * @return bool
1313140cfbcdSGerrit Uitslag *
131415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1315f3f0262cSandi */
1316d868eb89SAndreas Gohrfunction notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = [], $current_rev = false)
1317d868eb89SAndreas Gohr{
1318f3f0262cSandi    global $conf;
1319585bf44eSChristopher Smith    /* @var Input $INPUT */
1320585bf44eSChristopher Smith    global $INPUT;
1321b158d625SSteven Danz
13226df843eeSAndreas Gohr    // decide if there is something to do, eg. whom to mail
132326a0801fSAndreas Gohr    if ($who == 'admin') {
13243272d797SAndreas Gohr        if (empty($conf['notify'])) return false; //notify enabled?
13252ed38036SAndreas Gohr        $tpl = 'mailtext';
132626a0801fSAndreas Gohr        $to = $conf['notify'];
132726a0801fSAndreas Gohr    } elseif ($who == 'subscribers') {
132884c1127cSAndreas Gohr        if (!actionOK('subscribe')) return false; //subscribers enabled?
1329585bf44eSChristopher Smith        if ($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
133024870174SAndreas Gohr        $data = ['id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace];
1331cbb44eabSAndreas Gohr        Event::createAndTrigger(
1332dccd6b2bSAndreas Gohr            'COMMON_NOTIFY_ADDRESSLIST',
1333dccd6b2bSAndreas Gohr            $data,
133424870174SAndreas Gohr            [new SubscriberManager(), 'notifyAddresses']
13353272d797SAndreas Gohr        );
13362ed38036SAndreas Gohr        $to = $data['addresslist'];
13372ed38036SAndreas Gohr        if (empty($to)) return false;
13382ed38036SAndreas Gohr        $tpl = 'subscr_single';
133926a0801fSAndreas Gohr    } else {
13403272d797SAndreas Gohr        return false; //just to be safe
134126a0801fSAndreas Gohr    }
134226a0801fSAndreas Gohr
13436df843eeSAndreas Gohr    // prepare content
1344704a815fSMichael Große    $subscription = new PageSubscriptionSender();
134583734cddSPhy    return $subscription->sendPageDiff($to, $tpl, $id, $rev, $summary, $current_rev);
1346f3f0262cSandi}
13472ed38036SAndreas Gohr
134815fae107Sandi/**
134971f7bde7SAndreas Gohr * extracts the query from a search engine referrer
135015fae107Sandi *
13518b19906eSAndreas Gohr * @return array|string
135271f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1353140cfbcdSGerrit Uitslag *
13548b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1355f3f0262cSandi */
1356d868eb89SAndreas Gohrfunction getGoogleQuery()
1357d868eb89SAndreas Gohr{
1358585bf44eSChristopher Smith    /* @var Input $INPUT */
1359585bf44eSChristopher Smith    global $INPUT;
1360585bf44eSChristopher Smith
1361585bf44eSChristopher Smith    if (!$INPUT->server->has('HTTP_REFERER')) {
1362c66972f2SAdrian Lang        return '';
1363c66972f2SAdrian Lang    }
1364585bf44eSChristopher Smith    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1365f3f0262cSandi
1366079b3ac1SAndreas Gohr    // only handle common SEs
1367c7875401SJyoti S    if (!array_key_exists('host', $url)) return '';
1368079b3ac1SAndreas Gohr    if (!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/', $url['host'])) return '';
1369e4d8a516SKazutaka Miyasaka
137024870174SAndreas Gohr    $query = [];
1371181adffeSJulian Jeggle    if (!array_key_exists('query', $url)) return '';
1372f3f0262cSandi    parse_str($url['query'], $query);
1373e4d8a516SKazutaka Miyasaka
1374c66972f2SAdrian Lang    $q = '';
1375079b3ac1SAndreas Gohr    if (isset($query['q'])) {
1376079b3ac1SAndreas Gohr        $q = $query['q'];
1377079b3ac1SAndreas Gohr    } elseif (isset($query['p'])) {
1378079b3ac1SAndreas Gohr        $q = $query['p'];
1379079b3ac1SAndreas Gohr    } elseif (isset($query['query'])) {
1380079b3ac1SAndreas Gohr        $q = $query['query'];
1381079b3ac1SAndreas Gohr    }
1382079b3ac1SAndreas Gohr    $q = trim($q);
1383f3f0262cSandi
1384079b3ac1SAndreas Gohr    if (!$q) return '';
1385c7dc833bSPhy    // ignore if query includes a full URL
1386093fe67eSAndreas Gohr    if (str_contains($q, '//')) return '';
13876531ab03SAndreas Gohr    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1388f93b3b50SAndreas Gohr    return $q;
1389f3f0262cSandi}
1390f3f0262cSandi
1391f3f0262cSandi/**
1392f3f0262cSandi * Return the human readable size of a file
1393f3f0262cSandi *
1394f3f0262cSandi * @param int $size A file size
1395f3f0262cSandi * @param int $dec A number of decimal places
139674160ca1SGerrit Uitslag * @return string human readable size
1397140cfbcdSGerrit Uitslag *
1398f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1399f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1400f3f0262cSandi * @version     1.0.0
1401f3f0262cSandi */
1402d868eb89SAndreas Gohrfunction filesize_h($size, $dec = 1)
1403d868eb89SAndreas Gohr{
140424870174SAndreas Gohr    $sizes = ['B', 'KB', 'MB', 'GB'];
1405f3f0262cSandi    $count = count($sizes);
1406f3f0262cSandi    $i = 0;
1407f3f0262cSandi
1408f3f0262cSandi    while ($size >= 1024 && ($i < $count - 1)) {
1409f3f0262cSandi        $size /= 1024;
1410f3f0262cSandi        $i++;
1411f3f0262cSandi    }
1412f3f0262cSandi
1413ef08383eSAndreas Gohr    return round($size, $dec) . "\xC2\xA0" . $sizes[$i]; //non-breaking space
1414f3f0262cSandi}
1415f3f0262cSandi
141615fae107Sandi/**
1417c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1418c57e365eSAndreas Gohr *
1419140cfbcdSGerrit Uitslag * @param int $dt timestamp
1420140cfbcdSGerrit Uitslag * @return string
14218b19906eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
14228b19906eSAndreas Gohr *
1423c57e365eSAndreas Gohr */
1424d868eb89SAndreas Gohrfunction datetime_h($dt)
1425d868eb89SAndreas Gohr{
1426c57e365eSAndreas Gohr    global $lang;
1427c57e365eSAndreas Gohr
1428c57e365eSAndreas Gohr    $ago = time() - $dt;
1429c57e365eSAndreas Gohr    if ($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1430c57e365eSAndreas Gohr        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1431c57e365eSAndreas Gohr    }
1432c57e365eSAndreas Gohr    if ($ago > 24 * 60 * 60 * 30 * 2) {
1433c57e365eSAndreas Gohr        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1434c57e365eSAndreas Gohr    }
1435c57e365eSAndreas Gohr    if ($ago > 24 * 60 * 60 * 7 * 2) {
1436c57e365eSAndreas Gohr        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1437c57e365eSAndreas Gohr    }
1438c57e365eSAndreas Gohr    if ($ago > 24 * 60 * 60 * 2) {
1439c57e365eSAndreas Gohr        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1440c57e365eSAndreas Gohr    }
1441c57e365eSAndreas Gohr    if ($ago > 60 * 60 * 2) {
1442c57e365eSAndreas Gohr        return sprintf($lang['hours'], round($ago / (60 * 60)));
1443c57e365eSAndreas Gohr    }
1444c57e365eSAndreas Gohr    if ($ago > 60 * 2) {
1445c57e365eSAndreas Gohr        return sprintf($lang['minutes'], round($ago / (60)));
1446c57e365eSAndreas Gohr    }
1447c57e365eSAndreas Gohr    return sprintf($lang['seconds'], $ago);
1448c57e365eSAndreas Gohr}
1449c57e365eSAndreas Gohr
1450c57e365eSAndreas Gohr/**
1451f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1452f2263577SAndreas Gohr *
1453f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1454f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1455f2263577SAndreas Gohr *
1456140cfbcdSGerrit Uitslag * @param int|null $dt timestamp when given, null will take current timestamp
1457140cfbcdSGerrit Uitslag * @param string $format empty default to $conf['dformat'], or provide format as recognized by strftime()
1458140cfbcdSGerrit Uitslag * @return string
14598b19906eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
14608b19906eSAndreas Gohr *
14618b19906eSAndreas Gohr * @see datetime_h
1462f2263577SAndreas Gohr */
1463d868eb89SAndreas Gohrfunction dformat($dt = null, $format = '')
1464d868eb89SAndreas Gohr{
1465f2263577SAndreas Gohr    global $conf;
1466f2263577SAndreas Gohr
1467f2263577SAndreas Gohr    if (is_null($dt)) $dt = time();
1468f2263577SAndreas Gohr    $dt = (int)$dt;
1469f2263577SAndreas Gohr    if (!$format) $format = $conf['dformat'];
1470f2263577SAndreas Gohr
1471f2263577SAndreas Gohr    $format = str_replace('%f', datetime_h($dt), $format);
1472b3894732Ssplitbrain    return strftime($format, $dt);
1473f2263577SAndreas Gohr}
1474f2263577SAndreas Gohr
1475f2263577SAndreas Gohr/**
1476c4f79b71SMichael Hamann * Formats a timestamp as ISO 8601 date
1477c4f79b71SMichael Hamann *
14788b19906eSAndreas Gohr * @param int $int_date current date in UNIX timestamp
14798b19906eSAndreas Gohr * @return string
1480c4f79b71SMichael Hamann * @author <ungu at terong dot com>
148159752844SAnders Sandblad * @link http://php.net/manual/en/function.date.php#54072
1482140cfbcdSGerrit Uitslag *
1483c4f79b71SMichael Hamann */
1484d868eb89SAndreas Gohrfunction date_iso8601($int_date)
1485d868eb89SAndreas Gohr{
1486c4f79b71SMichael Hamann    $date_mod = date('Y-m-d\TH:i:s', $int_date);
1487c4f79b71SMichael Hamann    $pre_timezone = date('O', $int_date);
1488c4f79b71SMichael Hamann    $time_zone = substr($pre_timezone, 0, 3) . ":" . substr($pre_timezone, 3, 2);
1489c4f79b71SMichael Hamann    $date_mod .= $time_zone;
1490c4f79b71SMichael Hamann    return $date_mod;
1491c4f79b71SMichael Hamann}
1492c4f79b71SMichael Hamann
1493c4f79b71SMichael Hamann/**
149400a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
149500a7b5adSEsther Brunner *
14968b19906eSAndreas Gohr * @param string $email email address
14978b19906eSAndreas Gohr * @return string
149800a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
149900a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
1500140cfbcdSGerrit Uitslag *
150100a7b5adSEsther Brunner */
1502d868eb89SAndreas Gohrfunction obfuscate($email)
1503d868eb89SAndreas Gohr{
150400a7b5adSEsther Brunner    global $conf;
150500a7b5adSEsther Brunner
150600a7b5adSEsther Brunner    switch ($conf['mailguard']) {
150700a7b5adSEsther Brunner        case 'visible':
150824870174SAndreas Gohr            $obfuscate = ['@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] '];
150900a7b5adSEsther Brunner            return strtr($email, $obfuscate);
151000a7b5adSEsther Brunner
151100a7b5adSEsther Brunner        case 'hex':
151224870174SAndreas Gohr            return Conversion::toHtml($email, true);
151300a7b5adSEsther Brunner
151400a7b5adSEsther Brunner        case 'none':
151500a7b5adSEsther Brunner        default:
151600a7b5adSEsther Brunner            return $email;
151700a7b5adSEsther Brunner    }
151800a7b5adSEsther Brunner}
151900a7b5adSEsther Brunner
152000a7b5adSEsther Brunner/**
152189541d4bSAndreas Gohr * Removes quoting backslashes
152289541d4bSAndreas Gohr *
1523140cfbcdSGerrit Uitslag * @param string $string
1524140cfbcdSGerrit Uitslag * @param string $char backslashed character
1525140cfbcdSGerrit Uitslag * @return string
15268b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
15278b19906eSAndreas Gohr *
152889541d4bSAndreas Gohr */
1529d868eb89SAndreas Gohrfunction unslash($string, $char = "'")
1530d868eb89SAndreas Gohr{
153189541d4bSAndreas Gohr    return str_replace('\\' . $char, $char, $string);
153289541d4bSAndreas Gohr}
153389541d4bSAndreas Gohr
153473038c47SAndreas Gohr/**
153573038c47SAndreas Gohr * Convert php.ini shorthands to byte
153673038c47SAndreas Gohr *
1537a81f3d99SAndreas Gohr * On 32 bit systems values >= 2GB will fail!
1538140cfbcdSGerrit Uitslag *
1539a81f3d99SAndreas Gohr * -1 (infinite size) will be reported as -1
1540a81f3d99SAndreas Gohr *
1541a81f3d99SAndreas Gohr * @link   https://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
1542a81f3d99SAndreas Gohr * @param string $value PHP size shorthand
1543a81f3d99SAndreas Gohr * @return int
154473038c47SAndreas Gohr */
1545d868eb89SAndreas Gohrfunction php_to_byte($value)
1546d868eb89SAndreas Gohr{
1547093fe67eSAndreas Gohr    $ret = match (strtoupper(substr($value, -1))) {
1548093fe67eSAndreas Gohr        'G' => (int)substr($value, 0, -1) * 1024 * 1024 * 1024,
1549093fe67eSAndreas Gohr        'M' => (int)substr($value, 0, -1) * 1024 * 1024,
1550093fe67eSAndreas Gohr        'K' => (int)substr($value, 0, -1) * 1024,
1551093fe67eSAndreas Gohr        default => (int)$value,
1552093fe67eSAndreas Gohr    };
155373038c47SAndreas Gohr    return $ret;
155473038c47SAndreas Gohr}
155573038c47SAndreas Gohr
1556546d3a99SAndreas Gohr/**
1557546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1558140cfbcdSGerrit Uitslag *
1559140cfbcdSGerrit Uitslag * @param string $string
1560140cfbcdSGerrit Uitslag * @return string
1561546d3a99SAndreas Gohr */
1562d868eb89SAndreas Gohrfunction preg_quote_cb($string)
1563d868eb89SAndreas Gohr{
1564546d3a99SAndreas Gohr    return preg_quote($string, '/');
1565546d3a99SAndreas Gohr}
156673038c47SAndreas Gohr
1567bd2f6c2fSAndreas Gohr/**
1568bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1569bd2f6c2fSAndreas Gohr *
1570c66972f2SAdrian Lang * You can give the string in two parts, the first part $keep
1571bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1572bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1573bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1574bd2f6c2fSAndreas Gohr *
1575bd2f6c2fSAndreas Gohr * @param string $keep the part to keep
1576bd2f6c2fSAndreas Gohr * @param string $short the part to shorten
1577bd2f6c2fSAndreas Gohr * @param int $max maximum chars you want for the whole string
1578bd2f6c2fSAndreas Gohr * @param int $min minimum number of chars to have left for middle shortening
1579bd2f6c2fSAndreas Gohr * @param string $char the shortening character to use
15803272d797SAndreas Gohr * @return string
1581bd2f6c2fSAndreas Gohr */
1582d868eb89SAndreas Gohrfunction shorten($keep, $short, $max, $min = 9, $char = '…')
1583d868eb89SAndreas Gohr{
158424870174SAndreas Gohr    $max -= PhpString::strlen($keep);
1585bd2f6c2fSAndreas Gohr    if ($max < $min) return $keep;
158624870174SAndreas Gohr    $len = PhpString::strlen($short);
1587bd2f6c2fSAndreas Gohr    if ($len <= $max) return $keep . $short;
1588bd2f6c2fSAndreas Gohr    $half = floor($max / 2);
15896ce3e5f8SAndreas Gohr    return $keep .
159024870174SAndreas Gohr        PhpString::substr($short, 0, $half - 1) .
15916ce3e5f8SAndreas Gohr        $char .
159224870174SAndreas Gohr        PhpString::substr($short, $len - $half);
1593bd2f6c2fSAndreas Gohr}
1594bd2f6c2fSAndreas Gohr
1595dc58b6f4SAndy Webber/**
1596dc58b6f4SAndy Webber * Return the users real name or e-mail address for use
1597dc58b6f4SAndy Webber * in page footer and recent changes pages
1598dc58b6f4SAndy Webber *
1599b4b6c9a1SGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
160015f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1601c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
160215f3bc49SGerrit Uitslag *
1603dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1604dc58b6f4SAndy Webber */
1605d868eb89SAndreas Gohrfunction editorinfo($username, $textonly = false)
1606d868eb89SAndreas Gohr{
1607cd4635eeSGerrit Uitslag    return userlink($username, $textonly);
1608dc58b6f4SAndy Webber}
1609dc58b6f4SAndy Webber
161060a396c8SGerrit Uitslag/**
161160a396c8SGerrit Uitslag * Returns users realname w/o link
161260a396c8SGerrit Uitslag *
1613f168548cSGerrit Uitslag * @param string|null $username or null when currently logged-in user should be used
161415f3bc49SGerrit Uitslag * @param bool $textonly true returns only plain text, true allows returning html
1615c0953023SGerrit Uitslag * @return string html or plain text(not escaped) of formatted user name
161660a396c8SGerrit Uitslag *
161760a396c8SGerrit Uitslag * @triggers COMMON_USER_LINK
161860a396c8SGerrit Uitslag */
1619d868eb89SAndreas Gohrfunction userlink($username = null, $textonly = false)
1620d868eb89SAndreas Gohr{
162160a396c8SGerrit Uitslag    global $conf, $INFO;
1622e1d9dcc8SAndreas Gohr    /** @var AuthPlugin $auth */
162360a396c8SGerrit Uitslag    global $auth;
162430f6ec4bSGerrit Uitslag    /** @var Input $INPUT */
162530f6ec4bSGerrit Uitslag    global $INPUT;
162660a396c8SGerrit Uitslag
162760a396c8SGerrit Uitslag    // prepare initial event data
162824870174SAndreas Gohr    $data = [
162960a396c8SGerrit Uitslag        'username' => $username, // the unique user name
163060a396c8SGerrit Uitslag        'name' => '',
163124870174SAndreas Gohr        'link' => [
163224870174SAndreas Gohr            //setting 'link' to false disables linking
163360a396c8SGerrit Uitslag            'target' => '',
163460a396c8SGerrit Uitslag            'pre' => '',
163560a396c8SGerrit Uitslag            'suf' => '',
163660a396c8SGerrit Uitslag            'style' => '',
163760a396c8SGerrit Uitslag            'more' => '',
163860a396c8SGerrit Uitslag            'url' => '',
163960a396c8SGerrit Uitslag            'title' => '',
164024870174SAndreas Gohr            'class' => '',
164124870174SAndreas Gohr        ],
16424d5fc927SGerrit Uitslag        'userlink' => '', // formatted user name as will be returned
164324870174SAndreas Gohr        'textonly' => $textonly,
164424870174SAndreas Gohr    ];
164562c8004eSGerrit Uitslag    if ($username === null) {
164630f6ec4bSGerrit Uitslag        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
164715f3bc49SGerrit Uitslag        if ($textonly) {
164815f3bc49SGerrit Uitslag            $data['name'] = $INFO['userinfo']['name'] . ' (' . $INPUT->server->str('REMOTE_USER') . ')';
164915f3bc49SGerrit Uitslag        } else {
165064159a61SAndreas Gohr            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> ' .
165164159a61SAndreas Gohr                '(<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
165260a396c8SGerrit Uitslag        }
165315f3bc49SGerrit Uitslag    }
165460a396c8SGerrit Uitslag
1655e1d9dcc8SAndreas Gohr    $evt = new Event('COMMON_USER_LINK', $data);
165660a396c8SGerrit Uitslag    if ($evt->advise_before(true)) {
165760a396c8SGerrit Uitslag        if (empty($data['name'])) {
16586547cfc7SGerrit Uitslag            if ($auth instanceof AuthPlugin) {
16596547cfc7SGerrit Uitslag                $info = $auth->getUserData($username);
16606547cfc7SGerrit Uitslag            }
166165833968SGerrit Uitslag            if ($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1662dc58b6f4SAndy Webber                switch ($conf['showuseras']) {
1663dc58b6f4SAndy Webber                    case 'username':
16647f081821SGerrit Uitslag                    case 'username_link':
166515f3bc49SGerrit Uitslag                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
166660a396c8SGerrit Uitslag                        break;
1667dc58b6f4SAndy Webber                    case 'email':
1668dc58b6f4SAndy Webber                    case 'email_link':
166960a396c8SGerrit Uitslag                        $data['name'] = obfuscate($info['mail']);
167060a396c8SGerrit Uitslag                        break;
1671dc58b6f4SAndy Webber                }
167265833968SGerrit Uitslag            } else {
167365833968SGerrit Uitslag                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
167460a396c8SGerrit Uitslag            }
167560a396c8SGerrit Uitslag        }
16767f081821SGerrit Uitslag
16777f081821SGerrit Uitslag        /** @var Doku_Renderer_xhtml $xhtml_renderer */
16787f081821SGerrit Uitslag        static $xhtml_renderer = null;
16797f081821SGerrit Uitslag
168015f3bc49SGerrit Uitslag        if (!$data['textonly'] && empty($data['link']['url'])) {
168124870174SAndreas Gohr            if (in_array($conf['showuseras'], ['email_link', 'username_link'])) {
16826547cfc7SGerrit Uitslag                if (!isset($info) && $auth instanceof AuthPlugin) {
16836547cfc7SGerrit Uitslag                    $info = $auth->getUserData($username);
168460a396c8SGerrit Uitslag                }
168560a396c8SGerrit Uitslag                if (isset($info) && $info) {
16867f081821SGerrit Uitslag                    if ($conf['showuseras'] == 'email_link') {
168760a396c8SGerrit Uitslag                        $data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
1688dc58b6f4SAndy Webber                    } else {
16897f081821SGerrit Uitslag                        if (is_null($xhtml_renderer)) {
16907f081821SGerrit Uitslag                            $xhtml_renderer = p_get_renderer('xhtml');
16917f081821SGerrit Uitslag                        }
16928407f251Ssplitbrain                        if ($xhtml_renderer->interwiki === []) {
16937f081821SGerrit Uitslag                            $xhtml_renderer->interwiki = getInterwiki();
16947f081821SGerrit Uitslag                        }
16957f081821SGerrit Uitslag                        $shortcut = 'user';
1696533772e1SGerrit Uitslag                        $exists = null;
16976496c33fSGerrit Uitslag                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
16982a2a43c4SGerrit Uitslag                        $data['link']['class'] .= ' interwiki iw_user';
16996496c33fSGerrit Uitslag                        if ($exists !== null) {
17006496c33fSGerrit Uitslag                            if ($exists) {
17016496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink1';
17026496c33fSGerrit Uitslag                            } else {
17036496c33fSGerrit Uitslag                                $data['link']['class'] .= ' wikilink2';
17046496c33fSGerrit Uitslag                                $data['link']['rel'] = 'nofollow';
17056496c33fSGerrit Uitslag                            }
17066496c33fSGerrit Uitslag                        }
1707dc58b6f4SAndy Webber                    }
1708dc58b6f4SAndy Webber                } else {
170915f3bc49SGerrit Uitslag                    $data['textonly'] = true;
1710dc58b6f4SAndy Webber                }
171160a396c8SGerrit Uitslag            } else {
171215f3bc49SGerrit Uitslag                $data['textonly'] = true;
171360a396c8SGerrit Uitslag            }
171460a396c8SGerrit Uitslag        }
171560a396c8SGerrit Uitslag
171615f3bc49SGerrit Uitslag        if ($data['textonly']) {
17174d5fc927SGerrit Uitslag            $data['userlink'] = $data['name'];
171860a396c8SGerrit Uitslag        } else {
171960a396c8SGerrit Uitslag            $data['link']['name'] = $data['name'];
172060a396c8SGerrit Uitslag            if (is_null($xhtml_renderer)) {
172160a396c8SGerrit Uitslag                $xhtml_renderer = p_get_renderer('xhtml');
172260a396c8SGerrit Uitslag            }
17234d5fc927SGerrit Uitslag            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
172460a396c8SGerrit Uitslag        }
172560a396c8SGerrit Uitslag    }
172660a396c8SGerrit Uitslag    $evt->advise_after();
172760a396c8SGerrit Uitslag    unset($evt);
172860a396c8SGerrit Uitslag
17294d5fc927SGerrit Uitslag    return $data['userlink'];
1730066fee30SAndreas Gohr}
1731066fee30SAndreas Gohr
1732066fee30SAndreas Gohr/**
1733066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1734066fee30SAndreas Gohr * When no image exists, returns an empty string
1735066fee30SAndreas Gohr *
1736066fee30SAndreas Gohr * @param string $type - type of image 'badge' or 'button'
17373272d797SAndreas Gohr * @return string
17388b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
17398b19906eSAndreas Gohr *
1740066fee30SAndreas Gohr */
1741d868eb89SAndreas Gohrfunction license_img($type)
1742d868eb89SAndreas Gohr{
1743066fee30SAndreas Gohr    global $license;
1744066fee30SAndreas Gohr    global $conf;
1745066fee30SAndreas Gohr    if (!$conf['license']) return '';
1746066fee30SAndreas Gohr    if (!is_array($license[$conf['license']])) return '';
174724870174SAndreas Gohr    $try = [];
1748066fee30SAndreas Gohr    $try[] = 'lib/images/license/' . $type . '/' . $conf['license'] . '.png';
1749066fee30SAndreas Gohr    $try[] = 'lib/images/license/' . $type . '/' . $conf['license'] . '.gif';
17506c16a3a9Sfiwswe    if (str_starts_with($conf['license'], 'cc-')) {
1751066fee30SAndreas Gohr        $try[] = 'lib/images/license/' . $type . '/cc.png';
1752066fee30SAndreas Gohr    }
1753066fee30SAndreas Gohr    foreach ($try as $src) {
175479e79377SAndreas Gohr        if (file_exists(DOKU_INC . $src)) return $src;
1755066fee30SAndreas Gohr    }
1756066fee30SAndreas Gohr    return '';
1757dc58b6f4SAndy Webber}
1758dc58b6f4SAndy Webber
175913c08e2fSMichael Klier/**
176013c08e2fSMichael Klier * Checks if the given amount of memory is available
176113c08e2fSMichael Klier *
176213c08e2fSMichael Klier * If the memory_get_usage() function is not available the
176313c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
176413c08e2fSMichael Klier *
17653272d797SAndreas Gohr * @param int $mem Size of memory you want to allocate in bytes
1766140cfbcdSGerrit Uitslag * @param int $bytes already allocated memory (see above)
17673272d797SAndreas Gohr * @return bool
17688b19906eSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
17698b19906eSAndreas Gohr *
17708b19906eSAndreas Gohr * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
177113c08e2fSMichael Klier */
1772d868eb89SAndreas Gohrfunction is_mem_available($mem, $bytes = 1_048_576)
1773d868eb89SAndreas Gohr{
177413c08e2fSMichael Klier    $limit = trim(ini_get('memory_limit'));
177513c08e2fSMichael Klier    if (empty($limit)) return true; // no limit set!
1776985d6187SElenchus    if ($limit == -1) return true; // unlimited
177713c08e2fSMichael Klier
177813c08e2fSMichael Klier    // parse limit to bytes
177913c08e2fSMichael Klier    $limit = php_to_byte($limit);
178013c08e2fSMichael Klier
178113c08e2fSMichael Klier    // get used memory if possible
178213c08e2fSMichael Klier    if (function_exists('memory_get_usage')) {
178313c08e2fSMichael Klier        $used = memory_get_usage();
178449eb6e38SAndreas Gohr    } else {
178549eb6e38SAndreas Gohr        $used = $bytes;
178613c08e2fSMichael Klier    }
178713c08e2fSMichael Klier
178813c08e2fSMichael Klier    if ($used + $mem > $limit) {
178913c08e2fSMichael Klier        return false;
179013c08e2fSMichael Klier    }
179113c08e2fSMichael Klier
179213c08e2fSMichael Klier    return true;
179313c08e2fSMichael Klier}
179413c08e2fSMichael Klier
1795af2408d5SAndreas Gohr/**
1796af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1797af2408d5SAndreas Gohr *
1798af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1799af2408d5SAndreas Gohr *
1800af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1801af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1802140cfbcdSGerrit Uitslag *
1803140cfbcdSGerrit Uitslag * @param string $url url being directed to
1804af2408d5SAndreas Gohr */
1805d868eb89SAndreas Gohrfunction send_redirect($url)
1806d868eb89SAndreas Gohr{
180798ca30d2SAndreas Gohr    $url = stripctl($url); // defend against HTTP Response Splitting
180898ca30d2SAndreas Gohr
1809585bf44eSChristopher Smith    /* @var Input $INPUT */
1810585bf44eSChristopher Smith    global $INPUT;
1811585bf44eSChristopher Smith
18120181f021SAndreas Gohr    //are there any undisplayed messages? keep them in session for display
18130181f021SAndreas Gohr    global $MSG;
18140181f021SAndreas Gohr    if (isset($MSG) && count($MSG) && !defined('NOSESSION')) {
18150181f021SAndreas Gohr        //reopen session, store data and close session again
18160181f021SAndreas Gohr        @session_start();
18170181f021SAndreas Gohr        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
18180181f021SAndreas Gohr    }
18190181f021SAndreas Gohr
1820d4869846SAndreas Gohr    // always close the session
1821d4869846SAndreas Gohr    session_write_close();
1822d4869846SAndreas Gohr
1823af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
18247d34963bSAndreas Gohr    if (
18257d34963bSAndreas Gohr        $INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1826093fe67eSAndreas Gohr        (str_contains($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI')) &&
1827585bf44eSChristopher Smith        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
18283272d797SAndreas Gohr        $matches[1] < 6
18293272d797SAndreas Gohr    ) {
1830af2408d5SAndreas Gohr        header('Refresh: 0;url=' . $url);
1831af2408d5SAndreas Gohr    } else {
1832af2408d5SAndreas Gohr        header('Location: ' . $url);
1833af2408d5SAndreas Gohr    }
183481781cb6SAndreas Gohr
1835572dc222SLarsDW223    // no exits during unit tests
183627c0c399SAndreas Gohr    if (defined('DOKU_UNITTEST')) {
183727c0c399SAndreas Gohr        // pass info about the redirect back to the test suite
183827c0c399SAndreas Gohr        $testRequest = TestRequest::getRunning();
183927c0c399SAndreas Gohr        if ($testRequest !== null) {
184027c0c399SAndreas Gohr            $testRequest->addData('send_redirect', $url);
184127c0c399SAndreas Gohr        }
1842572dc222SLarsDW223        return;
1843572dc222SLarsDW223    }
184427c0c399SAndreas Gohr
1845af2408d5SAndreas Gohr    exit;
1846af2408d5SAndreas Gohr}
1847af2408d5SAndreas Gohr
18485b75cd1fSAdrian Lang/**
18495b75cd1fSAdrian Lang * Validate a value using a set of valid values
18505b75cd1fSAdrian Lang *
18515b75cd1fSAdrian Lang * This function checks whether a specified value is set and in the array
18525b75cd1fSAdrian Lang * $valid_values. If not, the function returns a default value or, if no
18535b75cd1fSAdrian Lang * default is specified, throws an exception.
18545b75cd1fSAdrian Lang *
18555b75cd1fSAdrian Lang * @param string $param The name of the parameter
18565b75cd1fSAdrian Lang * @param array $valid_values A set of valid values; Optionally a default may
18575b75cd1fSAdrian Lang *                             be marked by the key “default”.
18585b75cd1fSAdrian Lang * @param array $array The array containing the value (typically $_POST
18595b75cd1fSAdrian Lang *                             or $_GET)
18605b75cd1fSAdrian Lang * @param string $exc The text of the raised exception
18615b75cd1fSAdrian Lang *
18623272d797SAndreas Gohr * @return mixed
18638b19906eSAndreas Gohr * @throws Exception
18645b75cd1fSAdrian Lang * @author Adrian Lang <lang@cosmocode.de>
18655b75cd1fSAdrian Lang */
1866d868eb89SAndreas Gohrfunction valid_input_set($param, $valid_values, $array, $exc = '')
1867d868eb89SAndreas Gohr{
18685b75cd1fSAdrian Lang    if (isset($array[$param]) && in_array($array[$param], $valid_values)) {
18695b75cd1fSAdrian Lang        return $array[$param];
18705b75cd1fSAdrian Lang    } elseif (isset($valid_values['default'])) {
18715b75cd1fSAdrian Lang        return $valid_values['default'];
18725b75cd1fSAdrian Lang    } else {
18735b75cd1fSAdrian Lang        throw new Exception($exc);
18745b75cd1fSAdrian Lang    }
18755b75cd1fSAdrian Lang}
18765b75cd1fSAdrian Lang
187763703ba5SAndreas Gohr/**
187863703ba5SAndreas Gohr * Read a preference from the DokuWiki cookie
18793f108b37SAndreas Gohr *
18803f108b37SAndreas Gohr * Consider using PrefCookie directly
1881140cfbcdSGerrit Uitslag *
1882140cfbcdSGerrit Uitslag * @param string $pref preference key
1883b4b6c9a1SGerrit Uitslag * @param mixed $default value returned when preference not found
18843f108b37SAndreas Gohr * @return mixed preference value
188563703ba5SAndreas Gohr */
1886d868eb89SAndreas Gohrfunction get_doku_pref($pref, $default)
1887d868eb89SAndreas Gohr{
18883f108b37SAndreas Gohr    return (new PrefCookie())->get($pref, $default);
1889554a8c9fSAdrian Lang}
1890554a8c9fSAdrian Lang
18913c94d07bSAnika Henke/**
18923c94d07bSAnika Henke * Add a preference to the DokuWiki cookie
18933f108b37SAndreas Gohr *
18943f108b37SAndreas Gohr * Remove it by setting $val to false.
18953f108b37SAndreas Gohr * Consider using PrefCookie directly
1896140cfbcdSGerrit Uitslag *
1897140cfbcdSGerrit Uitslag * @param string $pref preference key
18983f108b37SAndreas Gohr * @param string|false $val preference value
18993c94d07bSAnika Henke */
1900d868eb89SAndreas Gohrfunction set_doku_pref($pref, $val)
1901d868eb89SAndreas Gohr{
19023f108b37SAndreas Gohr    if ($val === false) {
19033f108b37SAndreas Gohr        $val = null;
19043a970889SAnika Henke    } else {
19053f108b37SAndreas Gohr        $val = (string) $val;
19063c94d07bSAnika Henke    }
19073c94d07bSAnika Henke
19083f108b37SAndreas Gohr    (new PrefCookie())->set($pref, $val);
19093c94d07bSAnika Henke}
19103c94d07bSAnika Henke
1911f8fb2d18SAndreas Gohr/**
1912f8fb2d18SAndreas Gohr * Strips source mapping declarations from given text #601
1913f8fb2d18SAndreas Gohr *
191442ea7f44SGerrit Uitslag * @param string &$text reference to the CSS or JavaScript code to clean
1915f8fb2d18SAndreas Gohr */
1916d868eb89SAndreas Gohrfunction stripsourcemaps(&$text)
1917d868eb89SAndreas Gohr{
1918f8fb2d18SAndreas Gohr    $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text);
1919f8fb2d18SAndreas Gohr}
1920f8fb2d18SAndreas Gohr
19213c27983bSAndreas Gohr/**
192271de5572SAndreas Gohr * Returns the contents of a given SVG file for embedding
19233c27983bSAndreas Gohr *
19243c27983bSAndreas Gohr * Inlining SVGs saves on HTTP requests and more importantly allows for styling them through
19253c27983bSAndreas Gohr * CSS. However it should used with small SVGs only. The $maxsize setting ensures only small
19263c27983bSAndreas Gohr * files are embedded.
19273c27983bSAndreas Gohr *
192871de5572SAndreas Gohr * This strips unneeded headers, comments and newline. The result is not a vaild standalone SVG!
192971de5572SAndreas Gohr *
19303c27983bSAndreas Gohr * @param string $file full path to the SVG file
19313c27983bSAndreas Gohr * @param int $maxsize maximum allowed size for the SVG to be embedded
193271de5572SAndreas Gohr * @return string|false the SVG content, false if the file couldn't be loaded
19333c27983bSAndreas Gohr */
1934d868eb89SAndreas Gohrfunction inlineSVG($file, $maxsize = 2048)
1935d868eb89SAndreas Gohr{
19363c27983bSAndreas Gohr    $file = trim($file);
19373c27983bSAndreas Gohr    if ($file === '') return false;
19383c27983bSAndreas Gohr    if (!file_exists($file)) return false;
19393c27983bSAndreas Gohr    if (filesize($file) > $maxsize) return false;
19403c27983bSAndreas Gohr    if (!is_readable($file)) return false;
19413c27983bSAndreas Gohr    $content = file_get_contents($file);
19420849fa88SAndreas Gohr    $content = preg_replace('/<!--.*?(-->)/s', '', $content); // comments
19430849fa88SAndreas Gohr    $content = preg_replace('/<\?xml .*?\?>/i', '', $content); // xml header
19440849fa88SAndreas Gohr    $content = preg_replace('/<!DOCTYPE .*?>/i', '', $content); // doc type
19450849fa88SAndreas Gohr    $content = preg_replace('/>\s+</s', '><', $content); // newlines between tags
19463c27983bSAndreas Gohr    $content = trim($content);
19476c16a3a9Sfiwswe    if (!str_starts_with($content, '<svg ')) return false;
194871de5572SAndreas Gohr    return $content;
19493c27983bSAndreas Gohr}
19503c27983bSAndreas Gohr
1951e3776c06SMichael Hamann//Setup VIM: ex: et ts=2 :
1952