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