xref: /dokuwiki/inc/common.php (revision c1482d1c08360e6401534a1391da2b650c37d34d)
1<?php
2/**
3 * Common DokuWiki functions
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Andreas Gohr <andi@splitbrain.org>
7 */
8use dokuwiki\PassHash;
9use dokuwiki\Draft;
10use dokuwiki\Utf8\Clean;
11use dokuwiki\Utf8\PhpString;
12use dokuwiki\Utf8\Conversion;
13use dokuwiki\Cache\CacheInstructions;
14use dokuwiki\Cache\CacheRenderer;
15use dokuwiki\ChangeLog\PageChangeLog;
16use dokuwiki\File\PageFile;
17use dokuwiki\Logger;
18use dokuwiki\Subscriptions\PageSubscriptionSender;
19use dokuwiki\Subscriptions\SubscriberManager;
20use dokuwiki\Extension\AuthPlugin;
21use dokuwiki\Extension\Event;
22
23/**
24 * Wrapper around htmlspecialchars()
25 *
26 * @author Andreas Gohr <andi@splitbrain.org>
27 * @see    htmlspecialchars()
28 *
29 * @param string $string the string being converted
30 * @return string converted string
31 */
32function hsc($string) {
33    return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, 'UTF-8');
34}
35
36/**
37 * A safer explode for fixed length lists
38 *
39 * This works just like explode(), but will always return the wanted number of elements.
40 * If the $input string does not contain enough elements, the missing elements will be
41 * filled up with the $default value. If the input string contains more elements, the last
42 * one will NOT be split up and will still contain $separator
43 *
44 * @param string $separator The boundary string
45 * @param string $string The input string
46 * @param int $limit The number of expected elements
47 * @param mixed $default The value to use when filling up missing elements
48 * @see explode
49 * @return array
50 */
51function sexplode($separator, $string, $limit, $default = null)
52{
53    return array_pad(explode($separator, $string, $limit), $limit, $default);
54}
55
56/**
57 * Checks if the given input is blank
58 *
59 * This is similar to empty() but will return false for "0".
60 *
61 * Please note: when you pass uninitialized variables, they will implicitly be created
62 * with a NULL value without warning.
63 *
64 * To avoid this it's recommended to guard the call with isset like this:
65 *
66 * (isset($foo) && !blank($foo))
67 * (!isset($foo) || blank($foo))
68 *
69 * @param $in
70 * @param bool $trim Consider a string of whitespace to be blank
71 * @return bool
72 */
73function blank(&$in, $trim = false) {
74    if(is_null($in)) return true;
75    if(is_array($in)) return $in === [];
76    if($in === "\0") return true;
77    if($trim && trim($in) === '') return true;
78    if(strlen($in) > 0) return false;
79    return empty($in);
80}
81
82/**
83 * print a newline terminated string
84 *
85 * You can give an indention as optional parameter
86 *
87 * @author Andreas Gohr <andi@splitbrain.org>
88 *
89 * @param string $string  line of text
90 * @param int    $indent  number of spaces indention
91 */
92function ptln($string, $indent = 0) {
93    echo str_repeat(' ', $indent)."$string\n";
94}
95
96/**
97 * strips control characters (<32) from the given string
98 *
99 * @author Andreas Gohr <andi@splitbrain.org>
100 *
101 * @param string $string being stripped
102 * @return string
103 */
104function stripctl($string) {
105    return preg_replace('/[\x00-\x1F]+/s', '', $string);
106}
107
108/**
109 * Return a secret token to be used for CSRF attack prevention
110 *
111 * @author  Andreas Gohr <andi@splitbrain.org>
112 * @link    http://en.wikipedia.org/wiki/Cross-site_request_forgery
113 * @link    http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
114 *
115 * @return  string
116 */
117function getSecurityToken() {
118    /** @var Input $INPUT */
119    global $INPUT;
120
121    $user = $INPUT->server->str('REMOTE_USER');
122    $session = session_id();
123
124    // CSRF checks are only for logged in users - do not generate for anonymous
125    if(trim($user) == '' || trim($session) == '') return '';
126    return PassHash::hmac('md5', $session.$user, auth_cookiesalt());
127}
128
129/**
130 * Check the secret CSRF token
131 *
132 * @param null|string $token security token or null to read it from request variable
133 * @return bool success if the token matched
134 */
135function checkSecurityToken($token = null) {
136    /** @var Input $INPUT */
137    global $INPUT;
138    if(!$INPUT->server->str('REMOTE_USER')) return true; // no logged in user, no need for a check
139
140    if(is_null($token)) $token = $INPUT->str('sectok');
141    if(getSecurityToken() != $token) {
142        msg('Security Token did not match. Possible CSRF attack.', -1);
143        return false;
144    }
145    return true;
146}
147
148/**
149 * Print a hidden form field with a secret CSRF token
150 *
151 * @author  Andreas Gohr <andi@splitbrain.org>
152 *
153 * @param bool $print  if true print the field, otherwise html of the field is returned
154 * @return string html of hidden form field
155 */
156function formSecurityToken($print = true) {
157    $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
158    if($print) echo $ret;
159    return $ret;
160}
161
162/**
163 * Determine basic information for a request of $id
164 *
165 * @author Andreas Gohr <andi@splitbrain.org>
166 * @author Chris Smith <chris@jalakai.co.uk>
167 *
168 * @param string $id         pageid
169 * @param bool   $htmlClient add info about whether is mobile browser
170 * @return array with info for a request of $id
171 *
172 */
173function basicinfo($id, $htmlClient=true){
174    global $USERINFO;
175    /* @var Input $INPUT */
176    global $INPUT;
177
178    // set info about manager/admin status.
179    $info = [];
180    $info['isadmin']   = false;
181    $info['ismanager'] = false;
182    if($INPUT->server->has('REMOTE_USER')) {
183        $info['userinfo']   = $USERINFO;
184        $info['perm']       = auth_quickaclcheck($id);
185        $info['client']     = $INPUT->server->str('REMOTE_USER');
186
187        if($info['perm'] == AUTH_ADMIN) {
188            $info['isadmin']   = true;
189            $info['ismanager'] = true;
190        } elseif(auth_ismanager()) {
191            $info['ismanager'] = true;
192        }
193
194        // if some outside auth were used only REMOTE_USER is set
195        if(empty($info['userinfo']['name'])) {
196            $info['userinfo']['name'] = $INPUT->server->str('REMOTE_USER');
197        }
198
199    } else {
200        $info['perm']       = auth_aclcheck($id, '', null);
201        $info['client']     = clientIP(true);
202    }
203
204    $info['namespace'] = getNS($id);
205
206    // mobile detection
207    if ($htmlClient) {
208        $info['ismobile'] = clientismobile();
209    }
210
211    return $info;
212 }
213
214/**
215 * Return info about the current document as associative
216 * array.
217 *
218 * @author Andreas Gohr <andi@splitbrain.org>
219 *
220 * @return array with info about current document
221 */
222function pageinfo() {
223    global $ID;
224    global $REV;
225    global $RANGE;
226    global $lang;
227    /* @var Input $INPUT */
228    global $INPUT;
229
230    $info = basicinfo($ID);
231
232    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
233    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
234    $info['id']  = $ID;
235    $info['rev'] = $REV;
236
237    $subManager = new SubscriberManager();
238    $info['subscribed'] = $subManager->userSubscription();
239
240    $info['locked']     = checklock($ID);
241    $info['filepath']   = wikiFN($ID);
242    $info['exists']     = file_exists($info['filepath']);
243    $info['currentrev'] = @filemtime($info['filepath']);
244
245    if ($REV) {
246        //check if current revision was meant
247        if ($info['exists'] && ($info['currentrev'] == $REV)) {
248            $REV = '';
249        } elseif ($RANGE) {
250            //section editing does not work with old revisions!
251            $REV   = '';
252            $RANGE = '';
253            msg($lang['nosecedit'], 0);
254        } else {
255            //really use old revision
256            $info['filepath'] = wikiFN($ID, $REV);
257            $info['exists']   = file_exists($info['filepath']);
258        }
259    }
260    $info['rev'] = $REV;
261    if ($info['exists']) {
262        $info['writable'] = (is_writable($info['filepath']) && $info['perm'] >= AUTH_EDIT);
263    } else {
264        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
265    }
266    $info['editable'] = ($info['writable'] && empty($info['locked']));
267    $info['lastmod']  = @filemtime($info['filepath']);
268
269    //load page meta data
270    $info['meta'] = p_get_metadata($ID);
271
272    //who's the editor
273    $pagelog = new PageChangeLog($ID, 1024);
274    if ($REV) {
275        $revinfo = $pagelog->getRevisionInfo($REV);
276    } elseif (!empty($info['meta']['last_change']) && is_array($info['meta']['last_change'])) {
277        $revinfo = $info['meta']['last_change'];
278    } else {
279        $revinfo = $pagelog->getRevisionInfo($info['lastmod']);
280        // cache most recent changelog line in metadata if missing and still valid
281        if ($revinfo !== false) {
282            $info['meta']['last_change'] = $revinfo;
283            p_set_metadata($ID, ['last_change' => $revinfo]);
284        }
285    }
286    //and check for an external edit
287    if ($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
288        // cached changelog line no longer valid
289        $revinfo                     = false;
290        $info['meta']['last_change'] = $revinfo;
291        p_set_metadata($ID, ['last_change' => $revinfo]);
292    }
293
294    if ($revinfo !== false) {
295        $info['ip']   = $revinfo['ip'];
296        $info['user'] = $revinfo['user'];
297        $info['sum']  = $revinfo['sum'];
298        // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
299        // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
300
301        $info['editor'] = $revinfo['user'] ?: $revinfo['ip'];
302    } else {
303        $info['ip']     = null;
304        $info['user']   = null;
305        $info['sum']    = null;
306        $info['editor'] = null;
307    }
308
309    // draft
310    $draft = new Draft($ID, $info['client']);
311    if ($draft->isDraftAvailable()) {
312        $info['draft'] = $draft->getDraftFilename();
313    }
314
315    return $info;
316}
317
318/**
319 * Initialize and/or fill global $JSINFO with some basic info to be given to javascript
320 */
321function jsinfo() {
322    global $JSINFO, $ID, $INFO, $ACT;
323
324    if (!is_array($JSINFO)) {
325        $JSINFO = [];
326    }
327    //export minimal info to JS, plugins can add more
328    $JSINFO['id']                    = $ID;
329    $JSINFO['namespace']             = isset($INFO) ? (string) $INFO['namespace'] : '';
330    $JSINFO['ACT']                   = act_clean($ACT);
331    $JSINFO['useHeadingNavigation']  = (int) useHeading('navigation');
332    $JSINFO['useHeadingContent']     = (int) useHeading('content');
333}
334
335/**
336 * Return information about the current media item as an associative array.
337 *
338 * @return array with info about current media item
339 */
340function mediainfo() {
341    global $NS;
342    global $IMG;
343
344    $info = basicinfo("$NS:*");
345    $info['image'] = $IMG;
346
347    return $info;
348}
349
350/**
351 * Build an string of URL parameters
352 *
353 * @author Andreas Gohr
354 *
355 * @param array  $params    array with key-value pairs
356 * @param string $sep       series of pairs are separated by this character
357 * @return string query string
358 */
359function buildURLparams($params, $sep = '&amp;') {
360    $url = '';
361    $amp = false;
362    foreach($params as $key => $val) {
363        if($amp) $url .= $sep;
364
365        $url .= rawurlencode($key).'=';
366        $url .= rawurlencode((string) $val);
367        $amp = true;
368    }
369    return $url;
370}
371
372/**
373 * Build an string of html tag attributes
374 *
375 * Skips keys starting with '_', values get HTML encoded
376 *
377 * @author Andreas Gohr
378 *
379 * @param array $params           array with (attribute name-attribute value) pairs
380 * @param bool  $skipEmptyStrings skip empty string values?
381 * @return string
382 */
383function buildAttributes($params, $skipEmptyStrings = false) {
384    $url   = '';
385    $white = false;
386    foreach($params as $key => $val) {
387        if($key[0] == '_') continue;
388        if($val === '' && $skipEmptyStrings) continue;
389        if($white) $url .= ' ';
390
391        $url .= $key.'="';
392        $url .= hsc($val);
393        $url .= '"';
394        $white = true;
395    }
396    return $url;
397}
398
399/**
400 * This builds the breadcrumb trail and returns it as array
401 *
402 * @author Andreas Gohr <andi@splitbrain.org>
403 *
404 * @return string[] with the data: array(pageid=>name, ... )
405 */
406function breadcrumbs() {
407    // we prepare the breadcrumbs early for quick session closing
408    static $crumbs = null;
409    if($crumbs != null) return $crumbs;
410
411    global $ID;
412    global $ACT;
413    global $conf;
414    global $INFO;
415
416    //first visit?
417    $crumbs = $_SESSION[DOKU_COOKIE]['bc'] ?? [];
418    //we only save on show and existing visible readable wiki documents
419    $file = wikiFN($ID);
420    if($ACT != 'show' || $INFO['perm'] < AUTH_READ || isHiddenPage($ID) || !file_exists($file)) {
421        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
422        return $crumbs;
423    }
424
425    // page names
426    $name = noNSorNS($ID);
427    if(useHeading('navigation')) {
428        // get page title
429        $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
430        if($title) {
431            $name = $title;
432        }
433    }
434
435    //remove ID from array
436    if(isset($crumbs[$ID])) {
437        unset($crumbs[$ID]);
438    }
439
440    //add to array
441    $crumbs[$ID] = $name;
442    //reduce size
443    while(count($crumbs) > $conf['breadcrumbs']) {
444        array_shift($crumbs);
445    }
446    //save to session
447    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
448    return $crumbs;
449}
450
451/**
452 * Filter for page IDs
453 *
454 * This is run on a ID before it is outputted somewhere
455 * currently used to replace the colon with something else
456 * on Windows (non-IIS) systems and to have proper URL encoding
457 *
458 * See discussions at https://github.com/dokuwiki/dokuwiki/pull/84 and
459 * https://github.com/dokuwiki/dokuwiki/pull/173 why we use a whitelist of
460 * unaffected servers instead of blacklisting affected servers here.
461 *
462 * Urlencoding is ommitted when the second parameter is false
463 *
464 * @author Andreas Gohr <andi@splitbrain.org>
465 *
466 * @param string $id pageid being filtered
467 * @param bool   $ue apply urlencoding?
468 * @return string
469 */
470function idfilter($id, $ue = true) {
471    global $conf;
472    /* @var Input $INPUT */
473    global $INPUT;
474
475    $id = (string) $id;
476
477    if($conf['useslash'] && $conf['userewrite']) {
478        $id = strtr($id, ':', '/');
479    } elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
480        $conf['userewrite'] &&
481        strpos($INPUT->server->str('SERVER_SOFTWARE'), 'Microsoft-IIS') === false
482    ) {
483        $id = strtr($id, ':', ';');
484    }
485    if($ue) {
486        $id = rawurlencode($id);
487        $id = str_replace('%3A', ':', $id); //keep as colon
488        $id = str_replace('%3B', ';', $id); //keep as semicolon
489        $id = str_replace('%2F', '/', $id); //keep as slash
490    }
491    return $id;
492}
493
494/**
495 * This builds a link to a wikipage
496 *
497 * It handles URL rewriting and adds additional parameters
498 *
499 * @author Andreas Gohr <andi@splitbrain.org>
500 *
501 * @param string       $id             page id, defaults to start page
502 * @param string|array $urlParameters  URL parameters, associative array recommended
503 * @param bool         $absolute       request an absolute URL instead of relative
504 * @param string       $separator      parameter separator
505 * @return string
506 */
507function wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;') {
508    global $conf;
509    if(is_array($urlParameters)) {
510        if(isset($urlParameters['rev']) && !$urlParameters['rev']) unset($urlParameters['rev']);
511        if(isset($urlParameters['at']) && $conf['date_at_format']) {
512            $urlParameters['at'] = date($conf['date_at_format'], $urlParameters['at']);
513        }
514        $urlParameters = buildURLparams($urlParameters, $separator);
515    } else {
516        $urlParameters = str_replace(',', $separator, $urlParameters);
517    }
518    if($id === '') {
519        $id = $conf['start'];
520    }
521    $id = idfilter($id);
522    if($absolute) {
523        $xlink = DOKU_URL;
524    } else {
525        $xlink = DOKU_BASE;
526    }
527
528    if($conf['userewrite'] == 2) {
529        $xlink .= DOKU_SCRIPT.'/'.$id;
530        if($urlParameters) $xlink .= '?'.$urlParameters;
531    } elseif($conf['userewrite']) {
532        $xlink .= $id;
533        if($urlParameters) $xlink .= '?'.$urlParameters;
534    } elseif($id !== '') {
535        $xlink .= DOKU_SCRIPT.'?id='.$id;
536        if($urlParameters) $xlink .= $separator.$urlParameters;
537    } else {
538        $xlink .= DOKU_SCRIPT;
539        if($urlParameters) $xlink .= '?'.$urlParameters;
540    }
541
542    return $xlink;
543}
544
545/**
546 * This builds a link to an alternate page format
547 *
548 * Handles URL rewriting if enabled. Follows the style of wl().
549 *
550 * @author Ben Coburn <btcoburn@silicodon.net>
551 * @param string       $id             page id, defaults to start page
552 * @param string       $format         the export renderer to use
553 * @param string|array $urlParameters  URL parameters, associative array recommended
554 * @param bool         $abs            request an absolute URL instead of relative
555 * @param string       $sep            parameter separator
556 * @return string
557 */
558function exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;') {
559    global $conf;
560    if(is_array($urlParameters)) {
561        $urlParameters = buildURLparams($urlParameters, $sep);
562    } else {
563        $urlParameters = str_replace(',', $sep, $urlParameters);
564    }
565
566    $format = rawurlencode($format);
567    $id     = idfilter($id);
568    if($abs) {
569        $xlink = DOKU_URL;
570    } else {
571        $xlink = DOKU_BASE;
572    }
573
574    if($conf['userewrite'] == 2) {
575        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
576        if($urlParameters) $xlink .= $sep.$urlParameters;
577    } elseif($conf['userewrite'] == 1) {
578        $xlink .= '_export/'.$format.'/'.$id;
579        if($urlParameters) $xlink .= '?'.$urlParameters;
580    } else {
581        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
582        if($urlParameters) $xlink .= $sep.$urlParameters;
583    }
584
585    return $xlink;
586}
587
588/**
589 * Build a link to a media file
590 *
591 * Will return a link to the detail page if $direct is false
592 *
593 * The $more parameter should always be given as array, the function then
594 * will strip default parameters to produce even cleaner URLs
595 *
596 * @param string  $id     the media file id or URL
597 * @param mixed   $more   string or array with additional parameters
598 * @param bool    $direct link to detail page if false
599 * @param string  $sep    URL parameter separator
600 * @param bool    $abs    Create an absolute URL
601 * @return string
602 */
603function ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false) {
604    global $conf;
605    $isexternalimage = media_isexternal($id);
606    if(!$isexternalimage) {
607        $id = cleanID($id);
608    }
609
610    if(is_array($more)) {
611        // add token for resized images
612        $w = $more['w'] ?? null;
613        $h = $more['h'] ?? null;
614        if($w || $h || $isexternalimage){
615            $more['tok'] = media_get_token($id, $w, $h);
616        }
617        // strip defaults for shorter URLs
618        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
619        if(empty($more['w'])) unset($more['w']);
620        if(empty($more['h'])) unset($more['h']);
621        if(isset($more['id']) && $direct) unset($more['id']);
622        if(isset($more['rev']) && !$more['rev']) unset($more['rev']);
623        $more = buildURLparams($more, $sep);
624    } else {
625        $matches = [];
626        if (preg_match_all('/\b(w|h)=(\d*)\b/', $more, $matches, PREG_SET_ORDER) || $isexternalimage){
627            $resize = ['w'=>0, 'h'=>0];
628            foreach ($matches as $match){
629                $resize[$match[1]] = $match[2];
630            }
631            $more .= $more === '' ? '' : $sep;
632            $more .= 'tok='.media_get_token($id, $resize['w'], $resize['h']);
633        }
634        $more = str_replace('cache=cache', '', $more); //skip default
635        $more = str_replace(',,', ',', $more);
636        $more = str_replace(',', $sep, $more);
637    }
638
639    if($abs) {
640        $xlink = DOKU_URL;
641    } else {
642        $xlink = DOKU_BASE;
643    }
644
645    // external URLs are always direct without rewriting
646    if($isexternalimage) {
647        $xlink .= 'lib/exe/fetch.php';
648        $xlink .= '?'.$more;
649        $xlink .= $sep.'media='.rawurlencode($id);
650        return $xlink;
651    }
652
653    $id = idfilter($id);
654
655    // decide on scriptname
656    if ($direct) {
657        if($conf['userewrite'] == 1) {
658            $script = '_media';
659        } else {
660            $script = 'lib/exe/fetch.php';
661        }
662    } elseif ($conf['userewrite'] == 1) {
663        $script = '_detail';
664    } else {
665        $script = 'lib/exe/detail.php';
666    }
667
668    // build URL based on rewrite mode
669    if ($conf['userewrite']) {
670        $xlink .= $script.'/'.$id;
671        if($more) $xlink .= '?'.$more;
672    } elseif ($more) {
673        $xlink .= $script.'?'.$more;
674        $xlink .= $sep.'media='.$id;
675    } else {
676        $xlink .= $script.'?media='.$id;
677    }
678
679    return $xlink;
680}
681
682/**
683 * Returns the URL to the DokuWiki base script
684 *
685 * Consider using wl() instead, unless you absoutely need the doku.php endpoint
686 *
687 * @author Andreas Gohr <andi@splitbrain.org>
688 *
689 * @return string
690 */
691function script() {
692    return DOKU_BASE.DOKU_SCRIPT;
693}
694
695/**
696 * Spamcheck against wordlist
697 *
698 * Checks the wikitext against a list of blocked expressions
699 * returns true if the text contains any bad words
700 *
701 * Triggers COMMON_WORDBLOCK_BLOCKED
702 *
703 *  Action Plugins can use this event to inspect the blocked data
704 *  and gain information about the user who was blocked.
705 *
706 *  Event data:
707 *    data['matches']  - array of matches
708 *    data['userinfo'] - information about the blocked user
709 *      [ip]           - ip address
710 *      [user]         - username (if logged in)
711 *      [mail]         - mail address (if logged in)
712 *      [name]         - real name (if logged in)
713 *
714 * @author Andreas Gohr <andi@splitbrain.org>
715 * @author Michael Klier <chi@chimeric.de>
716 *
717 * @param  string $text - optional text to check, if not given the globals are used
718 * @return bool         - true if a spam word was found
719 */
720function checkwordblock($text = '') {
721    global $TEXT;
722    global $PRE;
723    global $SUF;
724    global $SUM;
725    global $conf;
726    global $INFO;
727    /* @var Input $INPUT */
728    global $INPUT;
729
730    if(!$conf['usewordblock']) return false;
731
732    if(!$text) $text = "$PRE $TEXT $SUF $SUM";
733
734    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
735    // phpcs:disable Generic.Files.LineLength.TooLong
736    $text = preg_replace(
737        '!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i',
738        '\1http://\2 \2\3',
739        $text
740    );
741    // phpcs:enable
742
743    $wordblocks = getWordblocks();
744    // read file in chunks of 200 - this should work around the
745    // MAX_PATTERN_SIZE in modern PCRE
746    $chunksize = 200;
747
748    while($blocks = array_splice($wordblocks, 0, $chunksize)) {
749        $re = [];
750        // build regexp from blocks
751        foreach($blocks as $block) {
752            $block = preg_replace('/#.*$/', '', $block);
753            $block = trim($block);
754            if(empty($block)) continue;
755            $re[] = $block;
756        }
757        if(count($re) && preg_match('#('.implode('|', $re).')#si', $text, $matches)) {
758            // prepare event data
759            $data = [];
760            $data['matches']        = $matches;
761            $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
762            if($INPUT->server->str('REMOTE_USER')) {
763                $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
764                $data['userinfo']['name'] = $INFO['userinfo']['name'];
765                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
766            }
767            $callback = static fn() => true;
768            return Event::createAndTrigger('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
769        }
770    }
771    return false;
772}
773
774/**
775 * Return the IP of the client
776 *
777 * Honours X-Forwarded-For and X-Real-IP Proxy Headers
778 *
779 * It returns a comma separated list of IPs if the above mentioned
780 * headers are set. If the single parameter is set, it tries to return
781 * a routable public address, prefering the ones suplied in the X
782 * headers
783 *
784 * @author Andreas Gohr <andi@splitbrain.org>
785 *
786 * @param  boolean $single If set only a single IP is returned
787 * @return string
788 */
789function clientIP($single = false) {
790    /* @var Input $INPUT */
791    global $INPUT, $conf;
792
793    $ip   = [];
794    $ip[] = $INPUT->server->str('REMOTE_ADDR');
795    if($INPUT->server->str('HTTP_X_FORWARDED_FOR')) {
796        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_FORWARDED_FOR'))));
797    }
798    if($INPUT->server->str('HTTP_X_REAL_IP')) {
799        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_REAL_IP'))));
800    }
801
802    // remove any non-IP stuff
803    $cnt   = count($ip);
804    for($i = 0; $i < $cnt; $i++) {
805        if(filter_var($ip[$i], FILTER_VALIDATE_IP) === false) {
806            unset($ip[$i]);
807        }
808    }
809    $ip = array_values(array_unique($ip));
810    if($ip === [] || !$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
811
812    if(!$single) return implode(',', $ip);
813
814    // skip trusted local addresses
815    foreach($ip as $i) {
816        if(!empty($conf['trustedproxy']) && preg_match('/'.$conf['trustedproxy'].'/', $i)) {
817            continue;
818        } else {
819            return $i;
820        }
821    }
822
823    // still here? just use the last address
824    // this case all ips in the list are trusted
825    return $ip[count($ip)-1];
826}
827
828/**
829 * Check if the browser is on a mobile device
830 *
831 * Adapted from the example code at url below
832 *
833 * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
834 *
835 * @deprecated 2018-04-27 you probably want media queries instead anyway
836 * @return bool if true, client is mobile browser; otherwise false
837 */
838function clientismobile() {
839    /* @var Input $INPUT */
840    global $INPUT;
841
842    if($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
843
844    if(preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
845
846    if(!$INPUT->server->has('HTTP_USER_AGENT')) return false;
847
848    $uamatches = implode(
849        '|',
850        [
851            'midp', 'j2me', 'avantg', 'docomo', 'novarra', 'palmos', 'palmsource', '240x320', 'opwv',
852            'chtml', 'pda', 'windows ce', 'mmp\/', 'blackberry', 'mib\/', 'symbian', 'wireless', 'nokia',
853            'hand', 'mobi', 'phone', 'cdm', 'up\.b', 'audio', 'SIE\-', 'SEC\-', 'samsung', 'HTC', 'mot\-',
854            'mitsu', 'sagem', 'sony', 'alcatel', 'lg', 'erics', 'vx', 'NEC', 'philips', 'mmm', 'xx',
855            'panasonic', 'sharp', 'wap', 'sch', 'rover', 'pocket', 'benq', 'java', 'pt', 'pg', 'vox',
856            'amoi', 'bird', 'compal', 'kg', 'voda', 'sany', 'kdd', 'dbt', 'sendo', 'sgh', 'gradi', 'jb',
857            '\d\d\di', 'moto'
858        ]
859    );
860
861    if(preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
862
863    return false;
864}
865
866/**
867 * check if a given link is interwiki link
868 *
869 * @param string $link the link, e.g. "wiki>page"
870 * @return bool
871 */
872function link_isinterwiki($link){
873    if (preg_match('/^[a-zA-Z0-9\.]+>/u', $link)) return true;
874    return false;
875}
876
877/**
878 * Convert one or more comma separated IPs to hostnames
879 *
880 * If $conf['dnslookups'] is disabled it simply returns the input string
881 *
882 * @author Glen Harris <astfgl@iamnota.org>
883 *
884 * @param  string $ips comma separated list of IP addresses
885 * @return string a comma separated list of hostnames
886 */
887function gethostsbyaddrs($ips) {
888    global $conf;
889    if(!$conf['dnslookups']) return $ips;
890
891    $hosts = [];
892    $ips   = explode(',', $ips);
893
894    if(is_array($ips)) {
895        foreach($ips as $ip) {
896            $hosts[] = gethostbyaddr(trim($ip));
897        }
898        return implode(',', $hosts);
899    } else {
900        return gethostbyaddr(trim($ips));
901    }
902}
903
904/**
905 * Checks if a given page is currently locked.
906 *
907 * removes stale lockfiles
908 *
909 * @author Andreas Gohr <andi@splitbrain.org>
910 *
911 * @param string $id page id
912 * @return bool page is locked?
913 */
914function checklock($id) {
915    global $conf;
916    /* @var Input $INPUT */
917    global $INPUT;
918
919    $lock = wikiLockFN($id);
920
921    //no lockfile
922    if(!file_exists($lock)) return false;
923
924    //lockfile expired
925    if((time() - filemtime($lock)) > $conf['locktime']) {
926        @unlink($lock);
927        return false;
928    }
929
930    //my own lock
931    @[$ip, $session] = explode("\n", io_readFile($lock));
932    if($ip == $INPUT->server->str('REMOTE_USER') || (session_id() && $session === session_id())) {
933        return false;
934    }
935
936    return $ip;
937}
938
939/**
940 * Lock a page for editing
941 *
942 * @author Andreas Gohr <andi@splitbrain.org>
943 *
944 * @param string $id page id to lock
945 */
946function lock($id) {
947    global $conf;
948    /* @var Input $INPUT */
949    global $INPUT;
950
951    if($conf['locktime'] == 0) {
952        return;
953    }
954
955    $lock = wikiLockFN($id);
956    if($INPUT->server->str('REMOTE_USER')) {
957        io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
958    } else {
959        io_saveFile($lock, clientIP()."\n".session_id());
960    }
961}
962
963/**
964 * Unlock a page if it was locked by the user
965 *
966 * @author Andreas Gohr <andi@splitbrain.org>
967 *
968 * @param string $id page id to unlock
969 * @return bool true if a lock was removed
970 */
971function unlock($id) {
972    /* @var Input $INPUT */
973    global $INPUT;
974
975    $lock = wikiLockFN($id);
976    if(file_exists($lock)) {
977        @[$ip, $session] = explode("\n", io_readFile($lock));
978        if($ip == $INPUT->server->str('REMOTE_USER') || $session == session_id()) {
979            @unlink($lock);
980            return true;
981        }
982    }
983    return false;
984}
985
986/**
987 * convert line ending to unix format
988 *
989 * also makes sure the given text is valid UTF-8
990 *
991 * @see    formText() for 2crlf conversion
992 * @author Andreas Gohr <andi@splitbrain.org>
993 *
994 * @param string $text
995 * @return string
996 */
997function cleanText($text) {
998    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
999
1000    // if the text is not valid UTF-8 we simply assume latin1
1001    // this won't break any worse than it breaks with the wrong encoding
1002    // but might actually fix the problem in many cases
1003    if(!Clean::isUtf8($text)) $text = utf8_encode($text);
1004
1005    return $text;
1006}
1007
1008/**
1009 * Prepares text for print in Webforms by encoding special chars.
1010 * It also converts line endings to Windows format which is
1011 * pseudo standard for webforms.
1012 *
1013 * @see    cleanText() for 2unix conversion
1014 * @author Andreas Gohr <andi@splitbrain.org>
1015 *
1016 * @param string $text
1017 * @return string
1018 */
1019function formText($text) {
1020    $text = str_replace("\012", "\015\012", $text ?? '');
1021    return htmlspecialchars($text);
1022}
1023
1024/**
1025 * Returns the specified local text in raw format
1026 *
1027 * @author Andreas Gohr <andi@splitbrain.org>
1028 *
1029 * @param string $id   page id
1030 * @param string $ext  extension of file being read, default 'txt'
1031 * @return string
1032 */
1033function rawLocale($id, $ext = 'txt') {
1034    return io_readFile(localeFN($id, $ext));
1035}
1036
1037/**
1038 * Returns the raw WikiText
1039 *
1040 * @author Andreas Gohr <andi@splitbrain.org>
1041 *
1042 * @param string $id   page id
1043 * @param string|int $rev  timestamp when a revision of wikitext is desired
1044 * @return string
1045 */
1046function rawWiki($id, $rev = '') {
1047    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1048}
1049
1050/**
1051 * Returns the pagetemplate contents for the ID's namespace
1052 *
1053 * @triggers COMMON_PAGETPL_LOAD
1054 * @author Andreas Gohr <andi@splitbrain.org>
1055 *
1056 * @param string $id the id of the page to be created
1057 * @return string parsed pagetemplate content
1058 */
1059function pageTemplate($id) {
1060    global $conf;
1061
1062    if(is_array($id)) $id = $id[0];
1063
1064    // prepare initial event data
1065    $data = [
1066        'id'        => $id, // the id of the page to be created
1067        'tpl'       => '', // the text used as template
1068        'tplfile'   => '', // the file above text was/should be loaded from
1069        'doreplace' => true,
1070    ];
1071
1072    $evt = new Event('COMMON_PAGETPL_LOAD', $data);
1073    if($evt->advise_before(true)) {
1074        // the before event might have loaded the content already
1075        if(empty($data['tpl'])) {
1076            // if the before event did not set a template file, try to find one
1077            if(empty($data['tplfile'])) {
1078                $path = dirname(wikiFN($id));
1079                if(file_exists($path.'/_template.txt')) {
1080                    $data['tplfile'] = $path.'/_template.txt';
1081                } else {
1082                    // search upper namespaces for templates
1083                    $len = strlen(rtrim($conf['datadir'], '/'));
1084                    while(strlen($path) >= $len) {
1085                        if(file_exists($path.'/__template.txt')) {
1086                            $data['tplfile'] = $path.'/__template.txt';
1087                            break;
1088                        }
1089                        $path = substr($path, 0, strrpos($path, '/'));
1090                    }
1091                }
1092            }
1093            // load the content
1094            $data['tpl'] = io_readFile($data['tplfile']);
1095        }
1096        if($data['doreplace']) parsePageTemplate($data);
1097    }
1098    $evt->advise_after();
1099    unset($evt);
1100
1101    return $data['tpl'];
1102}
1103
1104/**
1105 * Performs common page template replacements
1106 * This works on data from COMMON_PAGETPL_LOAD
1107 *
1108 * @author Andreas Gohr <andi@splitbrain.org>
1109 *
1110 * @param array $data array with event data
1111 * @return string
1112 */
1113function parsePageTemplate(&$data) {
1114    /**
1115     * @var string $id        the id of the page to be created
1116     * @var string $tpl       the text used as template
1117     * @var string $tplfile   the file above text was/should be loaded from
1118     * @var bool   $doreplace should wildcard replacements be done on the text?
1119     */
1120    extract($data);
1121
1122    global $USERINFO;
1123    global $conf;
1124    /* @var Input $INPUT */
1125    global $INPUT;
1126
1127    // replace placeholders
1128    $file = noNS($id);
1129    $page = strtr($file, $conf['sepchar'], ' ');
1130
1131    $tpl = str_replace(
1132        [
1133            '@ID@',
1134            '@NS@',
1135            '@CURNS@',
1136            '@!CURNS@',
1137            '@!!CURNS@',
1138            '@!CURNS!@',
1139            '@FILE@',
1140            '@!FILE@',
1141            '@!FILE!@',
1142            '@PAGE@',
1143            '@!PAGE@',
1144            '@!!PAGE@',
1145            '@!PAGE!@',
1146            '@USER@',
1147            '@NAME@',
1148            '@MAIL@',
1149            '@DATE@'
1150        ],
1151        [
1152            $id,
1153            getNS($id),
1154            curNS($id),
1155            PhpString::ucfirst(curNS($id)),
1156            PhpString::ucwords(curNS($id)),
1157            PhpString::strtoupper(curNS($id)),
1158            $file,
1159            PhpString::ucfirst($file),
1160            PhpString::strtoupper($file),
1161            $page,
1162            PhpString::ucfirst($page),
1163            PhpString::ucwords($page),
1164            PhpString::strtoupper($page),
1165            $INPUT->server->str('REMOTE_USER'),
1166            $USERINFO ? $USERINFO['name'] : '',
1167            $USERINFO ? $USERINFO['mail'] : '',
1168            $conf['dformat']
1169        ],
1170        $tpl
1171    );
1172
1173    // we need the callback to work around strftime's char limit
1174    $tpl = preg_replace_callback(
1175        '/%./',
1176        static fn($m) => dformat(null, $m[0]),
1177        $tpl
1178    );
1179    $data['tpl'] = $tpl;
1180    return $tpl;
1181}
1182
1183/**
1184 * Returns the raw Wiki Text in three slices.
1185 *
1186 * The range parameter needs to have the form "from-to"
1187 * and gives the range of the section in bytes - no
1188 * UTF-8 awareness is needed.
1189 * The returned order is prefix, section and suffix.
1190 *
1191 * @author Andreas Gohr <andi@splitbrain.org>
1192 *
1193 * @param string $range in form "from-to"
1194 * @param string $id    page id
1195 * @param string $rev   optional, the revision timestamp
1196 * @return string[] with three slices
1197 */
1198function rawWikiSlices($range, $id, $rev = '') {
1199    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1200
1201    // Parse range
1202    [$from, $to] = sexplode('-', $range, 2);
1203    // Make range zero-based, use defaults if marker is missing
1204    $from = $from ? $from - 1 : (0);
1205    $to   = $to ? $to - 1 : (strlen($text));
1206
1207    $slices = [];
1208    $slices[0] = substr($text, 0, $from);
1209    $slices[1] = substr($text, $from, $to - $from);
1210    $slices[2] = substr($text, $to);
1211    return $slices;
1212}
1213
1214/**
1215 * Joins wiki text slices
1216 *
1217 * function to join the text slices.
1218 * When the pretty parameter is set to true it adds additional empty
1219 * lines between sections if needed (used on saving).
1220 *
1221 * @author Andreas Gohr <andi@splitbrain.org>
1222 *
1223 * @param string $pre   prefix
1224 * @param string $text  text in the middle
1225 * @param string $suf   suffix
1226 * @param bool $pretty add additional empty lines between sections
1227 * @return string
1228 */
1229function con($pre, $text, $suf, $pretty = false) {
1230    if($pretty) {
1231        if($pre !== '' && substr($pre, -1) !== "\n" &&
1232            substr($text, 0, 1) !== "\n"
1233        ) {
1234            $pre .= "\n";
1235        }
1236        if($suf !== '' && substr($text, -1) !== "\n" &&
1237            substr($suf, 0, 1) !== "\n"
1238        ) {
1239            $text .= "\n";
1240        }
1241    }
1242
1243    return $pre.$text.$suf;
1244}
1245
1246/**
1247 * Checks if the current page version is newer than the last entry in the page's
1248 * changelog. If so, we assume it has been an external edit and we create an
1249 * attic copy and add a proper changelog line.
1250 *
1251 * This check is only executed when the page is about to be saved again from the
1252 * wiki, triggered in @see saveWikiText()
1253 *
1254 * @param string $id the page ID
1255 * @deprecated 2021-11-28
1256 */
1257function detectExternalEdit($id) {
1258    dbg_deprecated(PageFile::class .'::detectExternalEdit()');
1259    (new PageFile($id))->detectExternalEdit();
1260}
1261
1262/**
1263 * Saves a wikitext by calling io_writeWikiPage.
1264 * Also directs changelog and attic updates.
1265 *
1266 * @author Andreas Gohr <andi@splitbrain.org>
1267 * @author Ben Coburn <btcoburn@silicodon.net>
1268 *
1269 * @param string $id       page id
1270 * @param string $text     wikitext being saved
1271 * @param string $summary  summary of text update
1272 * @param bool   $minor    mark this saved version as minor update
1273 */
1274function saveWikiText($id, $text, $summary, $minor = false) {
1275
1276    // get COMMON_WIKIPAGE_SAVE event data
1277    $data = (new PageFile($id))->saveWikiText($text, $summary, $minor);
1278    if(!$data) return; // save was cancelled (for no changes or by a plugin)
1279
1280    // send notify mails
1281    ['oldRevision' => $rev, 'newRevision' => $new_rev, 'summary' => $summary] = $data;
1282    notify($id, 'admin', $rev, $summary, $minor, $new_rev);
1283    notify($id, 'subscribers', $rev, $summary, $minor, $new_rev);
1284
1285    // if useheading is enabled, purge the cache of all linking pages
1286    if (useHeading('content')) {
1287        $pages = ft_backlinks($id, true);
1288        foreach ($pages as $page) {
1289            $cache = new CacheRenderer($page, wikiFN($page), 'xhtml');
1290            $cache->removeCache();
1291        }
1292    }
1293}
1294
1295/**
1296 * moves the current version to the attic and returns its revision date
1297 *
1298 * @author Andreas Gohr <andi@splitbrain.org>
1299 *
1300 * @param string $id page id
1301 * @return int|string revision timestamp
1302 * @deprecated 2021-11-28
1303 */
1304function saveOldRevision($id) {
1305    dbg_deprecated(PageFile::class .'::saveOldRevision()');
1306    return (new PageFile($id))->saveOldRevision();
1307}
1308
1309/**
1310 * Sends a notify mail on page change or registration
1311 *
1312 * @param string     $id       The changed page
1313 * @param string     $who      Who to notify (admin|subscribers|register)
1314 * @param int|string $rev      Old page revision
1315 * @param string     $summary  What changed
1316 * @param boolean    $minor    Is this a minor edit?
1317 * @param string[]   $replace  Additional string substitutions, @KEY@ to be replaced by value
1318 * @param int|string $current_rev  New page revision
1319 * @return bool
1320 *
1321 * @author Andreas Gohr <andi@splitbrain.org>
1322 */
1323function notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = [], $current_rev = false) {
1324    global $conf;
1325    /* @var Input $INPUT */
1326    global $INPUT;
1327
1328    // decide if there is something to do, eg. whom to mail
1329    if ($who == 'admin') {
1330        if (empty($conf['notify'])) return false; //notify enabled?
1331        $tpl = 'mailtext';
1332        $to  = $conf['notify'];
1333    } elseif ($who == 'subscribers') {
1334        if (!actionOK('subscribe')) return false; //subscribers enabled?
1335        if ($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
1336        $data = ['id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace];
1337        Event::createAndTrigger(
1338            'COMMON_NOTIFY_ADDRESSLIST', $data,
1339            [new SubscriberManager(), 'notifyAddresses']
1340        );
1341        $to = $data['addresslist'];
1342        if (empty($to)) return false;
1343        $tpl = 'subscr_single';
1344    } else {
1345        return false; //just to be safe
1346    }
1347
1348    // prepare content
1349    $subscription = new PageSubscriptionSender();
1350    return $subscription->sendPageDiff($to, $tpl, $id, $rev, $summary, $current_rev);
1351}
1352
1353/**
1354 * extracts the query from a search engine referrer
1355 *
1356 * @author Andreas Gohr <andi@splitbrain.org>
1357 * @author Todd Augsburger <todd@rollerorgans.com>
1358 *
1359 * @return array|string
1360 */
1361function getGoogleQuery() {
1362    /* @var Input $INPUT */
1363    global $INPUT;
1364
1365    if(!$INPUT->server->has('HTTP_REFERER')) {
1366        return '';
1367    }
1368    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1369
1370    // only handle common SEs
1371    if(!array_key_exists('host', $url)) return '';
1372    if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/', $url['host'])) return '';
1373
1374    $query = [];
1375    if(!array_key_exists('query', $url)) return '';
1376    parse_str($url['query'], $query);
1377
1378    $q = '';
1379    if(isset($query['q'])){
1380        $q = $query['q'];
1381    }elseif(isset($query['p'])){
1382        $q = $query['p'];
1383    }elseif(isset($query['query'])){
1384        $q = $query['query'];
1385    }
1386    $q = trim($q);
1387
1388    if(!$q) return '';
1389    // ignore if query includes a full URL
1390    if(strpos($q, '//') !== false) return '';
1391    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1392    return $q;
1393}
1394
1395/**
1396 * Return the human readable size of a file
1397 *
1398 * @param int $size A file size
1399 * @param int $dec A number of decimal places
1400 * @return string human readable size
1401 *
1402 * @author      Martin Benjamin <b.martin@cybernet.ch>
1403 * @author      Aidan Lister <aidan@php.net>
1404 * @version     1.0.0
1405 */
1406function filesize_h($size, $dec = 1) {
1407    $sizes = ['B', 'KB', 'MB', 'GB'];
1408    $count = count($sizes);
1409    $i     = 0;
1410
1411    while($size >= 1024 && ($i < $count - 1)) {
1412        $size /= 1024;
1413        $i++;
1414    }
1415
1416    return round($size, $dec)."\xC2\xA0".$sizes[$i]; //non-breaking space
1417}
1418
1419/**
1420 * Return the given timestamp as human readable, fuzzy age
1421 *
1422 * @author Andreas Gohr <gohr@cosmocode.de>
1423 *
1424 * @param int $dt timestamp
1425 * @return string
1426 */
1427function datetime_h($dt) {
1428    global $lang;
1429
1430    $ago = time() - $dt;
1431    if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1432        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1433    }
1434    if($ago > 24 * 60 * 60 * 30 * 2) {
1435        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1436    }
1437    if($ago > 24 * 60 * 60 * 7 * 2) {
1438        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1439    }
1440    if($ago > 24 * 60 * 60 * 2) {
1441        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1442    }
1443    if($ago > 60 * 60 * 2) {
1444        return sprintf($lang['hours'], round($ago / (60 * 60)));
1445    }
1446    if($ago > 60 * 2) {
1447        return sprintf($lang['minutes'], round($ago / (60)));
1448    }
1449    return sprintf($lang['seconds'], $ago);
1450}
1451
1452/**
1453 * Wraps around strftime but provides support for fuzzy dates
1454 *
1455 * The format default to $conf['dformat']. It is passed to
1456 * strftime - %f can be used to get the value from datetime_h()
1457 *
1458 * @see datetime_h
1459 * @author Andreas Gohr <gohr@cosmocode.de>
1460 *
1461 * @param int|null $dt      timestamp when given, null will take current timestamp
1462 * @param string   $format  empty default to $conf['dformat'], or provide format as recognized by strftime()
1463 * @return string
1464 */
1465function dformat($dt = null, $format = '') {
1466    global $conf;
1467
1468    if(is_null($dt)) $dt = time();
1469    $dt = (int) $dt;
1470    if(!$format) $format = $conf['dformat'];
1471
1472    $format = str_replace('%f', datetime_h($dt), $format);
1473    return strftime($format, $dt);
1474}
1475
1476/**
1477 * Formats a timestamp as ISO 8601 date
1478 *
1479 * @author <ungu at terong dot com>
1480 * @link http://php.net/manual/en/function.date.php#54072
1481 *
1482 * @param int $int_date current date in UNIX timestamp
1483 * @return string
1484 */
1485function date_iso8601($int_date) {
1486    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1487    $pre_timezone = date('O', $int_date);
1488    $time_zone    = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1489    $date_mod .= $time_zone;
1490    return $date_mod;
1491}
1492
1493/**
1494 * return an obfuscated email address in line with $conf['mailguard'] setting
1495 *
1496 * @author Harry Fuecks <hfuecks@gmail.com>
1497 * @author Christopher Smith <chris@jalakai.co.uk>
1498 *
1499 * @param string $email email address
1500 * @return string
1501 */
1502function obfuscate($email) {
1503    global $conf;
1504
1505    switch($conf['mailguard']) {
1506        case 'visible' :
1507            $obfuscate = ['@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] '];
1508            return strtr($email, $obfuscate);
1509
1510        case 'hex' :
1511            return Conversion::toHtml($email, true);
1512
1513        case 'none' :
1514        default :
1515            return $email;
1516    }
1517}
1518
1519/**
1520 * Removes quoting backslashes
1521 *
1522 * @author Andreas Gohr <andi@splitbrain.org>
1523 *
1524 * @param string $string
1525 * @param string $char backslashed character
1526 * @return string
1527 */
1528function unslash($string, $char = "'") {
1529    return str_replace('\\'.$char, $char, $string);
1530}
1531
1532/**
1533 * Convert php.ini shorthands to byte
1534 *
1535 * On 32 bit systems values >= 2GB will fail!
1536 *
1537 * -1 (infinite size) will be reported as -1
1538 *
1539 * @link   https://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
1540 * @param string $value PHP size shorthand
1541 * @return int
1542 */
1543function php_to_byte($value) {
1544    switch (strtoupper(substr($value, -1))) {
1545        case 'G':
1546            $ret = (int) substr($value, 0, -1) * 1024 * 1024 * 1024;
1547            break;
1548        case 'M':
1549            $ret = (int) substr($value, 0, -1) * 1024 * 1024;
1550            break;
1551        case 'K':
1552            $ret = (int) substr($value, 0, -1) * 1024;
1553            break;
1554        default:
1555            $ret = (int) $value;
1556            break;
1557    }
1558    return $ret;
1559}
1560
1561/**
1562 * Wrapper around preg_quote adding the default delimiter
1563 *
1564 * @param string $string
1565 * @return string
1566 */
1567function preg_quote_cb($string) {
1568    return preg_quote($string, '/');
1569}
1570
1571/**
1572 * Shorten a given string by removing data from the middle
1573 *
1574 * You can give the string in two parts, the first part $keep
1575 * will never be shortened. The second part $short will be cut
1576 * in the middle to shorten but only if at least $min chars are
1577 * left to display it. Otherwise it will be left off.
1578 *
1579 * @param string $keep   the part to keep
1580 * @param string $short  the part to shorten
1581 * @param int    $max    maximum chars you want for the whole string
1582 * @param int    $min    minimum number of chars to have left for middle shortening
1583 * @param string $char   the shortening character to use
1584 * @return string
1585 */
1586function shorten($keep, $short, $max, $min = 9, $char = '…') {
1587    $max -= PhpString::strlen($keep);
1588    if($max < $min) return $keep;
1589    $len = PhpString::strlen($short);
1590    if($len <= $max) return $keep.$short;
1591    $half = floor($max / 2);
1592    return $keep .
1593        PhpString::substr($short, 0, $half - 1) .
1594        $char .
1595        PhpString::substr($short, $len - $half);
1596}
1597
1598/**
1599 * Return the users real name or e-mail address for use
1600 * in page footer and recent changes pages
1601 *
1602 * @param string|null $username or null when currently logged-in user should be used
1603 * @param bool $textonly true returns only plain text, true allows returning html
1604 * @return string html or plain text(not escaped) of formatted user name
1605 *
1606 * @author Andy Webber <dokuwiki AT andywebber DOT com>
1607 */
1608function editorinfo($username, $textonly = false) {
1609    return userlink($username, $textonly);
1610}
1611
1612/**
1613 * Returns users realname w/o link
1614 *
1615 * @param string|null $username or null when currently logged-in user should be used
1616 * @param bool $textonly true returns only plain text, true allows returning html
1617 * @return string html or plain text(not escaped) of formatted user name
1618 *
1619 * @triggers COMMON_USER_LINK
1620 */
1621function userlink($username = null, $textonly = false) {
1622    global $conf, $INFO;
1623    /** @var AuthPlugin $auth */
1624    global $auth;
1625    /** @var Input $INPUT */
1626    global $INPUT;
1627
1628    // prepare initial event data
1629    $data = [
1630        'username' => $username, // the unique user name
1631        'name' => '',
1632        'link' => [
1633            //setting 'link' to false disables linking
1634            'target' => '',
1635            'pre' => '',
1636            'suf' => '',
1637            'style' => '',
1638            'more' => '',
1639            'url' => '',
1640            'title' => '',
1641            'class' => '',
1642        ],
1643        'userlink' => '', // formatted user name as will be returned
1644        'textonly' => $textonly,
1645    ];
1646    if($username === null) {
1647        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
1648        if($textonly){
1649            $data['name'] = $INFO['userinfo']['name']. ' (' . $INPUT->server->str('REMOTE_USER') . ')';
1650        }else {
1651            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> '.
1652                '(<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
1653        }
1654    }
1655
1656    $evt = new Event('COMMON_USER_LINK', $data);
1657    if($evt->advise_before(true)) {
1658        if(empty($data['name'])) {
1659            if($auth) $info = $auth->getUserData($username);
1660            if($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1661                switch($conf['showuseras']) {
1662                    case 'username':
1663                    case 'username_link':
1664                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
1665                        break;
1666                    case 'email':
1667                    case 'email_link':
1668                        $data['name'] = obfuscate($info['mail']);
1669                        break;
1670                }
1671            } else {
1672                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
1673            }
1674        }
1675
1676        /** @var Doku_Renderer_xhtml $xhtml_renderer */
1677        static $xhtml_renderer = null;
1678
1679        if(!$data['textonly'] && empty($data['link']['url'])) {
1680
1681            if(in_array($conf['showuseras'], ['email_link', 'username_link'])) {
1682                if(!isset($info)) {
1683                    if($auth) $info = $auth->getUserData($username);
1684                }
1685                if(isset($info) && $info) {
1686                    if($conf['showuseras'] == 'email_link') {
1687                        $data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
1688                    } else {
1689                        if(is_null($xhtml_renderer)) {
1690                            $xhtml_renderer = p_get_renderer('xhtml');
1691                        }
1692                        if(empty($xhtml_renderer->interwiki)) {
1693                            $xhtml_renderer->interwiki = getInterwiki();
1694                        }
1695                        $shortcut = 'user';
1696                        $exists = null;
1697                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
1698                        $data['link']['class'] .= ' interwiki iw_user';
1699                        if($exists !== null) {
1700                            if($exists) {
1701                                $data['link']['class'] .= ' wikilink1';
1702                            } else {
1703                                $data['link']['class'] .= ' wikilink2';
1704                                $data['link']['rel'] = 'nofollow';
1705                            }
1706                        }
1707                    }
1708                } else {
1709                    $data['textonly'] = true;
1710                }
1711
1712            } else {
1713                $data['textonly'] = true;
1714            }
1715        }
1716
1717        if($data['textonly']) {
1718            $data['userlink'] = $data['name'];
1719        } else {
1720            $data['link']['name'] = $data['name'];
1721            if(is_null($xhtml_renderer)) {
1722                $xhtml_renderer = p_get_renderer('xhtml');
1723            }
1724            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
1725        }
1726    }
1727    $evt->advise_after();
1728    unset($evt);
1729
1730    return $data['userlink'];
1731}
1732
1733/**
1734 * Returns the path to a image file for the currently chosen license.
1735 * When no image exists, returns an empty string
1736 *
1737 * @author Andreas Gohr <andi@splitbrain.org>
1738 *
1739 * @param  string $type - type of image 'badge' or 'button'
1740 * @return string
1741 */
1742function license_img($type) {
1743    global $license;
1744    global $conf;
1745    if(!$conf['license']) return '';
1746    if(!is_array($license[$conf['license']])) return '';
1747    $try   = [];
1748    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1749    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1750    if(substr($conf['license'], 0, 3) == 'cc-') {
1751        $try[] = 'lib/images/license/'.$type.'/cc.png';
1752    }
1753    foreach($try as $src) {
1754        if(file_exists(DOKU_INC.$src)) return $src;
1755    }
1756    return '';
1757}
1758
1759/**
1760 * Checks if the given amount of memory is available
1761 *
1762 * If the memory_get_usage() function is not available the
1763 * function just assumes $bytes of already allocated memory
1764 *
1765 * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
1766 * @author Andreas Gohr <andi@splitbrain.org>
1767 *
1768 * @param int  $mem    Size of memory you want to allocate in bytes
1769 * @param int  $bytes  already allocated memory (see above)
1770 * @return bool
1771 */
1772function is_mem_available($mem, $bytes = 1_048_576) {
1773    $limit = trim(ini_get('memory_limit'));
1774    if(empty($limit)) return true; // no limit set!
1775    if($limit == -1) return true; // unlimited
1776
1777    // parse limit to bytes
1778    $limit = php_to_byte($limit);
1779
1780    // get used memory if possible
1781    if(function_exists('memory_get_usage')) {
1782        $used = memory_get_usage();
1783    } else {
1784        $used = $bytes;
1785    }
1786
1787    if($used + $mem > $limit) {
1788        return false;
1789    }
1790
1791    return true;
1792}
1793
1794/**
1795 * Send a HTTP redirect to the browser
1796 *
1797 * Works arround Microsoft IIS cookie sending bug. Exits the script.
1798 *
1799 * @link   http://support.microsoft.com/kb/q176113/
1800 * @author Andreas Gohr <andi@splitbrain.org>
1801 *
1802 * @param string $url url being directed to
1803 */
1804function send_redirect($url) {
1805    $url = stripctl($url); // defend against HTTP Response Splitting
1806
1807    /* @var Input $INPUT */
1808    global $INPUT;
1809
1810    //are there any undisplayed messages? keep them in session for display
1811    global $MSG;
1812    if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
1813        //reopen session, store data and close session again
1814        @session_start();
1815        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
1816    }
1817
1818    // always close the session
1819    session_write_close();
1820
1821    // check if running on IIS < 6 with CGI-PHP
1822    if($INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1823        (strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) &&
1824        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
1825        $matches[1] < 6
1826    ) {
1827        header('Refresh: 0;url='.$url);
1828    } else {
1829        header('Location: '.$url);
1830    }
1831
1832    // no exits during unit tests
1833    if(defined('DOKU_UNITTEST')) {
1834        // pass info about the redirect back to the test suite
1835        $testRequest = TestRequest::getRunning();
1836        if($testRequest !== null) {
1837            $testRequest->addData('send_redirect', $url);
1838        }
1839        return;
1840    }
1841
1842    exit;
1843}
1844
1845/**
1846 * Validate a value using a set of valid values
1847 *
1848 * This function checks whether a specified value is set and in the array
1849 * $valid_values. If not, the function returns a default value or, if no
1850 * default is specified, throws an exception.
1851 *
1852 * @param string $param        The name of the parameter
1853 * @param array  $valid_values A set of valid values; Optionally a default may
1854 *                             be marked by the key “default”.
1855 * @param array  $array        The array containing the value (typically $_POST
1856 *                             or $_GET)
1857 * @param string $exc          The text of the raised exception
1858 *
1859 * @throws Exception
1860 * @return mixed
1861 * @author Adrian Lang <lang@cosmocode.de>
1862 */
1863function valid_input_set($param, $valid_values, $array, $exc = '') {
1864    if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
1865        return $array[$param];
1866    } elseif(isset($valid_values['default'])) {
1867        return $valid_values['default'];
1868    } else {
1869        throw new Exception($exc);
1870    }
1871}
1872
1873/**
1874 * Read a preference from the DokuWiki cookie
1875 * (remembering both keys & values are urlencoded)
1876 *
1877 * @param string $pref     preference key
1878 * @param mixed  $default  value returned when preference not found
1879 * @return string preference value
1880 */
1881function get_doku_pref($pref, $default) {
1882    $enc_pref = urlencode($pref);
1883    if(isset($_COOKIE['DOKU_PREFS']) && strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
1884        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
1885        $cnt   = count($parts);
1886
1887        // due to #2721 there might be duplicate entries,
1888        // so we read from the end
1889        for($i = $cnt-2; $i >= 0; $i -= 2) {
1890            if($parts[$i] === $enc_pref) {
1891                return urldecode($parts[$i + 1]);
1892            }
1893        }
1894    }
1895    return $default;
1896}
1897
1898/**
1899 * Add a preference to the DokuWiki cookie
1900 * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
1901 * Remove it by setting $val to false
1902 *
1903 * @param string $pref  preference key
1904 * @param string $val   preference value
1905 */
1906function set_doku_pref($pref, $val) {
1907    global $conf;
1908    $orig = get_doku_pref($pref, false);
1909    $cookieVal = '';
1910
1911    if ($orig !== false && ($orig !== $val)) {
1912        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
1913        $cnt   = count($parts);
1914        // urlencode $pref for the comparison
1915        $enc_pref = rawurlencode($pref);
1916        $seen = false;
1917        for ($i = 0; $i < $cnt; $i += 2) {
1918            if ($parts[$i] === $enc_pref) {
1919                if (!$seen){
1920                    if ($val !== false) {
1921                        $parts[$i + 1] = rawurlencode($val ?? '');
1922                    } else {
1923                        unset($parts[$i]);
1924                        unset($parts[$i + 1]);
1925                    }
1926                    $seen = true;
1927                } else {
1928                    // no break because we want to remove duplicate entries
1929                    unset($parts[$i]);
1930                    unset($parts[$i + 1]);
1931                }
1932            }
1933        }
1934        $cookieVal = implode('#', $parts);
1935    } elseif ($orig === false && $val !== false) {
1936        $cookieVal = (isset($_COOKIE['DOKU_PREFS']) ? $_COOKIE['DOKU_PREFS'] . '#' : '') .
1937            rawurlencode($pref) . '#' . rawurlencode($val);
1938    }
1939
1940    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1941    if(defined('DOKU_UNITTEST')) {
1942        $_COOKIE['DOKU_PREFS'] = $cookieVal;
1943    }else{
1944        setcookie('DOKU_PREFS', $cookieVal, [
1945            'expires' => time() + 365 * 24 * 3600,
1946            'path' => $cookieDir,
1947            'secure' => ($conf['securecookie'] && is_ssl()),
1948            'samesite' => 'Lax'
1949        ]);
1950    }
1951}
1952
1953/**
1954 * Strips source mapping declarations from given text #601
1955 *
1956 * @param string &$text reference to the CSS or JavaScript code to clean
1957 */
1958function stripsourcemaps(&$text){
1959    $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text);
1960}
1961
1962/**
1963 * Returns the contents of a given SVG file for embedding
1964 *
1965 * Inlining SVGs saves on HTTP requests and more importantly allows for styling them through
1966 * CSS. However it should used with small SVGs only. The $maxsize setting ensures only small
1967 * files are embedded.
1968 *
1969 * This strips unneeded headers, comments and newline. The result is not a vaild standalone SVG!
1970 *
1971 * @param string $file full path to the SVG file
1972 * @param int $maxsize maximum allowed size for the SVG to be embedded
1973 * @return string|false the SVG content, false if the file couldn't be loaded
1974 */
1975function inlineSVG($file, $maxsize = 2048) {
1976    $file = trim($file);
1977    if($file === '') return false;
1978    if(!file_exists($file)) return false;
1979    if(filesize($file) > $maxsize) return false;
1980    if(!is_readable($file)) return false;
1981    $content = file_get_contents($file);
1982    $content = preg_replace('/<!--.*?(-->)/s', '', $content); // comments
1983    $content = preg_replace('/<\?xml .*?\?>/i', '', $content); // xml header
1984    $content = preg_replace('/<!DOCTYPE .*?>/i', '', $content); // doc type
1985    $content = preg_replace('/>\s+</s', '><', $content); // newlines between tags
1986    $content = trim($content);
1987    if(substr($content, 0, 5) !== '<svg ') return false;
1988    return $content;
1989}
1990
1991//Setup VIM: ex: et ts=2 :
1992