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