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