xref: /plugin/discussion/action.php (revision 106e02ebb475e6cb4c4d12d0187489eb6eb2c5f8)
1<?php
2/**
3 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
4 * @author     Esther Brunner <wikidesign@gmail.com>
5 */
6
7// must be run within Dokuwiki
8if (!defined('DOKU_INC')) die();
9
10if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
11require_once(DOKU_PLUGIN.'action.php');
12
13if (!defined('NL')) define('NL',"\n");
14
15class action_plugin_discussion extends DokuWiki_Action_Plugin{
16
17  /**
18   * Return some info
19   */
20  function getInfo(){
21    return array(
22      'author' => 'Esther Brunner',
23      'email'  => 'wikidesign@gmail.com',
24      'date'   => '2007-01-05',
25      'name'   => 'Discussion Plugin',
26      'desc'   => 'Enables discussion features',
27      'url'    => 'http://www.wikidesign.ch/en/plugin/discussion/start',
28    );
29  }
30
31  /**
32   * Register the eventhandlers
33   */
34  function register(&$contr){
35    $contr->register_hook(
36      'ACTION_ACT_PREPROCESS',
37      'BEFORE',
38      $this,
39      'handle_act_preprocess',
40      array()
41    );
42    $contr->register_hook(
43      'TPL_ACT_RENDER',
44      'AFTER',
45      $this,
46      'comments',
47      array()
48    );
49    $contr->register_hook(
50      'RENDERER_CONTENT_POSTPROCESS',
51      'AFTER',
52      $this,
53      'add_toc_item',
54      array()
55    );
56  }
57
58  /**
59   * Main function; dispatches the comment actions
60   */
61  function comments(&$event, $param){
62    global $ADMDISCUSSION;
63
64    if (($event->data != 'admin') && ($event->data != 'show')) return; // nothing to do for us
65
66    if(isset($ADMDISCUSSION['breakaction'])) return;
67
68    $cid  = $_REQUEST['cid'];
69
70    switch ($_REQUEST['comment']){
71
72      case 'add':
73        $comment = array(
74          'user'    => array(
75            'id'      => hsc($_REQUEST['user']),
76            'name'    => hsc($_REQUEST['name']),
77            'mail'    => hsc($_REQUEST['mail']),
78            'url'     => hsc($_REQUEST['url']),
79            'address' => hsc($_REQUEST['address'])),
80          'date'    => array('created' => $_REQUEST['date']),
81          'raw'     => cleanText($_REQUEST['text'])
82        );
83        $repl = $_REQUEST['reply'];
84        $this->_add($comment, $repl);
85        break;
86
87      case 'edit':
88        $this->_show(NULL, $cid);
89        break;
90
91      case 'save':
92        $raw  = cleanText($_REQUEST['text']);
93        $this->_save($cid, $raw);
94        break;
95
96      case 'delete':
97        $this->_save($cid, '');
98        break;
99
100      case 'toogle':
101        $this->_save($cid, '', true);
102        break;
103
104      default: // 'show' => $this->_show(), 'reply' => $this->_show($cid)
105        $this->_show($cid);
106    }
107  }
108
109  /**
110   * Shows all comments of the current page
111   */
112  function _show($reply = NULL, $edit = NULL){
113    global $ID, $INFO , $ADMDISCUSSION;
114
115    // get .comments meta file name
116    $file = metaFN($ID, '.comments');
117
118    if (!@file_exists($file)){
119      // create .comments meta file if automatic setting is switched on
120      if ($this->getConf('automatic') && $INFO['exists']){
121        $data = array('status' => 1, 'number' => 0);
122        io_saveFile($file, serialize($data));
123      }
124    } else { // load data
125      $data = unserialize(io_readFile($file, false));
126    }
127
128    if (!$data['status']) return false; // comments are turned off
129
130    // section title
131    $title = $this->getLang('discussion').((isset($ADMDISCUSSION['page']))?$ADMDISCUSSION['page']:'');
132    echo '<div class="comment_wrapper">';
133    echo '<h2><a name="discussion__section" id="discussion__section">'.$title.'</a></h2>';
134    echo '<div class="level2 hfeed">';
135
136    // now display the comments
137    if (isset($data['comments'])){
138      foreach ($data['comments'] as $key => $value){
139        if ($key == $edit) $this->_form($value['raw'], 'save', $edit); // edit form
140        else $this->_print($key, $data, '', $reply);
141      }
142    }
143
144    // comment form
145    if (($data['status'] == 1) && !$reply && !$edit) $this->_form('');
146
147    echo '</div>'; // level2
148    echo '</div>'; // comment_wrapper
149
150    return true;
151  }
152
153  /**
154   * Adds a new comment and then displays all comments
155   */
156  function _add($comment, $parent){
157    global $ID;
158    global $TEXT;
159    global $ADMDISCUSSION;
160
161    $otxt = $TEXT; // set $TEXT to comment text for wordblock check
162    $TEXT = $comment['raw'];
163
164    // spamcheck against the DokuWiki blacklist
165    if (checkwordblock()){
166      msg($this->getLang('wordblock'), -1);
167      $this->_show();
168      return false;
169    }
170
171    $TEXT = $otxt; // restore global $TEXT
172
173    // get discussion meta file name
174    $file = metaFN($ID, '.comments');
175
176    $data = array();
177    $data = unserialize(io_readFile($file, false));
178
179    if ($data['status'] != 1) return false;                // comments off or closed
180    if ((!$this->getConf('allowguests'))
181      && ($comment['user']['id'] != $_SERVER['REMOTE_USER']))
182      return false;                                        // guest comments not allowed
183
184    if ($comment['date']['created']) $date = strtotime($comment['date']['created']);
185    else $date = time();
186    if ($date == -1) $date = time();
187    $cid  = md5($comment['user']['id'].$date);             // create a unique id
188
189    if (!is_array($data['comments'][$parent])) $parent = NULL; // invalid parent comment
190
191    // render the comment
192    $xhtml = $this->_render($comment['raw']);
193
194    // fill in the new comment
195    $data['comments'][$cid] = array(
196      'user'    => $comment['user'],
197      'date'    => array('created' => $date),
198      'show'    => true,
199      'raw'     => $comment['raw'],
200      'xhtml'   => $xhtml,
201      'parent'  => $parent,
202      'replies' => array()
203    );
204
205    // update parent comment
206    if ($parent) $data['comments'][$parent]['replies'][] = $cid;
207
208    // update the number of comments
209    $data['number']++;
210
211    // save the comment metadata file
212    io_saveFile($file, serialize($data));
213    $this->_addLogEntry($date, $ID, 'cc', '', $cid);
214
215    // notify subscribers of the page
216    $this->_notify($data['comments'][$cid]);
217
218    if (!isset($ADMDISCUSSION['page']))
219    	$this->_show();
220    return true;
221  }
222
223  /**
224   * Saves the comment with the given ID and then displays all comments
225   */
226  function _save($cid, $raw, $toogle = false){
227    global $ID;
228    global $INFO;
229    global $ADMDISCUSSION;
230
231    if ($raw){
232      global $TEXT;
233
234      $otxt = $TEXT; // set $TEXT to comment text for wordblock check
235      $TEXT = $raw;
236
237      // spamcheck against the DokuWiki blacklist
238      if (checkwordblock()){
239        msg($this->getLang('wordblock'), -1);
240        $this->_show();
241        return false;
242      }
243
244      $TEXT = $otxt; // restore global $TEXT
245    }
246
247    // get discussion meta file name
248    $file = metaFN($ID, '.comments');
249
250    $data = array();
251    $data = unserialize(io_readFile($file, false));
252
253    if (is_array($data['comments'][$cid]['user'])){
254      $user    = $data['comments'][$cid]['user']['id'];
255      $convert = false;
256    } else {
257      $user    = $data['comments'][$cid]['user'];
258      $convert = true;
259    }
260
261    // someone else was trying to edit our comment -> abort
262    if (($user != $_SERVER['REMOTE_USER']) && ($INFO['perm'] != AUTH_ADMIN)) return false;
263
264    $date = time();
265
266    // need to convert to new format?
267    if ($convert){
268      $data['comments'][$cid]['user'] = array(
269        'id'      => $user,
270        'name'    => $data['comments'][$cid]['name'],
271        'mail'    => $data['comments'][$cid]['mail'],
272        'url'     => $data['comments'][$cid]['url'],
273        'address' => $data['comments'][$cid]['address'],
274      );
275      $data['comments'][$cid]['date'] = array(
276        'created' => $data['comments'][$cid]['date']
277      );
278    }
279
280    if ($toogle){     // toogle visibility
281      $now = $data['comments'][$cid]['show'];
282      $data['comments'][$cid]['show'] = !$now;
283      $data['number'] = $this->_count($data);
284
285      $type = ($data['comments'][$cid]['show'] ? 'sc' : 'hc');
286
287    } elseif (!$raw){ // remove the comment
288      unset($data['comments'][$cid]);
289      $data['number'] = $this->_count($data);
290
291      $type = 'dc';
292
293    } else {          // save changed comment
294      $xhtml = $this->_render($raw);
295
296      // now change the comment's content
297      $data['comments'][$cid]['date']['modified'] = $date;
298      $data['comments'][$cid]['raw']              = $raw;
299      $data['comments'][$cid]['xhtml']            = $xhtml;
300
301      $type = 'ec';
302    }
303
304    // save the comment metadata file
305
306    io_saveFile($file, serialize($data));
307    $this->_addLogEntry($date, $ID, $type, '', $cid);
308
309    if (!isset($ADMDISCUSSION['page']))
310    	$this->_show();
311    return true;
312  }
313
314  /**
315   * Prints an individual comment
316   */
317  function _print($cid, &$data, $parent = '', $reply = '', $visible = true){
318    global $conf;
319    global $lang;
320    global $ID;
321    global $INFO;
322
323    if (!isset($data['comments'][$cid])) return false; // comment was removed
324    $comment = $data['comments'][$cid];
325
326    if (!is_array($comment)) return false;             // corrupt datatype
327
328    if ($comment['parent'] != $parent) return true;    // reply to an other comment
329
330    if (!$comment['show']){                            // comment hidden
331      if ($INFO['perm'] == AUTH_ADMIN) echo '<div class="comment_hidden">'.NL;
332      else return true;
333    }
334
335    // comment head with date and user data
336    echo '<div class="hentry"><div class="comment_head">'.NL.
337      '<a name="comment__'.$cid.'" id="comment__'.$cid.'"></a>'.NL.
338      '<span class="vcard author">';
339
340    // prepare variables
341    if (is_array($comment['user'])){ // new format
342      $user    = $comment['user']['id'];
343      $name    = $comment['user']['name'];
344      $mail    = $comment['user']['mail'];
345      $url     = $comment['user']['url'];
346      $address = $comment['user']['address'];
347    } else {                         // old format
348      $user    = $comment['user'];
349      $name    = $comment['name'];
350      $mail    = $comment['mail'];
351      $url     = $comment['url'];
352      $address = $comment['address'];
353    }
354    if (is_array($comment['date'])){ // new format
355      $created  = $comment['date']['created'];
356      $modified = $comment['date']['modified'];
357    } else {                         // old format
358      $created  = $comment['date'];
359      $modified = $comment['edited'];
360    }
361
362    // show gravatar image
363    if ($this->getConf('usegravatar')){
364      $default = DOKU_URL.'lib/plugins/discussion/images/default.gif';
365      $size    = $this->getConf('gravatar_size');
366      if ($mail) $src = ml('http://www.gravatar.com/avatar.php?'.
367        'gravatar_id='.md5($mail).
368        '&default='.urlencode($default).
369        '&size='.$size.
370        '&rating='.$this->getConf('gravatar_rating').
371        '&.jpg', 'cache=recache');
372      else $src = $default;
373      $title = ($name ? $name : obfuscate($mail));
374      echo '<ADMDISCUSSIONimg src="'.$src.'" class="medialeft photo" title="'.$title.'"'.
375        ' alt="'.$title.'" width="'.$size.'" height="'.$size.'" />'.NL;
376      $style = ' style="margin-left: '.($size + 14).'px;"';
377    } else {
378      $style = ' style="margin-left: 20px;"';
379    }
380
381    if ($this->getConf('linkemail') && $mail){
382      echo $this->email($mail, $name, 'email fn');
383    } elseif ($url){
384      echo $this->external_link($url, $name, 'urlextern url fn');
385    } else {
386      echo '<span class="fn">'.$name.'</span>';
387    }
388    if ($address) echo ', <span class="adr">'.$address.'</span>';
389    echo '</span>, <abbr class="published" title="'.gmdate('Y-m-d\TH:i:s\Z', $created).
390      '">'.date($conf['dformat'], $created).'</abbr>';
391    if ($comment['edited']) echo ' (<abbr class="updated" title="'.
392      gmdate('Y-m-d\TH:i:s\Z', $modified).'">'.date($conf['dformat'], $modified).
393      '</abbr>)';
394    echo ':'.NL.'</div>'.NL; // class="comment_head"
395
396    // main comment content
397    echo '<div class="comment_body entry-content"'.
398      ($this->getConf('usegravatar') ? $style : '').'>'.NL.
399      $comment['xhtml'].NL.
400      '</div>'.NL.'</div>'.NL; // class="comment_body" and class="hentry"
401
402    if ($visible){
403      // show hide/show toogle button?
404      echo '<div class="comment_buttons">'.NL;
405      if ($INFO['perm'] == AUTH_ADMIN){
406        if (!$comment['show']) $label = $this->getLang('btn_show');
407        else $label = $this->getLang('btn_hide');
408
409        $this->_button($cid, $label, 'toogle');
410      }
411
412      // show reply button?
413      if (($data['status'] == 1) && !$reply && $comment['show']
414        && ($this->getConf('allowguests') || $_SERVER['REMOTE_USER']))
415        $this->_button($cid, $this->getLang('btn_reply'), 'reply', true);
416
417      // show edit and delete button?
418      if ((($user == $_SERVER['REMOTE_USER']) && ($user != ''))
419        || ($INFO['perm'] == AUTH_ADMIN))
420        $this->_button($cid, $lang['btn_secedit'], 'edit', true);
421      if ($INFO['perm'] == AUTH_ADMIN)
422        $this->_button($cid, $lang['btn_delete'], 'delete');
423      echo '</div>'.NL; // class="comment_buttons"
424      echo '<div class="comment_line" '.
425        ($this->getConf('usegravatar') ? $style : '').'>&nbsp;</div>'.NL;
426    }
427
428    // replies to this comment entry?
429    if (count($comment['replies'])){
430      echo '<div class="comment_replies"'.$style.'>'.NL;
431      $visible = ($comment['show'] && $visible);
432      foreach ($comment['replies'] as $rid){
433        $this->_print($rid, $data, $cid, $reply, $visible);
434      }
435      echo '</div>'.NL; // class="comment_replies"
436    }
437
438    if (!$comment['show']) echo '</div>'.NL; // class="comment_hidden"
439
440    // reply form
441    if ($reply == $cid){
442      echo '<div class="comment_replies">'.NL;
443      $this->_form('', 'add', $cid);
444      echo '</div>'.NL; // class="comment_replies"
445    }
446  }
447
448  /**
449   * Outputs the comment form
450   */
451  function _form($raw = '', $act = 'add', $cid = NULL){
452    global $lang;
453    global $conf;
454    global $ID;
455    global $INFO;
456    global $ADMDISCUSSION;
457
458    // not for unregistered users when guest comments aren't allowed
459    if (!$_SERVER['REMOTE_USER'] && !$this->getConf('allowguests')) return false;
460
461    // fill $raw with $_REQUEST['text'] if it's empty (for failed CAPTCHA check)
462    if (!$raw && ($_REQUEST['comment'] == 'show')) $raw = $_REQUEST['text'];
463
464    ?>
465
466
467    <div class="comment_form">
468      <form id="discussion__comment_form" method="post" action="<?php echo ((isset($ADMDISCUSSION['page']))?'':script()) ?>" accept-charset="<?php echo $lang['encoding'] ?>" onsubmit="return validate(this);">
469        <div class="no">
470	<?php if (isset($ADMDISCUSSION['page'])) {
471	?>
472		<input type="hidden" name="page" value="<?php echo @$_GET['page'] ?>" />
473	<?php
474	}
475	?>
476          <input type="hidden" name="id" value="<?php echo $ID ?>" />
477          <input type="hidden" name="do" value="<?php echo ((isset($ADMDISCUSSION['page']))?'admin':'show') ?>" />
478          <input type="hidden" name="comment" value="<?php echo $act ?>" />
479    <?php
480
481    // for adding a comment
482    if ($act == 'add'){
483      ?>
484          <input type="hidden" name="reply" value="<?php echo $cid ?>" />
485      <?php
486      // for registered user (and we're not in admin import mode)
487      if ($conf['useacl'] && $_SERVER['REMOTE_USER']
488        && (!($this->getConf('adminimport') && ($INFO['perm'] == AUTH_ADMIN)))){
489      ?>
490          <input type="hidden" name="user" value="<?php echo hsc($_SERVER['REMOTE_USER']) ?>" />
491          <input type="hidden" name="name" value="<?php echo hsc($INFO['userinfo']['name']) ?>" />
492          <input type="hidden" name="mail" value="<?php echo hsc($INFO['userinfo']['mail']) ?>" />
493      <?php
494      // for guest: show name and e-mail entry fields
495      } else {
496      ?>
497          <input type="hidden" name="user" value="<?php echo clientIP() ?>" />
498          <div class="comment_name">
499            <label class="block" for="discussion__comment_name">
500              <span><?php echo $lang['fullname'] ?>:</span>
501              <input type="text" class="edit" name="name" id="discussion__comment_name" size="50" tabindex="1" value="<?php echo hsc($_REQUEST['name'])?>" />
502            </label>
503          </div>
504          <div class="comment_mail">
505            <label class="block" for="discussion__comment_mail">
506              <span><?php echo $lang['email'] ?>:</span>
507              <input type="text" class="edit" name="mail" id="discussion__comment_mail" size="50" tabindex="2" value="<?php echo hsc($_REQUEST['mail'])?>" />
508            </label>
509          </div>
510      <?php
511      }
512
513      // allow entering an URL
514      if ($this->getConf('urlfield')){
515      ?>
516          <div class="comment_url">
517            <label class="block" for="discussion__comment_url">
518              <span><?php echo $this->getLang('url') ?>:</span>
519              <input type="text" class="edit" name="url" id="discussion__comment_url" size="50" tabindex="3" value="<?php echo hsc($_REQUEST['url'])?>" />
520            </label>
521          </div>
522      <?php
523      }
524
525      // allow entering an address
526      if ($this->getConf('addressfield')){
527      ?>
528          <div class="comment_address">
529            <label class="block" for="discussion__comment_address">
530              <span><?php echo $this->getLang('address') ?>:</span>
531              <input type="text" class="edit" name="address" id="discussion__comment_address" size="50" tabindex="4" value="<?php echo hsc($_REQUEST['address'])?>" />
532            </label>
533          </div>
534      <?php
535      }
536
537      // allow setting the comment date
538      if ($this->getConf('adminimport') && ($INFO['perm'] == AUTH_ADMIN)){
539      ?>
540          <div class="comment_date">
541            <label class="block" for="discussion__comment_date">
542              <span><?php echo $this->getLang('date') ?>:</span>
543              <input type="text" class="edit" name="date" id="discussion__comment_date" size="50" />
544            </label>
545          </div>
546      <?php
547      }
548
549    // for saving a comment
550    } else {
551    ?>
552          <input type="hidden" name="cid" value="<?php echo $cid ?>" />
553    <?php
554    }
555    ?>
556          <div class="comment_text">
557            <textarea class="edit" name="text" cols="80" rows="10" id="discussion__comment_text" tabindex="5"><?php echo formText($raw) ?></textarea>
558          </div>
559    <?php //bad and dirty event insert hook
560    $evdata = array('writable' => true);
561    trigger_event('HTML_EDITFORM_INJECTION', $evdata);
562    ?>
563          <input class="button" type="submit" name="submit" value="<?php echo $lang['btn_save'] ?>" tabindex="6" />
564        </div>
565      </form>
566    </div>
567    <?php
568    if ($this->getConf('usecocomment')) echo $this->_coComment();
569  }
570
571  /**
572   * Adds a javascript to interact with coComments
573   */
574  function _coComment(){
575    global $ID;
576    global $conf;
577    global $INFO;
578	 global  $ADMDISCUSSION;
579	if (isset($ADMDISCUSSION['page'])) return;
580
581    $user = $_SERVER['REMOTE_USER'];
582
583    ?>
584    <script type="text/javascript"><!--//--><![CDATA[//><!--
585      var blogTool  = "DokuWiki";
586      var blogURL   = "<?php echo DOKU_URL ?>";
587      var blogTitle = "<?php echo $conf['title'] ?>";
588      var postURL   = "<?php echo wl($ID, '', true) ?>";
589      var postTitle = "<?php echo tpl_pagetitle($ID, true) ?>";
590    <?php
591    if ($user){
592    ?>
593      var commentAuthor = "<?php echo $INFO['userinfo']['name'] ?>";
594    <?php
595    } else {
596    ?>
597      var commentAuthorFieldName = "name";
598    <?php
599    }
600    ?>
601      var commentAuthorLoggedIn = <?php echo ($user ? 'true' : 'false') ?>;
602      var commentFormID         = "discussion__comment_form";
603      var commentTextFieldName  = "text";
604      var commentButtonName     = "submit";
605      var cocomment_force       = false;
606    //--><!]]></script>
607    <script type="text/javascript" src="http://www.cocomment.com/js/cocomment.js">
608    </script>
609    <?php
610  }
611
612  /**
613   * General button function
614   */
615  function _button($cid, $label, $act, $jump = false){
616    global $ID;
617    global $ADMDISCUSSION;
618
619    $anchor = ($jump ? '#discussion__comment_form' : '' );
620
621    ?>
622    <form class="button" method="post" action="<?php echo ((isset($ADMDISCUSSION['page']))?'':script().$anchor) ?>">
623      <div class="no">
624	<?php if (isset($ADMDISCUSSION['page'])) {
625	?>
626		<input type="hidden" name="page" value="<?php echo @$_GET['page'] ?>" />
627	<?php
628	}
629	?>
630        <input type="hidden" name="id" value="<?php echo $ID ?>" />
631        <input type="hidden" name="do" value="<?php echo ((isset($ADMDISCUSSION['page']))?'admin':'show') ?>" />
632        <input type="hidden" name="comment" value="<?php echo $act ?>" />
633        <input type="hidden" name="cid" value="<?php echo $cid ?>" />
634        <input type="submit" value="<?php echo $label ?>" class="button" title="<?php echo $label ?>" />
635      </div>
636    </form>
637    <?php
638    return true;
639  }
640
641  /**
642   * Adds an entry to the comments changelog
643   *
644   * @author Esther Brunner <wikidesign@gmail.com>
645   * @author Ben Coburn <btcoburn@silicodon.net>
646   */
647  function _addLogEntry($date, $id, $type = 'cc', $summary = '', $extra = ''){
648    global $conf;
649
650    $changelog = $conf['metadir'].'/_comments.changes';
651
652    if(!$date) $date = time(); //use current time if none supplied
653    $remote = $_SERVER['REMOTE_ADDR'];
654    $user   = $_SERVER['REMOTE_USER'];
655
656    $strip = array("\t", "\n");
657    $logline = array(
658      'date'  => $date,
659      'ip'    => $remote,
660      'type'  => str_replace($strip, '', $type),
661      'id'    => $id,
662      'user'  => $user,
663      'sum'   => str_replace($strip, '', $summary),
664      'extra' => str_replace($strip, '', $extra)
665    );
666
667    // add changelog line
668    $logline = implode("\t", $logline)."\n";
669    io_saveFile($changelog, $logline, true); //global changelog cache
670    $this->_trimRecentCommentsLog($changelog);
671  }
672
673  /**
674   * Trims the recent comments cache to the last $conf['changes_days'] recent
675   * changes or $conf['recent'] items, which ever is larger.
676   * The trimming is only done once a day.
677   *
678   * @author Ben Coburn <btcoburn@silicodon.net>
679   */
680  function _trimRecentCommentsLog($changelog){
681    global $conf;
682
683    if (@file_exists($changelog) &&
684      (filectime($changelog) + 86400) < time() &&
685      !@file_exists($changelog.'_tmp')){
686
687      io_lock($changelog);
688      $lines = file($changelog);
689      if (count($lines)<$conf['recent']) {
690          // nothing to trim
691          io_unlock($changelog);
692          return true;
693      }
694
695      io_saveFile($changelog.'_tmp', '');                  // presave tmp as 2nd lock
696      $trim_time = time() - $conf['recent_days']*86400;
697      $out_lines = array();
698
699      for ($i=0; $i<count($lines); $i++) {
700        $log = parseChangelogLine($lines[$i]);
701        if ($log === false) continue;                      // discard junk
702        if ($log['date'] < $trim_time) {
703          $old_lines[$log['date'].".$i"] = $lines[$i];     // keep old lines for now (append .$i to prevent key collisions)
704        } else {
705          $out_lines[$log['date'].".$i"] = $lines[$i];     // definitely keep these lines
706        }
707      }
708
709      // sort the final result, it shouldn't be necessary,
710      // however the extra robustness in making the changelog cache self-correcting is worth it
711      ksort($out_lines);
712      $extra = $conf['recent'] - count($out_lines);        // do we need extra lines do bring us up to minimum
713      if ($extra > 0) {
714        ksort($old_lines);
715        $out_lines = array_merge(array_slice($old_lines,-$extra),$out_lines);
716      }
717
718      // save trimmed changelog
719      io_saveFile($changelog.'_tmp', implode('', $out_lines));
720      @unlink($changelog);
721      if (!rename($changelog.'_tmp', $changelog)) {
722        // rename failed so try another way...
723        io_unlock($changelog);
724        io_saveFile($changelog, implode('', $out_lines));
725        @unlink($changelog.'_tmp');
726      } else {
727        io_unlock($changelog);
728      }
729      return true;
730    }
731  }
732
733  /**
734   * Sends a notify mail on new comment
735   *
736   * @param  array  $comment  data array of the new comment
737   *
738   * @author Andreas Gohr <andi@splitbrain.org>
739   * @author Esther Brunner <wikidesign@gmail.com>
740   */
741  function _notify($comment){
742    global $conf;
743    global $ID;
744
745    if ((!$conf['subscribers']) && (!$conf['notify'])) return; //subscribers enabled?
746    $bcc  = subscriber_addresslist($ID);
747    if ((empty($bcc)) && (!$conf['notify'])) return;
748    $to   = $conf['notify'];
749    $text = io_readFile($this->localFN('subscribermail'));
750
751    $search = array(
752      '@PAGE@',
753      '@TITLE@',
754      '@DATE@',
755      '@NAME@',
756      '@TEXT@',
757      '@UNSUBSCRIBE@',
758      '@DOKUWIKIURL@',
759    );
760    $replace = array(
761      $ID,
762      $conf['title'],
763      date($conf['dformat'], $comment['date']['created']),
764      $comment['user']['name'],
765      $comment['raw'],
766      wl($ID, 'do=unsubscribe', true, '&'),
767      DOKU_URL,
768    );
769    $text = str_replace($search, $replace, $text);
770
771    $subject = '['.$conf['title'].'] '.$this->getLang('mail_newcomment');
772
773    mail_send($to, $subject, $text, $conf['mailfrom'], '', $bcc);
774  }
775
776  /**
777   * Counts the number of visible comments
778   */
779  function _count($data){
780    $number = 0;
781    foreach ($data['comments'] as $cid => $comment){
782      if ($comment['parent']) continue;
783      if (!$comment['show']) continue;
784      $number++;
785      $rids = $comment['replies'];
786      if (count($rids)) $number = $number + $this->_countReplies($data, $rids);
787    }
788    return $number;
789  }
790
791  function _countReplies(&$data, $rids){
792    $number = 0;
793    foreach ($rids as $rid){
794      if (!isset($data['comments'][$rid])) continue; // reply was removed
795      if (!$data['comments'][$rid]['show']) continue;
796      $number++;
797      $rids = $data['comments'][$rid]['replies'];
798      if (count($rids)) $number = $number + $this->_countReplies($data, $rids);
799    }
800    return $number;
801  }
802
803  /**
804   * Renders the comment text
805   */
806  function _render($raw){
807    if ($this->getConf('wikisyntaxok')){
808      $xhtml = $this->render($raw);
809    } else { // wiki syntax not allowed -> just encode special chars
810      $xhtml = htmlspecialchars(trim($raw));
811    }
812    return $xhtml;
813  }
814
815  /**
816   * Adds a TOC item for the discussion section
817   */
818  function add_toc_item(&$event, $param){
819    if ($event->data[0] != 'xhtml') return; // nothing to do for us
820    if (!$this->_hasDiscussion()) return;   // no discussion section
821
822    $pattern = '/<div id="toc__inside">(.*?)<\/div>\s<\/div>/s';
823    if (!preg_match($pattern, $event->data[1], $match)) return; // no TOC on this page
824
825    // ok, then let's do it!
826    global $conf;
827
828    $title   = $this->getLang('discussion');
829    $section = '#discussion__section';
830    $level   = 3 - $conf['toptoclevel'];
831
832    $item = '<li class="level'.$level.'"><div class="li"><span class="li"><a href="'.
833      $section.'" class="toc">'.$title.'</a></span></div></li>';
834
835    if ($level == 1) $search = "</ul>\n</div>";
836    else $search = "</ul>\n</li></ul>\n</div>";
837
838    $new = str_replace($search, $item.$search, $match[0]);
839    $event->data[1] = preg_replace($pattern, $new, $event->data[1]);
840  }
841
842  /**
843   * Finds out whether there is a discussion section for the current page
844   */
845  function _hasDiscussion(){
846    global $ID;
847
848    $cfile = metaFN($ID, '.comments');
849
850    if (!@file_exists($cfile)){
851      if ($this->getConf('automatic')) return true;
852      else return false;
853    }
854
855    $comments = unserialize(io_readFile($cfile, false));
856
857    $num = $comments['number'];
858    if ((!$comments['status']) || (($comments['status'] == 2) && (!$num))) return false;
859    else return true;
860  }
861
862  /**
863   * Checks if 'newthread' was given as action or the comment form was submitted
864   */
865  function handle_act_preprocess(&$event, $param){
866    if ($event->data == 'newthread'){
867      // we can handle it -> prevent others
868      // $event->stopPropagation();
869      $event->preventDefault();
870
871      $event->data = $this->_newThread();
872    }
873    if ((in_array($_REQUEST['comment'], array('add', 'save')))
874      && (@file_exists(DOKU_PLUGIN.'captcha/action.php'))){
875      $this->_captchaCheck();
876    }
877  }
878
879  /**
880   * Creates a new thread page
881   */
882  function _newThread(){
883    global $ID;
884    global $INFO;
885
886    $ns    = cleanID($_REQUEST['ns']);
887    $title = str_replace(':', '', $_REQUEST['title']);
888    $back  = $ID;
889    $ID    = ($ns ? $ns.':' : '').cleanID($title);
890    $INFO  = pageinfo();
891
892    // check if we are allowed to create this file
893    if ($INFO['perm'] >= AUTH_CREATE){
894
895      //check if locked by anyone - if not lock for my self
896      if ($INFO['locked']) return 'locked';
897      else lock($ID);
898
899      // prepare the new thread file with default stuff
900      if (!@file_exists($INFO['filepath'])){
901        global $TEXT;
902        global $conf;
903
904        $TEXT = pageTemplate(array(($ns ? $ns.':' : '').$title));
905        if (!$TEXT){
906          $TEXT = "<- [[:$back]]\n\n====== $title ======\n\n";
907          if ($this->getConf('usegravatar'))
908            $TEXT .= '{{gravatar>'.$INFO['userinfo']['mail'].' }} ';
909          $TEXT .= "//".$INFO['userinfo']['name'].", ".date($conf['dformat']).": //\n\n";
910          if ((@file_exists(DOKU_PLUGIN.'tag/syntax/tag.php'))
911            && (!plugin_isdisabled('tag')))
912            $TEXT .= "\n\n{{tag>}}";
913          $TEXT .= "\n\n~~DISCUSSION~~";
914        }
915        return 'preview';
916      } else {
917        return 'edit';
918      }
919    } else {
920      return 'show';
921    }
922  }
923
924  /**
925   * Checks if the CAPTCHA string submitted is valid
926   *
927   * @author     Andreas Gohr <gohr@cosmocode.de>
928   * @adaption   Esther Brunner <wikidesign@gmail.com>
929   */
930  function _captchaCheck(){
931    if (@file_exists(DOKU_PLUGIN.'captcha/disabled')) return; // CAPTCHA is disabled
932
933    require_once(DOKU_PLUGIN.'captcha/action.php');
934    $captcha = new action_plugin_captcha;
935
936    // do nothing if logged in user and no CAPTCHA required
937    if (!$captcha->getConf('forusers') && $_SERVER['REMOTE_USER']) return;
938
939    // compare provided string with decrypted captcha
940    $rand = PMA_blowfish_decrypt($_REQUEST['plugin__captcha_secret'], auth_cookiesalt());
941    $code = $captcha->_generateCAPTCHA($captcha->_fixedIdent(), $rand);
942
943    if (!$_REQUEST['plugin__captcha_secret'] ||
944      !$_REQUEST['plugin__captcha'] ||
945      strtoupper($_REQUEST['plugin__captcha']) != $code){
946
947      // CAPTCHA test failed! Continue to edit instead of saving
948      msg($captcha->getLang('testfailed'), -1);
949      if ($_REQUEST['comment'] == 'save') $_REQUEST['comment'] = 'edit';
950      elseif ($_REQUEST['comment'] == 'add') $_REQUEST['comment'] = 'show';
951    }
952    // if we arrive here it was a valid save
953  }
954
955}
956
957//Setup VIM: ex: et ts=4 enc=utf-8 :
958