xref: /dokuwiki/inc/common.php (revision 7eaa7703a43b9f22f12be04e8580a3f2515fb146)
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 */
26function hsc($string) {
27    return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
28}
29
30/**
31 * print a newline terminated string
32 *
33 * You can give an indention as optional parameter
34 *
35 * @author Andreas Gohr <andi@splitbrain.org>
36 */
37function ptln($string, $indent = 0) {
38    echo str_repeat(' ', $indent)."$string\n";
39}
40
41/**
42 * strips control characters (<32) from the given string
43 *
44 * @author Andreas Gohr <andi@splitbrain.org>
45 */
46function stripctl($string) {
47    return preg_replace('/[\x00-\x1F]+/s', '', $string);
48}
49
50/**
51 * Return a secret token to be used for CSRF attack prevention
52 *
53 * @author  Andreas Gohr <andi@splitbrain.org>
54 * @link    http://en.wikipedia.org/wiki/Cross-site_request_forgery
55 * @link    http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
56 * @return  string
57 */
58function getSecurityToken() {
59    return md5(auth_cookiesalt().session_id().$_SERVER['REMOTE_USER']);
60}
61
62/**
63 * Check the secret CSRF token
64 */
65function checkSecurityToken($token = null) {
66    global $INPUT;
67    if(!$_SERVER['REMOTE_USER']) return true; // no logged in user, no need for a check
68
69    if(is_null($token)) $token = $INPUT->str('sectok');
70    if(getSecurityToken() != $token) {
71        msg('Security Token did not match. Possible CSRF attack.', -1);
72        return false;
73    }
74    return true;
75}
76
77/**
78 * Print a hidden form field with a secret CSRF token
79 *
80 * @author  Andreas Gohr <andi@splitbrain.org>
81 */
82function formSecurityToken($print = true) {
83    $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
84    if($print) echo $ret;
85    return $ret;
86}
87
88/**
89 * Return info about the current document as associative
90 * array.
91 *
92 * @author Andreas Gohr <andi@splitbrain.org>
93 */
94function pageinfo() {
95    global $ID;
96    global $REV;
97    global $RANGE;
98    global $USERINFO;
99    global $lang;
100
101    // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
102    // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
103    $info['id']  = $ID;
104    $info['rev'] = $REV;
105
106    // set info about manager/admin status.
107    $info['isadmin']   = false;
108    $info['ismanager'] = false;
109    if(isset($_SERVER['REMOTE_USER'])) {
110        $info['userinfo']   = $USERINFO;
111        $info['perm']       = auth_quickaclcheck($ID);
112        $info['subscribed'] = get_info_subscribed();
113        $info['client']     = $_SERVER['REMOTE_USER'];
114
115        if($info['perm'] == AUTH_ADMIN) {
116            $info['isadmin']   = true;
117            $info['ismanager'] = true;
118        } elseif(auth_ismanager()) {
119            $info['ismanager'] = true;
120        }
121
122        // if some outside auth were used only REMOTE_USER is set
123        if(!$info['userinfo']['name']) {
124            $info['userinfo']['name'] = $_SERVER['REMOTE_USER'];
125        }
126
127    } else {
128        $info['perm']       = auth_aclcheck($ID, '', null);
129        $info['subscribed'] = false;
130        $info['client']     = clientIP(true);
131    }
132
133    $info['namespace'] = getNS($ID);
134    $info['locked']    = checklock($ID);
135    $info['filepath']  = fullpath(wikiFN($ID));
136    $info['exists']    = @file_exists($info['filepath']);
137    if($REV) {
138        //check if current revision was meant
139        if($info['exists'] && (@filemtime($info['filepath']) == $REV)) {
140            $REV = '';
141        } elseif($RANGE) {
142            //section editing does not work with old revisions!
143            $REV   = '';
144            $RANGE = '';
145            msg($lang['nosecedit'], 0);
146        } else {
147            //really use old revision
148            $info['filepath'] = fullpath(wikiFN($ID, $REV));
149            $info['exists']   = @file_exists($info['filepath']);
150        }
151    }
152    $info['rev'] = $REV;
153    if($info['exists']) {
154        $info['writable'] = (is_writable($info['filepath']) &&
155            ($info['perm'] >= AUTH_EDIT));
156    } else {
157        $info['writable'] = ($info['perm'] >= AUTH_CREATE);
158    }
159    $info['editable'] = ($info['writable'] && empty($info['locked']));
160    $info['lastmod']  = @filemtime($info['filepath']);
161
162    //load page meta data
163    $info['meta'] = p_get_metadata($ID);
164
165    //who's the editor
166    if($REV) {
167        $revinfo = getRevisionInfo($ID, $REV, 1024);
168    } else {
169        if(is_array($info['meta']['last_change'])) {
170            $revinfo = $info['meta']['last_change'];
171        } else {
172            $revinfo = getRevisionInfo($ID, $info['lastmod'], 1024);
173            // cache most recent changelog line in metadata if missing and still valid
174            if($revinfo !== false) {
175                $info['meta']['last_change'] = $revinfo;
176                p_set_metadata($ID, array('last_change' => $revinfo));
177            }
178        }
179    }
180    //and check for an external edit
181    if($revinfo !== false && $revinfo['date'] != $info['lastmod']) {
182        // cached changelog line no longer valid
183        $revinfo                     = false;
184        $info['meta']['last_change'] = $revinfo;
185        p_set_metadata($ID, array('last_change' => $revinfo));
186    }
187
188    $info['ip']   = $revinfo['ip'];
189    $info['user'] = $revinfo['user'];
190    $info['sum']  = $revinfo['sum'];
191    // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
192    // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
193
194    if($revinfo['user']) {
195        $info['editor'] = $revinfo['user'];
196    } else {
197        $info['editor'] = $revinfo['ip'];
198    }
199
200    // draft
201    $draft = getCacheName($info['client'].$ID, '.draft');
202    if(@file_exists($draft)) {
203        if(@filemtime($draft) < @filemtime(wikiFN($ID))) {
204            // remove stale draft
205            @unlink($draft);
206        } else {
207            $info['draft'] = $draft;
208        }
209    }
210
211    // mobile detection
212    $info['ismobile'] = clientismobile();
213
214    return $info;
215}
216
217/**
218 * Build an string of URL parameters
219 *
220 * @author Andreas Gohr
221 */
222function buildURLparams($params, $sep = '&amp;') {
223    $url = '';
224    $amp = false;
225    foreach($params as $key => $val) {
226        if($amp) $url .= $sep;
227
228        $url .= rawurlencode($key).'=';
229        $url .= rawurlencode((string) $val);
230        $amp = true;
231    }
232    return $url;
233}
234
235/**
236 * Build an string of html tag attributes
237 *
238 * Skips keys starting with '_', values get HTML encoded
239 *
240 * @author Andreas Gohr
241 */
242function buildAttributes($params, $skipempty = false) {
243    $url   = '';
244    $white = false;
245    foreach($params as $key => $val) {
246        if($key{0} == '_') continue;
247        if($val === '' && $skipempty) continue;
248        if($white) $url .= ' ';
249
250        $url .= $key.'="';
251        $url .= htmlspecialchars($val);
252        $url .= '"';
253        $white = true;
254    }
255    return $url;
256}
257
258/**
259 * This builds the breadcrumb trail and returns it as array
260 *
261 * @author Andreas Gohr <andi@splitbrain.org>
262 */
263function breadcrumbs() {
264    // we prepare the breadcrumbs early for quick session closing
265    static $crumbs = null;
266    if($crumbs != null) return $crumbs;
267
268    global $ID;
269    global $ACT;
270    global $conf;
271
272    //first visit?
273    $crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array();
274    //we only save on show and existing wiki documents
275    $file = wikiFN($ID);
276    if($ACT != 'show' || !@file_exists($file)) {
277        $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
278        return $crumbs;
279    }
280
281    // page names
282    $name = noNSorNS($ID);
283    if(useHeading('navigation')) {
284        // get page title
285        $title = p_get_first_heading($ID, METADATA_RENDER_USING_SIMPLE_CACHE);
286        if($title) {
287            $name = $title;
288        }
289    }
290
291    //remove ID from array
292    if(isset($crumbs[$ID])) {
293        unset($crumbs[$ID]);
294    }
295
296    //add to array
297    $crumbs[$ID] = $name;
298    //reduce size
299    while(count($crumbs) > $conf['breadcrumbs']) {
300        array_shift($crumbs);
301    }
302    //save to session
303    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
304    return $crumbs;
305}
306
307/**
308 * Filter for page IDs
309 *
310 * This is run on a ID before it is outputted somewhere
311 * currently used to replace the colon with something else
312 * on Windows systems and to have proper URL encoding
313 *
314 * Urlencoding is ommitted when the second parameter is false
315 *
316 * @author Andreas Gohr <andi@splitbrain.org>
317 */
318function idfilter($id, $ue = true) {
319    global $conf;
320    if($conf['useslash'] && $conf['userewrite']) {
321        $id = strtr($id, ':', '/');
322    } elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
323        $conf['userewrite'] &&
324        strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') === false
325    ) {
326        $id = strtr($id, ':', ';');
327    }
328    if($ue) {
329        $id = rawurlencode($id);
330        $id = str_replace('%3A', ':', $id); //keep as colon
331        $id = str_replace('%3B', ';', $id); //keep as semicolon
332        $id = str_replace('%2F', '/', $id); //keep as slash
333    }
334    return $id;
335}
336
337/**
338 * This builds a link to a wikipage
339 *
340 * It handles URL rewriting and adds additional parameter if
341 * given in $more
342 *
343 * @author Andreas Gohr <andi@splitbrain.org>
344 */
345function wl($id = '', $urlParameters = '', $absolute = false, $separator = '&amp;') {
346    global $conf;
347    if(is_array($urlParameters)) {
348        $urlParameters = buildURLparams($urlParameters, $separator);
349    } else {
350        $urlParameters = str_replace(',', $separator, $urlParameters);
351    }
352    if($id === '') {
353        $id = $conf['start'];
354    }
355    $id = idfilter($id);
356    if($absolute) {
357        $xlink = DOKU_URL;
358    } else {
359        $xlink = DOKU_BASE;
360    }
361
362    if($conf['userewrite'] == 2) {
363        $xlink .= DOKU_SCRIPT.'/'.$id;
364        if($urlParameters) $xlink .= '?'.$urlParameters;
365    } elseif($conf['userewrite']) {
366        $xlink .= $id;
367        if($urlParameters) $xlink .= '?'.$urlParameters;
368    } elseif($id) {
369        $xlink .= DOKU_SCRIPT.'?id='.$id;
370        if($urlParameters) $xlink .= $separator.$urlParameters;
371    } else {
372        $xlink .= DOKU_SCRIPT;
373        if($urlParameters) $xlink .= '?'.$urlParameters;
374    }
375
376    return $xlink;
377}
378
379/**
380 * This builds a link to an alternate page format
381 *
382 * Handles URL rewriting if enabled. Follows the style of wl().
383 *
384 * @author Ben Coburn <btcoburn@silicodon.net>
385 */
386function exportlink($id = '', $format = 'raw', $more = '', $abs = false, $sep = '&amp;') {
387    global $conf;
388    if(is_array($more)) {
389        $more = buildURLparams($more, $sep);
390    } else {
391        $more = str_replace(',', $sep, $more);
392    }
393
394    $format = rawurlencode($format);
395    $id     = idfilter($id);
396    if($abs) {
397        $xlink = DOKU_URL;
398    } else {
399        $xlink = DOKU_BASE;
400    }
401
402    if($conf['userewrite'] == 2) {
403        $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
404        if($more) $xlink .= $sep.$more;
405    } elseif($conf['userewrite'] == 1) {
406        $xlink .= '_export/'.$format.'/'.$id;
407        if($more) $xlink .= '?'.$more;
408    } else {
409        $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
410        if($more) $xlink .= $sep.$more;
411    }
412
413    return $xlink;
414}
415
416/**
417 * Build a link to a media file
418 *
419 * Will return a link to the detail page if $direct is false
420 *
421 * The $more parameter should always be given as array, the function then
422 * will strip default parameters to produce even cleaner URLs
423 *
424 * @param string  $id     the media file id or URL
425 * @param mixed   $more   string or array with additional parameters
426 * @param bool    $direct link to detail page if false
427 * @param string  $sep    URL parameter separator
428 * @param bool    $abs    Create an absolute URL
429 * @return string
430 */
431function ml($id = '', $more = '', $direct = true, $sep = '&amp;', $abs = false) {
432    global $conf;
433    if(is_array($more)) {
434        // strip defaults for shorter URLs
435        if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
436        if(!$more['w']) unset($more['w']);
437        if(!$more['h']) unset($more['h']);
438        if(isset($more['id']) && $direct) unset($more['id']);
439        $more = buildURLparams($more, $sep);
440    } else {
441        $more = str_replace('cache=cache', '', $more); //skip default
442        $more = str_replace(',,', ',', $more);
443        $more = str_replace(',', $sep, $more);
444    }
445
446    if($abs) {
447        $xlink = DOKU_URL;
448    } else {
449        $xlink = DOKU_BASE;
450    }
451
452    // external URLs are always direct without rewriting
453    if(preg_match('#^(https?|ftp)://#i', $id)) {
454        $xlink .= 'lib/exe/fetch.php';
455        // add hash:
456        $xlink .= '?hash='.substr(md5(auth_cookiesalt().$id), 0, 6);
457        if($more) {
458            $xlink .= $sep.$more;
459            $xlink .= $sep.'media='.rawurlencode($id);
460        } else {
461            $xlink .= $sep.'media='.rawurlencode($id);
462        }
463        return $xlink;
464    }
465
466    $id = idfilter($id);
467
468    // decide on scriptname
469    if($direct) {
470        if($conf['userewrite'] == 1) {
471            $script = '_media';
472        } else {
473            $script = 'lib/exe/fetch.php';
474        }
475    } else {
476        if($conf['userewrite'] == 1) {
477            $script = '_detail';
478        } else {
479            $script = 'lib/exe/detail.php';
480        }
481    }
482
483    // build URL based on rewrite mode
484    if($conf['userewrite']) {
485        $xlink .= $script.'/'.$id;
486        if($more) $xlink .= '?'.$more;
487    } else {
488        if($more) {
489            $xlink .= $script.'?'.$more;
490            $xlink .= $sep.'media='.$id;
491        } else {
492            $xlink .= $script.'?media='.$id;
493        }
494    }
495
496    return $xlink;
497}
498
499/**
500 * Returns the URL to the DokuWiki base script
501 *
502 * Consider using wl() instead, unless you absoutely need the doku.php endpoint
503 *
504 * @author Andreas Gohr <andi@splitbrain.org>
505 */
506function script() {
507    return DOKU_BASE.DOKU_SCRIPT;
508}
509
510/**
511 * Spamcheck against wordlist
512 *
513 * Checks the wikitext against a list of blocked expressions
514 * returns true if the text contains any bad words
515 *
516 * Triggers COMMON_WORDBLOCK_BLOCKED
517 *
518 *  Action Plugins can use this event to inspect the blocked data
519 *  and gain information about the user who was blocked.
520 *
521 *  Event data:
522 *    data['matches']  - array of matches
523 *    data['userinfo'] - information about the blocked user
524 *      [ip]           - ip address
525 *      [user]         - username (if logged in)
526 *      [mail]         - mail address (if logged in)
527 *      [name]         - real name (if logged in)
528 *
529 * @author Andreas Gohr <andi@splitbrain.org>
530 * @author Michael Klier <chi@chimeric.de>
531 * @param  string $text - optional text to check, if not given the globals are used
532 * @return bool         - true if a spam word was found
533 */
534function checkwordblock($text = '') {
535    global $TEXT;
536    global $PRE;
537    global $SUF;
538    global $conf;
539    global $INFO;
540
541    if(!$conf['usewordblock']) return false;
542
543    if(!$text) $text = "$PRE $TEXT $SUF";
544
545    // we prepare the text a tiny bit to prevent spammers circumventing URL checks
546    $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i', '\1http://\2 \2\3', $text);
547
548    $wordblocks = getWordblocks();
549    // how many lines to read at once (to work around some PCRE limits)
550    if(version_compare(phpversion(), '4.3.0', '<')) {
551        // old versions of PCRE define a maximum of parenthesises even if no
552        // backreferences are used - the maximum is 99
553        // this is very bad performancewise and may even be too high still
554        $chunksize = 40;
555    } else {
556        // read file in chunks of 200 - this should work around the
557        // MAX_PATTERN_SIZE in modern PCRE
558        $chunksize = 200;
559    }
560    while($blocks = array_splice($wordblocks, 0, $chunksize)) {
561        $re = array();
562        // build regexp from blocks
563        foreach($blocks as $block) {
564            $block = preg_replace('/#.*$/', '', $block);
565            $block = trim($block);
566            if(empty($block)) continue;
567            $re[] = $block;
568        }
569        if(count($re) && preg_match('#('.join('|', $re).')#si', $text, $matches)) {
570            // prepare event data
571            $data['matches']        = $matches;
572            $data['userinfo']['ip'] = $_SERVER['REMOTE_ADDR'];
573            if($_SERVER['REMOTE_USER']) {
574                $data['userinfo']['user'] = $_SERVER['REMOTE_USER'];
575                $data['userinfo']['name'] = $INFO['userinfo']['name'];
576                $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
577            }
578            $callback = create_function('', 'return true;');
579            return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
580        }
581    }
582    return false;
583}
584
585/**
586 * Return the IP of the client
587 *
588 * Honours X-Forwarded-For and X-Real-IP Proxy Headers
589 *
590 * It returns a comma separated list of IPs if the above mentioned
591 * headers are set. If the single parameter is set, it tries to return
592 * a routable public address, prefering the ones suplied in the X
593 * headers
594 *
595 * @author Andreas Gohr <andi@splitbrain.org>
596 * @param  boolean $single If set only a single IP is returned
597 * @return string
598 */
599function clientIP($single = false) {
600    $ip   = array();
601    $ip[] = $_SERVER['REMOTE_ADDR'];
602    if(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
603        $ip = array_merge($ip, explode(',', str_replace(' ', '', $_SERVER['HTTP_X_FORWARDED_FOR'])));
604    if(!empty($_SERVER['HTTP_X_REAL_IP']))
605        $ip = array_merge($ip, explode(',', str_replace(' ', '', $_SERVER['HTTP_X_REAL_IP'])));
606
607    // some IPv4/v6 regexps borrowed from Feyd
608    // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
609    $dec_octet   = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
610    $hex_digit   = '[A-Fa-f0-9]';
611    $h16         = "{$hex_digit}{1,4}";
612    $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
613    $ls32        = "(?:$h16:$h16|$IPv4Address)";
614    $IPv6Address =
615        "(?:(?:{$IPv4Address})|(?:".
616            "(?:$h16:){6}$ls32".
617            "|::(?:$h16:){5}$ls32".
618            "|(?:$h16)?::(?:$h16:){4}$ls32".
619            "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32".
620            "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32".
621            "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32".
622            "|(?:(?:$h16:){0,4}$h16)?::$ls32".
623            "|(?:(?:$h16:){0,5}$h16)?::$h16".
624            "|(?:(?:$h16:){0,6}$h16)?::".
625            ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
626
627    // remove any non-IP stuff
628    $cnt   = count($ip);
629    $match = array();
630    for($i = 0; $i < $cnt; $i++) {
631        if(preg_match("/^$IPv4Address$/", $ip[$i], $match) || preg_match("/^$IPv6Address$/", $ip[$i], $match)) {
632            $ip[$i] = $match[0];
633        } else {
634            $ip[$i] = '';
635        }
636        if(empty($ip[$i])) unset($ip[$i]);
637    }
638    $ip = array_values(array_unique($ip));
639    if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
640
641    if(!$single) return join(',', $ip);
642
643    // decide which IP to use, trying to avoid local addresses
644    $ip = array_reverse($ip);
645    foreach($ip as $i) {
646        if(preg_match('/^(::1|[fF][eE]80:|127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/', $i)) {
647            continue;
648        } else {
649            return $i;
650        }
651    }
652    // still here? just use the first (last) address
653    return $ip[0];
654}
655
656/**
657 * Check if the browser is on a mobile device
658 *
659 * Adapted from the example code at url below
660 *
661 * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
662 */
663function clientismobile() {
664
665    if(isset($_SERVER['HTTP_X_WAP_PROFILE'])) return true;
666
667    if(preg_match('/wap\.|\.wap/i', $_SERVER['HTTP_ACCEPT'])) return true;
668
669    if(!isset($_SERVER['HTTP_USER_AGENT'])) return false;
670
671    $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';
672
673    if(preg_match("/$uamatches/i", $_SERVER['HTTP_USER_AGENT'])) return true;
674
675    return false;
676}
677
678/**
679 * Convert one or more comma separated IPs to hostnames
680 *
681 * If $conf['dnslookups'] is disabled it simply returns the input string
682 *
683 * @author Glen Harris <astfgl@iamnota.org>
684 * @param  string $ips comma separated list of IP addresses
685 * @return string a comma separated list of hostnames
686 */
687function gethostsbyaddrs($ips) {
688    global $conf;
689    if(!$conf['dnslookups']) return $ips;
690
691    $hosts = array();
692    $ips   = explode(',', $ips);
693
694    if(is_array($ips)) {
695        foreach($ips as $ip) {
696            $hosts[] = gethostbyaddr(trim($ip));
697        }
698        return join(',', $hosts);
699    } else {
700        return gethostbyaddr(trim($ips));
701    }
702}
703
704/**
705 * Checks if a given page is currently locked.
706 *
707 * removes stale lockfiles
708 *
709 * @author Andreas Gohr <andi@splitbrain.org>
710 */
711function checklock($id) {
712    global $conf;
713    $lock = wikiLockFN($id);
714
715    //no lockfile
716    if(!@file_exists($lock)) return false;
717
718    //lockfile expired
719    if((time() - filemtime($lock)) > $conf['locktime']) {
720        @unlink($lock);
721        return false;
722    }
723
724    //my own lock
725    list($ip, $session) = explode("\n", io_readFile($lock));
726    if($ip == $_SERVER['REMOTE_USER'] || $ip == clientIP() || $session == session_id()) {
727        return false;
728    }
729
730    return $ip;
731}
732
733/**
734 * Lock a page for editing
735 *
736 * @author Andreas Gohr <andi@splitbrain.org>
737 */
738function lock($id) {
739    global $conf;
740
741    if($conf['locktime'] == 0) {
742        return;
743    }
744
745    $lock = wikiLockFN($id);
746    if($_SERVER['REMOTE_USER']) {
747        io_saveFile($lock, $_SERVER['REMOTE_USER']);
748    } else {
749        io_saveFile($lock, clientIP()."\n".session_id());
750    }
751}
752
753/**
754 * Unlock a page if it was locked by the user
755 *
756 * @author Andreas Gohr <andi@splitbrain.org>
757 * @param string $id page id to unlock
758 * @return bool true if a lock was removed
759 */
760function unlock($id) {
761    $lock = wikiLockFN($id);
762    if(@file_exists($lock)) {
763        list($ip, $session) = explode("\n", io_readFile($lock));
764        if($ip == $_SERVER['REMOTE_USER'] || $ip == clientIP() || $session == session_id()) {
765            @unlink($lock);
766            return true;
767        }
768    }
769    return false;
770}
771
772/**
773 * convert line ending to unix format
774 *
775 * @see    formText() for 2crlf conversion
776 * @author Andreas Gohr <andi@splitbrain.org>
777 */
778function cleanText($text) {
779    $text = preg_replace("/(\015\012)|(\015)/", "\012", $text);
780    return $text;
781}
782
783/**
784 * Prepares text for print in Webforms by encoding special chars.
785 * It also converts line endings to Windows format which is
786 * pseudo standard for webforms.
787 *
788 * @see    cleanText() for 2unix conversion
789 * @author Andreas Gohr <andi@splitbrain.org>
790 */
791function formText($text) {
792    $text = str_replace("\012", "\015\012", $text);
793    return htmlspecialchars($text);
794}
795
796/**
797 * Returns the specified local text in raw format
798 *
799 * @author Andreas Gohr <andi@splitbrain.org>
800 */
801function rawLocale($id, $ext = 'txt') {
802    return io_readFile(localeFN($id, $ext));
803}
804
805/**
806 * Returns the raw WikiText
807 *
808 * @author Andreas Gohr <andi@splitbrain.org>
809 */
810function rawWiki($id, $rev = '') {
811    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
812}
813
814/**
815 * Returns the pagetemplate contents for the ID's namespace
816 *
817 * @triggers COMMON_PAGETPL_LOAD
818 * @author Andreas Gohr <andi@splitbrain.org>
819 */
820function pageTemplate($id) {
821    global $conf;
822
823    if(is_array($id)) $id = $id[0];
824
825    // prepare initial event data
826    $data = array(
827        'id'        => $id, // the id of the page to be created
828        'tpl'       => '', // the text used as template
829        'tplfile'   => '', // the file above text was/should be loaded from
830        'doreplace' => true // should wildcard replacements be done on the text?
831    );
832
833    $evt = new Doku_Event('COMMON_PAGETPL_LOAD', $data);
834    if($evt->advise_before(true)) {
835        // the before event might have loaded the content already
836        if(empty($data['tpl'])) {
837            // if the before event did not set a template file, try to find one
838            if(empty($data['tplfile'])) {
839                $path = dirname(wikiFN($id));
840                if(@file_exists($path.'/_template.txt')) {
841                    $data['tplfile'] = $path.'/_template.txt';
842                } else {
843                    // search upper namespaces for templates
844                    $len = strlen(rtrim($conf['datadir'], '/'));
845                    while(strlen($path) >= $len) {
846                        if(@file_exists($path.'/__template.txt')) {
847                            $data['tplfile'] = $path.'/__template.txt';
848                            break;
849                        }
850                        $path = substr($path, 0, strrpos($path, '/'));
851                    }
852                }
853            }
854            // load the content
855            $data['tpl'] = io_readFile($data['tplfile']);
856        }
857        if($data['doreplace']) parsePageTemplate($data);
858    }
859    $evt->advise_after();
860    unset($evt);
861
862    return $data['tpl'];
863}
864
865/**
866 * Performs common page template replacements
867 * This works on data from COMMON_PAGETPL_LOAD
868 *
869 * @author Andreas Gohr <andi@splitbrain.org>
870 */
871function parsePageTemplate(&$data) {
872    /**
873     * @var string $id        the id of the page to be created
874     * @var string $tpl       the text used as template
875     * @var string $tplfile   the file above text was/should be loaded from
876     * @var bool   $doreplace should wildcard replacements be done on the text?
877     */
878    extract($data);
879
880    global $USERINFO;
881    global $conf;
882
883    // replace placeholders
884    $file = noNS($id);
885    $page = strtr($file, $conf['sepchar'], ' ');
886
887    $tpl = str_replace(
888        array(
889             '@ID@',
890             '@NS@',
891             '@FILE@',
892             '@!FILE@',
893             '@!FILE!@',
894             '@PAGE@',
895             '@!PAGE@',
896             '@!!PAGE@',
897             '@!PAGE!@',
898             '@USER@',
899             '@NAME@',
900             '@MAIL@',
901             '@DATE@',
902        ),
903        array(
904             $id,
905             getNS($id),
906             $file,
907             utf8_ucfirst($file),
908             utf8_strtoupper($file),
909             $page,
910             utf8_ucfirst($page),
911             utf8_ucwords($page),
912             utf8_strtoupper($page),
913             $_SERVER['REMOTE_USER'],
914             $USERINFO['name'],
915             $USERINFO['mail'],
916             $conf['dformat'],
917        ), $tpl
918    );
919
920    // we need the callback to work around strftime's char limit
921    $tpl         = preg_replace_callback('/%./', create_function('$m', 'return strftime($m[0]);'), $tpl);
922    $data['tpl'] = $tpl;
923    return $tpl;
924}
925
926/**
927 * Returns the raw Wiki Text in three slices.
928 *
929 * The range parameter needs to have the form "from-to"
930 * and gives the range of the section in bytes - no
931 * UTF-8 awareness is needed.
932 * The returned order is prefix, section and suffix.
933 *
934 * @author Andreas Gohr <andi@splitbrain.org>
935 */
936function rawWikiSlices($range, $id, $rev = '') {
937    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
938
939    // Parse range
940    list($from, $to) = explode('-', $range, 2);
941    // Make range zero-based, use defaults if marker is missing
942    $from = !$from ? 0 : ($from - 1);
943    $to   = !$to ? strlen($text) : ($to - 1);
944
945    $slices[0] = substr($text, 0, $from);
946    $slices[1] = substr($text, $from, $to - $from);
947    $slices[2] = substr($text, $to);
948    return $slices;
949}
950
951/**
952 * Joins wiki text slices
953 *
954 * function to join the text slices.
955 * When the pretty parameter is set to true it adds additional empty
956 * lines between sections if needed (used on saving).
957 *
958 * @author Andreas Gohr <andi@splitbrain.org>
959 */
960function con($pre, $text, $suf, $pretty = false) {
961    if($pretty) {
962        if($pre !== '' && substr($pre, -1) !== "\n" &&
963            substr($text, 0, 1) !== "\n"
964        ) {
965            $pre .= "\n";
966        }
967        if($suf !== '' && substr($text, -1) !== "\n" &&
968            substr($suf, 0, 1) !== "\n"
969        ) {
970            $text .= "\n";
971        }
972    }
973
974    return $pre.$text.$suf;
975}
976
977/**
978 * Saves a wikitext by calling io_writeWikiPage.
979 * Also directs changelog and attic updates.
980 *
981 * @author Andreas Gohr <andi@splitbrain.org>
982 * @author Ben Coburn <btcoburn@silicodon.net>
983 */
984function saveWikiText($id, $text, $summary, $minor = false) {
985    /* Note to developers:
986       This code is subtle and delicate. Test the behavior of
987       the attic and changelog with dokuwiki and external edits
988       after any changes. External edits change the wiki page
989       directly without using php or dokuwiki.
990     */
991    global $conf;
992    global $lang;
993    global $REV;
994    // ignore if no changes were made
995    if($text == rawWiki($id, '')) {
996        return;
997    }
998
999    $file        = wikiFN($id);
1000    $old         = @filemtime($file); // from page
1001    $wasRemoved  = (trim($text) == ''); // check for empty or whitespace only
1002    $wasCreated  = !@file_exists($file);
1003    $wasReverted = ($REV == true);
1004    $newRev      = false;
1005    $oldRev      = getRevisions($id, -1, 1, 1024); // from changelog
1006    $oldRev      = (int) (empty($oldRev) ? 0 : $oldRev[0]);
1007    if(!@file_exists(wikiFN($id, $old)) && @file_exists($file) && $old >= $oldRev) {
1008        // add old revision to the attic if missing
1009        saveOldRevision($id);
1010        // add a changelog entry if this edit came from outside dokuwiki
1011        if($old > $oldRev) {
1012            addLogEntry($old, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=> true));
1013            // remove soon to be stale instructions
1014            $cache = new cache_instructions($id, $file);
1015            $cache->removeCache();
1016        }
1017    }
1018
1019    if($wasRemoved) {
1020        // Send "update" event with empty data, so plugins can react to page deletion
1021        $data = array(array($file, '', false), getNS($id), noNS($id), false);
1022        trigger_event('IO_WIKIPAGE_WRITE', $data);
1023        // pre-save deleted revision
1024        @touch($file);
1025        clearstatcache();
1026        $newRev = saveOldRevision($id);
1027        // remove empty file
1028        @unlink($file);
1029        // don't remove old meta info as it should be saved, plugins can use IO_WIKIPAGE_WRITE for removing their metadata...
1030        // purge non-persistant meta data
1031        p_purge_metadata($id);
1032        $del = true;
1033        // autoset summary on deletion
1034        if(empty($summary)) $summary = $lang['deleted'];
1035        // remove empty namespaces
1036        io_sweepNS($id, 'datadir');
1037        io_sweepNS($id, 'mediadir');
1038    } else {
1039        // save file (namespace dir is created in io_writeWikiPage)
1040        io_writeWikiPage($file, $text, $id);
1041        // pre-save the revision, to keep the attic in sync
1042        $newRev = saveOldRevision($id);
1043        $del    = false;
1044    }
1045
1046    // select changelog line type
1047    $extra = '';
1048    $type  = DOKU_CHANGE_TYPE_EDIT;
1049    if($wasReverted) {
1050        $type  = DOKU_CHANGE_TYPE_REVERT;
1051        $extra = $REV;
1052    } else if($wasCreated) {
1053        $type = DOKU_CHANGE_TYPE_CREATE;
1054    } else if($wasRemoved) {
1055        $type = DOKU_CHANGE_TYPE_DELETE;
1056    } else if($minor && $conf['useacl'] && $_SERVER['REMOTE_USER']) {
1057        $type = DOKU_CHANGE_TYPE_MINOR_EDIT;
1058    } //minor edits only for logged in users
1059
1060    addLogEntry($newRev, $id, $type, $summary, $extra);
1061    // send notify mails
1062    notify($id, 'admin', $old, $summary, $minor);
1063    notify($id, 'subscribers', $old, $summary, $minor);
1064
1065    // update the purgefile (timestamp of the last time anything within the wiki was changed)
1066    io_saveFile($conf['cachedir'].'/purgefile', time());
1067
1068    // if useheading is enabled, purge the cache of all linking pages
1069    if(useHeading('content')) {
1070        $pages = ft_backlinks($id);
1071        foreach($pages as $page) {
1072            $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
1073            $cache->removeCache();
1074        }
1075    }
1076}
1077
1078/**
1079 * moves the current version to the attic and returns its
1080 * revision date
1081 *
1082 * @author Andreas Gohr <andi@splitbrain.org>
1083 */
1084function saveOldRevision($id) {
1085    global $conf;
1086    $oldf = wikiFN($id);
1087    if(!@file_exists($oldf)) return '';
1088    $date = filemtime($oldf);
1089    $newf = wikiFN($id, $date);
1090    io_writeWikiPage($newf, rawWiki($id), $id, $date);
1091    return $date;
1092}
1093
1094/**
1095 * Sends a notify mail on page change or registration
1096 *
1097 * @param string     $id       The changed page
1098 * @param string     $who      Who to notify (admin|subscribers|register)
1099 * @param int|string $rev Old page revision
1100 * @param string     $summary  What changed
1101 * @param boolean    $minor    Is this a minor edit?
1102 * @param array      $replace  Additional string substitutions, @KEY@ to be replaced by value
1103 *
1104 * @return bool
1105 * @author Andreas Gohr <andi@splitbrain.org>
1106 */
1107function notify($id, $who, $rev = '', $summary = '', $minor = false, $replace = array()) {
1108    global $lang;
1109    global $conf;
1110    global $INFO;
1111    global $DIFF_INLINESTYLES;
1112
1113    // decide if there is something to do, eg. whom to mail
1114    if($who == 'admin') {
1115        if(empty($conf['notify'])) return false; //notify enabled?
1116        $text = rawLocale('mailtext');
1117        $to   = $conf['notify'];
1118        $bcc  = '';
1119    } elseif($who == 'subscribers') {
1120        if(!$conf['subscribers']) return false; //subscribers enabled?
1121        if($conf['useacl'] && $_SERVER['REMOTE_USER'] && $minor) return false; //skip minors
1122        $data = array('id' => $id, 'addresslist' => '', 'self' => false);
1123        trigger_event(
1124            'COMMON_NOTIFY_ADDRESSLIST', $data,
1125            'subscription_addresslist'
1126        );
1127        $bcc = $data['addresslist'];
1128        if(empty($bcc)) return false;
1129        $to   = '';
1130        $text = rawLocale('subscr_single');
1131    } elseif($who == 'register') {
1132        if(empty($conf['registernotify'])) return false;
1133        $text = rawLocale('registermail');
1134        $to   = $conf['registernotify'];
1135        $bcc  = '';
1136    } else {
1137        return false; //just to be safe
1138    }
1139
1140    // prepare replacements (keys not set in hrep will be taken from trep)
1141    $trep = array(
1142        'NEWPAGE' => wl($id, '', true, '&'),
1143        'PAGE'    => $id,
1144        'SUMMARY' => $summary
1145    );
1146    $trep = array_merge($trep, $replace);
1147    $hrep = array();
1148
1149    // prepare content
1150    if($who == 'register') {
1151        $subject = $lang['mail_new_user'].' '.$summary;
1152    } elseif($rev) {
1153        $subject         = $lang['mail_changed'].' '.$id;
1154        $trep['OLDPAGE'] = wl($id, "rev=$rev", true, '&');
1155        $old_content     = rawWiki($id, $rev);
1156        $new_content     = rawWiki($id);
1157        $df              = new Diff(explode("\n", $old_content),
1158                                    explode("\n", $new_content));
1159        $dformat         = new UnifiedDiffFormatter();
1160        $tdiff           = $dformat->format($df);
1161
1162        $DIFF_INLINESTYLES = true;
1163        $hdf               = new Diff(explode("\n", hsc($old_content)),
1164                                      explode("\n", hsc($new_content)));
1165        $dformat           = new InlineDiffFormatter();
1166        $hdiff             = $dformat->format($hdf);
1167        $hdiff             = '<table>'.$hdiff.'</table>';
1168        $DIFF_INLINESTYLES = false;
1169    } else {
1170        $subject         = $lang['mail_newpage'].' '.$id;
1171        $trep['OLDPAGE'] = '---';
1172        $tdiff           = rawWiki($id);
1173        $hdiff           = nl2br(hsc($tdiff));
1174    }
1175    $trep['DIFF'] = $tdiff;
1176    $hrep['DIFF'] = $hdiff;
1177
1178    // send mail
1179    $mail = new Mailer();
1180    $mail->to($to);
1181    $mail->bcc($bcc);
1182    $mail->subject($subject);
1183    $mail->setBody($text, $trep, $hrep);
1184    if($who == 'subscribers') {
1185        $mail->setHeader(
1186            'List-Unsubscribe',
1187            '<'.wl($id, array('do'=> 'subscribe'), true, '&').'>',
1188            false
1189        );
1190    }
1191    return $mail->send();
1192}
1193
1194/**
1195 * extracts the query from a search engine referrer
1196 *
1197 * @author Andreas Gohr <andi@splitbrain.org>
1198 * @author Todd Augsburger <todd@rollerorgans.com>
1199 */
1200function getGoogleQuery() {
1201    if(!isset($_SERVER['HTTP_REFERER'])) {
1202        return '';
1203    }
1204    $url = parse_url($_SERVER['HTTP_REFERER']);
1205
1206    // only handle common SEs
1207    if(!preg_match('/(google|bing|yahoo|ask|duckduckgo|babylon|aol|yandex)/',$url['host'])) return '';
1208
1209    $query = array();
1210    // temporary workaround against PHP bug #49733
1211    // see http://bugs.php.net/bug.php?id=49733
1212    if(UTF8_MBSTRING) $enc = mb_internal_encoding();
1213    parse_str($url['query'], $query);
1214    if(UTF8_MBSTRING) mb_internal_encoding($enc);
1215
1216    $q = '';
1217    if(isset($query['q'])){
1218        $q = $query['q'];
1219    }elseif(isset($query['p'])){
1220        $q = $query['p'];
1221    }elseif(isset($query['query'])){
1222        $q = $query['query'];
1223    }
1224    $q = trim($q);
1225
1226    if(!$q) return '';
1227    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/', $q, -1, PREG_SPLIT_NO_EMPTY);
1228    return $q;
1229}
1230
1231/**
1232 * Try to set correct locale
1233 *
1234 * @deprecated No longer used
1235 * @author     Andreas Gohr <andi@splitbrain.org>
1236 */
1237function setCorrectLocale() {
1238    global $conf;
1239    global $lang;
1240
1241    $enc = strtoupper($lang['encoding']);
1242    foreach($lang['locales'] as $loc) {
1243        //try locale
1244        if(@setlocale(LC_ALL, $loc)) return;
1245        //try loceale with encoding
1246        if(@setlocale(LC_ALL, "$loc.$enc")) return;
1247    }
1248    //still here? try to set from environment
1249    @setlocale(LC_ALL, "");
1250}
1251
1252/**
1253 * Return the human readable size of a file
1254 *
1255 * @param       int    $size   A file size
1256 * @param       int    $dec    A number of decimal places
1257 * @author      Martin Benjamin <b.martin@cybernet.ch>
1258 * @author      Aidan Lister <aidan@php.net>
1259 * @version     1.0.0
1260 */
1261function filesize_h($size, $dec = 1) {
1262    $sizes = array('B', 'KB', 'MB', 'GB');
1263    $count = count($sizes);
1264    $i     = 0;
1265
1266    while($size >= 1024 && ($i < $count - 1)) {
1267        $size /= 1024;
1268        $i++;
1269    }
1270
1271    return round($size, $dec).' '.$sizes[$i];
1272}
1273
1274/**
1275 * Return the given timestamp as human readable, fuzzy age
1276 *
1277 * @author Andreas Gohr <gohr@cosmocode.de>
1278 */
1279function datetime_h($dt) {
1280    global $lang;
1281
1282    $ago = time() - $dt;
1283    if($ago > 24 * 60 * 60 * 30 * 12 * 2) {
1284        return sprintf($lang['years'], round($ago / (24 * 60 * 60 * 30 * 12)));
1285    }
1286    if($ago > 24 * 60 * 60 * 30 * 2) {
1287        return sprintf($lang['months'], round($ago / (24 * 60 * 60 * 30)));
1288    }
1289    if($ago > 24 * 60 * 60 * 7 * 2) {
1290        return sprintf($lang['weeks'], round($ago / (24 * 60 * 60 * 7)));
1291    }
1292    if($ago > 24 * 60 * 60 * 2) {
1293        return sprintf($lang['days'], round($ago / (24 * 60 * 60)));
1294    }
1295    if($ago > 60 * 60 * 2) {
1296        return sprintf($lang['hours'], round($ago / (60 * 60)));
1297    }
1298    if($ago > 60 * 2) {
1299        return sprintf($lang['minutes'], round($ago / (60)));
1300    }
1301    return sprintf($lang['seconds'], $ago);
1302}
1303
1304/**
1305 * Wraps around strftime but provides support for fuzzy dates
1306 *
1307 * The format default to $conf['dformat']. It is passed to
1308 * strftime - %f can be used to get the value from datetime_h()
1309 *
1310 * @see datetime_h
1311 * @author Andreas Gohr <gohr@cosmocode.de>
1312 */
1313function dformat($dt = null, $format = '') {
1314    global $conf;
1315
1316    if(is_null($dt)) $dt = time();
1317    $dt = (int) $dt;
1318    if(!$format) $format = $conf['dformat'];
1319
1320    $format = str_replace('%f', datetime_h($dt), $format);
1321    return strftime($format, $dt);
1322}
1323
1324/**
1325 * Formats a timestamp as ISO 8601 date
1326 *
1327 * @author <ungu at terong dot com>
1328 * @link http://www.php.net/manual/en/function.date.php#54072
1329 * @param int $int_date: current date in UNIX timestamp
1330 * @return string
1331 */
1332function date_iso8601($int_date) {
1333    $date_mod     = date('Y-m-d\TH:i:s', $int_date);
1334    $pre_timezone = date('O', $int_date);
1335    $time_zone    = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1336    $date_mod .= $time_zone;
1337    return $date_mod;
1338}
1339
1340/**
1341 * return an obfuscated email address in line with $conf['mailguard'] setting
1342 *
1343 * @author Harry Fuecks <hfuecks@gmail.com>
1344 * @author Christopher Smith <chris@jalakai.co.uk>
1345 */
1346function obfuscate($email) {
1347    global $conf;
1348
1349    switch($conf['mailguard']) {
1350        case 'visible' :
1351            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
1352            return strtr($email, $obfuscate);
1353
1354        case 'hex' :
1355            $encode = '';
1356            $len    = strlen($email);
1357            for($x = 0; $x < $len; $x++) {
1358                $encode .= '&#x'.bin2hex($email{$x}).';';
1359            }
1360            return $encode;
1361
1362        case 'none' :
1363        default :
1364            return $email;
1365    }
1366}
1367
1368/**
1369 * Removes quoting backslashes
1370 *
1371 * @author Andreas Gohr <andi@splitbrain.org>
1372 */
1373function unslash($string, $char = "'") {
1374    return str_replace('\\'.$char, $char, $string);
1375}
1376
1377/**
1378 * Convert php.ini shorthands to byte
1379 *
1380 * @author <gilthans dot NO dot SPAM at gmail dot com>
1381 * @link   http://de3.php.net/manual/en/ini.core.php#79564
1382 */
1383function php_to_byte($v) {
1384    $l   = substr($v, -1);
1385    $ret = substr($v, 0, -1);
1386    switch(strtoupper($l)) {
1387        case 'P':
1388            $ret *= 1024;
1389        case 'T':
1390            $ret *= 1024;
1391        case 'G':
1392            $ret *= 1024;
1393        case 'M':
1394            $ret *= 1024;
1395        case 'K':
1396            $ret *= 1024;
1397            break;
1398        default;
1399            $ret *= 10;
1400            break;
1401    }
1402    return $ret;
1403}
1404
1405/**
1406 * Wrapper around preg_quote adding the default delimiter
1407 */
1408function preg_quote_cb($string) {
1409    return preg_quote($string, '/');
1410}
1411
1412/**
1413 * Shorten a given string by removing data from the middle
1414 *
1415 * You can give the string in two parts, the first part $keep
1416 * will never be shortened. The second part $short will be cut
1417 * in the middle to shorten but only if at least $min chars are
1418 * left to display it. Otherwise it will be left off.
1419 *
1420 * @param string $keep   the part to keep
1421 * @param string $short  the part to shorten
1422 * @param int    $max    maximum chars you want for the whole string
1423 * @param int    $min    minimum number of chars to have left for middle shortening
1424 * @param string $char   the shortening character to use
1425 * @return string
1426 */
1427function shorten($keep, $short, $max, $min = 9, $char = '…') {
1428    $max = $max - utf8_strlen($keep);
1429    if($max < $min) return $keep;
1430    $len = utf8_strlen($short);
1431    if($len <= $max) return $keep.$short;
1432    $half = floor($max / 2);
1433    return $keep.utf8_substr($short, 0, $half - 1).$char.utf8_substr($short, $len - $half);
1434}
1435
1436/**
1437 * Return the users realname or e-mail address for use
1438 * in page footer and recent changes pages
1439 *
1440 * @author Andy Webber <dokuwiki AT andywebber DOT com>
1441 */
1442function editorinfo($username) {
1443    global $conf;
1444    global $auth;
1445
1446    switch($conf['showuseras']) {
1447        case 'username':
1448        case 'email':
1449        case 'email_link':
1450            if($auth) $info = $auth->getUserData($username);
1451            break;
1452        default:
1453            return hsc($username);
1454    }
1455
1456    if(isset($info) && $info) {
1457        switch($conf['showuseras']) {
1458            case 'username':
1459                return hsc($info['name']);
1460            case 'email':
1461                return obfuscate($info['mail']);
1462            case 'email_link':
1463                $mail = obfuscate($info['mail']);
1464                return '<a href="mailto:'.$mail.'">'.$mail.'</a>';
1465            default:
1466                return hsc($username);
1467        }
1468    } else {
1469        return hsc($username);
1470    }
1471}
1472
1473/**
1474 * Returns the path to a image file for the currently chosen license.
1475 * When no image exists, returns an empty string
1476 *
1477 * @author Andreas Gohr <andi@splitbrain.org>
1478 * @param  string $type - type of image 'badge' or 'button'
1479 * @return string
1480 */
1481function license_img($type) {
1482    global $license;
1483    global $conf;
1484    if(!$conf['license']) return '';
1485    if(!is_array($license[$conf['license']])) return '';
1486    $lic   = $license[$conf['license']];
1487    $try   = array();
1488    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1489    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1490    if(substr($conf['license'], 0, 3) == 'cc-') {
1491        $try[] = 'lib/images/license/'.$type.'/cc.png';
1492    }
1493    foreach($try as $src) {
1494        if(@file_exists(DOKU_INC.$src)) return $src;
1495    }
1496    return '';
1497}
1498
1499/**
1500 * Checks if the given amount of memory is available
1501 *
1502 * If the memory_get_usage() function is not available the
1503 * function just assumes $bytes of already allocated memory
1504 *
1505 * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
1506 * @author Andreas Gohr <andi@splitbrain.org>
1507 *
1508 * @param  int $mem  Size of memory you want to allocate in bytes
1509 * @param int  $bytes
1510 * @internal param int $used already allocated memory (see above)
1511 * @return bool
1512 */
1513function is_mem_available($mem, $bytes = 1048576) {
1514    $limit = trim(ini_get('memory_limit'));
1515    if(empty($limit)) return true; // no limit set!
1516
1517    // parse limit to bytes
1518    $limit = php_to_byte($limit);
1519
1520    // get used memory if possible
1521    if(function_exists('memory_get_usage')) {
1522        $used = memory_get_usage();
1523    } else {
1524        $used = $bytes;
1525    }
1526
1527    if($used + $mem > $limit) {
1528        return false;
1529    }
1530
1531    return true;
1532}
1533
1534/**
1535 * Send a HTTP redirect to the browser
1536 *
1537 * Works arround Microsoft IIS cookie sending bug. Exits the script.
1538 *
1539 * @link   http://support.microsoft.com/kb/q176113/
1540 * @author Andreas Gohr <andi@splitbrain.org>
1541 */
1542function send_redirect($url) {
1543    //are there any undisplayed messages? keep them in session for display
1544    global $MSG;
1545    if(isset($MSG) && count($MSG) && !defined('NOSESSION')) {
1546        //reopen session, store data and close session again
1547        @session_start();
1548        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
1549    }
1550
1551    // always close the session
1552    session_write_close();
1553
1554    // work around IE bug
1555    // http://www.ianhoar.com/2008/11/16/internet-explorer-6-and-redirected-anchor-links/
1556    list($url, $hash) = explode('#', $url);
1557    if($hash) {
1558        if(strpos($url, '?')) {
1559            $url = $url.'&#'.$hash;
1560        } else {
1561            $url = $url.'?&#'.$hash;
1562        }
1563    }
1564
1565    // check if running on IIS < 6 with CGI-PHP
1566    if(isset($_SERVER['SERVER_SOFTWARE']) && isset($_SERVER['GATEWAY_INTERFACE']) &&
1567        (strpos($_SERVER['GATEWAY_INTERFACE'], 'CGI') !== false) &&
1568        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($_SERVER['SERVER_SOFTWARE']), $matches)) &&
1569        $matches[1] < 6
1570    ) {
1571        header('Refresh: 0;url='.$url);
1572    } else {
1573        header('Location: '.$url);
1574    }
1575    exit;
1576}
1577
1578/**
1579 * Validate a value using a set of valid values
1580 *
1581 * This function checks whether a specified value is set and in the array
1582 * $valid_values. If not, the function returns a default value or, if no
1583 * default is specified, throws an exception.
1584 *
1585 * @param string $param        The name of the parameter
1586 * @param array  $valid_values A set of valid values; Optionally a default may
1587 *                             be marked by the key “default”.
1588 * @param array  $array        The array containing the value (typically $_POST
1589 *                             or $_GET)
1590 * @param string $exc          The text of the raised exception
1591 *
1592 * @throws Exception
1593 * @return mixed
1594 * @author Adrian Lang <lang@cosmocode.de>
1595 */
1596function valid_input_set($param, $valid_values, $array, $exc = '') {
1597    if(isset($array[$param]) && in_array($array[$param], $valid_values)) {
1598        return $array[$param];
1599    } elseif(isset($valid_values['default'])) {
1600        return $valid_values['default'];
1601    } else {
1602        throw new Exception($exc);
1603    }
1604}
1605
1606/**
1607 * Read a preference from the DokuWiki cookie
1608 */
1609function get_doku_pref($pref, $default) {
1610    if(strpos($_COOKIE['DOKU_PREFS'], $pref) !== false) {
1611        $parts = explode('#', $_COOKIE['DOKU_PREFS']);
1612        $cnt   = count($parts);
1613        for($i = 0; $i < $cnt; $i += 2) {
1614            if($parts[$i] == $pref) {
1615                return $parts[$i + 1];
1616            }
1617        }
1618    }
1619    return $default;
1620}
1621
1622//Setup VIM: ex: et ts=2 :
1623