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