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