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