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