xref: /dokuwiki/inc/common.php (revision 8a7bcf66942276b413e7d4accf3ab6c278a59ab0)
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']   = 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'] = 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             '@CURNS@',
1107             '@FILE@',
1108             '@!FILE@',
1109             '@!FILE!@',
1110             '@PAGE@',
1111             '@!PAGE@',
1112             '@!!PAGE@',
1113             '@!PAGE!@',
1114             '@USER@',
1115             '@NAME@',
1116             '@MAIL@',
1117             '@DATE@',
1118        ),
1119        array(
1120             $id,
1121             getNS($id),
1122             curNS($id),
1123             $file,
1124             utf8_ucfirst($file),
1125             utf8_strtoupper($file),
1126             $page,
1127             utf8_ucfirst($page),
1128             utf8_ucwords($page),
1129             utf8_strtoupper($page),
1130             $INPUT->server->str('REMOTE_USER'),
1131             $USERINFO['name'],
1132             $USERINFO['mail'],
1133             $conf['dformat'],
1134        ), $tpl
1135    );
1136
1137    // we need the callback to work around strftime's char limit
1138    $tpl         = preg_replace_callback('/%./', create_function('$m', 'return strftime($m[0]);'), $tpl);
1139    $data['tpl'] = $tpl;
1140    return $tpl;
1141}
1142
1143/**
1144 * Returns the raw Wiki Text in three slices.
1145 *
1146 * The range parameter needs to have the form "from-to"
1147 * and gives the range of the section in bytes - no
1148 * UTF-8 awareness is needed.
1149 * The returned order is prefix, section and suffix.
1150 *
1151 * @author Andreas Gohr <andi@splitbrain.org>
1152 *
1153 * @param string $range in form "from-to"
1154 * @param string $id    page id
1155 * @param string $rev   optional, the revision timestamp
1156 * @return string[] with three slices
1157 */
1158function rawWikiSlices($range, $id, $rev = '') {
1159    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
1160
1161    // Parse range
1162    list($from, $to) = explode('-', $range, 2);
1163    // Make range zero-based, use defaults if marker is missing
1164    $from = !$from ? 0 : ($from - 1);
1165    $to   = !$to ? strlen($text) : ($to - 1);
1166
1167    $slices = array();
1168    $slices[0] = substr($text, 0, $from);
1169    $slices[1] = substr($text, $from, $to - $from);
1170    $slices[2] = substr($text, $to);
1171    return $slices;
1172}
1173
1174/**
1175 * Joins wiki text slices
1176 *
1177 * function to join the text slices.
1178 * When the pretty parameter is set to true it adds additional empty
1179 * lines between sections if needed (used on saving).
1180 *
1181 * @author Andreas Gohr <andi@splitbrain.org>
1182 *
1183 * @param string $pre   prefix
1184 * @param string $text  text in the middle
1185 * @param string $suf   suffix
1186 * @param bool $pretty add additional empty lines between sections
1187 * @return string
1188 */
1189function con($pre, $text, $suf, $pretty = false) {
1190    if($pretty) {
1191        if($pre !== '' && substr($pre, -1) !== "\n" &&
1192            substr($text, 0, 1) !== "\n"
1193        ) {
1194            $pre .= "\n";
1195        }
1196        if($suf !== '' && substr($text, -1) !== "\n" &&
1197            substr($suf, 0, 1) !== "\n"
1198        ) {
1199            $text .= "\n";
1200        }
1201    }
1202
1203    return $pre.$text.$suf;
1204}
1205
1206/**
1207 * Checks if the current page version is newer than the last entry in the page's
1208 * changelog. If so, we assume it has been an external edit and we create an
1209 * attic copy and add a proper changelog line.
1210 *
1211 * This check is only executed when the page is about to be saved again from the
1212 * wiki, triggered in @see saveWikiText()
1213 *
1214 * @param string $id the page ID
1215 */
1216function detectExternalEdit($id) {
1217    global $lang;
1218
1219    $fileLastMod = wikiFN($id);
1220    $lastMod     = @filemtime($fileLastMod); // from page
1221    $pagelog     = new PageChangeLog($id, 1024);
1222    $lastRev     = $pagelog->getRevisions(-1, 1); // from changelog
1223    $lastRev     = (int) (empty($lastRev) ? 0 : $lastRev[0]);
1224
1225    if(!file_exists(wikiFN($id, $lastMod)) && file_exists($fileLastMod) && $lastMod >= $lastRev) {
1226        // add old revision to the attic if missing
1227        saveOldRevision($id);
1228        // add a changelog entry if this edit came from outside dokuwiki
1229        if($lastMod > $lastRev) {
1230            $fileLastRev = wikiFN($id, $lastRev);
1231            $revinfo = $pagelog->getRevisionInfo($lastRev);
1232            if(empty($lastRev) || !file_exists($fileLastRev) || $revinfo['type'] == DOKU_CHANGE_TYPE_DELETE) {
1233                $filesize_old = 0;
1234            } else {
1235                $filesize_old = io_getSizeFile($fileLastRev);
1236            }
1237            $filesize_new = filesize($fileLastMod);
1238            $sizechange = $filesize_new - $filesize_old;
1239
1240            addLogEntry($lastMod, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=> true), $sizechange);
1241            // remove soon to be stale instructions
1242            $cache = new cache_instructions($id, $fileLastMod);
1243            $cache->removeCache();
1244        }
1245    }
1246}
1247
1248/**
1249 * Saves a wikitext by calling io_writeWikiPage.
1250 * Also directs changelog and attic updates.
1251 *
1252 * @author Andreas Gohr <andi@splitbrain.org>
1253 * @author Ben Coburn <btcoburn@silicodon.net>
1254 *
1255 * @param string $id       page id
1256 * @param string $text     wikitext being saved
1257 * @param string $summary  summary of text update
1258 * @param bool   $minor    mark this saved version as minor update
1259 */
1260function saveWikiText($id, $text, $summary, $minor = false) {
1261    /* Note to developers:
1262       This code is subtle and delicate. Test the behavior of
1263       the attic and changelog with dokuwiki and external edits
1264       after any changes. External edits change the wiki page
1265       directly without using php or dokuwiki.
1266     */
1267    global $conf;
1268    global $lang;
1269    global $REV;
1270    /* @var Input $INPUT */
1271    global $INPUT;
1272
1273    // prepare data for event
1274    $svdta = array();
1275    $svdta['id']             = $id;
1276    $svdta['file']           = wikiFN($id);
1277    $svdta['revertFrom']     = $REV;
1278    $svdta['oldRevision']    = @filemtime($svdta['file']);
1279    $svdta['newRevision']    = 0;
1280    $svdta['newContent']     = $text;
1281    $svdta['oldContent']     = rawWiki($id);
1282    $svdta['summary']        = $summary;
1283    $svdta['contentChanged'] = ($svdta['newContent'] != $svdta['oldContent']);
1284    $svdta['changeInfo']     = '';
1285    $svdta['changeType']     = DOKU_CHANGE_TYPE_EDIT;
1286    $svdta['sizechange']     = null;
1287
1288    // select changelog line type
1289    if($REV) {
1290        $svdta['changeType']  = DOKU_CHANGE_TYPE_REVERT;
1291        $svdta['changeInfo'] = $REV;
1292    } else if(!file_exists($svdta['file'])) {
1293        $svdta['changeType'] = DOKU_CHANGE_TYPE_CREATE;
1294    } else if(trim($text) == '') {
1295        // empty or whitespace only content deletes
1296        $svdta['changeType'] = DOKU_CHANGE_TYPE_DELETE;
1297        // autoset summary on deletion
1298        if(blank($svdta['summary'])) {
1299            $svdta['summary'] = $lang['deleted'];
1300        }
1301    } else if($minor && $conf['useacl'] && $INPUT->server->str('REMOTE_USER')) {
1302        //minor edits only for logged in users
1303        $svdta['changeType'] = DOKU_CHANGE_TYPE_MINOR_EDIT;
1304    }
1305
1306    $event = new Doku_Event('COMMON_WIKIPAGE_SAVE', $svdta);
1307    if(!$event->advise_before()) return;
1308
1309    // if the content has not been changed, no save happens (plugins may override this)
1310    if(!$svdta['contentChanged']) return;
1311
1312    detectExternalEdit($id);
1313
1314    if(
1315        $svdta['changeType'] == DOKU_CHANGE_TYPE_CREATE ||
1316        ($svdta['changeType'] == DOKU_CHANGE_TYPE_REVERT && !file_exists($svdta['file']))
1317    ) {
1318        $filesize_old = 0;
1319    } else {
1320        $filesize_old = filesize($svdta['file']);
1321    }
1322    if($svdta['changeType'] == DOKU_CHANGE_TYPE_DELETE) {
1323        // Send "update" event with empty data, so plugins can react to page deletion
1324        $data = array(array($svdta['file'], '', false), getNS($id), noNS($id), false);
1325        trigger_event('IO_WIKIPAGE_WRITE', $data);
1326        // pre-save deleted revision
1327        @touch($svdta['file']);
1328        clearstatcache();
1329        $svdta['newRevision'] = saveOldRevision($id);
1330        // remove empty file
1331        @unlink($svdta['file']);
1332        $filesize_new = 0;
1333        // don't remove old meta info as it should be saved, plugins can use IO_WIKIPAGE_WRITE for removing their metadata...
1334        // purge non-persistant meta data
1335        p_purge_metadata($id);
1336        // remove empty namespaces
1337        io_sweepNS($id, 'datadir');
1338        io_sweepNS($id, 'mediadir');
1339    } else {
1340        // save file (namespace dir is created in io_writeWikiPage)
1341        io_writeWikiPage($svdta['file'], $svdta['newContent'], $id);
1342        // pre-save the revision, to keep the attic in sync
1343        $svdta['newRevision'] = saveOldRevision($id);
1344        $filesize_new = filesize($svdta['file']);
1345    }
1346    $svdta['sizechange'] = $filesize_new - $filesize_old;
1347
1348    $event->advise_after();
1349
1350    addLogEntry($svdta['newRevision'], $svdta['id'], $svdta['changeType'], $svdta['summary'], $svdta['changeInfo'], null, $svdta['sizechange']);
1351
1352    // send notify mails
1353    notify($svdta['id'], 'admin', $svdta['oldRevision'], $svdta['summary'], $minor);
1354    notify($svdta['id'], 'subscribers', $svdta['oldRevision'], $svdta['summary'], $minor);
1355
1356    // update the purgefile (timestamp of the last time anything within the wiki was changed)
1357    io_saveFile($conf['cachedir'].'/purgefile', time());
1358
1359    // if useheading is enabled, purge the cache of all linking pages
1360    if(useHeading('content')) {
1361        $pages = ft_backlinks($id, true);
1362        foreach($pages as $page) {
1363            $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
1364            $cache->removeCache();
1365        }
1366    }
1367}
1368
1369/**
1370 * moves the current version to the attic and returns its
1371 * revision date
1372 *
1373 * @author Andreas Gohr <andi@splitbrain.org>
1374 *
1375 * @param string $id page id
1376 * @return int|string revision timestamp
1377 */
1378function saveOldRevision($id) {
1379    $oldf = wikiFN($id);
1380    if(!file_exists($oldf)) return '';
1381    $date = filemtime($oldf);
1382    $newf = wikiFN($id, $date);
1383    io_writeWikiPage($newf, rawWiki($id), $id, $date);
1384    return $date;
1385}
1386
1387/**
1388 * Sends a notify mail on page change or registration
1389 *
1390 * @param string     $id       The changed page
1391 * @param string     $who      Who to notify (admin|subscribers|register)
1392 * @param int|string $rev Old page revision
1393 * @param string     $summary  What changed
1394 * @param boolean    $minor    Is this a minor edit?
1395 * @param string[]   $replace  Additional string substitutions, @KEY@ to be replaced by value
1396 * @return bool
1397 *
1398 * @author Andreas Gohr <andi@splitbrain.org>
1399 */
1400function notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array()) {
1401    global $conf;
1402    /* @var Input $INPUT */
1403    global $INPUT;
1404
1405    // decide if there is something to do, eg. whom to mail
1406    if($who == 'admin') {
1407        if(empty($conf['notify'])) return false; //notify enabled?
1408        $tpl = 'mailtext';
1409        $to  = $conf['notify'];
1410    } elseif($who == 'subscribers') {
1411        if(!actionOK('subscribe')) return false; //subscribers enabled?
1412        if($conf['useacl'] && $INPUT->server->str('REMOTE_USER') && $minor) return false; //skip minors
1413        $data = array('id' => $id, 'addresslist' => '', 'self' => false, 'replacements' => $replace);
1414        trigger_event(
1415            'COMMON_NOTIFY_ADDRESSLIST', $data,
1416            array(new Subscription(), 'notifyaddresses')
1417        );
1418        $to = $data['addresslist'];
1419        if(empty($to)) return false;
1420        $tpl = 'subscr_single';
1421    } else {
1422        return false; //just to be safe
1423    }
1424
1425    // prepare content
1426    $subscription = new Subscription();
1427    return $subscription->send_diff($to, $tpl, $id, $rev, $summary);
1428}
1429
1430/**
1431 * extracts the query from a search engine referrer
1432 *
1433 * @author Andreas Gohr <andi@splitbrain.org>
1434 * @author Todd Augsburger <todd@rollerorgans.com>
1435 *
1436 * @return array|string
1437 */
1438function getGoogleQuery() {
1439    /* @var Input $INPUT */
1440    global $INPUT;
1441
1442    if(!$INPUT->server->has('HTTP_REFERER')) {
1443        return '';
1444    }
1445    $url = parse_url($INPUT->server->str('HTTP_REFERER'));
1446
1447    // only handle common SEs
1448    if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/',$url['host'])) return '';
1449
1450    $query = array();
1451    // temporary workaround against PHP bug #49733
1452    // see http://bugs.php.net/bug.php?id=49733
1453    if(UTF8_MBSTRING) $enc = mb_internal_encoding();
1454    parse_str($url['query'], $query);
1455    if(UTF8_MBSTRING) mb_internal_encoding($enc);
1456
1457    $q = '';
1458    if(isset($query['q'])){
1459        $q = $query['q'];
1460    }elseif(isset($query['p'])){
1461        $q = $query['p'];
1462    }elseif(isset($query['query'])){
1463        $q = $query['query'];
1464    }
1465    $q = trim($q);
1466
1467    if(!$q) return '';
1468    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1469    return $q;
1470}
1471
1472/**
1473 * Return the human readable size of a file
1474 *
1475 * @param int $size A file size
1476 * @param int $dec A number of decimal places
1477 * @return string human readable size
1478 *
1479 * @author      Martin Benjamin <b.martin@cybernet.ch>
1480 * @author      Aidan Lister <aidan@php.net>
1481 * @version     1.0.0
1482 */
1483function filesize_h($size, $dec = 1) {
1484    $sizes = array('B', 'KB', 'MB', 'GB');
1485    $count = count($sizes);
1486    $i     = 0;
1487
1488    while($size >= 1024 && ($i < $count - 1)) {
1489        $size /= 1024;
1490        $i++;
1491    }
1492
1493    return round($size, $dec)."\xC2\xA0".$sizes[$i]; //non-breaking space
1494}
1495
1496/**
1497 * Return the given timestamp as human readable, fuzzy age
1498 *
1499 * @author Andreas Gohr <gohr@cosmocode.de>
1500 *
1501 * @param int $dt timestamp
1502 * @return string
1503 */
1504function datetime_h($dt) {
1505    global $lang;
1506
1507    $ago = time() - $dt;
1508    if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1509        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1510    }
1511    if($ago > 24 * 60 * 60 * 30 * 2) {
1512        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1513    }
1514    if($ago > 24 * 60 * 60 * 7 * 2) {
1515        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1516    }
1517    if($ago > 24 * 60 * 60 * 2) {
1518        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1519    }
1520    if($ago > 60 * 60 * 2) {
1521        return sprintf($lang['hours'], round($ago / (60 * 60)));
1522    }
1523    if($ago > 60 * 2) {
1524        return sprintf($lang['minutes'], round($ago / (60)));
1525    }
1526    return sprintf($lang['seconds'], $ago);
1527}
1528
1529/**
1530 * Wraps around strftime but provides support for fuzzy dates
1531 *
1532 * The format default to $conf['dformat']. It is passed to
1533 * strftime - %f can be used to get the value from datetime_h()
1534 *
1535 * @see datetime_h
1536 * @author Andreas Gohr <gohr@cosmocode.de>
1537 *
1538 * @param int|null $dt      timestamp when given, null will take current timestamp
1539 * @param string   $format  empty default to $conf['dformat'], or provide format as recognized by strftime()
1540 * @return string
1541 */
1542function dformat($dt = null, $format = '') {
1543    global $conf;
1544
1545    if(is_null($dt)) $dt = time();
1546    $dt = (int) $dt;
1547    if(!$format) $format = $conf['dformat'];
1548
1549    $format = str_replace('%f', datetime_h($dt), $format);
1550    return strftime($format, $dt);
1551}
1552
1553/**
1554 * Formats a timestamp as ISO 8601 date
1555 *
1556 * @author <ungu at terong dot com>
1557 * @link http://php.net/manual/en/function.date.php#54072
1558 *
1559 * @param int $int_date current date in UNIX timestamp
1560 * @return string
1561 */
1562function date_iso8601($int_date) {
1563    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1564    $pre_timezone = date('O', $int_date);
1565    $time_zone    = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1566    $date_mod .= $time_zone;
1567    return $date_mod;
1568}
1569
1570/**
1571 * return an obfuscated email address in line with $conf['mailguard'] setting
1572 *
1573 * @author Harry Fuecks <hfuecks@gmail.com>
1574 * @author Christopher Smith <chris@jalakai.co.uk>
1575 *
1576 * @param string $email email address
1577 * @return string
1578 */
1579function obfuscate($email) {
1580    global $conf;
1581
1582    switch($conf['mailguard']) {
1583        case 'visible' :
1584            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
1585            return strtr($email, $obfuscate);
1586
1587        case 'hex' :
1588            $encode = '';
1589            $len    = strlen($email);
1590            for($x = 0; $x < $len; $x++) {
1591                $encode .= '&#x'.bin2hex($email{$x}).';';
1592            }
1593            return $encode;
1594
1595        case 'none' :
1596        default :
1597            return $email;
1598    }
1599}
1600
1601/**
1602 * Removes quoting backslashes
1603 *
1604 * @author Andreas Gohr <andi@splitbrain.org>
1605 *
1606 * @param string $string
1607 * @param string $char backslashed character
1608 * @return string
1609 */
1610function unslash($string, $char = "'") {
1611    return str_replace('\\'.$char, $char, $string);
1612}
1613
1614/**
1615 * Convert php.ini shorthands to byte
1616 *
1617 * @author <gilthans dot NO dot SPAM at gmail dot com>
1618 * @link   http://php.net/manual/en/ini.core.php#79564
1619 *
1620 * @param string $v shorthands
1621 * @return int|string
1622 */
1623function php_to_byte($v) {
1624    $l   = substr($v, -1);
1625    $ret = substr($v, 0, -1);
1626    switch(strtoupper($l)) {
1627        /** @noinspection PhpMissingBreakStatementInspection */
1628        case 'P':
1629            $ret *= 1024;
1630        /** @noinspection PhpMissingBreakStatementInspection */
1631        case 'T':
1632            $ret *= 1024;
1633        /** @noinspection PhpMissingBreakStatementInspection */
1634        case 'G':
1635            $ret *= 1024;
1636        /** @noinspection PhpMissingBreakStatementInspection */
1637        case 'M':
1638            $ret *= 1024;
1639        /** @noinspection PhpMissingBreakStatementInspection */
1640        case 'K':
1641            $ret *= 1024;
1642            break;
1643        default;
1644            $ret *= 10;
1645            break;
1646    }
1647    return $ret;
1648}
1649
1650/**
1651 * Wrapper around preg_quote adding the default delimiter
1652 *
1653 * @param string $string
1654 * @return string
1655 */
1656function preg_quote_cb($string) {
1657    return preg_quote($string, '/');
1658}
1659
1660/**
1661 * Shorten a given string by removing data from the middle
1662 *
1663 * You can give the string in two parts, the first part $keep
1664 * will never be shortened. The second part $short will be cut
1665 * in the middle to shorten but only if at least $min chars are
1666 * left to display it. Otherwise it will be left off.
1667 *
1668 * @param string $keep   the part to keep
1669 * @param string $short  the part to shorten
1670 * @param int    $max    maximum chars you want for the whole string
1671 * @param int    $min    minimum number of chars to have left for middle shortening
1672 * @param string $char   the shortening character to use
1673 * @return string
1674 */
1675function shorten($keep, $short, $max, $min = 9, $char = '…') {
1676    $max = $max - utf8_strlen($keep);
1677    if($max < $min) return $keep;
1678    $len = utf8_strlen($short);
1679    if($len <= $max) return $keep.$short;
1680    $half = floor($max / 2);
1681    return $keep.utf8_substr($short, 0, $half - 1).$char.utf8_substr($short, $len - $half);
1682}
1683
1684/**
1685 * Return the users real name or e-mail address for use
1686 * in page footer and recent changes pages
1687 *
1688 * @param string|null $username or null when currently logged-in user should be used
1689 * @param bool $textonly true returns only plain text, true allows returning html
1690 * @return string html or plain text(not escaped) of formatted user name
1691 *
1692 * @author Andy Webber <dokuwiki AT andywebber DOT com>
1693 */
1694function editorinfo($username, $textonly = false) {
1695    return userlink($username, $textonly);
1696}
1697
1698/**
1699 * Returns users realname w/o link
1700 *
1701 * @param string|null $username or null when currently logged-in user should be used
1702 * @param bool $textonly true returns only plain text, true allows returning html
1703 * @return string html or plain text(not escaped) of formatted user name
1704 *
1705 * @triggers COMMON_USER_LINK
1706 */
1707function userlink($username = null, $textonly = false) {
1708    global $conf, $INFO;
1709    /** @var DokuWiki_Auth_Plugin $auth */
1710    global $auth;
1711    /** @var Input $INPUT */
1712    global $INPUT;
1713
1714    // prepare initial event data
1715    $data = array(
1716        'username' => $username, // the unique user name
1717        'name' => '',
1718        'link' => array( //setting 'link' to false disables linking
1719                         'target' => '',
1720                         'pre' => '',
1721                         'suf' => '',
1722                         'style' => '',
1723                         'more' => '',
1724                         'url' => '',
1725                         'title' => '',
1726                         'class' => ''
1727        ),
1728        'userlink' => '', // formatted user name as will be returned
1729        'textonly' => $textonly
1730    );
1731    if($username === null) {
1732        $data['username'] = $username = $INPUT->server->str('REMOTE_USER');
1733        if($textonly){
1734            $data['name'] = $INFO['userinfo']['name']. ' (' . $INPUT->server->str('REMOTE_USER') . ')';
1735        }else {
1736            $data['name'] = '<bdi>' . hsc($INFO['userinfo']['name']) . '</bdi> (<bdi>' . hsc($INPUT->server->str('REMOTE_USER')) . '</bdi>)';
1737        }
1738    }
1739
1740    $evt = new Doku_Event('COMMON_USER_LINK', $data);
1741    if($evt->advise_before(true)) {
1742        if(empty($data['name'])) {
1743            if($auth) $info = $auth->getUserData($username);
1744            if($conf['showuseras'] != 'loginname' && isset($info) && $info) {
1745                switch($conf['showuseras']) {
1746                    case 'username':
1747                    case 'username_link':
1748                        $data['name'] = $textonly ? $info['name'] : hsc($info['name']);
1749                        break;
1750                    case 'email':
1751                    case 'email_link':
1752                        $data['name'] = obfuscate($info['mail']);
1753                        break;
1754                }
1755            } else {
1756                $data['name'] = $textonly ? $data['username'] : hsc($data['username']);
1757            }
1758        }
1759
1760        /** @var Doku_Renderer_xhtml $xhtml_renderer */
1761        static $xhtml_renderer = null;
1762
1763        if(!$data['textonly'] && empty($data['link']['url'])) {
1764
1765            if(in_array($conf['showuseras'], array('email_link', 'username_link'))) {
1766                if(!isset($info)) {
1767                    if($auth) $info = $auth->getUserData($username);
1768                }
1769                if(isset($info) && $info) {
1770                    if($conf['showuseras'] == 'email_link') {
1771                        $data['link']['url'] = 'mailto:' . obfuscate($info['mail']);
1772                    } else {
1773                        if(is_null($xhtml_renderer)) {
1774                            $xhtml_renderer = p_get_renderer('xhtml');
1775                        }
1776                        if(empty($xhtml_renderer->interwiki)) {
1777                            $xhtml_renderer->interwiki = getInterwiki();
1778                        }
1779                        $shortcut = 'user';
1780                        $exists = null;
1781                        $data['link']['url'] = $xhtml_renderer->_resolveInterWiki($shortcut, $username, $exists);
1782                        $data['link']['class'] .= ' interwiki iw_user';
1783                        if($exists !== null) {
1784                            if($exists) {
1785                                $data['link']['class'] .= ' wikilink1';
1786                            } else {
1787                                $data['link']['class'] .= ' wikilink2';
1788                                $data['link']['rel'] = 'nofollow';
1789                            }
1790                        }
1791                    }
1792                } else {
1793                    $data['textonly'] = true;
1794                }
1795
1796            } else {
1797                $data['textonly'] = true;
1798            }
1799        }
1800
1801        if($data['textonly']) {
1802            $data['userlink'] = $data['name'];
1803        } else {
1804            $data['link']['name'] = $data['name'];
1805            if(is_null($xhtml_renderer)) {
1806                $xhtml_renderer = p_get_renderer('xhtml');
1807            }
1808            $data['userlink'] = $xhtml_renderer->_formatLink($data['link']);
1809        }
1810    }
1811    $evt->advise_after();
1812    unset($evt);
1813
1814    return $data['userlink'];
1815}
1816
1817/**
1818 * Returns the path to a image file for the currently chosen license.
1819 * When no image exists, returns an empty string
1820 *
1821 * @author Andreas Gohr <andi@splitbrain.org>
1822 *
1823 * @param  string $type - type of image 'badge' or 'button'
1824 * @return string
1825 */
1826function license_img($type) {
1827    global $license;
1828    global $conf;
1829    if(!$conf['license']) return '';
1830    if(!is_array($license[$conf['license']])) return '';
1831    $try   = array();
1832    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1833    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1834    if(substr($conf['license'], 0, 3) == 'cc-') {
1835        $try[] = 'lib/images/license/'.$type.'/cc.png';
1836    }
1837    foreach($try as $src) {
1838        if(file_exists(DOKU_INC.$src)) return $src;
1839    }
1840    return '';
1841}
1842
1843/**
1844 * Checks if the given amount of memory is available
1845 *
1846 * If the memory_get_usage() function is not available the
1847 * function just assumes $bytes of already allocated memory
1848 *
1849 * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
1850 * @author Andreas Gohr <andi@splitbrain.org>
1851 *
1852 * @param int  $mem    Size of memory you want to allocate in bytes
1853 * @param int  $bytes  already allocated memory (see above)
1854 * @return bool
1855 */
1856function is_mem_available($mem, $bytes = 1048576) {
1857    $limit = trim(ini_get('memory_limit'));
1858    if(empty($limit)) return true; // no limit set!
1859
1860    // parse limit to bytes
1861    $limit = php_to_byte($limit);
1862
1863    // get used memory if possible
1864    if(function_exists('memory_get_usage')) {
1865        $used = memory_get_usage();
1866    } else {
1867        $used = $bytes;
1868    }
1869
1870    if($used + $mem > $limit) {
1871        return false;
1872    }
1873
1874    return true;
1875}
1876
1877/**
1878 * Send a HTTP redirect to the browser
1879 *
1880 * Works arround Microsoft IIS cookie sending bug. Exits the script.
1881 *
1882 * @link   http://support.microsoft.com/kb/q176113/
1883 * @author Andreas Gohr <andi@splitbrain.org>
1884 *
1885 * @param string $url url being directed to
1886 */
1887function send_redirect($url) {
1888    $url = stripctl($url); // defend against HTTP Response Splitting
1889
1890    /* @var Input $INPUT */
1891    global $INPUT;
1892
1893    //are there any undisplayed messages? keep them in session for display
1894    global $MSG;
1895    if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
1896        //reopen session, store data and close session again
1897        @session_start();
1898        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
1899    }
1900
1901    // always close the session
1902    session_write_close();
1903
1904    // check if running on IIS < 6 with CGI-PHP
1905    if($INPUT->server->has('SERVER_SOFTWARE') && $INPUT->server->has('GATEWAY_INTERFACE') &&
1906        (strpos($INPUT->server->str('GATEWAY_INTERFACE'), 'CGI') !== false) &&
1907        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($INPUT->server->str('SERVER_SOFTWARE')), $matches)) &&
1908        $matches[1] < 6
1909    ) {
1910        header('Refresh: 0;url='.$url);
1911    } else {
1912        header('Location: '.$url);
1913    }
1914
1915    if(defined('DOKU_UNITTEST')) return; // no exits during unit tests
1916    exit;
1917}
1918
1919/**
1920 * Validate a value using a set of valid values
1921 *
1922 * This function checks whether a specified value is set and in the array
1923 * $valid_values. If not, the function returns a default value or, if no
1924 * default is specified, throws an exception.
1925 *
1926 * @param string $param        The name of the parameter
1927 * @param array  $valid_values A set of valid values; Optionally a default may
1928 *                             be marked by the key “default”.
1929 * @param array  $array        The array containing the value (typically $_POST
1930 *                             or $_GET)
1931 * @param string $exc          The text of the raised exception
1932 *
1933 * @throws Exception
1934 * @return mixed
1935 * @author Adrian Lang <lang@cosmocode.de>
1936 */
1937function valid_input_set($param, $valid_values, $array, $exc = '') {
1938    if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
1939        return $array[$param];
1940    } elseif(isset($valid_values['default'])) {
1941        return $valid_values['default'];
1942    } else {
1943        throw new Exception($exc);
1944    }
1945}
1946
1947/**
1948 * Read a preference from the DokuWiki cookie
1949 * (remembering both keys & values are urlencoded)
1950 *
1951 * @param string $pref     preference key
1952 * @param mixed  $default  value returned when preference not found
1953 * @return string preference value
1954 */
1955function get_doku_pref($pref, $default) {
1956    $enc_pref = urlencode($pref);
1957    if(isset($_COOKIE['DOKU_PREFS']) && strpos($_COOKIE['DOKU_PREFS'], $enc_pref) !== false) {
1958        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
1959        $cnt   = count($parts);
1960        for($i = 0; $i < $cnt; $i += 2) {
1961            if($parts[$i] == $enc_pref) {
1962                return urldecode($parts[$i + 1]);
1963            }
1964        }
1965    }
1966    return $default;
1967}
1968
1969/**
1970 * Add a preference to the DokuWiki cookie
1971 * (remembering $_COOKIE['DOKU_PREFS'] is urlencoded)
1972 * Remove it by setting $val to false
1973 *
1974 * @param string $pref  preference key
1975 * @param string $val   preference value
1976 */
1977function set_doku_pref($pref, $val) {
1978    global $conf;
1979    $orig = get_doku_pref($pref, false);
1980    $cookieVal = '';
1981
1982    if($orig && ($orig != $val)) {
1983        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
1984        $cnt   = count($parts);
1985        // urlencode $pref for the comparison
1986        $enc_pref = rawurlencode($pref);
1987        for($i = 0; $i < $cnt; $i += 2) {
1988            if($parts[$i] == $enc_pref) {
1989                if ($val !== false) {
1990                    $parts[$i + 1] = rawurlencode($val);
1991                } else {
1992                    unset($parts[$i]);
1993                    unset($parts[$i + 1]);
1994                }
1995                break;
1996            }
1997        }
1998        $cookieVal = implode('#', $parts);
1999    } else if (!$orig && $val !== false) {
2000        $cookieVal = ($_COOKIE['DOKU_PREFS'] ? $_COOKIE['DOKU_PREFS'].'#' : '').rawurlencode($pref).'#'.rawurlencode($val);
2001    }
2002
2003    if (!empty($cookieVal)) {
2004        $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
2005        setcookie('DOKU_PREFS', $cookieVal, time()+365*24*3600, $cookieDir, '', ($conf['securecookie'] && is_ssl()));
2006    }
2007}
2008
2009/**
2010 * Strips source mapping declarations from given text #601
2011 *
2012 * @param string &$text reference to the CSS or JavaScript code to clean
2013 */
2014function stripsourcemaps(&$text){
2015    $text = preg_replace('/^(\/\/|\/\*)[@#]\s+sourceMappingURL=.*?(\*\/)?$/im', '\\1\\2', $text);
2016}
2017
2018/**
2019 * Returns the contents of a given SVG file for embedding
2020 *
2021 * Inlining SVGs saves on HTTP requests and more importantly allows for styling them through
2022 * CSS. However it should used with small SVGs only. The $maxsize setting ensures only small
2023 * files are embedded.
2024 *
2025 * This strips unneeded headers, comments and newline. The result is not a vaild standalone SVG!
2026 *
2027 * @param string $file full path to the SVG file
2028 * @param int $maxsize maximum allowed size for the SVG to be embedded
2029 * @return string|false the SVG content, false if the file couldn't be loaded
2030 */
2031function inlineSVG($file, $maxsize = 2048) {
2032    $file = trim($file);
2033    if($file === '') return false;
2034    if(!file_exists($file)) return false;
2035    if(filesize($file) > $maxsize) return false;
2036    if(!is_readable($file)) return false;
2037    $content = file_get_contents($file);
2038    $content = preg_replace('/<!--.*?(-->)/s','', $content); // comments
2039    $content = preg_replace('/<\?xml .*?\?>/i', '', $content); // xml header
2040    $content = preg_replace('/<!DOCTYPE .*?>/i', '', $content); // doc type
2041    $content = preg_replace('/>\s+</s', '><', $content); // newlines between tags
2042    $content = trim($content);
2043    if(substr($content, 0, 5) !== '<svg ') return false;
2044    return $content;
2045}
2046
2047//Setup VIM: ex: et ts=2 :
2048