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