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