xref: /dokuwiki/inc/common.php (revision cd7fd4a2c78ff5083a121a441142649ab5f6acad)
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
9  if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../').'/');
10  require_once(DOKU_CONF.'dokuwiki.php');
11  require_once(DOKU_INC.'inc/io.php');
12  require_once(DOKU_INC.'inc/utf8.php');
13  require_once(DOKU_INC.'inc/mail.php');
14  require_once(DOKU_INC.'inc/parserutils.php');
15
16/**
17 * These constants are used with the recents function
18 */
19define('RECENTS_SKIP_DELETED',2);
20define('RECENTS_SKIP_MINORS',4);
21define('RECENTS_SKIP_SUBSPACES',8);
22
23/**
24 * Wrapper around htmlspecialchars()
25 *
26 * @author Andreas Gohr <andi@splitbrain.org>
27 * @see    htmlspecialchars()
28 */
29function hsc($string){
30  return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
31}
32
33/**
34 * print a newline terminated string
35 *
36 * You can give an indention as optional parameter
37 *
38 * @author Andreas Gohr <andi@splitbrain.org>
39 */
40function ptln($string,$intend=0){
41  for($i=0; $i<$intend; $i++) print ' ';
42  print"$string\n";
43}
44
45/**
46 * Return info about the current document as associative
47 * array.
48 *
49 * @author Andreas Gohr <andi@splitbrain.org>
50 */
51function pageinfo(){
52  global $ID;
53  global $REV;
54  global $USERINFO;
55  global $conf;
56
57  if($_SERVER['REMOTE_USER']){
58    $info['userinfo']   = $USERINFO;
59    $info['perm']       = auth_quickaclcheck($ID);
60    $info['subscribed'] = is_subscribed($ID,$_SERVER['REMOTE_USER']);
61    $info['client']     = $_SERVER['REMOTE_USER'];
62
63    // if some outside auth were used only REMOTE_USER is set
64    if(!$info['userinfo']['name']){
65      $info['userinfo']['name'] = $_SERVER['REMOTE_USER'];
66    }
67
68  }else{
69    $info['perm']       = auth_aclcheck($ID,'',null);
70    $info['subscribed'] = false;
71    $info['client']     = clientIP(true);
72  }
73
74  $info['namespace'] = getNS($ID);
75  $info['locked']    = checklock($ID);
76  $info['filepath']  = realpath(wikiFN($ID,$REV));
77  $info['exists']    = @file_exists($info['filepath']);
78  if($REV && !$info['exists']){
79    //check if current revision was meant
80    $cur = wikiFN($ID);
81    if(@file_exists($cur) && (@filemtime($cur) == $REV)){
82      $info['filepath'] = realpath($cur);
83      $info['exists']   = true;
84      $REV = '';
85    }
86  }
87  $info['rev'] = $REV;
88  if($info['exists']){
89    $info['writable'] = (is_writable($info['filepath']) &&
90                         ($info['perm'] >= AUTH_EDIT));
91  }else{
92    $info['writable'] = ($info['perm'] >= AUTH_CREATE);
93  }
94  $info['editable']  = ($info['writable'] && empty($info['lock']));
95  $info['lastmod']   = @filemtime($info['filepath']);
96
97  //who's the editor
98  if($REV){
99    $revinfo = getRevisionInfo($ID,$REV);
100  }else{
101    $revinfo = getRevisionInfo($ID,$info['lastmod']);
102  }
103  $info['ip']     = $revinfo['ip'];
104  $info['user']   = $revinfo['user'];
105  $info['sum']    = $revinfo['sum'];
106  $info['minor']  = $revinfo['minor'];
107
108  if($revinfo['user']){
109    $info['editor'] = $revinfo['user'];
110  }else{
111    $info['editor'] = $revinfo['ip'];
112  }
113
114  // draft
115  $draft = getCacheName($info['client'].$ID,'.draft');
116  if(@file_exists($draft)){
117    if(@filemtime($draft) < @filemtime(wikiFN($ID))){
118      // remove stale draft
119      @unlink($draft);
120    }else{
121      $info['draft'] = $draft;
122    }
123  }
124
125  return $info;
126}
127
128/**
129 * Build an string of URL parameters
130 *
131 * @author Andreas Gohr
132 */
133function buildURLparams($params, $sep='&amp;'){
134  $url = '';
135  $amp = false;
136  foreach($params as $key => $val){
137    if($amp) $url .= $sep;
138
139    $url .= $key.'=';
140    $url .= rawurlencode($val);
141    $amp = true;
142  }
143  return $url;
144}
145
146/**
147 * Build an string of html tag attributes
148 *
149 * @author Andreas Gohr
150 */
151function buildAttributes($params){
152  $url = '';
153  foreach($params as $key => $val){
154    $url .= $key.'="';
155    $url .= htmlspecialchars ($val);
156    $url .= '" ';
157  }
158  return $url;
159}
160
161
162/**
163 * print a message
164 *
165 * If HTTP headers were not sent yet the message is added
166 * to the global message array else it's printed directly
167 * using html_msgarea()
168 *
169 *
170 * Levels can be:
171 *
172 * -1 error
173 *  0 info
174 *  1 success
175 *
176 * @author Andreas Gohr <andi@splitbrain.org>
177 * @see    html_msgarea
178 */
179function msg($message,$lvl=0,$line='',$file=''){
180  global $MSG;
181  $errors[-1] = 'error';
182  $errors[0]  = 'info';
183  $errors[1]  = 'success';
184
185  if($line || $file) $message.=' ['.basename($file).':'.$line.']';
186
187  if(!headers_sent()){
188    if(!isset($MSG)) $MSG = array();
189    $MSG[]=array('lvl' => $errors[$lvl], 'msg' => $message);
190  }else{
191    $MSG = array();
192    $MSG[]=array('lvl' => $errors[$lvl], 'msg' => $message);
193    if(function_exists('html_msgarea')){
194      html_msgarea();
195    }else{
196      print "ERROR($lvl) $message";
197    }
198  }
199}
200
201/**
202 * This builds the breadcrumb trail and returns it as array
203 *
204 * @author Andreas Gohr <andi@splitbrain.org>
205 */
206function breadcrumbs(){
207  // we prepare the breadcrumbs early for quick session closing
208  static $crumbs = null;
209  if($crumbs != null) return $crumbs;
210
211  global $ID;
212  global $ACT;
213  global $conf;
214  $crumbs = $_SESSION[$conf['title']]['bc'];
215
216  //first visit?
217  if (!is_array($crumbs)){
218    $crumbs = array();
219  }
220  //we only save on show and existing wiki documents
221  $file = wikiFN($ID);
222  if($ACT != 'show' || !@file_exists($file)){
223    $_SESSION[$conf['title']]['bc'] = $crumbs;
224    return $crumbs;
225  }
226
227  // page names
228  $name = noNS($ID);
229  if ($conf['useheading']) {
230    // get page title
231    $title = p_get_first_heading($ID);
232    if ($title) {
233      $name = $title;
234    }
235  }
236
237  //remove ID from array
238  if (isset($crumbs[$ID])) {
239    unset($crumbs[$ID]);
240  }
241
242  //add to array
243  $crumbs[$ID] = $name;
244  //reduce size
245  while(count($crumbs) > $conf['breadcrumbs']){
246    array_shift($crumbs);
247  }
248  //save to session
249  $_SESSION[$conf['title']]['bc'] = $crumbs;
250  return $crumbs;
251}
252
253/**
254 * Filter for page IDs
255 *
256 * This is run on a ID before it is outputted somewhere
257 * currently used to replace the colon with something else
258 * on Windows systems and to have proper URL encoding
259 *
260 * Urlencoding is ommitted when the second parameter is false
261 *
262 * @author Andreas Gohr <andi@splitbrain.org>
263 */
264function idfilter($id,$ue=true){
265  global $conf;
266  if ($conf['useslash'] && $conf['userewrite']){
267    $id = strtr($id,':','/');
268  }elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
269      $conf['userewrite']) {
270    $id = strtr($id,':',';');
271  }
272  if($ue){
273    $id = rawurlencode($id);
274    $id = str_replace('%3A',':',$id); //keep as colon
275    $id = str_replace('%2F','/',$id); //keep as slash
276  }
277  return $id;
278}
279
280/**
281 * This builds a link to a wikipage
282 *
283 * It handles URL rewriting and adds additional parameter if
284 * given in $more
285 *
286 * @author Andreas Gohr <andi@splitbrain.org>
287 */
288function wl($id='',$more='',$abs=false,$sep='&amp;'){
289  global $conf;
290  if(is_array($more)){
291    $more = buildURLparams($more,$sep);
292  }else{
293    $more = str_replace(',',$sep,$more);
294  }
295
296  $id    = idfilter($id);
297  if($abs){
298    $xlink = DOKU_URL;
299  }else{
300    $xlink = DOKU_BASE;
301  }
302
303  if($conf['userewrite'] == 2){
304    $xlink .= DOKU_SCRIPT.'/'.$id;
305    if($more) $xlink .= '?'.$more;
306  }elseif($conf['userewrite']){
307    $xlink .= $id;
308    if($more) $xlink .= '?'.$more;
309  }else{
310    $xlink .= DOKU_SCRIPT.'?id='.$id;
311    if($more) $xlink .= $sep.$more;
312  }
313
314  return $xlink;
315}
316
317/**
318 * This builds a link to an alternate page format
319 *
320 * Handles URL rewriting if enabled. Follows the style of wl().
321 *
322 * @author Ben Coburn <btcoburn@silicodon.net>
323 */
324function exportlink($id='',$format='raw',$more='',$abs=false,$sep='&amp;'){
325  global $conf;
326  if(is_array($more)){
327    $more = buildURLparams($more,$sep);
328  }else{
329    $more = str_replace(',',$sep,$more);
330  }
331
332  $format = rawurlencode($format);
333  $id = idfilter($id);
334  if($abs){
335    $xlink = DOKU_URL;
336  }else{
337    $xlink = DOKU_BASE;
338  }
339
340  if($conf['userewrite'] == 2){
341    $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
342    if($more) $xlink .= $sep.$more;
343  }elseif($conf['userewrite'] == 1){
344    $xlink .= '_export/'.$format.'/'.$id;
345    if($more) $xlink .= '?'.$more;
346  }else{
347    $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
348    if($more) $xlink .= $sep.$more;
349  }
350
351  return $xlink;
352}
353
354/**
355 * Build a link to a media file
356 *
357 * Will return a link to the detail page if $direct is false
358 */
359function ml($id='',$more='',$direct=true,$sep='&amp;'){
360  global $conf;
361  if(is_array($more)){
362    $more = buildURLparams($more,$sep);
363  }else{
364    $more = str_replace(',',$sep,$more);
365  }
366
367  $xlink = DOKU_BASE;
368
369  // external URLs are always direct without rewriting
370  if(preg_match('#^(https?|ftp)://#i',$id)){
371    $xlink .= 'lib/exe/fetch.php';
372    if($more){
373      $xlink .= '?'.$more;
374      $xlink .= $sep.'media='.rawurlencode($id);
375    }else{
376      $xlink .= '?media='.rawurlencode($id);
377    }
378    return $xlink;
379  }
380
381  $id = idfilter($id);
382
383  // decide on scriptname
384  if($direct){
385    if($conf['userewrite'] == 1){
386      $script = '_media';
387    }else{
388      $script = 'lib/exe/fetch.php';
389    }
390  }else{
391    if($conf['userewrite'] == 1){
392      $script = '_detail';
393    }else{
394      $script = 'lib/exe/detail.php';
395    }
396  }
397
398  // build URL based on rewrite mode
399   if($conf['userewrite']){
400     $xlink .= $script.'/'.$id;
401     if($more) $xlink .= '?'.$more;
402   }else{
403     if($more){
404       $xlink .= $script.'?'.$more;
405       $xlink .= $sep.'media='.$id;
406     }else{
407       $xlink .= $script.'?media='.$id;
408     }
409   }
410
411  return $xlink;
412}
413
414
415
416/**
417 * Just builds a link to a script
418 *
419 * @todo   maybe obsolete
420 * @author Andreas Gohr <andi@splitbrain.org>
421 */
422function script($script='doku.php'){
423#  $link = getBaseURL();
424#  $link .= $script;
425#  return $link;
426  return DOKU_BASE.DOKU_SCRIPT;
427}
428
429/**
430 * Spamcheck against wordlist
431 *
432 * Checks the wikitext against a list of blocked expressions
433 * returns true if the text contains any bad words
434 *
435 * @author Andreas Gohr <andi@splitbrain.org>
436 */
437function checkwordblock(){
438  global $TEXT;
439  global $conf;
440
441  if(!$conf['usewordblock']) return false;
442
443  $wordblocks = getWordblocks();
444  //how many lines to read at once (to work around some PCRE limits)
445  if(version_compare(phpversion(),'4.3.0','<')){
446    //old versions of PCRE define a maximum of parenthesises even if no
447    //backreferences are used - the maximum is 99
448    //this is very bad performancewise and may even be too high still
449    $chunksize = 40;
450  }else{
451    //read file in chunks of 600 - this should work around the
452    //MAX_PATTERN_SIZE in modern PCRE
453    $chunksize = 400;
454  }
455  while($blocks = array_splice($wordblocks,0,$chunksize)){
456    $re = array();
457    #build regexp from blocks
458    foreach($blocks as $block){
459      $block = preg_replace('/#.*$/','',$block);
460      $block = trim($block);
461      if(empty($block)) continue;
462      $re[]  = $block;
463    }
464    if(preg_match('#('.join('|',$re).')#si',$TEXT, $match=array())) {
465      return true;
466    }
467  }
468  return false;
469}
470
471/**
472 * Return the IP of the client
473 *
474 * Honours X-Forwarded-For and X-Real-IP Proxy Headers
475 *
476 * It returns a comma separated list of IPs if the above mentioned
477 * headers are set. If the single parameter is set, it tries to return
478 * a routable public address, prefering the ones suplied in the X
479 * headers
480 *
481 * @param  boolean $single If set only a single IP is returned
482 * @author Andreas Gohr <andi@splitbrain.org>
483 */
484function clientIP($single=false){
485  $ip = array();
486  $ip[] = $_SERVER['REMOTE_ADDR'];
487  if($_SERVER['HTTP_X_FORWARDED_FOR'])
488    $ip = array_merge($ip,explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']));
489  if($_SERVER['HTTP_X_REAL_IP'])
490    $ip = array_merge($ip,explode(',',$_SERVER['HTTP_X_REAL_IP']));
491
492  // remove any non-IP stuff
493  $cnt = count($ip);
494  for($i=0; $i<$cnt; $i++){
495    $ip[$i] = preg_replace('/[^0-9\.]+/','',$ip[$i]);
496    if(!preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/',$ip[$i])) $ip[$i] = '';
497    if(empty($ip[$i])) unset($ip[$i]);
498  }
499  $ip = array_values(array_unique($ip));
500  if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
501
502  if(!$single) return join(',',$ip);
503
504  // decide which IP to use, trying to avoid local addresses
505  $ip = array_reverse($ip);
506  foreach($ip as $i){
507    if(preg_match('/^(127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/',$i)){
508      continue;
509    }else{
510      return $i;
511    }
512  }
513  // still here? just use the first (last) address
514  return $ip[0];
515}
516
517/**
518 * Checks if a given page is currently locked.
519 *
520 * removes stale lockfiles
521 *
522 * @author Andreas Gohr <andi@splitbrain.org>
523 */
524function checklock($id){
525  global $conf;
526  $lock = wikiFN($id).'.lock';
527
528  //no lockfile
529  if(!@file_exists($lock)) return false;
530
531  //lockfile expired
532  if((time() - filemtime($lock)) > $conf['locktime']){
533    unlink($lock);
534    return false;
535  }
536
537  //my own lock
538  $ip = io_readFile($lock);
539  if( ($ip == clientIP()) || ($ip == $_SERVER['REMOTE_USER']) ){
540    return false;
541  }
542
543  return $ip;
544}
545
546/**
547 * Lock a page for editing
548 *
549 * @author Andreas Gohr <andi@splitbrain.org>
550 */
551function lock($id){
552  $lock = wikiFN($id).'.lock';
553  if($_SERVER['REMOTE_USER']){
554    io_saveFile($lock,$_SERVER['REMOTE_USER']);
555  }else{
556    io_saveFile($lock,clientIP());
557  }
558}
559
560/**
561 * Unlock a page if it was locked by the user
562 *
563 * @author Andreas Gohr <andi@splitbrain.org>
564 * @return bool true if a lock was removed
565 */
566function unlock($id){
567  $lock = wikiFN($id).'.lock';
568  if(@file_exists($lock)){
569    $ip = io_readFile($lock);
570    if( ($ip == clientIP()) || ($ip == $_SERVER['REMOTE_USER']) ){
571      @unlink($lock);
572      return true;
573    }
574  }
575  return false;
576}
577
578/**
579 * convert line ending to unix format
580 *
581 * @see    formText() for 2crlf conversion
582 * @author Andreas Gohr <andi@splitbrain.org>
583 */
584function cleanText($text){
585  $text = preg_replace("/(\015\012)|(\015)/","\012",$text);
586  return $text;
587}
588
589/**
590 * Prepares text for print in Webforms by encoding special chars.
591 * It also converts line endings to Windows format which is
592 * pseudo standard for webforms.
593 *
594 * @see    cleanText() for 2unix conversion
595 * @author Andreas Gohr <andi@splitbrain.org>
596 */
597function formText($text){
598  $text = preg_replace("/\012/","\015\012",$text);
599  return htmlspecialchars($text);
600}
601
602/**
603 * Returns the specified local text in raw format
604 *
605 * @author Andreas Gohr <andi@splitbrain.org>
606 */
607function rawLocale($id){
608  return io_readFile(localeFN($id));
609}
610
611/**
612 * Returns the raw WikiText
613 *
614 * @author Andreas Gohr <andi@splitbrain.org>
615 */
616function rawWiki($id,$rev=''){
617  return io_readFile(wikiFN($id,$rev));
618}
619
620/**
621 * Returns the pagetemplate contents for the ID's namespace
622 *
623 * @author Andreas Gohr <andi@splitbrain.org>
624 */
625function pageTemplate($id){
626  global $conf;
627  global $INFO;
628  $tpl = io_readFile(dirname(wikiFN($id)).'/_template.txt');
629  $tpl = str_replace('@ID@',$id,$tpl);
630  $tpl = str_replace('@NS@',getNS($id),$tpl);
631  $tpl = str_replace('@PAGE@',strtr(noNS($id),'_',' '),$tpl);
632  $tpl = str_replace('@USER@',$_SERVER['REMOTE_USER'],$tpl);
633  $tpl = str_replace('@NAME@',$INFO['userinfo']['name'],$tpl);
634  $tpl = str_replace('@MAIL@',$INFO['userinfo']['mail'],$tpl);
635  $tpl = str_replace('@DATE@',date($conf['dformat']),$tpl);
636  return $tpl;
637}
638
639
640/**
641 * Returns the raw Wiki Text in three slices.
642 *
643 * The range parameter needs to have the form "from-to"
644 * and gives the range of the section in bytes - no
645 * UTF-8 awareness is needed.
646 * The returned order is prefix, section and suffix.
647 *
648 * @author Andreas Gohr <andi@splitbrain.org>
649 */
650function rawWikiSlices($range,$id,$rev=''){
651  list($from,$to) = split('-',$range,2);
652  $text = io_readFile(wikiFN($id,$rev));
653  if(!$from) $from = 0;
654  if(!$to)   $to   = strlen($text)+1;
655
656  $slices[0] = substr($text,0,$from-1);
657  $slices[1] = substr($text,$from-1,$to-$from);
658  $slices[2] = substr($text,$to);
659
660  return $slices;
661}
662
663/**
664 * Joins wiki text slices
665 *
666 * function to join the text slices with correct lineendings again.
667 * When the pretty parameter is set to true it adds additional empty
668 * lines between sections if needed (used on saving).
669 *
670 * @author Andreas Gohr <andi@splitbrain.org>
671 */
672function con($pre,$text,$suf,$pretty=false){
673
674  if($pretty){
675    if($pre && substr($pre,-1) != "\n") $pre .= "\n";
676    if($suf && substr($text,-1) != "\n") $text .= "\n";
677  }
678
679  if($pre) $pre .= "\n";
680  if($suf) $text .= "\n";
681  return $pre.$text.$suf;
682}
683
684/**
685 * print debug messages
686 *
687 * little function to print the content of a var
688 *
689 * @author Andreas Gohr <andi@splitbrain.org>
690 */
691function dbg($msg,$hidden=false){
692  (!$hidden) ? print '<pre class="dbg">' : print "<!--\n";
693  print_r($msg);
694  (!$hidden) ? print '</pre>' : print "\n-->";
695}
696
697/**
698 * Add's an entry to the changelog
699 *
700 * @author Andreas Gohr <andi@splitbrain.org>
701 */
702function addLogEntry($date,$id,$summary='',$minor=false){
703  global $conf;
704
705  if(!@is_writable($conf['changelog'])){
706    msg($conf['changelog'].' is not writable!',-1);
707    return;
708  }
709
710  if(!$date) $date = time(); //use current time if none supplied
711  $remote = $_SERVER['REMOTE_ADDR'];
712  $user   = $_SERVER['REMOTE_USER'];
713
714  if($conf['useacl'] && $user && $minor){
715    $summary = '*'.$summary;
716  }else{
717    $summary = ' '.$summary;
718  }
719
720  $logline = join("\t",array($date,$remote,$id,$user,$summary))."\n";
721  io_saveFile($conf['changelog'],$logline,true);
722}
723
724/**
725 * Checks an summary entry if it was a minor edit
726 *
727 * The summary is cleaned of the marker char
728 *
729 * @author Andreas Gohr <andi@splitbrain.org>
730 */
731function isMinor(&$summary){
732  if(substr($summary,0,1) == '*'){
733    $summary = substr($summary,1);
734    return true;
735  }
736  $summary = trim($summary);
737  return false;
738}
739
740/**
741 * Internal function used by getRecents
742 *
743 * don't call directly
744 *
745 * @see getRecents()
746 * @author Andreas Gohr <andi@splitbrain.org>
747 */
748function _handleRecent($line,$ns,$flags){
749  static $seen  = array();         //caches seen pages and skip them
750  if(empty($line)) return false;   //skip empty lines
751
752  // split the line into parts
753  list($dt,$ip,$id,$usr,$sum) = explode("\t",$line);
754
755  // skip seen ones
756  if($seen[$id]) return false;
757  $recent = array();
758
759  // check minors
760  if(isMinor($sum)){
761    // skip minors
762    if($flags & RECENTS_SKIP_MINORS) return false;
763    $recent['minor'] = true;
764  }else{
765    $recent['minor'] = false;
766  }
767
768  // remember in seen to skip additional sights
769  $seen[$id] = 1;
770
771  // check if it's a hidden page
772  if(isHiddenPage($id)) return false;
773
774  // filter namespace
775  if (($ns) && (strpos($id,$ns.':') !== 0)) return false;
776
777  // exclude subnamespaces
778  if (($flags & RECENTS_SKIP_SUBSPACES) && (getNS($id) != $ns)) return false;
779
780  // check ACL
781  if (auth_quickaclcheck($id) < AUTH_READ) return false;
782
783  // check existance
784  if(!@file_exists(wikiFN($id))){
785    if($flags & RECENTS_SKIP_DELETED){
786      return false;
787    }else{
788      $recent['del'] = true;
789    }
790  }else{
791    $recent['del'] = false;
792  }
793
794  $recent['id']   = $id;
795  $recent['date'] = $dt;
796  $recent['ip']   = $ip;
797  $recent['user'] = $usr;
798  $recent['sum']  = $sum;
799
800  return $recent;
801}
802
803
804/**
805 * returns an array of recently changed files using the
806 * changelog
807 *
808 * The following constants can be used to control which changes are
809 * included. Add them together as needed.
810 *
811 * RECENTS_SKIP_DELETED   - don't include deleted pages
812 * RECENTS_SKIP_MINORS    - don't include minor changes
813 * RECENTS_SKIP_SUBSPACES - don't include subspaces
814 *
815 * @param int    $first   number of first entry returned (for paginating
816 * @param int    $num     return $num entries
817 * @param string $ns      restrict to given namespace
818 * @param bool   $flags   see above
819 *
820 * @author Andreas Gohr <andi@splitbrain.org>
821 */
822function getRecents($first,$num,$ns='',$flags=0){
823  global $conf;
824  $recent = array();
825  $count  = 0;
826
827  if(!$num)
828    return $recent;
829
830  if(!@is_readable($conf['changelog'])){
831    msg($conf['changelog'].' is not readable',-1);
832    return $recent;
833  }
834
835  $fh  = fopen($conf['changelog'],'r');
836  $buf = '';
837  $csz = 4096;                              //chunksize
838  fseek($fh,0,SEEK_END);                    // jump to the end
839  $pos = ftell($fh);                        // position pointer
840
841  // now read backwards into buffer
842  while($pos > 0){
843    $pos -= $csz;                           // seek to previous chunk...
844    if($pos < 0) {                          // ...or rest of file
845      $csz += $pos;
846      $pos = 0;
847    }
848
849    fseek($fh,$pos);
850
851    $buf = fread($fh,$csz).$buf;            // prepend to buffer
852
853    $lines = explode("\n",$buf);            // split buffer into lines
854
855    if($pos > 0){
856      $buf = array_shift($lines);           // first one may be still incomplete
857    }
858
859    $cnt = count($lines);
860    if(!$cnt) continue;                     // no lines yet
861
862    // handle lines
863    for($i = $cnt-1; $i >= 0; $i--){
864      $rec = _handleRecent($lines[$i],$ns,$flags);
865      if($rec !== false){
866        if(--$first >= 0) continue;         // skip first entries
867        $recent[] = $rec;
868        $count++;
869
870        // break while when we have enough entries
871        if($count >= $num){
872          $pos = 0; // will break the while loop
873          break;    // will break the for loop
874        }
875      }
876    }
877  }// end of while
878
879  fclose($fh);
880  return $recent;
881}
882
883/**
884 * Compare the logline $a to the timestamp $b
885 * @author Yann Hamon <yann.hamon@mandragor.org>
886 * @return integer 0 if the logline has timestamp $b, <0 if the timestam
887 *         of $a is greater than $b, >0 else.
888 */
889function hasTimestamp($a, $b)
890{
891  if (strpos($a, $b) === 0)
892    return 0;
893  else
894    return strcmp ($a, $b);
895}
896
897/**
898 * performs a dichotomic search on an array using
899 * a custom compare function
900 *
901 * @author Yann Hamon <yann.hamon@mandragor.org>
902 */
903function array_dichotomic_search($ar, $value, $compareFunc) {
904  $value = trim($value);
905  if (!$ar || !$value || !$compareFunc) return (null);
906  $len = count($ar);
907
908  $l = 0;
909  $r = $len-1;
910
911  do {
912    $i = floor(($l+$r)/2);
913    if ($compareFunc($ar[$i], $value)<0)
914      $l = $i+1;
915    else
916     $r = $i-1;
917  } while ($compareFunc($ar[$i], $value)!=0 && $l<=$r);
918
919  if ($compareFunc($ar[$i], $value)==0)
920    return $i;
921  else
922    return -1;
923}
924
925/**
926 * gets additonal informations for a certain pagerevison
927 * from the changelog
928 *
929 * @author Andreas Gohr <andi@splitbrain.org>
930 * @author Yann Hamon <yann.hamon@mandragor.org>
931 */
932function getRevisionInfo($id,$rev){
933  global $conf;
934
935  if(!$rev) return(null);
936
937  $info = array();
938  if(!@is_readable($conf['changelog'])){
939    msg($conf['changelog'].' is not readable',-1);
940    return $recent;
941  }
942  $loglines = file($conf['changelog']);
943
944  // Search for a line with a matching timestamp
945  $index = array_dichotomic_search ($loglines, $rev, hasTimestamp);
946  if ($index == -1)
947    return;
948
949  // The following code is necessary when there is more than
950  // one line with one same timestamp
951  $loglines_matching = array();
952  $loglines_matching[] =  $loglines[$index];
953  for ($i=$index-1;hasTimestamp($loglines[$i], $rev) == 0; $i--)
954    $loglines_matching[] = $loglines[$i];
955  for ($i=$index+1;hasTimestamp($loglines[$i], $rev) == 0; $i++)
956    $loglines_matching[] = $loglines[$i];
957
958  // Match only lines concerning the document $id
959  $loglines_matching = preg_grep("/$rev\t\d+\.\d+\.\d+\.\d+\t$id\t/",$loglines_matching);
960
961  $loglines_matching = array_reverse($loglines_matching); //reverse sort on timestamp
962  $line = split("\t",$loglines_matching[0]);
963
964  $info['date']  = $line[0];
965  $info['ip']    = $line[1];
966  $info['user']  = $line[3];
967  $info['sum']   = $line[4];
968  $info['minor'] = isMinor($info['sum']);
969  return $info;
970}
971
972
973/**
974 * Saves a wikitext by calling io_saveFile
975 *
976 * @author Andreas Gohr <andi@splitbrain.org>
977 */
978function saveWikiText($id,$text,$summary,$minor=false){
979  global $conf;
980  global $lang;
981  // ignore if no changes were made
982  if($text == rawWiki($id,'')){
983    return;
984  }
985
986  $file = wikiFN($id);
987  $old  = saveOldRevision($id);
988
989  if (empty($text)){
990    // remove empty file
991    @unlink($file);
992    // remove any meta info
993    $mfiles = metaFiles($id);
994    foreach ($mfiles as $mfile) {
995      if (file_exists($mfile)) @unlink($mfile);
996    }
997    $del = true;
998    // autoset summary on deletion
999    if(empty($summary)) $summary = $lang['deleted'];
1000    // unlock early
1001    unlock($id);
1002    // remove empty namespaces
1003    io_sweepNS($id);
1004  }else{
1005    // save file (datadir is created in io_saveFile)
1006    io_saveFile($file,$text);
1007    $del = false;
1008  }
1009
1010  addLogEntry(@filemtime($file),$id,$summary,$minor);
1011  // send notify mails
1012  notify($id,'admin',$old,$summary,$minor);
1013  notify($id,'subscribers',$old,$summary,$minor);
1014
1015  //purge cache on add by updating the purgefile
1016  if($conf['purgeonadd'] && (!$old || $del)){
1017    io_saveFile($conf['cachedir'].'/purgefile',time());
1018  }
1019}
1020
1021/**
1022 * moves the current version to the attic and returns its
1023 * revision date
1024 *
1025 * @author Andreas Gohr <andi@splitbrain.org>
1026 */
1027function saveOldRevision($id){
1028  global $conf;
1029  $oldf = wikiFN($id);
1030  if(!@file_exists($oldf)) return '';
1031  $date = filemtime($oldf);
1032  $newf = wikiFN($id,$date);
1033  if(substr($newf,-3)=='.gz'){
1034    io_saveFile($newf,rawWiki($id));
1035  }else{
1036    io_makeFileDir($newf);
1037    copy($oldf, $newf);
1038  }
1039  return $date;
1040}
1041
1042/**
1043 * Sends a notify mail on page change
1044 *
1045 * @param  string  $id       The changed page
1046 * @param  string  $who      Who to notify (admin|subscribers)
1047 * @param  int     $rev      Old page revision
1048 * @param  string  $summary  What changed
1049 * @param  boolean $minor    Is this a minor edit?
1050 *
1051 * @author Andreas Gohr <andi@splitbrain.org>
1052 */
1053function notify($id,$who,$rev='',$summary='',$minor=false){
1054  global $lang;
1055  global $conf;
1056
1057  // decide if there is something to do
1058  if($who == 'admin'){
1059    if(empty($conf['notify'])) return; //notify enabled?
1060    $text = rawLocale('mailtext');
1061    $to   = $conf['notify'];
1062    $bcc  = '';
1063  }elseif($who == 'subscribers'){
1064    if(!$conf['subscribers']) return; //subscribers enabled?
1065    if($conf['useacl'] && $_SERVER['REMOTE_USER'] && $minor) return; //skip minors
1066    $bcc  = subscriber_addresslist($id);
1067    if(empty($bcc)) return;
1068    $to   = '';
1069    $text = rawLocale('subscribermail');
1070  }else{
1071    return; //just to be safe
1072  }
1073
1074  $text = str_replace('@DATE@',date($conf['dformat']),$text);
1075  $text = str_replace('@BROWSER@',$_SERVER['HTTP_USER_AGENT'],$text);
1076  $text = str_replace('@IPADDRESS@',$_SERVER['REMOTE_ADDR'],$text);
1077  $text = str_replace('@HOSTNAME@',gethostbyaddr($_SERVER['REMOTE_ADDR']),$text);
1078  $text = str_replace('@NEWPAGE@',wl($id,'',true),$text);
1079  $text = str_replace('@PAGE@',$id,$text);
1080  $text = str_replace('@TITLE@',$conf['title'],$text);
1081  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
1082  $text = str_replace('@SUMMARY@',$summary,$text);
1083  $text = str_replace('@USER@',$_SERVER['REMOTE_USER'],$text);
1084
1085  if($rev){
1086    $subject = $lang['mail_changed'].' '.$id;
1087    $text = str_replace('@OLDPAGE@',wl($id,"rev=$rev",true),$text);
1088    require_once(DOKU_INC.'inc/DifferenceEngine.php');
1089    $df  = new Diff(split("\n",rawWiki($id,$rev)),
1090                    split("\n",rawWiki($id)));
1091    $dformat = new UnifiedDiffFormatter();
1092    $diff    = $dformat->format($df);
1093  }else{
1094    $subject=$lang['mail_newpage'].' '.$id;
1095    $text = str_replace('@OLDPAGE@','none',$text);
1096    $diff = rawWiki($id);
1097  }
1098  $text = str_replace('@DIFF@',$diff,$text);
1099  $subject = '['.$conf['title'].'] '.$subject;
1100
1101  mail_send($to,$subject,$text,$conf['mailfrom'],'',$bcc);
1102}
1103
1104/**
1105 * Return a list of available page revisons
1106 *
1107 * @author Andreas Gohr <andi@splitbrain.org>
1108 */
1109function getRevisions($id){
1110  $revd = dirname(wikiFN($id,'foo'));
1111  $revs = array();
1112  $clid = cleanID($id);
1113  if(strrpos($clid,':')) $clid = substr($clid,strrpos($clid,':')+1); //remove path
1114  $clid = utf8_encodeFN($clid);
1115
1116  if (is_dir($revd) && $dh = opendir($revd)) {
1117    while (($file = readdir($dh)) !== false) {
1118      if (is_dir($revd.'/'.$file)) continue;
1119      if (preg_match('/^'.$clid.'\.(\d+)\.txt(\.gz)?$/',$file,$match)){
1120        $revs[]=$match[1];
1121      }
1122    }
1123    closedir($dh);
1124  }
1125  rsort($revs);
1126  return $revs;
1127}
1128
1129/**
1130 * extracts the query from a google referer
1131 *
1132 * @todo   should be more generic and support yahoo et al
1133 * @author Andreas Gohr <andi@splitbrain.org>
1134 */
1135function getGoogleQuery(){
1136  $url = parse_url($_SERVER['HTTP_REFERER']);
1137  if(!$url) return '';
1138
1139  if(!preg_match("#google\.#i",$url['host'])) return '';
1140  $query = array();
1141  parse_str($url['query'],$query);
1142
1143  return $query['q'];
1144}
1145
1146/**
1147 * Try to set correct locale
1148 *
1149 * @deprecated No longer used
1150 * @author     Andreas Gohr <andi@splitbrain.org>
1151 */
1152function setCorrectLocale(){
1153  global $conf;
1154  global $lang;
1155
1156  $enc = strtoupper($lang['encoding']);
1157  foreach ($lang['locales'] as $loc){
1158    //try locale
1159    if(@setlocale(LC_ALL,$loc)) return;
1160    //try loceale with encoding
1161    if(@setlocale(LC_ALL,"$loc.$enc")) return;
1162  }
1163  //still here? try to set from environment
1164  @setlocale(LC_ALL,"");
1165}
1166
1167/**
1168 * Return the human readable size of a file
1169 *
1170 * @param       int    $size   A file size
1171 * @param       int    $dec    A number of decimal places
1172 * @author      Martin Benjamin <b.martin@cybernet.ch>
1173 * @author      Aidan Lister <aidan@php.net>
1174 * @version     1.0.0
1175 */
1176function filesize_h($size, $dec = 1){
1177  $sizes = array('B', 'KB', 'MB', 'GB');
1178  $count = count($sizes);
1179  $i = 0;
1180
1181  while ($size >= 1024 && ($i < $count - 1)) {
1182    $size /= 1024;
1183    $i++;
1184  }
1185
1186  return round($size, $dec) . ' ' . $sizes[$i];
1187}
1188
1189/**
1190 * return an obfuscated email address in line with $conf['mailguard'] setting
1191 *
1192 * @author Harry Fuecks <hfuecks@gmail.com>
1193 * @author Christopher Smith <chris@jalakai.co.uk>
1194 */
1195function obfuscate($email) {
1196  global $conf;
1197
1198  switch ($conf['mailguard']) {
1199    case 'visible' :
1200      $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
1201      return strtr($email, $obfuscate);
1202
1203    case 'hex' :
1204      $encode = '';
1205      for ($x=0; $x < strlen($email); $x++) $encode .= '&#x' . bin2hex($email{$x}).';';
1206      return $encode;
1207
1208    case 'none' :
1209    default :
1210      return $email;
1211  }
1212}
1213
1214/**
1215 * Return DokuWikis version
1216 *
1217 * @author Andreas Gohr <andi@splitbrain.org>
1218 */
1219function getVersion(){
1220  //import version string
1221  if(@file_exists('VERSION')){
1222    //official release
1223    return 'Release '.trim(io_readfile(DOKU_INC.'/VERSION'));
1224  }elseif(is_dir('_darcs')){
1225    //darcs checkout
1226    $inv = file('_darcs/inventory');
1227    $inv = preg_grep('#\*\*\d{14}[\]$]#',$inv);
1228    $cur = array_pop($inv);
1229    preg_match('#\*\*(\d{4})(\d{2})(\d{2})#',$cur,$matches);
1230    return 'Darcs '.$matches[1].'-'.$matches[2].'-'.$matches[3];
1231  }else{
1232    return 'snapshot?';
1233  }
1234}
1235
1236/**
1237 * Run a few sanity checks
1238 *
1239 * @author Andreas Gohr <andi@splitbrain.org>
1240 */
1241function check(){
1242  global $conf;
1243  global $INFO;
1244
1245  msg('DokuWiki version: '.getVersion(),1);
1246
1247  if(version_compare(phpversion(),'4.3.0','<')){
1248    msg('Your PHP version is too old ('.phpversion().' vs. 4.3.+ recommended)',-1);
1249  }elseif(version_compare(phpversion(),'4.3.10','<')){
1250    msg('Consider upgrading PHP to 4.3.10 or higher for security reasons (your version: '.phpversion().')',0);
1251  }else{
1252    msg('PHP version '.phpversion(),1);
1253  }
1254
1255  if(is_writable($conf['changelog'])){
1256    msg('Changelog is writable',1);
1257  }else{
1258    msg('Changelog is not writable',-1);
1259  }
1260
1261  if(is_writable($conf['datadir'])){
1262    msg('Datadir is writable',1);
1263  }else{
1264    msg('Datadir is not writable',-1);
1265  }
1266
1267  if(is_writable($conf['olddir'])){
1268    msg('Attic is writable',1);
1269  }else{
1270    msg('Attic is not writable',-1);
1271  }
1272
1273  if(is_writable($conf['mediadir'])){
1274    msg('Mediadir is writable',1);
1275  }else{
1276    msg('Mediadir is not writable',-1);
1277  }
1278
1279  if(is_writable($conf['cachedir'])){
1280    msg('Cachedir is writable',1);
1281  }else{
1282    msg('Cachedir is not writable',-1);
1283  }
1284
1285  if(is_writable(DOKU_CONF.'users.auth.php')){
1286    msg('conf/users.auth.php is writable',1);
1287  }else{
1288    msg('conf/users.auth.php is not writable',0);
1289  }
1290
1291  if(function_exists('mb_strpos')){
1292    if(defined('UTF8_NOMBSTRING')){
1293      msg('mb_string extension is available but will not be used',0);
1294    }else{
1295      msg('mb_string extension is available and will be used',1);
1296    }
1297  }else{
1298    msg('mb_string extension not available - PHP only replacements will be used',0);
1299  }
1300
1301  if($conf['allowdebug']){
1302    msg('Debugging support is enabled. If you don\'t need it you should set $conf[\'allowdebug\'] = 0',-1);
1303  }else{
1304    msg('Debugging support is disabled',1);
1305  }
1306
1307  msg('Your current permission for this page is '.$INFO['perm'],0);
1308
1309  if(is_writable($INFO['filepath'])){
1310    msg('The current page is writable by the webserver',0);
1311  }else{
1312    msg('The current page is not writable by the webserver',0);
1313  }
1314
1315  if($INFO['writable']){
1316    msg('The current page is writable by you',0);
1317  }else{
1318    msg('The current page is not writable you',0);
1319  }
1320}
1321
1322/**
1323 * Let us know if a user is tracking a page
1324 *
1325 * @author Andreas Gohr <andi@splitbrain.org>
1326 */
1327function is_subscribed($id,$uid){
1328  $file=metaFN($id,'.mlist');
1329  if (@file_exists($file)) {
1330    $mlist = file($file);
1331    $pos = array_search($uid."\n",$mlist);
1332    return is_int($pos);
1333  }
1334
1335  return false;
1336}
1337
1338/**
1339 * Return a string with the email addresses of all the
1340 * users subscribed to a page
1341 *
1342 * @author Steven Danz <steven-danz@kc.rr.com>
1343 */
1344function subscriber_addresslist($id){
1345  global $conf;
1346  global $auth;
1347
1348  $emails = '';
1349
1350  if (!$conf['subscribers']) return;
1351
1352  $mlist = array();
1353  $file=metaFN($id,'.mlist');
1354  if (file_exists($file)) {
1355    $mlist = file($file);
1356  }
1357  if(count($mlist) > 0) {
1358    foreach ($mlist as $who) {
1359      $who = rtrim($who);
1360      $info = $auth->getUserData($who);
1361      $level = auth_aclcheck($id,$who,$info['grps']);
1362      if ($level >= AUTH_READ) {
1363        if (strcasecmp($info['mail'],$conf['notify']) != 0) {
1364          if (empty($emails)) {
1365            $emails = $info['mail'];
1366          } else {
1367            $emails = "$emails,".$info['mail'];
1368          }
1369        }
1370      }
1371    }
1372  }
1373
1374  return $emails;
1375}
1376
1377/**
1378 * Removes quoting backslashes
1379 *
1380 * @author Andreas Gohr <andi@splitbrain.org>
1381 */
1382function unslash($string,$char="'"){
1383  return str_replace('\\'.$char,$char,$string);
1384}
1385
1386//Setup VIM: ex: et ts=2 enc=utf-8 :
1387