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