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