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