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