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