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