xref: /plugin/discussion/action.php (revision ce7b17cfc37895f67e42750c9c306d75d7a1d7ab)
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 avatar image?
360    if ($this->getConf('useavatar'))
361      && (!plugin_isdisabled('tag')
362      && ($avatar = plugin_load('helper', 'avatar'))){
363      if ($user) echo $avatar->getXHTML($user);
364      else echo $avatar->getXHTML($mail);
365      $style = ' style="margin-left: '.($avatar->getConf('size') + 14).'px;"';
366    } else {
367      $style = ' style="margin-left: 20px;"';
368    }
369
370    if ($this->getConf('linkemail') && $mail){
371      echo $this->email($mail, $name, 'email fn');
372    } elseif ($url){
373      echo $this->external_link($url, $name, 'urlextern url fn');
374    } else {
375      echo '<span class="fn">'.$name.'</span>';
376    }
377    if ($address) echo ', <span class="adr">'.$address.'</span>';
378    echo '</span>, <abbr class="published" title="'.gmdate('Y-m-d\TH:i:s\Z', $created).
379      '">'.date($conf['dformat'], $created).'</abbr>';
380    if ($comment['edited']) echo ' (<abbr class="updated" title="'.
381      gmdate('Y-m-d\TH:i:s\Z', $modified).'">'.date($conf['dformat'], $modified).
382      '</abbr>)';
383    echo ':'.NL.'</div>'.NL; // class="comment_head"
384
385    // main comment content
386    echo '<div class="comment_body entry-content"'.
387      ($this->getConf('usegravatar') ? $style : '').'>'.NL.
388      $comment['xhtml'].NL.
389      '</div>'.NL.'</div>'.NL; // class="comment_body" and class="hentry"
390
391    if ($visible){
392      // show hide/show toogle button?
393      echo '<div class="comment_buttons">'.NL;
394      if ($INFO['perm'] == AUTH_ADMIN){
395        if (!$comment['show']) $label = $this->getLang('btn_show');
396        else $label = $this->getLang('btn_hide');
397
398        $this->_button($cid, $label, 'toogle');
399      }
400
401      // show reply button?
402      if (($data['status'] == 1) && !$reply && $comment['show']
403        && ($this->getConf('allowguests') || $_SERVER['REMOTE_USER']))
404        $this->_button($cid, $this->getLang('btn_reply'), 'reply', true);
405
406      // show edit and delete button?
407      if ((($user == $_SERVER['REMOTE_USER']) && ($user != ''))
408        || ($INFO['perm'] == AUTH_ADMIN))
409        $this->_button($cid, $lang['btn_secedit'], 'edit', true);
410      if ($INFO['perm'] == AUTH_ADMIN)
411        $this->_button($cid, $lang['btn_delete'], 'delete');
412      echo '</div>'.NL; // class="comment_buttons"
413      echo '<div class="comment_line" '.
414        ($this->getConf('usegravatar') ? $style : '').'>&nbsp;</div>'.NL;
415    }
416
417    // replies to this comment entry?
418    if (count($comment['replies'])){
419      echo '<div class="comment_replies"'.$style.'>'.NL;
420      $visible = ($comment['show'] && $visible);
421      foreach ($comment['replies'] as $rid){
422        $this->_print($rid, $data, $cid, $reply, $visible);
423      }
424      echo '</div>'.NL; // class="comment_replies"
425    }
426
427    if (!$comment['show']) echo '</div>'.NL; // class="comment_hidden"
428
429    // reply form
430    if ($reply == $cid){
431      echo '<div class="comment_replies">'.NL;
432      $this->_form('', 'add', $cid);
433      echo '</div>'.NL; // class="comment_replies"
434    }
435  }
436
437  /**
438   * Outputs the comment form
439   */
440  function _form($raw = '', $act = 'add', $cid = NULL){
441    global $lang, $conf, $ID, $INFO;
442
443    // not for unregistered users when guest comments aren't allowed
444    if (!$_SERVER['REMOTE_USER'] && !$this->getConf('allowguests')) return false;
445
446    // fill $raw with $_REQUEST['text'] if it's empty (for failed CAPTCHA check)
447    if (!$raw && ($_REQUEST['comment'] == 'show')) $raw = $_REQUEST['text'];
448
449    ?>
450
451
452    <div class="comment_form">
453      <form id="discussion__comment_form" method="post" action="<?php echo script() ?>" accept-charset="<?php echo $lang['encoding'] ?>" onsubmit="return validate(this);">
454        <div class="no">
455          <input type="hidden" name="id" value="<?php echo $ID ?>" />
456          <input type="hidden" name="do" value="show" />
457          <input type="hidden" name="comment" value="<?php echo $act ?>" />
458    <?php
459
460    // for adding a comment
461    if ($act == 'add'){
462      ?>
463          <input type="hidden" name="reply" value="<?php echo $cid ?>" />
464      <?php
465      // for registered user (and we're not in admin import mode)
466      if ($conf['useacl'] && $_SERVER['REMOTE_USER']
467        && (!($this->getConf('adminimport') && ($INFO['perm'] == AUTH_ADMIN)))){
468      ?>
469          <input type="hidden" name="user" value="<?php echo hsc($_SERVER['REMOTE_USER']) ?>" />
470          <input type="hidden" name="name" value="<?php echo hsc($INFO['userinfo']['name']) ?>" />
471          <input type="hidden" name="mail" value="<?php echo hsc($INFO['userinfo']['mail']) ?>" />
472      <?php
473      // for guest: show name and e-mail entry fields
474      } else {
475      ?>
476          <input type="hidden" name="user" value="<?php echo clientIP() ?>" />
477          <div class="comment_name">
478            <label class="block" for="discussion__comment_name">
479              <span><?php echo $lang['fullname'] ?>:</span>
480              <input type="text" class="edit" name="name" id="discussion__comment_name" size="50" tabindex="1" value="<?php echo hsc($_REQUEST['name'])?>" />
481            </label>
482          </div>
483          <div class="comment_mail">
484            <label class="block" for="discussion__comment_mail">
485              <span><?php echo $lang['email'] ?>:</span>
486              <input type="text" class="edit" name="mail" id="discussion__comment_mail" size="50" tabindex="2" value="<?php echo hsc($_REQUEST['mail'])?>" />
487            </label>
488          </div>
489      <?php
490      }
491
492      // allow entering an URL
493      if ($this->getConf('urlfield')){
494      ?>
495          <div class="comment_url">
496            <label class="block" for="discussion__comment_url">
497              <span><?php echo $this->getLang('url') ?>:</span>
498              <input type="text" class="edit" name="url" id="discussion__comment_url" size="50" tabindex="3" value="<?php echo hsc($_REQUEST['url'])?>" />
499            </label>
500          </div>
501      <?php
502      }
503
504      // allow entering an address
505      if ($this->getConf('addressfield')){
506      ?>
507          <div class="comment_address">
508            <label class="block" for="discussion__comment_address">
509              <span><?php echo $this->getLang('address') ?>:</span>
510              <input type="text" class="edit" name="address" id="discussion__comment_address" size="50" tabindex="4" value="<?php echo hsc($_REQUEST['address'])?>" />
511            </label>
512          </div>
513      <?php
514      }
515
516      // allow setting the comment date
517      if ($this->getConf('adminimport') && ($INFO['perm'] == AUTH_ADMIN)){
518      ?>
519          <div class="comment_date">
520            <label class="block" for="discussion__comment_date">
521              <span><?php echo $this->getLang('date') ?>:</span>
522              <input type="text" class="edit" name="date" id="discussion__comment_date" size="50" />
523            </label>
524          </div>
525      <?php
526      }
527
528    // for saving a comment
529    } else {
530    ?>
531          <input type="hidden" name="cid" value="<?php echo $cid ?>" />
532    <?php
533    }
534    ?>
535          <div class="comment_text">
536            <textarea class="edit" name="text" cols="80" rows="10" id="discussion__comment_text" tabindex="5"><?php echo formText($raw) ?></textarea>
537          </div>
538    <?php //bad and dirty event insert hook
539    $evdata = array('writable' => true);
540    trigger_event('HTML_EDITFORM_INJECTION', $evdata);
541    ?>
542          <input class="button" type="submit" name="submit" value="<?php echo $lang['btn_save'] ?>" tabindex="6" />
543        </div>
544      </form>
545    </div>
546    <?php
547    if ($this->getConf('usecocomment')) echo $this->_coComment();
548  }
549
550  /**
551   * Adds a javascript to interact with coComments
552   */
553  function _coComment(){
554    global $ID, $conf, $INFO;
555
556    $user = $_SERVER['REMOTE_USER'];
557
558    ?>
559    <script type="text/javascript"><!--//--><![CDATA[//><!--
560      var blogTool  = "DokuWiki";
561      var blogURL   = "<?php echo DOKU_URL ?>";
562      var blogTitle = "<?php echo $conf['title'] ?>";
563      var postURL   = "<?php echo wl($ID, '', true) ?>";
564      var postTitle = "<?php echo tpl_pagetitle($ID, true) ?>";
565    <?php
566    if ($user){
567    ?>
568      var commentAuthor = "<?php echo $INFO['userinfo']['name'] ?>";
569    <?php
570    } else {
571    ?>
572      var commentAuthorFieldName = "name";
573    <?php
574    }
575    ?>
576      var commentAuthorLoggedIn = <?php echo ($user ? 'true' : 'false') ?>;
577      var commentFormID         = "discussion__comment_form";
578      var commentTextFieldName  = "text";
579      var commentButtonName     = "submit";
580      var cocomment_force       = false;
581    //--><!]]></script>
582    <script type="text/javascript" src="http://www.cocomment.com/js/cocomment.js">
583    </script>
584    <?php
585  }
586
587  /**
588   * General button function
589   */
590  function _button($cid, $label, $act, $jump = false){
591    global $ID;
592
593    $anchor = ($jump ? '#discussion__comment_form' : '' );
594
595    ?>
596    <form class="button" method="post" action="<?php echo script().$anchor ?>">
597      <div class="no">
598        <input type="hidden" name="id" value="<?php echo $ID ?>" />
599        <input type="hidden" name="do" value="show" />
600        <input type="hidden" name="comment" value="<?php echo $act ?>" />
601        <input type="hidden" name="cid" value="<?php echo $cid ?>" />
602        <input type="submit" value="<?php echo $label ?>" class="button" title="<?php echo $label ?>" />
603      </div>
604    </form>
605    <?php
606    return true;
607  }
608
609  /**
610   * Adds an entry to the comments changelog
611   *
612   * @author Esther Brunner <wikidesign@gmail.com>
613   * @author Ben Coburn <btcoburn@silicodon.net>
614   */
615  function _addLogEntry($date, $id, $type = 'cc', $summary = '', $extra = ''){
616    global $conf;
617
618    $changelog = $conf['metadir'].'/_comments.changes';
619
620    if(!$date) $date = time(); //use current time if none supplied
621    $remote = $_SERVER['REMOTE_ADDR'];
622    $user   = $_SERVER['REMOTE_USER'];
623
624    $strip = array("\t", "\n");
625    $logline = array(
626      'date'  => $date,
627      'ip'    => $remote,
628      'type'  => str_replace($strip, '', $type),
629      'id'    => $id,
630      'user'  => $user,
631      'sum'   => str_replace($strip, '', $summary),
632      'extra' => str_replace($strip, '', $extra)
633    );
634
635    // add changelog line
636    $logline = implode("\t", $logline)."\n";
637    io_saveFile($changelog, $logline, true); //global changelog cache
638    // io_saveFile($conf['metadir'].'/_dokuwiki.changes', $logline, true);
639    $this->_trimRecentCommentsLog($changelog);
640  }
641
642  /**
643   * Trims the recent comments cache to the last $conf['changes_days'] recent
644   * changes or $conf['recent'] items, which ever is larger.
645   * The trimming is only done once a day.
646   *
647   * @author Ben Coburn <btcoburn@silicodon.net>
648   */
649  function _trimRecentCommentsLog($changelog){
650    global $conf;
651
652    if (@file_exists($changelog) &&
653      (filectime($changelog) + 86400) < time() &&
654      !@file_exists($changelog.'_tmp')){
655
656      io_lock($changelog);
657      $lines = file($changelog);
658      if (count($lines)<$conf['recent']) {
659          // nothing to trim
660          io_unlock($changelog);
661          return true;
662      }
663
664      io_saveFile($changelog.'_tmp', '');                  // presave tmp as 2nd lock
665      $trim_time = time() - $conf['recent_days']*86400;
666      $out_lines = array();
667
668      for ($i=0; $i<count($lines); $i++) {
669        $log = parseChangelogLine($lines[$i]);
670        if ($log === false) continue;                      // discard junk
671        if ($log['date'] < $trim_time) {
672          $old_lines[$log['date'].".$i"] = $lines[$i];     // keep old lines for now (append .$i to prevent key collisions)
673        } else {
674          $out_lines[$log['date'].".$i"] = $lines[$i];     // definitely keep these lines
675        }
676      }
677
678      // sort the final result, it shouldn't be necessary,
679      // however the extra robustness in making the changelog cache self-correcting is worth it
680      ksort($out_lines);
681      $extra = $conf['recent'] - count($out_lines);        // do we need extra lines do bring us up to minimum
682      if ($extra > 0) {
683        ksort($old_lines);
684        $out_lines = array_merge(array_slice($old_lines,-$extra),$out_lines);
685      }
686
687      // save trimmed changelog
688      io_saveFile($changelog.'_tmp', implode('', $out_lines));
689      @unlink($changelog);
690      if (!rename($changelog.'_tmp', $changelog)) {
691        // rename failed so try another way...
692        io_unlock($changelog);
693        io_saveFile($changelog, implode('', $out_lines));
694        @unlink($changelog.'_tmp');
695      } else {
696        io_unlock($changelog);
697      }
698      return true;
699    }
700  }
701
702  /**
703   * Sends a notify mail on new comment
704   *
705   * @param  array  $comment  data array of the new comment
706   *
707   * @author Andreas Gohr <andi@splitbrain.org>
708   * @author Esther Brunner <wikidesign@gmail.com>
709   */
710  function _notify($comment){
711    global $conf;
712    global $ID;
713
714    if ((!$conf['subscribers']) && (!$conf['notify'])) return; //subscribers enabled?
715    $bcc  = subscriber_addresslist($ID);
716    if ((empty($bcc)) && (!$conf['notify'])) return;
717    $to   = $conf['notify'];
718    $text = io_readFile($this->localFN('subscribermail'));
719
720    $search = array(
721      '@PAGE@',
722      '@TITLE@',
723      '@DATE@',
724      '@NAME@',
725      '@TEXT@',
726      '@UNSUBSCRIBE@',
727      '@DOKUWIKIURL@',
728    );
729    $replace = array(
730      $ID,
731      $conf['title'],
732      date($conf['dformat'], $comment['date']['created']),
733      $comment['user']['name'],
734      $comment['raw'],
735      wl($ID, 'do=unsubscribe', true, '&'),
736      DOKU_URL,
737    );
738    $text = str_replace($search, $replace, $text);
739
740    $subject = '['.$conf['title'].'] '.$this->getLang('mail_newcomment');
741
742    mail_send($to, $subject, $text, $conf['mailfrom'], '', $bcc);
743  }
744
745  /**
746   * Counts the number of visible comments
747   */
748  function _count($data){
749    $number = 0;
750    foreach ($data['comments'] as $cid => $comment){
751      if ($comment['parent']) continue;
752      if (!$comment['show']) continue;
753      $number++;
754      $rids = $comment['replies'];
755      if (count($rids)) $number = $number + $this->_countReplies($data, $rids);
756    }
757    return $number;
758  }
759
760  function _countReplies(&$data, $rids){
761    $number = 0;
762    foreach ($rids as $rid){
763      if (!isset($data['comments'][$rid])) continue; // reply was removed
764      if (!$data['comments'][$rid]['show']) continue;
765      $number++;
766      $rids = $data['comments'][$rid]['replies'];
767      if (count($rids)) $number = $number + $this->_countReplies($data, $rids);
768    }
769    return $number;
770  }
771
772  /**
773   * Renders the comment text
774   */
775  function _render($raw){
776    if ($this->getConf('wikisyntaxok')){
777      $xhtml = $this->render($raw);
778    } else { // wiki syntax not allowed -> just encode special chars
779      $xhtml = htmlspecialchars(trim($raw));
780    }
781    return $xhtml;
782  }
783
784  /**
785   * Adds a TOC item for the discussion section
786   */
787  function add_toc_item(&$event, $param){
788    if ($event->data[0] != 'xhtml') return; // nothing to do for us
789    if (!$this->_hasDiscussion()) return;   // no discussion section
790
791    $pattern = '/<div id="toc__inside">(.*?)<\/div>\s<\/div>/s';
792    if (!preg_match($pattern, $event->data[1], $match)) return; // no TOC on this page
793
794    // ok, then let's do it!
795    global $conf;
796
797    $title   = $this->getLang('discussion');
798    $section = '#discussion__section';
799    $level   = 3 - $conf['toptoclevel'];
800
801    $item = '<li class="level'.$level.'"><div class="li"><span class="li"><a href="'.
802      $section.'" class="toc">'.$title.'</a></span></div></li>';
803
804    if ($level == 1) $search = "</ul>\n</div>";
805    else $search = "</ul>\n</li></ul>\n</div>";
806
807    $new = str_replace($search, $item.$search, $match[0]);
808    $event->data[1] = preg_replace($pattern, $new, $event->data[1]);
809  }
810
811  /**
812   * Finds out whether there is a discussion section for the current page
813   */
814  function _hasDiscussion(){
815    global $ID;
816
817    $cfile = metaFN($ID, '.comments');
818
819    if (!@file_exists($cfile)){
820      if ($this->getConf('automatic')) return true;
821      else return false;
822    }
823
824    $comments = unserialize(io_readFile($cfile, false));
825
826    $num = $comments['number'];
827    if ((!$comments['status']) || (($comments['status'] == 2) && (!$num))) return false;
828    else return true;
829  }
830
831  /**
832   * Checks if 'newthread' was given as action or the comment form was submitted
833   */
834  function handle_act_preprocess(&$event, $param){
835    if ($event->data == 'newthread'){
836      // we can handle it -> prevent others
837      // $event->stopPropagation();
838      $event->preventDefault();
839
840      $event->data = $this->_newThread();
841    }
842    if ((in_array($_REQUEST['comment'], array('add', 'save')))
843      && (@file_exists(DOKU_PLUGIN.'captcha/action.php'))){
844      $this->_captchaCheck();
845    }
846  }
847
848  /**
849   * Creates a new thread page
850   */
851  function _newThread(){
852    global $ID, $INFO;
853
854    $ns    = cleanID($_REQUEST['ns']);
855    $title = str_replace(':', '', $_REQUEST['title']);
856    $back  = $ID;
857    $ID    = ($ns ? $ns.':' : '').cleanID($title);
858    $INFO  = pageinfo();
859
860    // check if we are allowed to create this file
861    if ($INFO['perm'] >= AUTH_CREATE){
862
863      //check if locked by anyone - if not lock for my self
864      if ($INFO['locked']) return 'locked';
865      else lock($ID);
866
867      // prepare the new thread file with default stuff
868      if (!@file_exists($INFO['filepath'])){
869        global $TEXT;
870
871        $TEXT = pageTemplate(array(($ns ? $ns.':' : '').$title));
872        if (!$TEXT){
873          $data = array('id' => $ID, 'ns' => $ns, 'title' => $title, 'back' => $back);
874          $TEXT = $this->_pageTemplate($data);
875        }
876        return 'preview';
877      } else {
878        return 'edit';
879      }
880    } else {
881      return 'show';
882    }
883  }
884
885  /**
886   * Adapted version of pageTemplate() function
887   */
888  function _pageTemplate($data){
889    global $conf, $INFO;
890
891    $id   = $data['id'];
892    $user = $_SERVER['REMOTE_USER'];
893    $tpl  = io_readFile(DOKU_PLUGIN.'discussion/_template.txt');
894
895    // standard replacements
896    $replace = array(
897      '@ID@'   => $id,
898      '@NS@'   => $data['ns'],
899      '@PAGE@' => strtr(noNS($id),'_',' '),
900      '@USER@' => $user,
901      '@NAME@' => $INFO['userinfo']['name'],
902      '@MAIL@' => $INFO['userinfo']['mail'],
903      '@DATE@' => date($conf['dformat']),
904    );
905
906    // additional replacements
907    $replace['@BACK@']  = $data['back'];
908    $replace['@TITLE@'] = $data['title'];
909
910    // avatar if useavatar and avatar plugin available
911    if ($this->getConf('useavatar')
912      && (@file_exists(DOKU_PLUGIN.'avatar/syntax.php'))
913      && (!plugin_isdisabled('avatar'))){
914      $replace['@AVATAR@'] = '{{avatar>'.$user.' }} ';
915    } else {
916      $replace['@AVATAR@'] = '';
917    }
918
919    // tag if tag plugin is available
920    if ((@file_exists(DOKU_PLUGIN.'tag/syntax/tag.php'))
921      && (!plugin_isdisabled('tag'))){
922      $replace['@TAG@'] = "\n\n{{tag>}}";
923    } else {
924      $replace['@TAG@'] = '';
925    }
926
927    // do the replace
928    $tpl = str_replace(array_keys($replace), array_values($replace), $tpl);
929    return $tpl;
930  }
931
932  /**
933   * Checks if the CAPTCHA string submitted is valid
934   *
935   * @author     Andreas Gohr <gohr@cosmocode.de>
936   * @adaption   Esther Brunner <wikidesign@gmail.com>
937   */
938  function _captchaCheck(){
939    if (@file_exists(DOKU_PLUGIN.'captcha/disabled')) return; // CAPTCHA is disabled
940
941    require_once(DOKU_PLUGIN.'captcha/action.php');
942    $captcha = new action_plugin_captcha;
943
944    // do nothing if logged in user and no CAPTCHA required
945    if (!$captcha->getConf('forusers') && $_SERVER['REMOTE_USER']) return;
946
947    // compare provided string with decrypted captcha
948    $rand = PMA_blowfish_decrypt($_REQUEST['plugin__captcha_secret'], auth_cookiesalt());
949    $code = $captcha->_generateCAPTCHA($captcha->_fixedIdent(), $rand);
950
951    if (!$_REQUEST['plugin__captcha_secret'] ||
952      !$_REQUEST['plugin__captcha'] ||
953      strtoupper($_REQUEST['plugin__captcha']) != $code){
954
955      // CAPTCHA test failed! Continue to edit instead of saving
956      msg($captcha->getLang('testfailed'), -1);
957      if ($_REQUEST['comment'] == 'save') $_REQUEST['comment'] = 'edit';
958      elseif ($_REQUEST['comment'] == 'add') $_REQUEST['comment'] = 'show';
959    }
960    // if we arrive here it was a valid save
961  }
962
963  /**
964   * Adds the comments to the index
965   */
966  function idx_add_discussion(&$event, $param){
967
968    // get .comments meta file name
969    $file = metaFN($event->data[0], '.comments');
970
971    if (@file_exists($file)) $data = unserialize(io_readFile($file, false));
972    if ((!$data['status']) || ($data['number'] == 0)) return; // comments are turned off
973
974    // now add the comments
975    if (isset($data['comments'])){
976      foreach ($data['comments'] as $key => $value){
977        $event->data[1] .= _addCommentWords($key, $data);
978      }
979    }
980  }
981
982  /**
983   * Adds the wordsof a given comment to the index
984   */
985  function _addCommentWords($cid, &$data, $parent = '', $reply = '', $visible = true){
986
987    if (!isset($data['comments'][$cid])) return false; // comment was removed
988    $comment = $data['comments'][$cid];
989
990    if (!is_array($comment)) return false;             // corrupt datatype
991
992    if ($comment['parent'] != $parent) return true;    // reply to an other comment
993
994    if (!$comment['show']){                            // comment hidden
995      if ($INFO['perm'] == AUTH_ADMIN) echo '<div class="comment_hidden">'.NL;
996      else return true;
997    }
998  }
999
1000}
1001
1002//Setup VIM: ex: et ts=4 enc=utf-8 :
1003