xref: /dokuwiki/inc/common.php (revision d535a2e92c29b7a9cff84c344c6e474f654aaa9e)
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
1110    foreach ($replace as $key => $substitution) {
1111        $text = str_replace('@'.strtoupper($key).'@',$substitution, $text);
1112    }
1113
1114    if($who == 'register'){
1115        $subject = $lang['mail_new_user'].' '.$summary;
1116    }elseif($rev){
1117        $subject = $lang['mail_changed'].' '.$id;
1118        $text = str_replace('@OLDPAGE@',wl($id,"rev=$rev",true,'&'),$text);
1119        $df  = new Diff(explode("\n",rawWiki($id,$rev)),
1120                        explode("\n",rawWiki($id)));
1121        $dformat = new UnifiedDiffFormatter();
1122        $diff    = $dformat->format($df);
1123    }else{
1124        $subject=$lang['mail_newpage'].' '.$id;
1125        $text = str_replace('@OLDPAGE@','none',$text);
1126        $diff = rawWiki($id);
1127    }
1128    $text = str_replace('@DIFF@',$diff,$text);
1129    $subject = '['.$conf['title'].'] '.$subject;
1130
1131    $from = $conf['mailfrom'];
1132    $from = str_replace('@USER@',$_SERVER['REMOTE_USER'],$from);
1133    $from = str_replace('@NAME@',$INFO['userinfo']['name'],$from);
1134    $from = str_replace('@MAIL@',$INFO['userinfo']['mail'],$from);
1135
1136    mail_send($to,$subject,$text,$from,'',$bcc);
1137}
1138
1139/**
1140 * extracts the query from a search engine referrer
1141 *
1142 * @author Andreas Gohr <andi@splitbrain.org>
1143 * @author Todd Augsburger <todd@rollerorgans.com>
1144 */
1145function getGoogleQuery(){
1146    if (!isset($_SERVER['HTTP_REFERER'])) {
1147        return '';
1148    }
1149    $url = parse_url($_SERVER['HTTP_REFERER']);
1150
1151    $query = array();
1152
1153    // temporary workaround against PHP bug #49733
1154    // see http://bugs.php.net/bug.php?id=49733
1155    if(UTF8_MBSTRING) $enc = mb_internal_encoding();
1156    parse_str($url['query'],$query);
1157    if(UTF8_MBSTRING) mb_internal_encoding($enc);
1158
1159    $q = '';
1160    if(isset($query['q']))
1161        $q = $query['q'];        // google, live/msn, aol, ask, altavista, alltheweb, gigablast
1162    elseif(isset($query['p']))
1163        $q = $query['p'];        // yahoo
1164    elseif(isset($query['query']))
1165        $q = $query['query'];    // lycos, netscape, clusty, hotbot
1166    elseif(preg_match("#a9\.com#i",$url['host'])) // a9
1167        $q = urldecode(ltrim($url['path'],'/'));
1168
1169    if($q === '') return '';
1170    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/',$q,-1,PREG_SPLIT_NO_EMPTY);
1171    return $q;
1172}
1173
1174/**
1175 * Try to set correct locale
1176 *
1177 * @deprecated No longer used
1178 * @author     Andreas Gohr <andi@splitbrain.org>
1179 */
1180function setCorrectLocale(){
1181    global $conf;
1182    global $lang;
1183
1184    $enc = strtoupper($lang['encoding']);
1185    foreach ($lang['locales'] as $loc){
1186        //try locale
1187        if(@setlocale(LC_ALL,$loc)) return;
1188        //try loceale with encoding
1189        if(@setlocale(LC_ALL,"$loc.$enc")) return;
1190    }
1191    //still here? try to set from environment
1192    @setlocale(LC_ALL,"");
1193}
1194
1195/**
1196 * Return the human readable size of a file
1197 *
1198 * @param       int    $size   A file size
1199 * @param       int    $dec    A number of decimal places
1200 * @author      Martin Benjamin <b.martin@cybernet.ch>
1201 * @author      Aidan Lister <aidan@php.net>
1202 * @version     1.0.0
1203 */
1204function filesize_h($size, $dec = 1){
1205    $sizes = array('B', 'KB', 'MB', 'GB');
1206    $count = count($sizes);
1207    $i = 0;
1208
1209    while ($size >= 1024 && ($i < $count - 1)) {
1210        $size /= 1024;
1211        $i++;
1212    }
1213
1214    return round($size, $dec) . ' ' . $sizes[$i];
1215}
1216
1217/**
1218 * Return the given timestamp as human readable, fuzzy age
1219 *
1220 * @author Andreas Gohr <gohr@cosmocode.de>
1221 */
1222function datetime_h($dt){
1223    global $lang;
1224
1225    $ago = time() - $dt;
1226    if($ago > 24*60*60*30*12*2){
1227        return sprintf($lang['years'], round($ago/(24*60*60*30*12)));
1228    }
1229    if($ago > 24*60*60*30*2){
1230        return sprintf($lang['months'], round($ago/(24*60*60*30)));
1231    }
1232    if($ago > 24*60*60*7*2){
1233        return sprintf($lang['weeks'], round($ago/(24*60*60*7)));
1234    }
1235    if($ago > 24*60*60*2){
1236        return sprintf($lang['days'], round($ago/(24*60*60)));
1237    }
1238    if($ago > 60*60*2){
1239        return sprintf($lang['hours'], round($ago/(60*60)));
1240    }
1241    if($ago > 60*2){
1242        return sprintf($lang['minutes'], round($ago/(60)));
1243    }
1244    return sprintf($lang['seconds'], $ago);
1245}
1246
1247/**
1248 * Wraps around strftime but provides support for fuzzy dates
1249 *
1250 * The format default to $conf['dformat']. It is passed to
1251 * strftime - %f can be used to get the value from datetime_h()
1252 *
1253 * @see datetime_h
1254 * @author Andreas Gohr <gohr@cosmocode.de>
1255 */
1256function dformat($dt=null,$format=''){
1257    global $conf;
1258
1259    if(is_null($dt)) $dt = time();
1260    $dt = (int) $dt;
1261    if(!$format) $format = $conf['dformat'];
1262
1263    $format = str_replace('%f',datetime_h($dt),$format);
1264    return strftime($format,$dt);
1265}
1266
1267/**
1268 * return an obfuscated email address in line with $conf['mailguard'] setting
1269 *
1270 * @author Harry Fuecks <hfuecks@gmail.com>
1271 * @author Christopher Smith <chris@jalakai.co.uk>
1272 */
1273function obfuscate($email) {
1274    global $conf;
1275
1276    switch ($conf['mailguard']) {
1277        case 'visible' :
1278            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
1279            return strtr($email, $obfuscate);
1280
1281        case 'hex' :
1282            $encode = '';
1283            $len = strlen($email);
1284            for ($x=0; $x < $len; $x++){
1285                $encode .= '&#x' . bin2hex($email{$x}).';';
1286            }
1287            return $encode;
1288
1289        case 'none' :
1290        default :
1291            return $email;
1292    }
1293}
1294
1295/**
1296 * Removes quoting backslashes
1297 *
1298 * @author Andreas Gohr <andi@splitbrain.org>
1299 */
1300function unslash($string,$char="'"){
1301    return str_replace('\\'.$char,$char,$string);
1302}
1303
1304/**
1305 * Convert php.ini shorthands to byte
1306 *
1307 * @author <gilthans dot NO dot SPAM at gmail dot com>
1308 * @link   http://de3.php.net/manual/en/ini.core.php#79564
1309 */
1310function php_to_byte($v){
1311    $l = substr($v, -1);
1312    $ret = substr($v, 0, -1);
1313    switch(strtoupper($l)){
1314        case 'P':
1315            $ret *= 1024;
1316        case 'T':
1317            $ret *= 1024;
1318        case 'G':
1319            $ret *= 1024;
1320        case 'M':
1321            $ret *= 1024;
1322        case 'K':
1323            $ret *= 1024;
1324        break;
1325    }
1326    return $ret;
1327}
1328
1329/**
1330 * Wrapper around preg_quote adding the default delimiter
1331 */
1332function preg_quote_cb($string){
1333    return preg_quote($string,'/');
1334}
1335
1336/**
1337 * Shorten a given string by removing data from the middle
1338 *
1339 * You can give the string in two parts, the first part $keep
1340 * will never be shortened. The second part $short will be cut
1341 * in the middle to shorten but only if at least $min chars are
1342 * left to display it. Otherwise it will be left off.
1343 *
1344 * @param string $keep   the part to keep
1345 * @param string $short  the part to shorten
1346 * @param int    $max    maximum chars you want for the whole string
1347 * @param int    $min    minimum number of chars to have left for middle shortening
1348 * @param string $char   the shortening character to use
1349 */
1350function shorten($keep,$short,$max,$min=9,$char='…'){
1351    $max = $max - utf8_strlen($keep);
1352    if($max < $min) return $keep;
1353    $len = utf8_strlen($short);
1354    if($len <= $max) return $keep.$short;
1355    $half = floor($max/2);
1356    return $keep.utf8_substr($short,0,$half-1).$char.utf8_substr($short,$len-$half);
1357}
1358
1359/**
1360 * Return the users realname or e-mail address for use
1361 * in page footer and recent changes pages
1362 *
1363 * @author Andy Webber <dokuwiki AT andywebber DOT com>
1364 */
1365function editorinfo($username){
1366    global $conf;
1367    global $auth;
1368
1369    switch($conf['showuseras']){
1370        case 'username':
1371        case 'email':
1372        case 'email_link':
1373            if($auth) $info = $auth->getUserData($username);
1374            break;
1375        default:
1376            return hsc($username);
1377    }
1378
1379    if(isset($info) && $info) {
1380        switch($conf['showuseras']){
1381            case 'username':
1382                return hsc($info['name']);
1383            case 'email':
1384                return obfuscate($info['mail']);
1385            case 'email_link':
1386                $mail=obfuscate($info['mail']);
1387                return '<a href="mailto:'.$mail.'">'.$mail.'</a>';
1388            default:
1389                return hsc($username);
1390        }
1391    } else {
1392        return hsc($username);
1393    }
1394}
1395
1396/**
1397 * Returns the path to a image file for the currently chosen license.
1398 * When no image exists, returns an empty string
1399 *
1400 * @author Andreas Gohr <andi@splitbrain.org>
1401 * @param  string $type - type of image 'badge' or 'button'
1402 */
1403function license_img($type){
1404    global $license;
1405    global $conf;
1406    if(!$conf['license']) return '';
1407    if(!is_array($license[$conf['license']])) return '';
1408    $lic = $license[$conf['license']];
1409    $try = array();
1410    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1411    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1412    if(substr($conf['license'],0,3) == 'cc-'){
1413        $try[] = 'lib/images/license/'.$type.'/cc.png';
1414    }
1415    foreach($try as $src){
1416        if(@file_exists(DOKU_INC.$src)) return $src;
1417    }
1418    return '';
1419}
1420
1421/**
1422 * Checks if the given amount of memory is available
1423 *
1424 * If the memory_get_usage() function is not available the
1425 * function just assumes $bytes of already allocated memory
1426 *
1427 * @param  int $mem  Size of memory you want to allocate in bytes
1428 * @param  int $used already allocated memory (see above)
1429 * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
1430 * @author Andreas Gohr <andi@splitbrain.org>
1431 */
1432function is_mem_available($mem,$bytes=1048576){
1433    $limit = trim(ini_get('memory_limit'));
1434    if(empty($limit)) return true; // no limit set!
1435
1436    // parse limit to bytes
1437    $limit = php_to_byte($limit);
1438
1439    // get used memory if possible
1440    if(function_exists('memory_get_usage')){
1441        $used = memory_get_usage();
1442    }else{
1443        $used = $bytes;
1444    }
1445
1446    if($used+$mem > $limit){
1447        return false;
1448    }
1449
1450    return true;
1451}
1452
1453/**
1454 * Send a HTTP redirect to the browser
1455 *
1456 * Works arround Microsoft IIS cookie sending bug. Exits the script.
1457 *
1458 * @link   http://support.microsoft.com/kb/q176113/
1459 * @author Andreas Gohr <andi@splitbrain.org>
1460 */
1461function send_redirect($url){
1462    // always close the session
1463    session_write_close();
1464
1465    // check if running on IIS < 6 with CGI-PHP
1466    if( isset($_SERVER['SERVER_SOFTWARE']) && isset($_SERVER['GATEWAY_INTERFACE']) &&
1467        (strpos($_SERVER['GATEWAY_INTERFACE'],'CGI') !== false) &&
1468        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($_SERVER['SERVER_SOFTWARE']), $matches)) &&
1469        $matches[1] < 6 ){
1470        header('Refresh: 0;url='.$url);
1471    }else{
1472        header('Location: '.$url);
1473    }
1474    exit;
1475}
1476
1477/**
1478 * Validate a value using a set of valid values
1479 *
1480 * This function checks whether a specified value is set and in the array
1481 * $valid_values. If not, the function returns a default value or, if no
1482 * default is specified, throws an exception.
1483 *
1484 * @param string $param        The name of the parameter
1485 * @param array  $valid_values A set of valid values; Optionally a default may
1486 *                             be marked by the key “default”.
1487 * @param array  $array        The array containing the value (typically $_POST
1488 *                             or $_GET)
1489 * @param string $exc          The text of the raised exception
1490 *
1491 * @author Adrian Lang <lang@cosmocode.de>
1492 */
1493function valid_input_set($param, $valid_values, $array, $exc = '') {
1494    if (isset($array[$param]) && in_array($array[$param], $valid_values)) {
1495        return $array[$param];
1496    } elseif (isset($valid_values['default'])) {
1497        return $valid_values['default'];
1498    } else {
1499        throw new Exception($exc);
1500    }
1501}
1502
1503//Setup VIM: ex: et ts=2 enc=utf-8 :
1504