xref: /dokuwiki/inc/common.php (revision 0c59b0cf929e1226a31e238856ee99b0889aeaf3)
1<?
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
9  require_once("conf/dokuwiki.php");
10  require_once("inc/io.php");
11  require_once('inc/utf8.php');
12
13  //set up error reporting to sane values
14  error_reporting(E_ALL ^ E_NOTICE);
15
16  //make session rewrites XHTML compliant
17  ini_set('arg_separator.output', '&amp;');
18
19  //init session
20  session_name("DokuWiki");
21  session_start();
22
23  //kill magic quotes
24  if (get_magic_quotes_gpc()) {
25    if (!empty($_GET))    remove_magic_quotes($_GET);
26    if (!empty($_POST))   remove_magic_quotes($_POST);
27    if (!empty($_COOKIE)) remove_magic_quotes($_COOKIE);
28    if (!empty($_REQUEST)) remove_magic_quotes($_REQUEST);
29    if (!empty($_SESSION)) remove_magic_quotes($_SESSION);
30    ini_set('magic_quotes_gpc', 0);
31  }
32  set_magic_quotes_runtime(0);
33  ini_set('magic_quotes_sybase',0);
34
35  //disable gzip if not available
36  if($conf['usegzip'] && !function_exists('gzopen')){
37    $conf['usegzip'] = 0;
38  }
39
40/**
41 * remove magic quotes recursivly
42 *
43 * @author Andreas Gohr <andi@splitbrain.org>
44 */
45function remove_magic_quotes(&$array) {
46  foreach (array_keys($array) as $key) {
47    if (is_array($array[$key])) {
48      remove_magic_quotes($array[$key]);
49    }else {
50      $array[$key] = stripslashes($array[$key]);
51    }
52  }
53}
54
55/**
56 * Returns the full absolute URL to the directory where
57 * DokuWiki is installed in (includes a trailing slash)
58 *
59 * @author Andreas Gohr <andi@splitbrain.org>
60 */
61function getBaseURL($abs=false){
62  global $conf;
63  //if canonical url enabled always return absolute
64  if($conf['canonical']) $abs = true;
65
66  //relative URLs are easy
67  if(!$abs){
68    $dir = dirname($_SERVER['PHP_SELF']).'/';
69    $dir = preg_replace('#//#','/',$dir);
70    $dir = preg_replace('#\\\/#','/',$dir); #bugfix for weird WIN behaviour
71    return $dir;
72  }
73
74  $port = ':'.$_SERVER['SERVER_PORT'];
75  //remove port from hostheader as sent by IE
76  $host = preg_replace('/:.*$/','',$_SERVER['HTTP_HOST']);
77
78  // see if HTTPS is enabled - apache leaves this empty when not available,
79  // IIS sets it to 'off', 'false' and 'disabled' are just guessing
80  if (preg_match('/^(|off|false|disabled)$/i',$_SERVER['HTTPS'])){
81    $proto = 'http://';
82    if ($_SERVER['SERVER_PORT'] == '80') {
83      $port='';
84    }
85  }else{
86    $proto = 'https://';
87    if ($_SERVER['SERVER_PORT'] == '443') {
88      $port='';
89    }
90  }
91  $dir = (dirname($_SERVER['PHP_SELF'])).'/';
92  $dir = preg_replace('#//#','/',$dir);
93  $dir = preg_replace('#\/$#','/',$dir); #bugfix for weird WIN behaviour
94
95  return $proto.$host.$port.$dir;
96}
97
98/**
99 * Return info about the current document as associative
100 * array.
101 *
102 * @author Andreas Gohr <andi@splitbrain.org>
103 */
104function pageinfo(){
105  global $ID;
106  global $REV;
107  global $USERINFO;
108  global $conf;
109
110  if($_SERVER['REMOTE_USER']){
111    $info['user']     = $_SERVER['REMOTE_USER'];
112    $info['userinfo'] = $USERINFO;
113    $info['perm']     = auth_quickaclcheck($ID);
114  }else{
115    $info['user']     = '';
116    $info['perm']     = auth_aclcheck($ID,'',null);
117  }
118
119  $info['namespace'] = getNS($ID);
120  $info['locked']    = checklock($ID);
121  $info['filepath']  = realpath(wikiFN($ID,$REV));
122  $info['exists']    = @file_exists($info['filepath']);
123  if($REV && !$info['exists']){
124    //check if current revision was meant
125    $cur = wikiFN($ID);
126    if(@file_exists($cur) && (@filemtime($cur) == $REV)){
127      $info['filepath'] = realpath($cur);
128      $info['exists']   = true;
129      $REV = '';
130    }
131  }
132  if($info['exists']){
133    $info['writable'] = (is_writable($info['filepath']) &&
134                         ($info['perm'] >= AUTH_EDIT));
135  }else{
136    $info['writable'] = ($info['perm'] >= AUTH_CREATE);
137  }
138  $info['editable']  = ($info['writable'] && empty($info['lock']));
139  $info['lastmod']   = @filemtime($info['filepath']);
140
141  return $info;
142}
143
144/**
145 * print a message
146 *
147 * If HTTP headers were not sent yet the message is added
148 * to the global message array else it's printed directly
149 * using html_msgarea()
150 *
151 *
152 * Levels can be:
153 *
154 * -1 error
155 *  0 info
156 *  1 success
157 *
158 * @author Andreas Gohr <andi@splitbrain.org>
159 * @see    html_msgarea
160 */
161function msg($message,$lvl=0){
162  global $MSG;
163  $errors[-1] = 'error';
164  $errors[0]  = 'info';
165  $errors[1]  = 'success';
166
167  if(!headers_sent){
168    if(!isset($MSG)) $MSG = array();
169    $MSG[]=array('lvl' => $errors[$lvl], 'msg' => $message);
170  }else{
171    $MSG = array();
172    $MSG[]=array('lvl' => $errors[$lvl], 'msg' => $message);
173    html_msgarea();
174  }
175}
176
177/**
178 * This builds the breadcrumb trail and returns it as array
179 *
180 * @author Andreas Gohr <andi@splitbrain.org>
181 */
182function breadcrumbs(){
183  global $ID;
184  global $ACT;
185  global $conf;
186  $crumbs = $_SESSION[$conf['title']]['bc'];
187
188  //first visit?
189  if (!is_array($crumbs)){
190    $crumbs = array();
191  }
192  //we only save on show and existing wiki documents
193  if($ACT != 'show' || !@file_exists(wikiFN($ID))){
194    $_SESSION[$conf['title']]['bc'] = $crumbs;
195    return $crumbs;
196  }
197  //remove ID from array
198  $pos = array_search($ID,$crumbs);
199  if($pos !== false && $pos !== null){
200    array_splice($crumbs,$pos,1);
201  }
202
203  //add to array
204  $crumbs[] =$ID;
205  //reduce size
206  while(count($crumbs) > $conf['breadcrumbs']){
207    array_shift($crumbs);
208  }
209  //save to session
210  $_SESSION[$conf['title']]['bc'] = $crumbs;
211  return $crumbs;
212}
213
214/**
215 * Filter for page IDs
216 *
217 * This is run on a ID before it is outputted somewhere
218 * currently used to replace the colon with something else
219 * on Windows systems and to have proper URL encoding
220 *
221 * Urlencoding is ommitted when the second parameter is false
222 *
223 * @author Andreas Gohr <andi@splitbrain.org>
224 */
225function idfilter($id,$ue=true){
226  global $conf;
227  if ($conf['useslash'] && $conf['userewrite']){
228    $id = strtr($id,':','/');
229  }elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
230      $conf['userewrite']) {
231    $id = strtr($id,':',';');
232  }
233  if($ue){
234    $id = urlencode($id);
235    $id = str_replace('%3A',':',$id); //keep as colon
236    $id = str_replace('%2F','/',$id); //keep as slash
237  }
238  return $id;
239}
240
241/**
242 * This builds a link to a wikipage (using getBaseURL)
243 *
244 * @author Andreas Gohr <andi@splitbrain.org>
245 */
246function wl($id='',$more='',$script='doku.php',$canonical=false){
247  global $conf;
248  $more = str_replace(',','&amp;',$more);
249
250  $id    = idfilter($id);
251  $xlink = getBaseURL($canonical);
252
253  if(!$conf['userewrite']){
254    $xlink .= $script;
255    $xlink .= '?id='.$id;
256    if($more) $xlink .= '&amp;'.$more;
257  }else{
258    $xlink .= $id;
259    if($more) $xlink .= '?'.$more;
260  }
261
262  return $xlink;
263}
264
265/**
266 * Just builds a link to a script
267 *
268 * @author Andreas Gohr <andi@splitbrain.org>
269 */
270function script($script='doku.php'){
271  $link = getBaseURL();
272  $link .= $script;
273  return $link;
274}
275
276/**
277 * Return namespacepart of a wiki ID
278 *
279 * @author Andreas Gohr <andi@splitbrain.org>
280 */
281function getNS($id){
282 if(strpos($id,':')!==false){
283   return substr($id,0,strrpos($id,':'));
284 }
285 return false;
286}
287
288/**
289 * Returns the ID without the namespace
290 *
291 * @author Andreas Gohr <andi@splitbrain.org>
292 */
293function noNS($id){
294  return preg_replace('/.*:/','',$id);
295}
296
297/**
298 * Spamcheck against wordlist
299 *
300 * Checks the wikitext against a list of blocked expressions
301 * returns true if the text contains any bad words
302 *
303 * @author Andreas Gohr <andi@splitbrain.org>
304 */
305function checkwordblock(){
306  global $TEXT;
307  global $conf;
308
309  if(!$conf['usewordblock']) return false;
310
311  $blocks = file('conf/wordblock.conf');
312  $re = array();
313  #build regexp from blocks
314  foreach($blocks as $block){
315    $block = preg_replace('/#.*$/','',$block);
316    $block = trim($block);
317    if(empty($block)) continue;
318    $re[]  = $block;
319  }
320  if(preg_match('#('.join('|',$re).')#si',$TEXT)) return true;
321  return false;
322}
323
324/**
325 * Return the IP of the client
326 *
327 * Honours X-Forwarded-For Proxy Headers
328 *
329 * @author Andreas Gohr <andi@splitbrain.org>
330 */
331function clientIP(){
332  $my = $_SERVER['REMOTE_ADDR'];
333  if($_SERVER['HTTP_X_FORWARDED_FOR']){
334    $my .= ' ('.$_SERVER['HTTP_X_FORWARDED_FOR'].')';
335  }
336  return $my;
337}
338
339/**
340 * Checks if a given page is currently locked.
341 *
342 * removes stale lockfiles
343 *
344 * @author Andreas Gohr <andi@splitbrain.org>
345 */
346function checklock($id){
347  global $conf;
348  $lock = wikiFN($id).'.lock';
349
350  //no lockfile
351  if(!@file_exists($lock)) return false;
352
353  //lockfile expired
354  if((time() - filemtime($lock)) > $conf['locktime']){
355    unlink($lock);
356    return false;
357  }
358
359  //my own lock
360  $ip = io_readFile($lock);
361  if( ($ip == clientIP()) || ($ip == $_SERVER['REMOTE_USER']) ){
362    return false;
363  }
364
365  return $ip;
366}
367
368/**
369 * Lock a page for editing
370 *
371 * @author Andreas Gohr <andi@splitbrain.org>
372 */
373function lock($id){
374  $lock = wikiFN($id).'.lock';
375  if($_SERVER['REMOTE_USER']){
376    io_saveFile($lock,$_SERVER['REMOTE_USER']);
377  }else{
378    io_saveFile($lock,clientIP());
379  }
380}
381
382/**
383 * Unlock a page if it was locked by the user
384 *
385 * @author Andreas Gohr <andi@splitbrain.org>
386 * @return bool true if a lock was removed
387 */
388function unlock($id){
389  $lock = wikiFN($id).'.lock';
390  if(@file_exists($lock)){
391    $ip = io_readFile($lock);
392    if( ($ip == clientIP()) || ($ip == $_SERVER['REMOTE_USER']) ){
393      @unlink($lock);
394      return true;
395    }
396  }
397  return false;
398}
399
400/**
401 * Remove unwanted chars from ID
402 *
403 * Cleans a given ID to only use allowed characters. Accented characters are
404 * converted to unaccented ones
405 *
406 * @author Andreas Gohr <andi@splitbrain.org>
407 */
408function cleanID($id){
409  global $conf;
410  global $lang;
411  $id = trim($id);
412  $id = utf8_strtolower($id);
413
414  //alternative namespace seperator
415  $id = strtr($id,';',':');
416  if($conf['useslash']) $id = strtr($id,'/',':');
417
418  if($conf['deaccent']) $id = utf8_deaccent($id,-1);
419
420  //remove specials (only ascii specials are removed)
421  $id = preg_replace('#[0x00-0x20 !"§$%&()\[\]{}\\?`\'\#~*+=,<>\|^°@µ¹²³¼½¬]#u','_',$id);
422
423  //clean up
424  $id = preg_replace('#__#','_',$id);
425  $id = preg_replace('#:+#',':',$id);
426  $id = trim($id,':._-');
427  $id = preg_replace('#:[:\._\-]+#',':',$id);
428
429  return($id);
430}
431
432/**
433 * returns the full path to the datafile specified by ID and
434 * optional revision
435 *
436 * The filename is URL encoded to protect Unicode chars
437 *
438 * @author Andreas Gohr <andi@splitbrain.org>
439 */
440function wikiFN($id,$rev=''){
441  global $conf;
442  $id = cleanID($id);
443  $id = str_replace(':','/',$id);
444  if(empty($rev)){
445    $fn = $conf['datadir'].'/'.$id.'.txt';
446  }else{
447    $fn = $conf['olddir'].'/'.$id.'.'.$rev.'.txt';
448    if($conf['usegzip'] && !@file_exists($fn)){
449      //return gzip if enabled and plaintext doesn't exist
450      $fn .= '.gz';
451    }
452  }
453  $fn = utf8_encodeFN($fn);
454  return $fn;
455}
456
457/**
458 * Returns the full filepath to a localized textfile if local
459 * version isn't found the english one is returned
460 *
461 * @author Andreas Gohr <andi@splitbrain.org>
462 */
463function localeFN($id){
464  global $conf;
465  $file = './lang/'.$conf['lang'].'/'.$id.'.txt';
466  if(!@file_exists($file)){
467    //fall back to english
468    $file = './lang/en/'.$id.'.txt';
469  }
470  return cleanText($file);
471}
472
473/**
474 * convert line ending to unix format
475 *
476 * @see    formText() for 2crlf conversion
477 * @author Andreas Gohr <andi@splitbrain.org>
478 */
479function cleanText($text){
480  $text = preg_replace("/(\015\012)|(\015)/","\012",$text);
481  return $text;
482}
483
484/**
485 * Prepares text for print in Webforms by encoding special chars.
486 * It also converts line endings to Windows format which is
487 * pseudo standard for webforms.
488 *
489 * @see    cleanText() for 2unix conversion
490 * @author Andreas Gohr <andi@splitbrain.org>
491 */
492function formText($text){
493  $text = preg_replace("/\012/","\015\012",$text);
494  return htmlspecialchars($text);
495}
496
497/**
498 * Returns the specified local text in parsed format
499 *
500 * @author Andreas Gohr <andi@splitbrain.org>
501 */
502function parsedLocale($id){
503  //disable section editing
504  global $parser;
505  $se = $parser['secedit'];
506  $parser['secedit'] = false;
507  //fetch parsed locale
508  $html = io_cacheParse(localeFN($id));
509  //reset section editing
510  $parser['secedit'] = $se;
511  return $html;
512}
513
514/**
515 * Returns the specified local text in raw format
516 *
517 * @author Andreas Gohr <andi@splitbrain.org>
518 */
519function rawLocale($id){
520  return io_readFile(localeFN($id));
521}
522
523
524/**
525 * Returns the parsed Wikitext for the given id and revision.
526 *
527 * If $excuse is true an explanation is returned if the file
528 * wasn't found
529 *
530 * @author Andreas Gohr <andi@splitbrain.org>
531 */
532function parsedWiki($id,$rev='',$excuse=true){
533  $file = wikiFN($id,$rev);
534  $ret  = '';
535
536  //ensure $id is in global $ID (needed for parsing)
537  global $ID;
538  $ID = $id;
539
540  if($rev){
541    if(@file_exists($file)){
542      $ret = parse(io_readFile($file));
543    }elseif($excuse){
544      $ret = parsedLocale('norev');
545    }
546  }else{
547    if(@file_exists($file)){
548      $ret = io_cacheParse($file);
549    }elseif($excuse){
550      $ret = parsedLocale('newpage');
551    }
552  }
553  return $ret;
554}
555
556/**
557 * Returns the raw WikiText
558 *
559 * @author Andreas Gohr <andi@splitbrain.org>
560 */
561function rawWiki($id,$rev=''){
562  return io_readFile(wikiFN($id,$rev));
563}
564
565/**
566 * Returns the raw Wiki Text in three slices.
567 *
568 * The range parameter needs to have the form "from-to"
569 * and gives the range of the section.
570 * The returned order is prefix, section and suffix.
571 *
572 * @author Andreas Gohr <andi@splitbrain.org>
573 */
574function rawWikiSlices($range,$id,$rev=''){
575  list($from,$to) = split('-',$range,2);
576  $text = io_readFile(wikiFN($id,$rev));
577  $text = split("\n",$text);
578  if(!$from) $from = 0;
579  if(!$to)   $to   = count($text);
580
581  $slices[0] = join("\n",array_slice($text,0,$from));
582  $slices[1] = join("\n",array_slice($text,$from,$to + 1  - $from));
583  $slices[2] = join("\n",array_slice($text,$to+1));
584
585  return $slices;
586}
587
588/**
589 * Joins wiki text slices
590 *
591 * function to join the text slices with correct lineendings again.
592 * When the pretty parameter is set to true it adds additional empty
593 * lines between sections if needed (used on saving).
594 *
595 * @author Andreas Gohr <andi@splitbrain.org>
596 */
597function con($pre,$text,$suf,$pretty=false){
598
599  if($pretty){
600    if($pre && substr($pre,-1) != "\n") $pre .= "\n";
601    if($suf && substr($text,-1) != "\n") $text .= "\n";
602  }
603
604  if($pre) $pre .= "\n";
605  if($suf) $text .= "\n";
606  return $pre.$text.$suf;
607}
608
609/**
610 * print debug messages
611 *
612 * little function to print the content of a var
613 *
614 * @author Andreas Gohr <andi@splitbrain.org>
615 */
616function dbg($msg,$hidden=false){
617  (!$hidden) ? print '<pre class="dbg">' : print "<!--\n";
618  print_r($msg);
619  (!$hidden) ? print '</pre>' : print "\n-->";
620}
621
622/**
623 * Add's an entry to the changelog
624 *
625 * @author Andreas Gohr <andi@splitbrain.org>
626 */
627function addLogEntry($id,$summary=""){
628  global $conf;
629  $id     = cleanID($id);
630  $date   = time();
631  $remote = $_SERVER['REMOTE_ADDR'];
632  $user   = $_SERVER['REMOTE_USER'];
633
634  $logline = join("\t",array($date,$remote,$id,$user,$summary))."\n";
635
636  $fh = fopen($conf['changelog'],'a');
637  if($fh){
638    fwrite($fh,$logline);
639    fclose($fh);
640  }
641}
642
643/**
644 * returns an array of recently changed files using the
645 * changelog
646 *
647 * @author Andreas Gohr <andi@splitbrain.org>
648 */
649function getRecents($num=0,$incdel=false){
650  global $conf;
651  $recent = array();
652  if(!$num) $num = $conf['recent'];
653
654  $loglines = file($conf['changelog']);
655  rsort($loglines); //reverse sort on timestamp
656
657  foreach ($loglines as $line){
658    $line = rtrim($line);        //remove newline
659    if(empty($line)) continue;   //skip empty lines
660    $info = split("\t",$line);   //split into parts
661    //add id if not in yet and file still exists and is allowed to read
662    if(!$recent[$info[2]] &&
663       (@file_exists(wikiFN($info[2])) || $incdel) &&
664       (auth_quickaclcheck($info[2]) >= AUTH_READ)
665      ){
666      $recent[$info[2]]['date'] = $info[0];
667      $recent[$info[2]]['ip']   = $info[1];
668      $recent[$info[2]]['user'] = $info[3];
669      $recent[$info[2]]['sum']  = $info[4];
670      $recent[$info[2]]['del']  = !@file_exists(wikiFN($info[2]));
671    }
672    if(count($recent) >= $num){
673      break; //finish if enough items found
674    }
675  }
676  return $recent;
677}
678
679/**
680 * Saves a wikitext by calling io_saveFile
681 *
682 * @author Andreas Gohr <andi@splitbrain.org>
683 */
684function saveWikiText($id,$text,$summary){
685  global $conf;
686  global $lang;
687  umask($conf['umask']);
688  // ignore if no changes were made
689  if($text == rawWiki($id,'')){
690    return;
691  }
692
693  $file = wikiFN($id);
694  $old  = saveOldRevision($id);
695
696  if (empty($text)){
697    // remove empty files
698    @unlink($file);
699    $del = true;
700    $summary = $lang['deleted']; //autoset summary on deletion
701  }else{
702    // save file (datadir is created in io_saveFile)
703    io_saveFile($file,$text);
704    $del = false;
705  }
706
707  addLogEntry($id,$summary);
708  notify($id,$old,$summary);
709
710  //purge cache on add by updating the purgefile
711  if($conf['purgeonadd'] && (!$old || $del)){
712    io_saveFile($conf['datadir'].'/.cache/purgefile',time());
713  }
714}
715
716/**
717 * moves the current version to the attic and returns its
718 * revision date
719 *
720 * @author Andreas Gohr <andi@splitbrain.org>
721 */
722function saveOldRevision($id){
723	global $conf;
724  umask($conf['umask']);
725  $oldf = wikiFN($id);
726  if(!@file_exists($oldf)) return '';
727  $date = filemtime($oldf);
728  $newf = wikiFN($id,$date);
729  if(substr($newf,-3)=='.gz'){
730    io_saveFile($newf,rawWiki($id));
731  }else{
732    io_makeFileDir($newf);
733    copy($oldf, $newf);
734  }
735  return $date;
736}
737
738/**
739 * Sends a notify mail to the wikiadmin when a page was
740 * changed
741 *
742 * @author Andreas Gohr <andi@splitbrain.org>
743 */
744function notify($id,$rev="",$summary=""){
745  global $lang;
746  global $conf;
747  $hdrs ='';
748  if(empty($conf['notify'])) return; //notify enabled?
749
750  $text = rawLocale('mailtext');
751  $text = str_replace('@DATE@',date($conf['dformat']),$text);
752  $text = str_replace('@BROWSER@',$_SERVER['HTTP_USER_AGENT'],$text);
753  $text = str_replace('@IPADDRESS@',$_SERVER['REMOTE_ADDR'],$text);
754  $text = str_replace('@HOSTNAME@',gethostbyaddr($_SERVER['REMOTE_ADDR']),$text);
755  $text = str_replace('@NEWPAGE@',wl($id,'','',true),$text);
756  $text = str_replace('@DOKUWIKIURL@',getBaseURL(true),$text);
757  $text = str_replace('@SUMMARY@',$summary,$text);
758
759  if($rev){
760    $subject = $lang['mail_changed'].' '.$id;
761    $text = str_replace('@OLDPAGE@',wl($id,"rev=$rev",'',true),$text);
762    require_once("inc/DifferenceEngine.php");
763    $df  = new Diff(split("\n",rawWiki($id,$rev)),
764                    split("\n",rawWiki($id)));
765    $dformat = new UnifiedDiffFormatter();
766    $diff    = $dformat->format($df);
767  }else{
768    $subject=$lang['mail_newpage'].' '.$id;
769    $text = str_replace('@OLDPAGE@','none',$text);
770    $diff = rawWiki($id);
771  }
772  $text = str_replace('@DIFF@',$diff,$text);
773
774  if (!empty($conf['mailfrom'])) {
775    $hdrs = 'From: '.$conf['mailfrom']."\n";
776  }
777  @mail($conf['notify'],$subject,$text,$hdrs);
778}
779
780/**
781 * Return a list of available page revisons
782 *
783 * @author Andreas Gohr <andi@splitbrain.org>
784 */
785function getRevisions($id){
786  $revd = dirname(wikiFN($id,'foo'));
787  $revs = array();
788  $clid = cleanID($id);
789  if(strrpos($clid,':')) $clid = substr($clid,strrpos($clid,':')+1); //remove path
790
791  if (is_dir($revd) && $dh = opendir($revd)) {
792    while (($file = readdir($dh)) !== false) {
793      if (is_dir($revd.'/'.$file)) continue;
794      if (preg_match('/^'.$clid.'\.(\d+)\.txt(\.gz)?$/',$file,$match)){
795        $revs[]=$match[1];
796      }
797    }
798    closedir($dh);
799  }
800  rsort($revs);
801  return $revs;
802}
803
804/**
805 * downloads a file from the net and saves it to the given location
806 *
807 * @author Andreas Gohr <andi@splitbrain.org>
808 */
809function download($url,$file){
810  $fp = @fopen($url,"rb");
811  if(!$fp) return false;
812
813  while(!feof($fp)){
814    $cont.= fread($fp,1024);
815  }
816  fclose($fp);
817
818  $fp2 = @fopen($file,"w");
819  if(!$fp2) return false;
820  fwrite($fp2,$cont);
821  fclose($fp2);
822  return true;
823}
824
825/**
826 * extracts the query from a google referer
827 *
828 * @author Andreas Gohr <andi@splitbrain.org>
829 */
830function getGoogleQuery(){
831  $url = parse_url($_SERVER['HTTP_REFERER']);
832
833  if(!preg_match("#google\.#i",$url['host'])) return '';
834  $query = array();
835  parse_str($url['query'],$query);
836
837  return $query['q'];
838}
839
840/**
841 * Try to set correct locale
842 *
843 * @deprecated No longer used
844 * @author     Andreas Gohr <andi@splitbrain.org>
845 */
846function setCorrectLocale(){
847  global $conf;
848  global $lang;
849
850  $enc = strtoupper($lang['encoding']);
851  foreach ($lang['locales'] as $loc){
852    //try locale
853    if(@setlocale(LC_ALL,$loc)) return;
854    //try loceale with encoding
855    if(@setlocale(LC_ALL,"$loc.$enc")) return;
856  }
857  //still here? try to set from environment
858  @setlocale(LC_ALL,"");
859}
860
861/**
862 * Return the human readable size of a file
863 *
864 * @param       int    $size   A file size
865 * @param       int    $dec    A number of decimal places
866 * @author      Martin Benjamin <b.martin@cybernet.ch>
867 * @author      Aidan Lister <aidan@php.net>
868 * @version     1.0.0
869 */
870function filesize_h($size, $dec = 1){
871  $sizes = array('B', 'KB', 'MB', 'GB');
872  $count = count($sizes);
873  $i = 0;
874
875  while ($size >= 1024 && ($i < $count - 1)) {
876    $size /= 1024;
877    $i++;
878  }
879
880  return round($size, $dec) . ' ' . $sizes[$i];
881}
882
883/**
884 * Run a few sanity checks
885 *
886 * @author Andreas Gohr <andi@splitbrain.org>
887 */
888function getVersion(){
889  //import version string
890  if(@file_exists('VERSION')){
891    //official release
892    return 'Release '.io_readfile('VERSION');
893  }elseif(is_dir('_darcs')){
894    //darcs checkout
895    $inv = file('_darcs/inventory');
896    $inv = preg_grep('#andi@splitbrain\.org\*\*\d{14}#',$inv);
897    $cur = array_pop($inv);
898    preg_match('#\*\*(\d{4})(\d{2})(\d{2})#',$cur,$matches);
899    return 'Darcs '.$matches[1].'-'.$matches[2].'-'.$matches[3];
900  }else{
901    return 'snapshot?';
902  }
903}
904
905/**
906 * Run a few sanity checks
907 *
908 * @author Andreas Gohr <andi@splitbrain.org>
909 */
910function check(){
911  global $conf;
912  global $INFO;
913
914  msg('DokuWiki version: '.getVersion(),1);
915
916  if(version_compare(phpversion(),'4.3.0','<')){
917    msg('Your PHP version is too old ('.phpversion().' vs. 4.3.+ recommended)',-1);
918  }elseif(version_compare(phpversion(),'4.3.10','<')){
919    msg('Consider upgrading PHP to 4.3.10 or higher for security reasons (your version: '.phpversion().')',0);
920  }else{
921    msg('PHP version '.phpversion(),1);
922  }
923
924  if(is_writable($conf['changelog'])){
925    msg('Changelog is writable',1);
926  }else{
927    msg('Changelog is not writable',-1);
928  }
929
930  if(is_writable($conf['datadir'])){
931    msg('Datadir is writable',1);
932  }else{
933    msg('Datadir is not writable',-1);
934  }
935
936  if(is_writable($conf['olddir'])){
937    msg('Attic is writable',1);
938  }else{
939    msg('Attic is not writable',-1);
940  }
941
942  if(is_writable($conf['mediadir'])){
943    msg('Mediadir is writable',1);
944  }else{
945    msg('Mediadir is not writable',-1);
946  }
947
948  if(is_writable('conf/users.auth')){
949    msg('conf/users.auth is writable',1);
950  }else{
951    msg('conf/users.auth is not writable',0);
952  }
953
954  if(function_exists('mb_strpos')){
955    if(defined('UTF8_NOMBSTRING')){
956      msg('mb_string extension is available but will not be used',0);
957    }else{
958      msg('mb_string extension is available and will be used',1);
959    }
960  }else{
961    msg('mb_string extension not available - PHP only replacements will be used',0);
962  }
963
964  msg('Your current permission for this page is '.$INFO['perm'],0);
965
966  if(is_writable($INFO['filepath'])){
967    msg('The current page is writable by the webserver',0);
968  }else{
969    msg('The current page is not writable by the webserver',0);
970  }
971
972  if($INFO['writable']){
973    msg('The current page is writable by you',0);
974  }else{
975    msg('The current page is not writable you',0);
976  }
977}
978?>
979