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