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