xref: /dokuwiki/inc/common.php (revision c2a6d81662045023bdf1617b6b49f71c274d55ca)
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['lock']));
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    $lock = wikiLockFN($id);
729    if($_SERVER['REMOTE_USER']){
730        io_saveFile($lock,$_SERVER['REMOTE_USER']);
731    }else{
732        io_saveFile($lock,clientIP());
733    }
734}
735
736/**
737 * Unlock a page if it was locked by the user
738 *
739 * @author Andreas Gohr <andi@splitbrain.org>
740 * @return bool true if a lock was removed
741 */
742function unlock($id){
743    $lock = wikiLockFN($id);
744    if(@file_exists($lock)){
745        $ip = io_readFile($lock);
746        if( ($ip == clientIP()) || ($ip == $_SERVER['REMOTE_USER']) ){
747            @unlink($lock);
748            return true;
749        }
750    }
751    return false;
752}
753
754/**
755 * convert line ending to unix format
756 *
757 * @see    formText() for 2crlf conversion
758 * @author Andreas Gohr <andi@splitbrain.org>
759 */
760function cleanText($text){
761    $text = preg_replace("/(\015\012)|(\015)/","\012",$text);
762    return $text;
763}
764
765/**
766 * Prepares text for print in Webforms by encoding special chars.
767 * It also converts line endings to Windows format which is
768 * pseudo standard for webforms.
769 *
770 * @see    cleanText() for 2unix conversion
771 * @author Andreas Gohr <andi@splitbrain.org>
772 */
773function formText($text){
774    $text = str_replace("\012","\015\012",$text);
775    return htmlspecialchars($text);
776}
777
778/**
779 * Returns the specified local text in raw format
780 *
781 * @author Andreas Gohr <andi@splitbrain.org>
782 */
783function rawLocale($id){
784    return io_readFile(localeFN($id));
785}
786
787/**
788 * Returns the raw WikiText
789 *
790 * @author Andreas Gohr <andi@splitbrain.org>
791 */
792function rawWiki($id,$rev=''){
793    return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
794}
795
796/**
797 * Returns the pagetemplate contents for the ID's namespace
798 *
799 * @author Andreas Gohr <andi@splitbrain.org>
800 */
801function pageTemplate($data){
802    $id = $data[0];
803    global $conf;
804    global $INFO;
805
806    $path = dirname(wikiFN($id));
807
808    if(@file_exists($path.'/_template.txt')){
809        $tpl = io_readFile($path.'/_template.txt');
810    }else{
811        // search upper namespaces for templates
812        $len = strlen(rtrim($conf['datadir'],'/'));
813        while (strlen($path) >= $len){
814            if(@file_exists($path.'/__template.txt')){
815                $tpl = io_readFile($path.'/__template.txt');
816                break;
817            }
818            $path = substr($path, 0, strrpos($path, '/'));
819        }
820    }
821    if(!$tpl) return '';
822
823    // replace placeholders
824    $file = noNS($id);
825    $page = strtr($file,'_',' ');
826
827    $tpl = str_replace(array(
828                '@ID@',
829                '@NS@',
830                '@FILE@',
831                '@!FILE@',
832                '@!FILE!@',
833                '@PAGE@',
834                '@!PAGE@',
835                '@!!PAGE@',
836                '@!PAGE!@',
837                '@USER@',
838                '@NAME@',
839                '@MAIL@',
840                '@DATE@',
841                ),
842            array(
843                $id,
844                getNS($id),
845                $file,
846                utf8_ucfirst($file),
847                utf8_strtoupper($file),
848                $page,
849                utf8_ucfirst($page),
850                utf8_ucwords($page),
851                utf8_strtoupper($page),
852                $_SERVER['REMOTE_USER'],
853                $INFO['userinfo']['name'],
854                $INFO['userinfo']['mail'],
855                $conf['dformat'],
856                ), $tpl);
857
858    // we need the callback to work around strftime's char limit
859    $tpl = preg_replace_callback('/%./',create_function('$m','return strftime($m[0]);'),$tpl);
860
861    return $tpl;
862}
863
864
865/**
866 * Returns the raw Wiki Text in three slices.
867 *
868 * The range parameter needs to have the form "from-to"
869 * and gives the range of the section in bytes - no
870 * UTF-8 awareness is needed.
871 * The returned order is prefix, section and suffix.
872 *
873 * @author Andreas Gohr <andi@splitbrain.org>
874 */
875function rawWikiSlices($range,$id,$rev=''){
876    list($from,$to) = explode('-',$range,2);
877    $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
878    if(!$from) $from = 0;
879    if(!$to)   $to   = strlen($text)+1;
880
881    $slices[0] = substr($text,0,$from-1);
882    $slices[1] = substr($text,$from-1,$to-$from);
883    $slices[2] = substr($text,$to);
884
885    return $slices;
886}
887
888/**
889 * Joins wiki text slices
890 *
891 * function to join the text slices with correct lineendings again.
892 * When the pretty parameter is set to true it adds additional empty
893 * lines between sections if needed (used on saving).
894 *
895 * @author Andreas Gohr <andi@splitbrain.org>
896 */
897function con($pre,$text,$suf,$pretty=false){
898    if($pretty){
899        if($pre && substr($pre,-1) != "\n") $pre .= "\n";
900        if($suf && substr($text,-1) != "\n") $text .= "\n";
901    }
902
903    // Avoid double newline above section when saving section edit
904    //if($pre) $pre .= "\n";
905    if($suf) $text .= "\n";
906    return $pre.$text.$suf;
907}
908
909/**
910 * Saves a wikitext by calling io_writeWikiPage.
911 * Also directs changelog and attic updates.
912 *
913 * @author Andreas Gohr <andi@splitbrain.org>
914 * @author Ben Coburn <btcoburn@silicodon.net>
915 */
916function saveWikiText($id,$text,$summary,$minor=false){
917    /* Note to developers:
918       This code is subtle and delicate. Test the behavior of
919       the attic and changelog with dokuwiki and external edits
920       after any changes. External edits change the wiki page
921       directly without using php or dokuwiki.
922     */
923    global $conf;
924    global $lang;
925    global $REV;
926    // ignore if no changes were made
927    if($text == rawWiki($id,'')){
928        return;
929    }
930
931    $file = wikiFN($id);
932    $old = @filemtime($file); // from page
933    $wasRemoved = empty($text);
934    $wasCreated = !@file_exists($file);
935    $wasReverted = ($REV==true);
936    $newRev = false;
937    $oldRev = getRevisions($id, -1, 1, 1024); // from changelog
938    $oldRev = (int)(empty($oldRev)?0:$oldRev[0]);
939    if(!@file_exists(wikiFN($id, $old)) && @file_exists($file) && $old>=$oldRev) {
940        // add old revision to the attic if missing
941        saveOldRevision($id);
942        // add a changelog entry if this edit came from outside dokuwiki
943        if ($old>$oldRev) {
944            addLogEntry($old, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=>true));
945            // remove soon to be stale instructions
946            $cache = new cache_instructions($id, $file);
947            $cache->removeCache();
948        }
949    }
950
951    if ($wasRemoved){
952        // Send "update" event with empty data, so plugins can react to page deletion
953        $data = array(array($file, '', false), getNS($id), noNS($id), false);
954        trigger_event('IO_WIKIPAGE_WRITE', $data);
955        // pre-save deleted revision
956        @touch($file);
957        clearstatcache();
958        $newRev = saveOldRevision($id);
959        // remove empty file
960        @unlink($file);
961        // remove old meta info...
962        $mfiles = metaFiles($id);
963        $changelog = metaFN($id, '.changes');
964        $metadata  = metaFN($id, '.meta');
965        foreach ($mfiles as $mfile) {
966            // but keep per-page changelog to preserve page history and keep meta data
967            if (@file_exists($mfile) && $mfile!==$changelog && $mfile!==$metadata) { @unlink($mfile); }
968        }
969        // purge meta data
970        p_purge_metadata($id);
971        $del = true;
972        // autoset summary on deletion
973        if(empty($summary)) $summary = $lang['deleted'];
974        // remove empty namespaces
975        io_sweepNS($id, 'datadir');
976        io_sweepNS($id, 'mediadir');
977    }else{
978        // save file (namespace dir is created in io_writeWikiPage)
979        io_writeWikiPage($file, $text, $id);
980        // pre-save the revision, to keep the attic in sync
981        $newRev = saveOldRevision($id);
982        $del = false;
983    }
984
985    // select changelog line type
986    $extra = '';
987    $type = DOKU_CHANGE_TYPE_EDIT;
988    if ($wasReverted) {
989        $type = DOKU_CHANGE_TYPE_REVERT;
990        $extra = $REV;
991    }
992    else if ($wasCreated) { $type = DOKU_CHANGE_TYPE_CREATE; }
993    else if ($wasRemoved) { $type = DOKU_CHANGE_TYPE_DELETE; }
994    else if ($minor && $conf['useacl'] && $_SERVER['REMOTE_USER']) { $type = DOKU_CHANGE_TYPE_MINOR_EDIT; } //minor edits only for logged in users
995
996    addLogEntry($newRev, $id, $type, $summary, $extra);
997    // send notify mails
998    notify($id,'admin',$old,$summary,$minor);
999    notify($id,'subscribers',$old,$summary,$minor);
1000
1001    // update the purgefile (timestamp of the last time anything within the wiki was changed)
1002    io_saveFile($conf['cachedir'].'/purgefile',time());
1003
1004    // if useheading is enabled, purge the cache of all linking pages
1005    if(useHeading('content')){
1006        $pages = ft_backlinks($id);
1007        foreach ($pages as $page) {
1008            $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
1009            $cache->removeCache();
1010        }
1011    }
1012}
1013
1014/**
1015 * moves the current version to the attic and returns its
1016 * revision date
1017 *
1018 * @author Andreas Gohr <andi@splitbrain.org>
1019 */
1020function saveOldRevision($id){
1021    global $conf;
1022    $oldf = wikiFN($id);
1023    if(!@file_exists($oldf)) return '';
1024    $date = filemtime($oldf);
1025    $newf = wikiFN($id,$date);
1026    io_writeWikiPage($newf, rawWiki($id), $id, $date);
1027    return $date;
1028}
1029
1030/**
1031 * Sends a notify mail on page change or registration
1032 *
1033 * @param  string  $id       The changed page
1034 * @param  string  $who      Who to notify (admin|subscribers|register)
1035 * @param  int     $rev      Old page revision
1036 * @param  string  $summary  What changed
1037 * @param  boolean $minor    Is this a minor edit?
1038 * @param  array   $replace  Additional string substitutions, @KEY@ to be replaced by value
1039 *
1040 * @author Andreas Gohr <andi@splitbrain.org>
1041 */
1042function notify($id,$who,$rev='',$summary='',$minor=false,$replace=array()){
1043    global $lang;
1044    global $conf;
1045    global $INFO;
1046
1047    // decide if there is something to do
1048    if($who == 'admin'){
1049        if(empty($conf['notify'])) return; //notify enabled?
1050        $text = rawLocale('mailtext');
1051        $to   = $conf['notify'];
1052        $bcc  = '';
1053    }elseif($who == 'subscribers'){
1054        if(!$conf['subscribers']) return; //subscribers enabled?
1055        if($conf['useacl'] && $_SERVER['REMOTE_USER'] && $minor) return; //skip minors
1056        $data = array('id' => $id, 'addresslist' => '', 'self' => false);
1057        trigger_event('COMMON_NOTIFY_ADDRESSLIST', $data,
1058                      'subscription_addresslist');
1059        $bcc = $data['addresslist'];
1060        if(empty($bcc)) return;
1061        $to   = '';
1062        $text = rawLocale('subscr_single');
1063    }elseif($who == 'register'){
1064        if(empty($conf['registernotify'])) return;
1065        $text = rawLocale('registermail');
1066        $to   = $conf['registernotify'];
1067        $bcc  = '';
1068    }else{
1069        return; //just to be safe
1070    }
1071
1072    $ip   = clientIP();
1073    $text = str_replace('@DATE@',dformat(),$text);
1074    $text = str_replace('@BROWSER@',$_SERVER['HTTP_USER_AGENT'],$text);
1075    $text = str_replace('@IPADDRESS@',$ip,$text);
1076    $text = str_replace('@HOSTNAME@',gethostsbyaddrs($ip),$text);
1077    $text = str_replace('@NEWPAGE@',wl($id,'',true,'&'),$text);
1078    $text = str_replace('@PAGE@',$id,$text);
1079    $text = str_replace('@TITLE@',$conf['title'],$text);
1080    $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
1081    $text = str_replace('@SUMMARY@',$summary,$text);
1082    $text = str_replace('@USER@',$_SERVER['REMOTE_USER'],$text);
1083
1084    foreach ($replace as $key => $substitution) {
1085        $text = str_replace('@'.strtoupper($key).'@',$substitution, $text);
1086    }
1087
1088    if($who == 'register'){
1089        $subject = $lang['mail_new_user'].' '.$summary;
1090    }elseif($rev){
1091        $subject = $lang['mail_changed'].' '.$id;
1092        $text = str_replace('@OLDPAGE@',wl($id,"rev=$rev",true,'&'),$text);
1093        $df  = new Diff(explode("\n",rawWiki($id,$rev)),
1094                        explode("\n",rawWiki($id)));
1095        $dformat = new UnifiedDiffFormatter();
1096        $diff    = $dformat->format($df);
1097    }else{
1098        $subject=$lang['mail_newpage'].' '.$id;
1099        $text = str_replace('@OLDPAGE@','none',$text);
1100        $diff = rawWiki($id);
1101    }
1102    $text = str_replace('@DIFF@',$diff,$text);
1103    $subject = '['.$conf['title'].'] '.$subject;
1104
1105    $from = $conf['mailfrom'];
1106    $from = str_replace('@USER@',$_SERVER['REMOTE_USER'],$from);
1107    $from = str_replace('@NAME@',$INFO['userinfo']['name'],$from);
1108    $from = str_replace('@MAIL@',$INFO['userinfo']['mail'],$from);
1109
1110    mail_send($to,$subject,$text,$from,'',$bcc);
1111}
1112
1113/**
1114 * extracts the query from a search engine referrer
1115 *
1116 * @author Andreas Gohr <andi@splitbrain.org>
1117 * @author Todd Augsburger <todd@rollerorgans.com>
1118 */
1119function getGoogleQuery(){
1120    if (!isset($_SERVER['HTTP_REFERER'])) {
1121        return '';
1122    }
1123    $url = parse_url($_SERVER['HTTP_REFERER']);
1124
1125    $query = array();
1126
1127    // temporary workaround against PHP bug #49733
1128    // see http://bugs.php.net/bug.php?id=49733
1129    if(UTF8_MBSTRING) $enc = mb_internal_encoding();
1130    parse_str($url['query'],$query);
1131    if(UTF8_MBSTRING) mb_internal_encoding($enc);
1132
1133    $q = '';
1134    if(isset($query['q']))
1135        $q = $query['q'];        // google, live/msn, aol, ask, altavista, alltheweb, gigablast
1136    elseif(isset($query['p']))
1137        $q = $query['p'];        // yahoo
1138    elseif(isset($query['query']))
1139        $q = $query['query'];    // lycos, netscape, clusty, hotbot
1140    elseif(preg_match("#a9\.com#i",$url['host'])) // a9
1141        $q = urldecode(ltrim($url['path'],'/'));
1142
1143    if($q === '') return '';
1144    $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/',$q,-1,PREG_SPLIT_NO_EMPTY);
1145    return $q;
1146}
1147
1148/**
1149 * Try to set correct locale
1150 *
1151 * @deprecated No longer used
1152 * @author     Andreas Gohr <andi@splitbrain.org>
1153 */
1154function setCorrectLocale(){
1155    global $conf;
1156    global $lang;
1157
1158    $enc = strtoupper($lang['encoding']);
1159    foreach ($lang['locales'] as $loc){
1160        //try locale
1161        if(@setlocale(LC_ALL,$loc)) return;
1162        //try loceale with encoding
1163        if(@setlocale(LC_ALL,"$loc.$enc")) return;
1164    }
1165    //still here? try to set from environment
1166    @setlocale(LC_ALL,"");
1167}
1168
1169/**
1170 * Return the human readable size of a file
1171 *
1172 * @param       int    $size   A file size
1173 * @param       int    $dec    A number of decimal places
1174 * @author      Martin Benjamin <b.martin@cybernet.ch>
1175 * @author      Aidan Lister <aidan@php.net>
1176 * @version     1.0.0
1177 */
1178function filesize_h($size, $dec = 1){
1179    $sizes = array('B', 'KB', 'MB', 'GB');
1180    $count = count($sizes);
1181    $i = 0;
1182
1183    while ($size >= 1024 && ($i < $count - 1)) {
1184        $size /= 1024;
1185        $i++;
1186    }
1187
1188    return round($size, $dec) . ' ' . $sizes[$i];
1189}
1190
1191/**
1192 * Return the given timestamp as human readable, fuzzy age
1193 *
1194 * @author Andreas Gohr <gohr@cosmocode.de>
1195 */
1196function datetime_h($dt){
1197    global $lang;
1198
1199    $ago = time() - $dt;
1200    if($ago > 24*60*60*30*12*2){
1201        return sprintf($lang['years'], round($ago/(24*60*60*30*12)));
1202    }
1203    if($ago > 24*60*60*30*2){
1204        return sprintf($lang['months'], round($ago/(24*60*60*30)));
1205    }
1206    if($ago > 24*60*60*7*2){
1207        return sprintf($lang['weeks'], round($ago/(24*60*60*7)));
1208    }
1209    if($ago > 24*60*60*2){
1210        return sprintf($lang['days'], round($ago/(24*60*60)));
1211    }
1212    if($ago > 60*60*2){
1213        return sprintf($lang['hours'], round($ago/(60*60)));
1214    }
1215    if($ago > 60*2){
1216        return sprintf($lang['minutes'], round($ago/(60)));
1217    }
1218    return sprintf($lang['seconds'], $ago);
1219}
1220
1221/**
1222 * Wraps around strftime but provides support for fuzzy dates
1223 *
1224 * The format default to $conf['dformat']. It is passed to
1225 * strftime - %f can be used to get the value from datetime_h()
1226 *
1227 * @see datetime_h
1228 * @author Andreas Gohr <gohr@cosmocode.de>
1229 */
1230function dformat($dt=null,$format=''){
1231    global $conf;
1232
1233    if(is_null($dt)) $dt = time();
1234    $dt = (int) $dt;
1235    if(!$format) $format = $conf['dformat'];
1236
1237    $format = str_replace('%f',datetime_h($dt),$format);
1238    return strftime($format,$dt);
1239}
1240
1241/**
1242 * return an obfuscated email address in line with $conf['mailguard'] setting
1243 *
1244 * @author Harry Fuecks <hfuecks@gmail.com>
1245 * @author Christopher Smith <chris@jalakai.co.uk>
1246 */
1247function obfuscate($email) {
1248    global $conf;
1249
1250    switch ($conf['mailguard']) {
1251        case 'visible' :
1252            $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
1253            return strtr($email, $obfuscate);
1254
1255        case 'hex' :
1256            $encode = '';
1257            $len = strlen($email);
1258            for ($x=0; $x < $len; $x++){
1259                $encode .= '&#x' . bin2hex($email{$x}).';';
1260            }
1261            return $encode;
1262
1263        case 'none' :
1264        default :
1265            return $email;
1266    }
1267}
1268
1269/**
1270 * Removes quoting backslashes
1271 *
1272 * @author Andreas Gohr <andi@splitbrain.org>
1273 */
1274function unslash($string,$char="'"){
1275    return str_replace('\\'.$char,$char,$string);
1276}
1277
1278/**
1279 * Convert php.ini shorthands to byte
1280 *
1281 * @author <gilthans dot NO dot SPAM at gmail dot com>
1282 * @link   http://de3.php.net/manual/en/ini.core.php#79564
1283 */
1284function php_to_byte($v){
1285    $l = substr($v, -1);
1286    $ret = substr($v, 0, -1);
1287    switch(strtoupper($l)){
1288        case 'P':
1289            $ret *= 1024;
1290        case 'T':
1291            $ret *= 1024;
1292        case 'G':
1293            $ret *= 1024;
1294        case 'M':
1295            $ret *= 1024;
1296        case 'K':
1297            $ret *= 1024;
1298        break;
1299    }
1300    return $ret;
1301}
1302
1303/**
1304 * Wrapper around preg_quote adding the default delimiter
1305 */
1306function preg_quote_cb($string){
1307    return preg_quote($string,'/');
1308}
1309
1310/**
1311 * Shorten a given string by removing data from the middle
1312 *
1313 * You can give the string in two parts, the first part $keep
1314 * will never be shortened. The second part $short will be cut
1315 * in the middle to shorten but only if at least $min chars are
1316 * left to display it. Otherwise it will be left off.
1317 *
1318 * @param string $keep   the part to keep
1319 * @param string $short  the part to shorten
1320 * @param int    $max    maximum chars you want for the whole string
1321 * @param int    $min    minimum number of chars to have left for middle shortening
1322 * @param string $char   the shortening character to use
1323 */
1324function shorten($keep,$short,$max,$min=9,$char='…'){
1325    $max = $max - utf8_strlen($keep);
1326    if($max < $min) return $keep;
1327    $len = utf8_strlen($short);
1328    if($len <= $max) return $keep.$short;
1329    $half = floor($max/2);
1330    return $keep.utf8_substr($short,0,$half-1).$char.utf8_substr($short,$len-$half);
1331}
1332
1333/**
1334 * Return the users realname or e-mail address for use
1335 * in page footer and recent changes pages
1336 *
1337 * @author Andy Webber <dokuwiki AT andywebber DOT com>
1338 */
1339function editorinfo($username){
1340    global $conf;
1341    global $auth;
1342
1343    switch($conf['showuseras']){
1344        case 'username':
1345        case 'email':
1346        case 'email_link':
1347            if($auth) $info = $auth->getUserData($username);
1348            break;
1349        default:
1350            return hsc($username);
1351    }
1352
1353    if(isset($info) && $info) {
1354        switch($conf['showuseras']){
1355            case 'username':
1356                return hsc($info['name']);
1357            case 'email':
1358                return obfuscate($info['mail']);
1359            case 'email_link':
1360                $mail=obfuscate($info['mail']);
1361                return '<a href="mailto:'.$mail.'">'.$mail.'</a>';
1362            default:
1363                return hsc($username);
1364        }
1365    } else {
1366        return hsc($username);
1367    }
1368}
1369
1370/**
1371 * Returns the path to a image file for the currently chosen license.
1372 * When no image exists, returns an empty string
1373 *
1374 * @author Andreas Gohr <andi@splitbrain.org>
1375 * @param  string $type - type of image 'badge' or 'button'
1376 */
1377function license_img($type){
1378    global $license;
1379    global $conf;
1380    if(!$conf['license']) return '';
1381    if(!is_array($license[$conf['license']])) return '';
1382    $lic = $license[$conf['license']];
1383    $try = array();
1384    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1385    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1386    if(substr($conf['license'],0,3) == 'cc-'){
1387        $try[] = 'lib/images/license/'.$type.'/cc.png';
1388    }
1389    foreach($try as $src){
1390        if(@file_exists(DOKU_INC.$src)) return $src;
1391    }
1392    return '';
1393}
1394
1395/**
1396 * Checks if the given amount of memory is available
1397 *
1398 * If the memory_get_usage() function is not available the
1399 * function just assumes $bytes of already allocated memory
1400 *
1401 * @param  int $mem  Size of memory you want to allocate in bytes
1402 * @param  int $used already allocated memory (see above)
1403 * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
1404 * @author Andreas Gohr <andi@splitbrain.org>
1405 */
1406function is_mem_available($mem,$bytes=1048576){
1407    $limit = trim(ini_get('memory_limit'));
1408    if(empty($limit)) return true; // no limit set!
1409
1410    // parse limit to bytes
1411    $limit = php_to_byte($limit);
1412
1413    // get used memory if possible
1414    if(function_exists('memory_get_usage')){
1415        $used = memory_get_usage();
1416    }else{
1417        $used = $bytes;
1418    }
1419
1420    if($used+$mem > $limit){
1421        return false;
1422    }
1423
1424    return true;
1425}
1426
1427/**
1428 * Send a HTTP redirect to the browser
1429 *
1430 * Works arround Microsoft IIS cookie sending bug. Exits the script.
1431 *
1432 * @link   http://support.microsoft.com/kb/q176113/
1433 * @author Andreas Gohr <andi@splitbrain.org>
1434 */
1435function send_redirect($url){
1436    // always close the session
1437    session_write_close();
1438
1439    // check if running on IIS < 6 with CGI-PHP
1440    if( isset($_SERVER['SERVER_SOFTWARE']) && isset($_SERVER['GATEWAY_INTERFACE']) &&
1441        (strpos($_SERVER['GATEWAY_INTERFACE'],'CGI') !== false) &&
1442        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($_SERVER['SERVER_SOFTWARE']), $matches)) &&
1443        $matches[1] < 6 ){
1444        header('Refresh: 0;url='.$url);
1445    }else{
1446        header('Location: '.$url);
1447    }
1448    exit;
1449}
1450
1451/**
1452 * Validate a value using a set of valid values
1453 *
1454 * This function checks whether a specified value is set and in the array
1455 * $valid_values. If not, the function returns a default value or, if no
1456 * default is specified, throws an exception.
1457 *
1458 * @param string $param        The name of the parameter
1459 * @param array  $valid_values A set of valid values; Optionally a default may
1460 *                             be marked by the key “default”.
1461 * @param array  $array        The array containing the value (typically $_POST
1462 *                             or $_GET)
1463 * @param string $exc          The text of the raised exception
1464 *
1465 * @author Adrian Lang <lang@cosmocode.de>
1466 */
1467function valid_input_set($param, $valid_values, $array, $exc = '') {
1468    if (isset($array[$param]) && in_array($array[$param], $valid_values)) {
1469        return $array[$param];
1470    } elseif (isset($valid_values['default'])) {
1471        return $valid_values['default'];
1472    } else {
1473        throw new Exception($exc);
1474    }
1475}
1476
1477//Setup VIM: ex: et ts=2 enc=utf-8 :
1478