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