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