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