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