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