xref: /dokuwiki/inc/common.php (revision 830c02df0fd83c298377d0036ae58f85e7defa68)
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, '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 .= htmlspecialchars($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    if($conf['useslash'] && $conf['userewrite']) {
454        $id = strtr($id, ':', '/');
455    } elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
456        $conf['userewrite'] &&
457        strpos($INPUT->server->str('SERVER_SOFTWARE'), 'Microsoft-IIS') === false
458    ) {
459        $id = strtr($id, ':', ';');
460    }
461    if($ue) {
462        $id = rawurlencode($id);
463        $id = str_replace('%3A', ':', $id); //keep as colon
464        $id = str_replace('%3B', ';', $id); //keep as semicolon
465        $id = str_replace('%2F', '/', $id); //keep as slash
466    }
467    return $id;
468}
469
470/**
471 * This builds a link to a wikipage
472 *
473 * It handles URL rewriting and adds additional parameters
474 *
475 * @author Andreas Gohr <andi@splitbrain.org>
476 *
477 * @param string       $id             page id, defaults to start page
478 * @param string|array $urlParameters  URL parameters, associative array recommended
479 * @param bool         $absolute       request an absolute URL instead of relative
480 * @param string       $separator      parameter separator
481 * @return string
482 */
483function wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;') {
484    global $conf;
485    if(is_array($urlParameters)) {
486        if(isset($urlParameters['rev']) && !$urlParameters['rev']) unset($urlParameters['rev']);
487        if(isset($urlParameters['at']) && $conf['date_at_format']) {
488            $urlParameters['at'] = date($conf['date_at_format'], $urlParameters['at']);
489        }
490        $urlParameters = buildURLparams($urlParameters, $separator);
491    } else {
492        $urlParameters = str_replace(',', $separator, $urlParameters);
493    }
494    if($id === '') {
495        $id = $conf['start'];
496    }
497    $id = idfilter($id);
498    if($absolute) {
499        $xlink = DOKU_URL;
500    } else {
501        $xlink = DOKU_BASE;
502    }
503
504    if($conf['userewrite'] == 2) {
505        $xlink .= DOKU_SCRIPT.'/'.$id;
506        if($urlParameters) $xlink .= '?'.$urlParameters;
507    } elseif($conf['userewrite']) {
508        $xlink .= $id;
509        if($urlParameters) $xlink .= '?'.$urlParameters;
510    } elseif($id !== '') {
511        $xlink .= DOKU_SCRIPT.'?id='.$id;
512        if($urlParameters) $xlink .= $separator.$urlParameters;
513    } else {
514        $xlink .= DOKU_SCRIPT;
515        if($urlParameters) $xlink .= '?'.$urlParameters;
516    }
517
518    return $xlink;
519}
520
521/**
522 * This builds a link to an alternate page format
523 *
524 * Handles URL rewriting if enabled. Follows the style of wl().
525 *
526 * @author Ben Coburn <btcoburn@silicodon.net>
527 * @param string       $id             page id, defaults to start page
528 * @param string       $format         the export renderer to use
529 * @param string|array $urlParameters  URL parameters, associative array recommended
530 * @param bool         $abs            request an absolute URL instead of relative
531 * @param string       $sep            parameter separator
532 * @return string
533 */
534function exportlink($id = '', $format = 'raw', $urlParameters = '', $abs = false, $sep = '&amp;') {
535    global $conf;
536    if(is_array($urlParameters)) {
537        $urlParameters = buildURLparams($urlParameters, $sep);
538    } else {
539        $urlParameters = str_replace(',', $sep, $urlParameters);
540    }
541
542    $format = rawurlencode($format);
543    $id     = idfilter($id);
544    if($abs) {
545        $xlink = DOKU_URL;
546    } else {
547        $xlink = DOKU_BASE;
548    }
549
550    if($conf['userewrite'] == 2) {
551        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
552        if($urlParameters) $xlink .= $sep.$urlParameters;
553    } elseif($conf['userewrite'] == 1) {
554        $xlink .= '_export/'.$format.'/'.$id;
555        if($urlParameters) $xlink .= '?'.$urlParameters;
556    } else {
557        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
558        if($urlParameters) $xlink .= $sep.$urlParameters;
559    }
560
561    return $xlink;
562}
563
564/**
565 * Build a link to a media file
566 *
567 * Will return a link to the detail page if $direct is false
568 *
569 * The $more parameter should always be given as array, the function then
570 * will strip default parameters to produce even cleaner URLs
571 *
572 * @param string  $id     the media file id or URL
573 * @param mixed   $more   string or array with additional parameters
574 * @param bool    $direct link to detail page if false
575 * @param string  $sep    URL parameter separator
576 * @param bool    $abs    Create an absolute URL
577 * @return string
578 */
579function ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false) {
580    global $conf;
581    $isexternalimage = media_isexternal($id);
582    if(!$isexternalimage) {
583        $id = cleanID($id);
584    }
585
586    if(is_array($more)) {
587        // add token for resized images
588        $w = isset($more['w']) ? $more['w'] : null;
589        $h = isset($more['h']) ? $more['h'] : null;
590        if($w || $h || $isexternalimage){
591            $more['tok'] = media_get_token($id, $w, $h);
592        }
593        // strip defaults for shorter URLs
594        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
595        if(empty($more['w'])) unset($more['w']);
596        if(empty($more['h'])) unset($more['h']);
597        if(isset($more['id']) && $direct) unset($more['id']);
598        if(isset($more['rev']) && !$more['rev']) unset($more['rev']);
599        $more = buildURLparams($more, $sep);
600    } else {
601        $matches = array();
602        if (preg_match_all('/\b(w|h)=(\d*)\b/',$more,$matches,PREG_SET_ORDER) || $isexternalimage){
603            $resize = array('w'=>0, 'h'=>0);
604            foreach ($matches as $match){
605                $resize[$match[1]] = $match[2];
606            }
607            $more .= $more === '' ? '' : $sep;
608            $more .= 'tok='.media_get_token($id,$resize['w'],$resize['h']);
609        }
610        $more = str_replace('cache=cache', '', $more); //skip default
611        $more = str_replace(',,', ',', $more);
612        $more = str_replace(',', $sep, $more);
613    }
614
615    if($abs) {
616        $xlink = DOKU_URL;
617    } else {
618        $xlink = DOKU_BASE;
619    }
620
621    // external URLs are always direct without rewriting
622    if($isexternalimage) {
623        $xlink .= 'lib/exe/fetch.php';
624        $xlink .= '?'.$more;
625        $xlink .= $sep.'media='.rawurlencode($id);
626        return $xlink;
627    }
628
629    $id = idfilter($id);
630
631    // decide on scriptname
632    if($direct) {
633        if($conf['userewrite'] == 1) {
634            $script = '_media';
635        } else {
636            $script = 'lib/exe/fetch.php';
637        }
638    } else {
639        if($conf['userewrite'] == 1) {
640            $script = '_detail';
641        } else {
642            $script = 'lib/exe/detail.php';
643        }
644    }
645
646    // build URL based on rewrite mode
647    if($conf['userewrite']) {
648        $xlink .= $script.'/'.$id;
649        if($more) $xlink .= '?'.$more;
650    } else {
651        if($more) {
652            $xlink .= $script.'?'.$more;
653            $xlink .= $sep.'media='.$id;
654        } else {
655            $xlink .= $script.'?media='.$id;
656        }
657    }
658
659    return $xlink;
660}
661
662/**
663 * Returns the URL to the DokuWiki base script
664 *
665 * Consider using wl() instead, unless you absoutely need the doku.php endpoint
666 *
667 * @author Andreas Gohr <andi@splitbrain.org>
668 *
669 * @return string
670 */
671function script() {
672    return DOKU_BASE.DOKU_SCRIPT;
673}
674
675/**
676 * Spamcheck against wordlist
677 *
678 * Checks the wikitext against a list of blocked expressions
679 * returns true if the text contains any bad words
680 *
681 * Triggers COMMON_WORDBLOCK_BLOCKED
682 *
683 *  Action Plugins can use this event to inspect the blocked data
684 *  and gain information about the user who was blocked.
685 *
686 *  Event data:
687 *    data['matches']  - array of matches
688 *    data['userinfo'] - information about the blocked user
689 *      [ip]           - ip address
690 *      [user]         - username (if logged in)
691 *      [mail]         - mail address (if logged in)
692 *      [name]         - real name (if logged in)
693 *
694 * @author Andreas Gohr <andi@splitbrain.org>
695 * @author Michael Klier <chi@chimeric.de>
696 *
697 * @param  string $text - optional text to check, if not given the globals are used
698 * @return bool         - true if a spam word was found
699 */
700function checkwordblock($text = '') {
701    global $TEXT;
702    global $PRE;
703    global $SUF;
704    global $SUM;
705    global $conf;
706    global $INFO;
707    /* @var Input $INPUT */
708    global $INPUT;
709
710    if(!$conf['usewordblock']) return false;
711
712    if(!$text) $text = "$PRE $TEXT $SUF $SUM";
713
714    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
715    // phpcs:disable Generic.Files.LineLength.TooLong
716    $text = preg_replace(
717        '!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i',
718        '\1http://\2 \2\3',
719        $text
720    );
721    // phpcs:enable
722
723    $wordblocks = getWordblocks();
724    // how many lines to read at once (to work around some PCRE limits)
725    if(version_compare(phpversion(), '4.3.0', '<')) {
726        // old versions of PCRE define a maximum of parenthesises even if no
727        // backreferences are used - the maximum is 99
728        // this is very bad performancewise and may even be too high still
729        $chunksize = 40;
730    } else {
731        // read file in chunks of 200 - this should work around the
732        // MAX_PATTERN_SIZE in modern PCRE
733        $chunksize = 200;
734    }
735    while($blocks = array_splice($wordblocks, 0, $chunksize)) {
736        $re = array();
737        // build regexp from blocks
738        foreach($blocks as $block) {
739            $block = preg_replace('/#.*$/', '', $block);
740            $block = trim($block);
741            if(empty($block)) continue;
742            $re[] = $block;
743        }
744        if(count($re) && preg_match('#('.join('|', $re).')#si', $text, $matches)) {
745            // prepare event data
746            $data = array();
747            $data['matches']        = $matches;
748            $data['userinfo']['ip'] = $INPUT->server->str('REMOTE_ADDR');
749            if($INPUT->server->str('REMOTE_USER')) {
750                $data['userinfo']['user'] = $INPUT->server->str('REMOTE_USER');
751                $data['userinfo']['name'] = $INFO['userinfo']['name'];
752                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
753            }
754            $callback = function () {
755                return true;
756            };
757            return Event::createAndTrigger('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
758        }
759    }
760    return false;
761}
762
763/**
764 * Return the IP of the client
765 *
766 * Honours X-Forwarded-For and X-Real-IP Proxy Headers
767 *
768 * It returns a comma separated list of IPs if the above mentioned
769 * headers are set. If the single parameter is set, it tries to return
770 * a routable public address, prefering the ones suplied in the X
771 * headers
772 *
773 * @author Andreas Gohr <andi@splitbrain.org>
774 *
775 * @param  boolean $single If set only a single IP is returned
776 * @return string
777 */
778function clientIP($single = false) {
779    /* @var Input $INPUT */
780    global $INPUT, $conf;
781
782    $ip   = array();
783    $ip[] = $INPUT->server->str('REMOTE_ADDR');
784    if($INPUT->server->str('HTTP_X_FORWARDED_FOR')) {
785        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_FORWARDED_FOR'))));
786    }
787    if($INPUT->server->str('HTTP_X_REAL_IP')) {
788        $ip = array_merge($ip, explode(',', str_replace(' ', '', $INPUT->server->str('HTTP_X_REAL_IP'))));
789    }
790
791    // remove any non-IP stuff
792    $cnt   = count($ip);
793    for($i = 0; $i < $cnt; $i++) {
794        if(filter_var($ip[$i], FILTER_VALIDATE_IP) === false) {
795            unset($ip[$i]);
796        }
797    }
798    $ip = array_values(array_unique($ip));
799    if(empty($ip) || !$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
800
801    if(!$single) return join(',', $ip);
802
803    // skip trusted local addresses
804    foreach($ip as $i) {
805        if(!empty($conf['trustedproxy']) && preg_match('/'.$conf['trustedproxy'].'/', $i)) {
806            continue;
807        } else {
808            return $i;
809        }
810    }
811
812    // still here? just use the last address
813    // this case all ips in the list are trusted
814    return $ip[count($ip)-1];
815}
816
817/**
818 * Check if the browser is on a mobile device
819 *
820 * Adapted from the example code at url below
821 *
822 * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
823 *
824 * @deprecated 2018-04-27 you probably want media queries instead anyway
825 * @return bool if true, client is mobile browser; otherwise false
826 */
827function clientismobile() {
828    /* @var Input $INPUT */
829    global $INPUT;
830
831    if($INPUT->server->has('HTTP_X_WAP_PROFILE')) return true;
832
833    if(preg_match('/wap\.|\.wap/i', $INPUT->server->str('HTTP_ACCEPT'))) return true;
834
835    if(!$INPUT->server->has('HTTP_USER_AGENT')) return false;
836
837    $uamatches = join(
838        '|',
839        [
840            'midp', 'j2me', 'avantg', 'docomo', 'novarra', 'palmos', 'palmsource', '240x320', 'opwv',
841            'chtml', 'pda', 'windows ce', 'mmp\/', 'blackberry', 'mib\/', 'symbian', 'wireless', 'nokia',
842            'hand', 'mobi', 'phone', 'cdm', 'up\.b', 'audio', 'SIE\-', 'SEC\-', 'samsung', 'HTC', 'mot\-',
843            'mitsu', 'sagem', 'sony', 'alcatel', 'lg', 'erics', 'vx', 'NEC', 'philips', 'mmm', 'xx',
844            'panasonic', 'sharp', 'wap', 'sch', 'rover', 'pocket', 'benq', 'java', 'pt', 'pg', 'vox',
845            'amoi', 'bird', 'compal', 'kg', 'voda', 'sany', 'kdd', 'dbt', 'sendo', 'sgh', 'gradi', 'jb',
846            '\d\d\di', 'moto'
847        ]
848    );
849
850    if(preg_match("/$uamatches/i", $INPUT->server->str('HTTP_USER_AGENT'))) return true;
851
852    return false;
853}
854
855/**
856 * check if a given link is interwiki link
857 *
858 * @param string $link the link, e.g. "wiki>page"
859 * @return bool
860 */
861function link_isinterwiki($link){
862    if (preg_match('/^[a-zA-Z0-9\.]+>/u',$link)) return true;
863    return false;
864}
865
866/**
867 * Convert one or more comma separated IPs to hostnames
868 *
869 * If $conf['dnslookups'] is disabled it simply returns the input string
870 *
871 * @author Glen Harris <astfgl@iamnota.org>
872 *
873 * @param  string $ips comma separated list of IP addresses
874 * @return string a comma separated list of hostnames
875 */
876function gethostsbyaddrs($ips) {
877    global $conf;
878    if(!$conf['dnslookups']) return $ips;
879
880    $hosts = array();
881    $ips   = explode(',', $ips);
882
883    if(is_array($ips)) {
884        foreach($ips as $ip) {
885            $hosts[] = gethostbyaddr(trim($ip));
886        }
887        return join(',', $hosts);
888    } else {
889        return gethostbyaddr(trim($ips));
890    }
891}
892
893/**
894 * Checks if a given page is currently locked.
895 *
896 * removes stale lockfiles
897 *
898 * @author Andreas Gohr <andi@splitbrain.org>
899 *
900 * @param string $id page id
901 * @return bool page is locked?
902 */
903function checklock($id) {
904    global $conf;
905    /* @var Input $INPUT */
906    global $INPUT;
907
908    $lock = wikiLockFN($id);
909
910    //no lockfile
911    if(!file_exists($lock)) return false;
912
913    //lockfile expired
914    if((time() - filemtime($lock)) > $conf['locktime']) {
915        @unlink($lock);
916        return false;
917    }
918
919    //my own lock
920    @list($ip, $session) = explode("\n", io_readFile($lock));
921    if($ip == $INPUT->server->str('REMOTE_USER') || (session_id() && $session == session_id())) {
922        return false;
923    }
924
925    return $ip;
926}
927
928/**
929 * Lock a page for editing
930 *
931 * @author Andreas Gohr <andi@splitbrain.org>
932 *
933 * @param string $id page id to lock
934 */
935function lock($id) {
936    global $conf;
937    /* @var Input $INPUT */
938    global $INPUT;
939
940    if($conf['locktime'] == 0) {
941        return;
942    }
943
944    $lock = wikiLockFN($id);
945    if($INPUT->server->str('REMOTE_USER')) {
946        io_saveFile($lock, $INPUT->server->str('REMOTE_USER'));
947    } else {
948        io_saveFile($lock, clientIP()."\n".session_id());
949    }
950}
951
952/**
953 * Unlock a page if it was locked by the user
954 *
955 * @author Andreas Gohr <andi@splitbrain.org>
956 *
957 * @param string $id page id to unlock
958 * @return bool true if a lock was removed
959 */
960function unlock($id) {
961    /* @var Input $INPUT */
962    global $INPUT;
963
964    $lock = wikiLockFN($id);
965    if(file_exists($lock)) {
966        @list($ip, $session) = explode("\n", io_readFile($lock));
967        if($ip == $INPUT->server->str('REMOTE_USER') || $session == session_id()) {
968            @unlink($lock);
969            return true;
970        }
971    }
972    return false;
973}
974
975/**
976 * convert line ending to unix format
977 *
978 * also makes sure the given text is valid UTF-8
979 *
980 * @see    formText() for 2crlf conversion
981 * @author Andreas Gohr <andi@splitbrain.org>
982 *
983 * @param string $text
984 * @return string
985 */
986function cleanText($text) {
987    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
988
989    // if the text is not valid UTF-8 we simply assume latin1
990    // this won't break any worse than it breaks with the wrong encoding
991    // but might actually fix the problem in many cases
992    if(!\dokuwiki\Utf8\Clean::isUtf8($text)) $text = utf8_encode($text);
993
994    return $text;
995}
996
997/**
998 * Prepares text for print in Webforms by encoding special chars.
999 * It also converts line endings to Windows format which is
1000 * pseudo standard for webforms.
1001 *
1002 * @see    cleanText() for 2unix conversion
1003 * @author Andreas Gohr <andi@splitbrain.org>
1004 *
1005 * @param string $text
1006 * @return string
1007 */
1008function formText($text) {
1009    $text = str_replace("\012", "\015\012", $text);
1010    return htmlspecialchars($text);
1011}
1012
1013/**
1014 * Returns the specified local text in raw format
1015 *
1016 * @author Andreas Gohr <andi@splitbrain.org>
1017 *
1018 * @param string $id   page id
1019 * @param string $ext  extension of file being read, default 'txt'
1020 * @return string
1021 */
1022function rawLocale($id, $ext = 'txt') {
1023    return io_readFile(localeFN($id, $ext));
1024}
1025
1026/**
1027 * Returns the raw WikiText
1028 *
1029 * @author Andreas Gohr <andi@splitbrain.org>
1030 *
1031 * @param string $id   page id
1032 * @param string|int $rev  timestamp when a revision of wikitext is desired
1033 * @return string
1034 */
1035function rawWiki($id, $rev = '') {
1036    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1037}
1038
1039/**
1040 * Returns the pagetemplate contents for the ID's namespace
1041 *
1042 * @triggers COMMON_PAGETPL_LOAD
1043 * @author Andreas Gohr <andi@splitbrain.org>
1044 *
1045 * @param string $id the id of the page to be created
1046 * @return string parsed pagetemplate content
1047 */
1048function pageTemplate($id) {
1049    global $conf;
1050
1051    if(is_array($id)) $id = $id[0];
1052
1053    // prepare initial event data
1054    $data = array(
1055        'id'        => $id, // the id of the page to be created
1056        'tpl'       => '', // the text used as template
1057        'tplfile'   => '', // the file above text was/should be loaded from
1058        'doreplace' => true // should wildcard replacements be done on the text?
1059    );
1060
1061    $evt = new Event('COMMON_PAGETPL_LOAD', $data);
1062    if($evt->advise_before(true)) {
1063        // the before event might have loaded the content already
1064        if(empty($data['tpl'])) {
1065            // if the before event did not set a template file, try to find one
1066            if(empty($data['tplfile'])) {
1067                $path = dirname(wikiFN($id));
1068                if(file_exists($path.'/_template.txt')) {
1069                    $data['tplfile'] = $path.'/_template.txt';
1070                } else {
1071                    // search upper namespaces for templates
1072                    $len = strlen(rtrim($conf['datadir'], '/'));
1073                    while(strlen($path) >= $len) {
1074                        if(file_exists($path.'/__template.txt')) {
1075                            $data['tplfile'] = $path.'/__template.txt';
1076                            break;
1077                        }
1078                        $path = substr($path, 0, strrpos($path, '/'));
1079                    }
1080                }
1081            }
1082            // load the content
1083            $data['tpl'] = io_readFile($data['tplfile']);
1084        }
1085        if($data['doreplace']) parsePageTemplate($data);
1086    }
1087    $evt->advise_after();
1088    unset($evt);
1089
1090    return $data['tpl'];
1091}
1092
1093/**
1094 * Performs common page template replacements
1095 * This works on data from COMMON_PAGETPL_LOAD
1096 *
1097 * @author Andreas Gohr <andi@splitbrain.org>
1098 *
1099 * @param array $data array with event data
1100 * @return string
1101 */
1102function parsePageTemplate(&$data) {
1103    /**
1104     * @var string $id        the id of the page to be created
1105     * @var string $tpl       the text used as template
1106     * @var string $tplfile   the file above text was/should be loaded from
1107     * @var bool   $doreplace should wildcard replacements be done on the text?
1108     */
1109    extract($data);
1110
1111    global $USERINFO;
1112    global $conf;
1113    /* @var Input $INPUT */
1114    global $INPUT;
1115
1116    // replace placeholders
1117    $file = noNS($id);
1118    $page = strtr($file, $conf['sepchar'], ' ');
1119
1120    $tpl = str_replace(
1121        array(
1122             '@ID@',
1123             '@NS@',
1124             '@CURNS@',
1125             '@!CURNS@',
1126             '@!!CURNS@',
1127             '@!CURNS!@',
1128             '@FILE@',
1129             '@!FILE@',
1130             '@!FILE!@',
1131             '@PAGE@',
1132             '@!PAGE@',
1133             '@!!PAGE@',
1134             '@!PAGE!@',
1135             '@USER@',
1136             '@NAME@',
1137             '@MAIL@',
1138             '@DATE@',
1139        ),
1140        array(
1141             $id,
1142             getNS($id),
1143             curNS($id),
1144             \dokuwiki\Utf8\PhpString::ucfirst(curNS($id)),
1145             \dokuwiki\Utf8\PhpString::ucwords(curNS($id)),
1146             \dokuwiki\Utf8\PhpString::strtoupper(curNS($id)),
1147             $file,
1148             \dokuwiki\Utf8\PhpString::ucfirst($file),
1149             \dokuwiki\Utf8\PhpString::strtoupper($file),
1150             $page,
1151             \dokuwiki\Utf8\PhpString::ucfirst($page),
1152             \dokuwiki\Utf8\PhpString::ucwords($page),
1153             \dokuwiki\Utf8\PhpString::strtoupper($page),
1154             $INPUT->server->str('REMOTE_USER'),
1155             $USERINFO ? $USERINFO['name'] : '',
1156             $USERINFO ? $USERINFO['mail'] : '',
1157             $conf['dformat'],
1158        ), $tpl
1159    );
1160
1161    // we need the callback to work around strftime's char limit
1162    $tpl = preg_replace_callback(
1163        '/%./',
1164        function ($m) {
1165            return strftime($m[0]);
1166        },
1167        $tpl
1168    );
1169    $data['tpl'] = $tpl;
1170    return $tpl;
1171}
1172
1173/**
1174 * Returns the raw Wiki Text in three slices.
1175 *
1176 * The range parameter needs to have the form "from-to"
1177 * and gives the range of the section in bytes - no
1178 * UTF-8 awareness is needed.
1179 * The returned order is prefix, section and suffix.
1180 *
1181 * @author Andreas Gohr <andi@splitbrain.org>
1182 *
1183 * @param string $range in form "from-to"
1184 * @param string $id    page id
1185 * @param string $rev   optional, the revision timestamp
1186 * @return string[] with three slices
1187 */
1188function rawWikiSlices($range, $id, $rev = '') {
1189    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1190
1191    // Parse range
1192    list($from, $to) = explode('-', $range, 2);
1193    // Make range zero-based, use defaults if marker is missing
1194    $from = !$from ? 0 : ($from - 1);
1195    $to   = !$to ? strlen($text) : ($to - 1);
1196
1197    $slices = array();
1198    $slices[0] = substr($text, 0, $from);
1199    $slices[1] = substr($text, $from, $to - $from);
1200    $slices[2] = substr($text, $to);
1201    return $slices;
1202}
1203
1204/**
1205 * Joins wiki text slices
1206 *
1207 * function to join the text slices.
1208 * When the pretty parameter is set to true it adds additional empty
1209 * lines between sections if needed (used on saving).
1210 *
1211 * @author Andreas Gohr <andi@splitbrain.org>
1212 *
1213 * @param string $pre   prefix
1214 * @param string $text  text in the middle
1215 * @param string $suf   suffix
1216 * @param bool $pretty add additional empty lines between sections
1217 * @return string
1218 */
1219function con($pre, $text, $suf, $pretty = false) {
1220    if($pretty) {
1221        if($pre !== '' && substr($pre, -1) !== "\n" &&
1222            substr($text, 0, 1) !== "\n"
1223        ) {
1224            $pre .= "\n";
1225        }
1226        if($suf !== '' && substr($text, -1) !== "\n" &&
1227            substr($suf, 0, 1) !== "\n"
1228        ) {
1229            $text .= "\n";
1230        }
1231    }
1232
1233    return $pre.$text.$suf;
1234}
1235
1236/**
1237 * Checks if the current page version is newer than the last entry in the page's
1238 * changelog. If so, we assume it has been an external edit and we create an
1239 * attic copy and add a proper changelog line.
1240 *
1241 * This check is only executed when the page is about to be saved again from the
1242 * wiki, triggered in @see saveWikiText()
1243 *
1244 * @param string $id the page ID
1245 * @deprecated 2021-11-28
1246 */
1247function detectExternalEdit($id) {
1248    dbg_deprecated(\dokuwiki\File\PageFile::class .'::detectExternalEdit()');
1249    (new PageFile($id))->detectExternalEdit();
1250}
1251
1252/**
1253 * Saves a wikitext by calling io_writeWikiPage.
1254 * Also directs changelog and attic updates.
1255 *
1256 * @author Andreas Gohr <andi@splitbrain.org>
1257 * @author Ben Coburn <btcoburn@silicodon.net>
1258 *
1259 * @param string $id       page id
1260 * @param string $text     wikitext being saved
1261 * @param string $summary  summary of text update
1262 * @param bool   $minor    mark this saved version as minor update
1263 */
1264function saveWikiText($id, $text, $summary, $minor = false) {
1265
1266    // get COMMON_WIKIPAGE_SAVE event data
1267    $data = (new PageFile($id))->saveWikiText($text, $summary, $minor);
1268
1269    // send notify mails
1270    list('oldRevision' => $rev, 'newRevision' => $new_rev, 'summary' => $summary) = $data;
1271    notify($id, 'admin', $rev, $summary, $minor, $new_rev);
1272    notify($id, 'subscribers', $rev, $summary, $minor, $new_rev);
1273
1274    // if useheading is enabled, purge the cache of all linking pages
1275    if (useHeading('content')) {
1276        $pages = ft_backlinks($id, true);
1277        foreach ($pages as $page) {
1278            $cache = new CacheRenderer($page, wikiFN($page), 'xhtml');
1279            $cache->removeCache();
1280        }
1281    }
1282}
1283
1284/**
1285 * moves the current version to the attic and returns its revision date
1286 *
1287 * @author Andreas Gohr <andi@splitbrain.org>
1288 *
1289 * @param string $id page id
1290 * @return int|string revision timestamp
1291 * @deprecated 2021-11-28
1292 */
1293function saveOldRevision($id) {
1294    dbg_deprecated(\dokuwiki\File\PageFile::class .'::saveOldRevision()');
1295    return (new PageFile($id))->saveOldRevision();
1296}
1297
1298/**
1299 * Sends a notify mail on page change or registration
1300 *
1301 * @param string     $id       The changed page
1302 * @param string     $who      Who to notify (admin|subscribers|register)
1303 * @param int|string $rev      Old page revision
1304 * @param string     $summary  What changed
1305 * @param boolean    $minor    Is this a minor edit?
1306 * @param string[]   $replace  Additional string substitutions, @KEY@ to be replaced by value
1307 * @param int|string $current_rev  New page revision
1308 * @return bool
1309 *
1310 * @author Andreas Gohr <andi@splitbrain.org>
1311 */
1312function notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array(), $current_rev = false) {
1313    global $conf;
1314    /* @var Input $INPUT */
1315    global $INPUT;
1316
1317    // decide if there is something to do, eg. whom to mail
1318    if ($who == 'admin') {
1319        if (empty($conf['notify'])) return false; //notify enabled?
1320        $tpl = 'mailtext';
1321        $to  = $conf['notify'];
1322    } elseif ($who == 'subscribers') {
1323        if (!actionOK('subscribe')) return false; //subscribers enabled?
1324        if ($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
1325        $data = array('id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace);
1326        Event::createAndTrigger(
1327            'COMMON_NOTIFY_ADDRESSLIST', $data,
1328            array(new SubscriberManager(), 'notifyAddresses')
1329        );
1330        $to = $data['addresslist'];
1331        if (empty($to)) return false;
1332        $tpl = 'subscr_single';
1333    } else {
1334        return false; //just to be safe
1335    }
1336
1337    // prepare content
1338    $subscription = new PageSubscriptionSender();
1339    return $subscription->sendPageDiff($to, $tpl, $id, $rev, $summary, $current_rev);
1340}
1341
1342/**
1343 * extracts the query from a search engine referrer
1344 *
1345 * @author Andreas Gohr <andi@splitbrain.org>
1346 * @author Todd Augsburger <todd@rollerorgans.com>
1347 *
1348 * @return array|string
1349 */
1350function getGoogleQuery() {
1351    /* @var Input $INPUT */
1352    global $INPUT;
1353
1354    if(!$INPUT->server->has('HTTP_REFERER')) {
1355        return '';
1356    }
1357    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1358
1359    // only handle common SEs
1360    if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/',$url['host'])) return '';
1361
1362    $query = array();
1363    parse_str($url['query'], $query);
1364
1365    $q = '';
1366    if(isset($query['q'])){
1367        $q = $query['q'];
1368    }elseif(isset($query['p'])){
1369        $q = $query['p'];
1370    }elseif(isset($query['query'])){
1371        $q = $query['query'];
1372    }
1373    $q = trim($q);
1374
1375    if(!$q) return '';
1376    // ignore if query includes a full URL
1377    if(strpos($q, '//') !== false) return '';
1378    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1379    return $q;
1380}
1381
1382/**
1383 * Return the human readable size of a file
1384 *
1385 * @param int $size A file size
1386 * @param int $dec A number of decimal places
1387 * @return string human readable size
1388 *
1389 * @author      Martin Benjamin <b.martin@cybernet.ch>
1390 * @author      Aidan Lister <aidan@php.net>
1391 * @version     1.0.0
1392 */
1393function filesize_h($size, $dec = 1) {
1394    $sizes = array('B', 'KB', 'MB', 'GB');
1395    $count = count($sizes);
1396    $i     = 0;
1397
1398    while($size >= 1024 && ($i < $count - 1)) {
1399        $size /= 1024;
1400        $i++;
1401    }
1402
1403    return round($size, $dec)."\xC2\xA0".$sizes[$i]; //non-breaking space
1404}
1405
1406/**
1407 * Return the given timestamp as human readable, fuzzy age
1408 *
1409 * @author Andreas Gohr <gohr@cosmocode.de>
1410 *
1411 * @param int $dt timestamp
1412 * @return string
1413 */
1414function datetime_h($dt) {
1415    global $lang;
1416
1417    $ago = time() - $dt;
1418    if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1419        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1420    }
1421    if($ago > 24 * 60 * 60 * 30 * 2) {
1422        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1423    }
1424    if($ago > 24 * 60 * 60 * 7 * 2) {
1425        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1426    }
1427    if($ago > 24 * 60 * 60 * 2) {
1428        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1429    }
1430    if($ago > 60 * 60 * 2) {
1431        return sprintf($lang['hours'], round($ago / (60 * 60)));
1432    }
1433    if($ago > 60 * 2) {
1434        return sprintf($lang['minutes'], round($ago / (60)));
1435    }
1436    return sprintf($lang['seconds'], $ago);
1437}
1438
1439/**
1440 * Wraps around strftime but provides support for fuzzy dates
1441 *
1442 * The format default to $conf['dformat']. It is passed to
1443 * strftime - %f can be used to get the value from datetime_h()
1444 *
1445 * @see datetime_h
1446 * @author Andreas Gohr <gohr@cosmocode.de>
1447 *
1448 * @param int|null $dt      timestamp when given, null will take current timestamp
1449 * @param string   $format  empty default to $conf['dformat'], or provide format as recognized by strftime()
1450 * @return string
1451 */
1452function dformat($dt = null, $format = '') {
1453    global $conf;
1454
1455    if(is_null($dt)) $dt = time();
1456    $dt = (int) $dt;
1457    if(!$format) $format = $conf['dformat'];
1458
1459    $format = str_replace('%f', datetime_h($dt), $format);
1460    return strftime($format, $dt);
1461}
1462
1463/**
1464 * Formats a timestamp as ISO 8601 date
1465 *
1466 * @author <ungu at terong dot com>
1467 * @link http://php.net/manual/en/function.date.php#54072
1468 *
1469 * @param int $int_date current date in UNIX timestamp
1470 * @return string
1471 */
1472function date_iso8601($int_date) {
1473    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1474    $pre_timezone = date('O', $int_date);
1475    $time_zone    = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1476    $date_mod .= $time_zone;
1477    return $date_mod;
1478}
1479
1480/**
1481 * return an obfuscated email address in line with $conf['mailguard'] setting
1482 *
1483 * @author Harry Fuecks <hfuecks@gmail.com>
1484 * @author Christopher Smith <chris@jalakai.co.uk>
1485 *
1486 * @param string $email email address
1487 * @return string
1488 */
1489function obfuscate($email) {
1490    global $conf;
1491
1492    switch($conf['mailguard']) {
1493        case 'visible' :
1494            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
1495            return strtr($email, $obfuscate);
1496
1497        case 'hex' :
1498            return \dokuwiki\Utf8\Conversion::toHtml($email, true);
1499
1500        case 'none' :
1501        default :
1502            return $email;
1503    }
1504}
1505
1506/**
1507 * Removes quoting backslashes
1508 *
1509 * @author Andreas Gohr <andi@splitbrain.org>
1510 *
1511 * @param string $string
1512 * @param string $char backslashed character
1513 * @return string
1514 */
1515function unslash($string, $char = "'") {
1516    return str_replace('\\'.$char, $char, $string);
1517}
1518
1519/**
1520 * Convert php.ini shorthands to byte
1521 *
1522 * On 32 bit systems values >= 2GB will fail!
1523 *
1524 * -1 (infinite size) will be reported as -1
1525 *
1526 * @link   https://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
1527 * @param string $value PHP size shorthand
1528 * @return int
1529 */
1530function php_to_byte($value) {
1531    switch (strtoupper(substr($value,-1))) {
1532        case 'G':
1533            $ret = intval(substr($value, 0, -1)) * 1024 * 1024 * 1024;
1534            break;
1535        case 'M':
1536            $ret = intval(substr($value, 0, -1)) * 1024 * 1024;
1537            break;
1538        case 'K':
1539            $ret = intval(substr($value, 0, -1)) * 1024;
1540            break;
1541        default:
1542            $ret = intval($value);
1543            break;
1544    }
1545    return $ret;
1546}
1547
1548/**
1549 * Wrapper around preg_quote adding the default delimiter
1550 *
1551 * @param string $string
1552 * @return string
1553 */
1554function preg_quote_cb($string) {
1555    return preg_quote($string, '/');
1556}
1557
1558/**
1559 * Shorten a given string by removing data from the middle
1560 *
1561 * You can give the string in two parts, the first part $keep
1562 * will never be shortened. The second part $short will be cut
1563 * in the middle to shorten but only if at least $min chars are
1564 * left to display it. Otherwise it will be left off.
1565 *
1566 * @param string $keep   the part to keep
1567 * @param string $short  the part to shorten
1568 * @param int    $max    maximum chars you want for the whole string
1569 * @param int    $min    minimum number of chars to have left for middle shortening
1570 * @param string $char   the shortening character to use
1571 * @return string
1572 */
1573function shorten($keep, $short, $max, $min = 9, $char = '…') {
1574    $max = $max - \dokuwiki\Utf8\PhpString::strlen($keep);
1575    if($max < $min) return $keep;
1576    $len = \dokuwiki\Utf8\PhpString::strlen($short);
1577    if($len <= $max) return $keep.$short;
1578    $half = floor($max / 2);
1579    return $keep .
1580        \dokuwiki\Utf8\PhpString::substr($short, 0, $half - 1) .
1581        $char .
1582        \dokuwiki\Utf8\PhpString::substr($short, $len - $half);
1583}
1584
1585/**
1586 * Return the users real name or e-mail address for use
1587 * in page footer and recent changes pages
1588 *
1589 * @param string|null $username or null when currently logged-in user should be used
1590 * @param bool $textonly true returns only plain text, true allows returning html
1591 * @return string html or plain text(not escaped) of formatted user name
1592 *
1593 * @author Andy Webber <dokuwiki AT andywebber DOT com>
1594 */
1595function editorinfo($username, $textonly = false) {
1596    return userlink($username, $textonly);
1597}
1598
1599/**
1600 * Returns users realname w/o link
1601 *
1602 * @param string|null $username or null when currently logged-in user should be used
1603 * @param bool $textonly true returns only plain text, true allows returning html
1604 * @return string html or plain text(not escaped) of formatted user name
1605 *
1606 * @triggers COMMON_USER_LINK
1607 */
1608function userlink($username = null, $textonly = false) {
1609    global $conf, $INFO;
1610    /** @var AuthPlugin $auth */
1611    global $auth;
1612    /** @var Input $INPUT */
1613    global $INPUT;
1614
1615    // prepare initial event data
1616    $data = array(
1617        'username' => $username, // the unique user name
1618        'name' => '',
1619        'link' => array( //setting 'link' to false disables linking
1620                         'target' => '',
1621                         'pre' => '',
1622                         'suf' => '',
1623                         'style' => '',
1624                         'more' => '',
1625                         'url' => '',
1626                         'title' => '',
1627                         'class' => ''
1628        ),
1629        'userlink' => '', // formatted user name as will be returned
1630        'textonly' => $textonly
1631    );
1632    if($username === null) {
1633        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
1634        if($textonly){
1635            $data['name'] = $INFO['userinfo']['name']. ' (' . $INPUT->server->str('REMOTE_USER') . ')';
1636        }else {
1637            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> '.
1638                '(<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
1639        }
1640    }
1641
1642    $evt = new Event('COMMON_USER_LINK', $data);
1643    if($evt->advise_before(true)) {
1644        if(empty($data['name'])) {
1645            if($auth) $info = $auth->getUserData($username);
1646            if($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1647                switch($conf['showuseras']) {
1648                    case 'username':
1649                    case 'username_link':
1650                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
1651                        break;
1652                    case 'email':
1653                    case 'email_link':
1654                        $data['name'] = obfuscate($info['mail']);
1655                        break;
1656                }
1657            } else {
1658                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
1659            }
1660        }
1661
1662        /** @var Doku_Renderer_xhtml $xhtml_renderer */
1663        static $xhtml_renderer = null;
1664
1665        if(!$data['textonly'] && empty($data['link']['url'])) {
1666
1667            if(in_array($conf['showuseras'], array('email_link', 'username_link'))) {
1668                if(!isset($info)) {
1669                    if($auth) $info = $auth->getUserData($username);
1670                }
1671                if(isset($info) && $info) {
1672                    if($conf['showuseras'] == 'email_link') {
1673                        $data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
1674                    } else {
1675                        if(is_null($xhtml_renderer)) {
1676                            $xhtml_renderer = p_get_renderer('xhtml');
1677                        }
1678                        if(empty($xhtml_renderer->interwiki)) {
1679                            $xhtml_renderer->interwiki = getInterwiki();
1680                        }
1681                        $shortcut = 'user';
1682                        $exists = null;
1683                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
1684                        $data['link']['class'] .= ' interwiki iw_user';
1685                        if($exists !== null) {
1686                            if($exists) {
1687                                $data['link']['class'] .= ' wikilink1';
1688                            } else {
1689                                $data['link']['class'] .= ' wikilink2';
1690                                $data['link']['rel'] = 'nofollow';
1691                            }
1692                        }
1693                    }
1694                } else {
1695                    $data['textonly'] = true;
1696                }
1697
1698            } else {
1699                $data['textonly'] = true;
1700            }
1701        }
1702
1703        if($data['textonly']) {
1704            $data['userlink'] = $data['name'];
1705        } else {
1706            $data['link']['name'] = $data['name'];
1707            if(is_null($xhtml_renderer)) {
1708                $xhtml_renderer = p_get_renderer('xhtml');
1709            }
1710            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
1711        }
1712    }
1713    $evt->advise_after();
1714    unset($evt);
1715
1716    return $data['userlink'];
1717}
1718
1719/**
1720 * Returns the path to a image file for the currently chosen license.
1721 * When no image exists, returns an empty string
1722 *
1723 * @author Andreas Gohr <andi@splitbrain.org>
1724 *
1725 * @param  string $type - type of image 'badge' or 'button'
1726 * @return string
1727 */
1728function license_img($type) {
1729    global $license;
1730    global $conf;
1731    if(!$conf['license']) return '';
1732    if(!is_array($license[$conf['license']])) return '';
1733    $try   = array();
1734    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1735    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1736    if(substr($conf['license'], 0, 3) == 'cc-') {
1737        $try[] = 'lib/images/license/'.$type.'/cc.png';
1738    }
1739    foreach($try as $src) {
1740        if(file_exists(DOKU_INC.$src)) return $src;
1741    }
1742    return '';
1743}
1744
1745/**
1746 * Checks if the given amount of memory is available
1747 *
1748 * If the memory_get_usage() function is not available the
1749 * function just assumes $bytes of already allocated memory
1750 *
1751 * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
1752 * @author Andreas Gohr <andi@splitbrain.org>
1753 *
1754 * @param int  $mem    Size of memory you want to allocate in bytes
1755 * @param int  $bytes  already allocated memory (see above)
1756 * @return bool
1757 */
1758function is_mem_available($mem, $bytes = 1048576) {
1759    $limit = trim(ini_get('memory_limit'));
1760    if(empty($limit)) return true; // no limit set!
1761    if($limit == -1) return true; // unlimited
1762
1763    // parse limit to bytes
1764    $limit = php_to_byte($limit);
1765
1766    // get used memory if possible
1767    if(function_exists('memory_get_usage')) {
1768        $used = memory_get_usage();
1769    } else {
1770        $used = $bytes;
1771    }
1772
1773    if($used + $mem > $limit) {
1774        return false;
1775    }
1776
1777    return true;
1778}
1779
1780/**
1781 * Send a HTTP redirect to the browser
1782 *
1783 * Works arround Microsoft IIS cookie sending bug. Exits the script.
1784 *
1785 * @link   http://support.microsoft.com/kb/q176113/
1786 * @author Andreas Gohr <andi@splitbrain.org>
1787 *
1788 * @param string $url url being directed to
1789 */
1790function send_redirect($url) {
1791    $url = stripctl($url); // defend against HTTP Response Splitting
1792
1793    /* @var Input $INPUT */
1794    global $INPUT;
1795
1796    //are there any undisplayed messages? keep them in session for display
1797    global $MSG;
1798    if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
1799        //reopen session, store data and close session again
1800        @session_start();
1801        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
1802    }
1803
1804    // always close the session
1805    session_write_close();
1806
1807    // check if running on IIS < 6 with CGI-PHP
1808    if($INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1809        (strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) &&
1810        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
1811        $matches[1] < 6
1812    ) {
1813        header('Refresh: 0;url='.$url);
1814    } else {
1815        header('Location: '.$url);
1816    }
1817
1818    // no exits during unit tests
1819    if(defined('DOKU_UNITTEST')) {
1820        // pass info about the redirect back to the test suite
1821        $testRequest = TestRequest::getRunning();
1822        if($testRequest !== null) {
1823            $testRequest->addData('send_redirect', $url);
1824        }
1825        return;
1826    }
1827
1828    exit;
1829}
1830
1831/**
1832 * Validate a value using a set of valid values
1833 *
1834 * This function checks whether a specified value is set and in the array
1835 * $valid_values. If not, the function returns a default value or, if no
1836 * default is specified, throws an exception.
1837 *
1838 * @param string $param        The name of the parameter
1839 * @param array  $valid_values A set of valid values; Optionally a default may
1840 *                             be marked by the key “default”.
1841 * @param array  $array        The array containing the value (typically $_POST
1842 *                             or $_GET)
1843 * @param string $exc          The text of the raised exception
1844 *
1845 * @throws Exception
1846 * @return mixed
1847 * @author Adrian Lang <lang@cosmocode.de>
1848 */
1849function valid_input_set($param, $valid_values, $array, $exc = '') {
1850    if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
1851        return $array[$param];
1852    } elseif(isset($valid_values['default'])) {
1853        return $valid_values['default'];
1854    } else {
1855        throw new Exception($exc);
1856    }
1857}
1858
1859/**
1860 * Read a preference from the DokuWiki cookie
1861 * (remembering both keys & values are urlencoded)
1862 *
1863 * @param string $pref     preference key
1864 * @param mixed  $default  value returned when preference not found
1865 * @return string preference value
1866 */
1867function get_doku_pref($pref, $default) {
1868    $enc_pref = urlencode($pref);
1869    if(isset($_COOKIE['DOKU_PREFS']) && strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
1870        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
1871        $cnt   = count($parts);
1872
1873        // due to #2721 there might be duplicate entries,
1874        // so we read from the end
1875        for($i = $cnt-2; $i >= 0; $i -= 2) {
1876            if($parts[$i] == $enc_pref) {
1877                return urldecode($parts[$i + 1]);
1878            }
1879        }
1880    }
1881    return $default;
1882}
1883
1884/**
1885 * Add a preference to the DokuWiki cookie
1886 * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
1887 * Remove it by setting $val to false
1888 *
1889 * @param string $pref  preference key
1890 * @param string $val   preference value
1891 */
1892function set_doku_pref($pref, $val) {
1893    global $conf;
1894    $orig = get_doku_pref($pref, false);
1895    $cookieVal = '';
1896
1897    if($orig !== false && ($orig !== $val)) {
1898        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
1899        $cnt   = count($parts);
1900        // urlencode $pref for the comparison
1901        $enc_pref = rawurlencode($pref);
1902        $seen = false;
1903        for ($i = 0; $i < $cnt; $i += 2) {
1904            if ($parts[$i] == $enc_pref) {
1905                if (!$seen){
1906                    if ($val !== false) {
1907                        $parts[$i + 1] = rawurlencode($val);
1908                    } else {
1909                        unset($parts[$i]);
1910                        unset($parts[$i + 1]);
1911                    }
1912                    $seen = true;
1913                } else {
1914                    // no break because we want to remove duplicate entries
1915                    unset($parts[$i]);
1916                    unset($parts[$i + 1]);
1917                }
1918            }
1919        }
1920        $cookieVal = implode('#', $parts);
1921    } else if ($orig === false && $val !== false) {
1922        $cookieVal = (isset($_COOKIE['DOKU_PREFS']) ? $_COOKIE['DOKU_PREFS'] . '#' : '') .
1923            rawurlencode($pref) . '#' . rawurlencode($val);
1924    }
1925
1926    $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
1927    if(defined('DOKU_UNITTEST')) {
1928        $_COOKIE['DOKU_PREFS'] = $cookieVal;
1929    }else{
1930        setcookie('DOKU_PREFS', $cookieVal, time()+365*24*3600, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
1931    }
1932}
1933
1934/**
1935 * Strips source mapping declarations from given text #601
1936 *
1937 * @param string &$text reference to the CSS or JavaScript code to clean
1938 */
1939function stripsourcemaps(&$text){
1940    $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text);
1941}
1942
1943/**
1944 * Returns the contents of a given SVG file for embedding
1945 *
1946 * Inlining SVGs saves on HTTP requests and more importantly allows for styling them through
1947 * CSS. However it should used with small SVGs only. The $maxsize setting ensures only small
1948 * files are embedded.
1949 *
1950 * This strips unneeded headers, comments and newline. The result is not a vaild standalone SVG!
1951 *
1952 * @param string $file full path to the SVG file
1953 * @param int $maxsize maximum allowed size for the SVG to be embedded
1954 * @return string|false the SVG content, false if the file couldn't be loaded
1955 */
1956function inlineSVG($file, $maxsize = 2048) {
1957    $file = trim($file);
1958    if($file === '') return false;
1959    if(!file_exists($file)) return false;
1960    if(filesize($file) > $maxsize) return false;
1961    if(!is_readable($file)) return false;
1962    $content = file_get_contents($file);
1963    $content = preg_replace('/<!--.*?(-->)/s','', $content); // comments
1964    $content = preg_replace('/<\?xml .*?\?>/i', '', $content); // xml header
1965    $content = preg_replace('/<!DOCTYPE .*?>/i', '', $content); // doc type
1966    $content = preg_replace('/>\s+</s', '><', $content); // newlines between tags
1967    $content = trim($content);
1968    if(substr($content, 0, 5) !== '<svg ') return false;
1969    return $content;
1970}
1971
1972//Setup VIM: ex: et ts=2 :
1973