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