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