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