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