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