xref: /plugin/discussion/action.php (revision 2d4bee9a4e627486d89fa890d96d03cd70ce38d0)
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)) {
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)) {
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'] ?>" onsubmit="return validate(this);">
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
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        <?php
794        echo $this->getLang('entercomment');
795        if ($this->getConf('wikisyntaxok')) {
796        ?>
797                <div id="discussion__comment_toolbar">&nbsp;</div>
798        <?php
799        }
800        ?>
801                <textarea class="edit" name="text" cols="80" rows="10" id="discussion__comment_text" tabindex="5"><?php echo formText($raw) ?></textarea>
802              </div>
803        <?php //bad and dirty event insert hook
804        $evdata = array('writable' => true);
805        trigger_event('HTML_EDITFORM_INJECTION', $evdata);
806        ?>
807              <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" />
808
809        <?php if(!$_SERVER['REMOTE_USER'] && $this->getConf('subscribe')) { ?>
810              <div class="comment_subscribe">
811                <input type="checkbox" id="discussion__comment_subscribe" name="subscribe" tabindex="6" />
812                <label class="block" for="discussion__comment_subscribe">
813                  <span><?php echo $this->getLang('subscribe') ?></span>
814                </label>
815              </div>
816        <?php } ?>
817
818              <div class="clearer"></div>
819
820            </div>
821          </form>
822        </div>
823        <?php
824        if ($this->getConf('usecocomment')) echo $this->_coComment();
825    }
826
827    /**
828     * Adds a javascript to interact with coComments
829     */
830    function _coComment() {
831        global $ID;
832        global $conf;
833        global $INFO;
834
835        $user = $_SERVER['REMOTE_USER'];
836
837        ?>
838        <script type="text/javascript"><!--//--><![CDATA[//><!--
839          var blogTool  = "DokuWiki";
840          var blogURL   = "<?php echo DOKU_URL ?>";
841          var blogTitle = "<?php echo $conf['title'] ?>";
842          var postURL   = "<?php echo wl($ID, '', true) ?>";
843          var postTitle = "<?php echo tpl_pagetitle($ID, true) ?>";
844        <?php
845        if ($user) {
846        ?>
847          var commentAuthor = "<?php echo $INFO['userinfo']['name'] ?>";
848        <?php
849        } else {
850        ?>
851          var commentAuthorFieldName = "name";
852        <?php
853        }
854        ?>
855          var commentAuthorLoggedIn = <?php echo ($user ? 'true' : 'false') ?>;
856          var commentFormID         = "discussion__comment_form";
857          var commentTextFieldName  = "text";
858          var commentButtonName     = "submit";
859          var cocomment_force       = false;
860        //--><!]]></script>
861        <script type="text/javascript" src="http://www.cocomment.com/js/cocomment.js">
862        </script>
863        <?php
864    }
865
866    /**
867     * General button function
868     */
869    function _button($cid, $label, $act, $jump = false) {
870        global $ID;
871
872        $anchor = ($jump ? '#discussion__comment_form' : '' );
873
874        ?>
875        <form class="button discussion__<?php echo $act?>" method="get" action="<?php echo script().$anchor ?>">
876          <div class="no">
877            <input type="hidden" name="id" value="<?php echo $ID ?>" />
878            <input type="hidden" name="do" value="show" />
879            <input type="hidden" name="comment" value="<?php echo $act ?>" />
880            <input type="hidden" name="cid" value="<?php echo $cid ?>" />
881            <input type="submit" value="<?php echo $label ?>" class="button" title="<?php echo $label ?>" />
882          </div>
883        </form>
884        <?php
885        return true;
886    }
887
888    /**
889     * Adds an entry to the comments changelog
890     *
891     * @author Esther Brunner <wikidesign@gmail.com>
892     * @author Ben Coburn <btcoburn@silicodon.net>
893     */
894    function _addLogEntry($date, $id, $type = 'cc', $summary = '', $extra = '') {
895        global $conf;
896
897        $changelog = $conf['metadir'].'/_comments.changes';
898
899        if(!$date) $date = time(); //use current time if none supplied
900        $remote = $_SERVER['REMOTE_ADDR'];
901        $user   = $_SERVER['REMOTE_USER'];
902
903        $strip = array("\t", "\n");
904        $logline = array(
905                'date'  => $date,
906                'ip'    => $remote,
907                'type'  => str_replace($strip, '', $type),
908                'id'    => $id,
909                'user'  => $user,
910                'sum'   => str_replace($strip, '', $summary),
911                'extra' => str_replace($strip, '', $extra)
912                );
913
914        // add changelog line
915        $logline = implode("\t", $logline)."\n";
916        io_saveFile($changelog, $logline, true); //global changelog cache
917        $this->_trimRecentCommentsLog($changelog);
918
919        // tell the indexer to re-index the page
920        @unlink(metaFN($id, '.indexed'));
921    }
922
923    /**
924     * Trims the recent comments cache to the last $conf['changes_days'] recent
925     * changes or $conf['recent'] items, which ever is larger.
926     * The trimming is only done once a day.
927     *
928     * @author Ben Coburn <btcoburn@silicodon.net>
929     */
930    function _trimRecentCommentsLog($changelog) {
931        global $conf;
932
933        if (@file_exists($changelog) &&
934                (filectime($changelog) + 86400) < time() &&
935                !@file_exists($changelog.'_tmp')) {
936
937            io_lock($changelog);
938            $lines = file($changelog);
939            if (count($lines)<$conf['recent']) {
940                // nothing to trim
941                io_unlock($changelog);
942                return true;
943            }
944
945            io_saveFile($changelog.'_tmp', '');                  // presave tmp as 2nd lock
946            $trim_time = time() - $conf['recent_days']*86400;
947            $out_lines = array();
948
949            $num = count($lines);
950            for ($i=0; $i<$num; $i++) {
951                $log = parseChangelogLine($lines[$i]);
952                if ($log === false) continue;                      // discard junk
953                if ($log['date'] < $trim_time) {
954                    $old_lines[$log['date'].".$i"] = $lines[$i];     // keep old lines for now (append .$i to prevent key collisions)
955                } else {
956                    $out_lines[$log['date'].".$i"] = $lines[$i];     // definitely keep these lines
957                }
958            }
959
960            // sort the final result, it shouldn't be necessary,
961            // however the extra robustness in making the changelog cache self-correcting is worth it
962            ksort($out_lines);
963            $extra = $conf['recent'] - count($out_lines);        // do we need extra lines do bring us up to minimum
964            if ($extra > 0) {
965                ksort($old_lines);
966                $out_lines = array_merge(array_slice($old_lines,-$extra),$out_lines);
967            }
968
969            // save trimmed changelog
970            io_saveFile($changelog.'_tmp', implode('', $out_lines));
971            @unlink($changelog);
972            if (!rename($changelog.'_tmp', $changelog)) {
973                // rename failed so try another way...
974                io_unlock($changelog);
975                io_saveFile($changelog, implode('', $out_lines));
976                @unlink($changelog.'_tmp');
977            } else {
978                io_unlock($changelog);
979            }
980            return true;
981        }
982    }
983
984    /**
985     * Sends a notify mail on new comment
986     *
987     * @param  array  $comment  data array of the new comment
988     *
989     * @author Andreas Gohr <andi@splitbrain.org>
990     * @author Esther Brunner <wikidesign@gmail.com>
991     */
992    function _notify($comment, $subscribers) {
993        global $conf;
994        global $ID;
995
996        $text = io_readfile($this->localfn('subscribermail'));
997        $subject = '['.$conf['title'].'] '.$this->getLang('mail_newcomment');
998
999        $search = array(
1000                '@PAGE@',
1001                '@TITLE@',
1002                '@DATE@',
1003                '@NAME@',
1004                '@TEXT@',
1005                '@COMMENTURL@',
1006                '@UNSUBSCRIBE@',
1007                '@DOKUWIKIURL@',
1008                );
1009
1010        // notify page subscribers
1011        if (($conf['subscribers']) && ($conf['notify'])) {
1012            $bcc = subscriber_addresslist($ID);
1013            $to = $conf['notify'];
1014
1015            $replace = array(
1016                    $ID,
1017                    $conf['title'],
1018                    strftime($conf['dformat'], $comment['date']['created']),
1019                    $comment['user']['name'],
1020                    $comment['raw'],
1021                    wl($ID, '', true) . '#comment_' . $comment['cid'],
1022                    wl($ID, 'do=unsubscribe', true, '&'),
1023                    DOKU_URL,
1024                    );
1025
1026                $body = str_replace($search, $replace, $text);
1027                mail_send($to, $subject, $body, $conf['mailfrom'], '', $bcc);
1028        }
1029
1030        // notify comment subscribers
1031        if (!empty($subscribers)) {
1032
1033            foreach($subscribers as $mail => $hash) {
1034                $to = $mail;
1035
1036                $replace = array(
1037                        $ID,
1038                        $conf['title'],
1039                        strftime($conf['dformat'], $comment['date']['created']),
1040                        $comment['user']['name'],
1041                        $comment['raw'],
1042                        wl($ID, '', true) . '#comment_' . $comment['cid'],
1043                        wl($ID, 'do=unsubscribe&hash=' . $hash, true, '&'),
1044                        DOKU_URL,
1045                        );
1046
1047                $body = str_replace($search, $replace, $text);
1048                mail_send($to, $subject, $body, $conf['mailfrom']);
1049            }
1050        }
1051    }
1052
1053    /**
1054     * Counts the number of visible comments
1055     */
1056    function _count($data) {
1057        $number = 0;
1058        foreach ($data['comments'] as $cid => $comment) {
1059            if ($comment['parent']) continue;
1060            if (!$comment['show']) continue;
1061            $number++;
1062            $rids = $comment['replies'];
1063            if (count($rids)) $number = $number + $this->_countReplies($data, $rids);
1064        }
1065        return $number;
1066    }
1067
1068    function _countReplies(&$data, $rids) {
1069        $number = 0;
1070        foreach ($rids as $rid) {
1071            if (!isset($data['comments'][$rid])) continue; // reply was removed
1072            if (!$data['comments'][$rid]['show']) continue;
1073            $number++;
1074            $rids = $data['comments'][$rid]['replies'];
1075            if (count($rids)) $number = $number + $this->_countReplies($data, $rids);
1076        }
1077        return $number;
1078    }
1079
1080    /**
1081     * Renders the comment text
1082     */
1083    function _render($raw) {
1084        if ($this->getConf('wikisyntaxok')) {
1085            $xhtml = $this->render($raw);
1086        } else { // wiki syntax not allowed -> just encode special chars
1087            $xhtml = htmlspecialchars(trim($raw));
1088        }
1089        return $xhtml;
1090    }
1091
1092    /**
1093     * Finds out whether there is a discussion section for the current page
1094     */
1095    function _hasDiscussion(&$title) {
1096        global $ID;
1097
1098        $cfile = metaFN($ID, '.comments');
1099
1100        if (!@file_exists($cfile)) {
1101            if ($this->getConf('automatic')) {
1102                return true;
1103            } else {
1104                return false;
1105            }
1106        }
1107
1108        $comments = unserialize(io_readFile($cfile, false));
1109
1110        if ($comments['title']) $title = hsc($comments['title']);
1111        $num = $comments['number'];
1112        if ((!$comments['status']) || (($comments['status'] == 2) && (!$num))) return false;
1113        else return true;
1114    }
1115
1116    /**
1117     * Creates a new thread page
1118     */
1119    function _newThread() {
1120        global $ID, $INFO;
1121
1122        $ns    = cleanID($_REQUEST['ns']);
1123        $title = str_replace(':', '', $_REQUEST['title']);
1124        $back  = $ID;
1125        $ID    = ($ns ? $ns.':' : '').cleanID($title);
1126        $INFO  = pageinfo();
1127
1128        // check if we are allowed to create this file
1129        if ($INFO['perm'] >= AUTH_CREATE) {
1130
1131            //check if locked by anyone - if not lock for my self
1132            if ($INFO['locked']) return 'locked';
1133            else lock($ID);
1134
1135            // prepare the new thread file with default stuff
1136            if (!@file_exists($INFO['filepath'])) {
1137                global $TEXT;
1138
1139                $TEXT = pageTemplate(array(($ns ? $ns.':' : '').$title));
1140                if (!$TEXT) {
1141                    $data = array('id' => $ID, 'ns' => $ns, 'title' => $title, 'back' => $back);
1142                    $TEXT = $this->_pageTemplate($data);
1143                }
1144                return 'preview';
1145            } else {
1146                return 'edit';
1147            }
1148        } else {
1149            return 'show';
1150        }
1151    }
1152
1153    /**
1154     * Adapted version of pageTemplate() function
1155     */
1156    function _pageTemplate($data) {
1157        global $conf, $INFO;
1158
1159        $id   = $data['id'];
1160        $user = $_SERVER['REMOTE_USER'];
1161        $tpl  = io_readFile(DOKU_PLUGIN.'discussion/_template.txt');
1162
1163        // standard replacements
1164        $replace = array(
1165                '@NS@'   => $data['ns'],
1166                '@PAGE@' => strtr(noNS($id),'_',' '),
1167                '@USER@' => $user,
1168                '@NAME@' => $INFO['userinfo']['name'],
1169                '@MAIL@' => $INFO['userinfo']['mail'],
1170                '@DATE@' => strftime($conf['dformat']),
1171                );
1172
1173        // additional replacements
1174        $replace['@BACK@']  = $data['back'];
1175        $replace['@TITLE@'] = $data['title'];
1176
1177        // avatar if useavatar and avatar plugin available
1178        if ($this->getConf('useavatar')
1179                && (@file_exists(DOKU_PLUGIN.'avatar/syntax.php'))
1180                && (!plugin_isdisabled('avatar'))) {
1181            $replace['@AVATAR@'] = '{{avatar>'.$user.' }} ';
1182        } else {
1183            $replace['@AVATAR@'] = '';
1184        }
1185
1186        // tag if tag plugin is available
1187        if ((@file_exists(DOKU_PLUGIN.'tag/syntax/tag.php'))
1188                && (!plugin_isdisabled('tag'))) {
1189            $replace['@TAG@'] = "\n\n{{tag>}}";
1190        } else {
1191            $replace['@TAG@'] = '';
1192        }
1193
1194        // do the replace
1195        $tpl = str_replace(array_keys($replace), array_values($replace), $tpl);
1196        return $tpl;
1197    }
1198
1199    /**
1200     * Checks if the CAPTCHA string submitted is valid
1201     *
1202     * @author     Andreas Gohr <gohr@cosmocode.de>
1203     * @adaption   Esther Brunner <wikidesign@gmail.com>
1204     */
1205    function _captchaCheck() {
1206        if (plugin_isdisabled('captcha') || (!$captcha = plugin_load('helper', 'captcha')))
1207            return; // CAPTCHA is disabled or not available
1208
1209        // do nothing if logged in user and no CAPTCHA required
1210        if (!$captcha->getConf('forusers') && $_SERVER['REMOTE_USER']) return;
1211
1212        // compare provided string with decrypted captcha
1213        $rand = PMA_blowfish_decrypt($_REQUEST['plugin__captcha_secret'], auth_cookiesalt());
1214        $code = $captcha->_generateCAPTCHA($captcha->_fixedIdent(), $rand);
1215
1216        if (!$_REQUEST['plugin__captcha_secret'] ||
1217                !$_REQUEST['plugin__captcha'] ||
1218                strtoupper($_REQUEST['plugin__captcha']) != $code) {
1219
1220            // CAPTCHA test failed! Continue to edit instead of saving
1221            msg($captcha->getLang('testfailed'), -1);
1222            if ($_REQUEST['comment'] == 'save') $_REQUEST['comment'] = 'edit';
1223            elseif ($_REQUEST['comment'] == 'add') $_REQUEST['comment'] = 'show';
1224        }
1225        // if we arrive here it was a valid save
1226    }
1227
1228    /**
1229     * Adds the comments to the index
1230     */
1231    function idx_add_discussion(&$event, $param) {
1232
1233        // get .comments meta file name
1234        $file = metaFN($event->data[0], '.comments');
1235
1236        if (@file_exists($file)) $data = unserialize(io_readFile($file, false));
1237        if ((!$data['status']) || ($data['number'] == 0)) return; // comments are turned off
1238
1239        // now add the comments
1240        if (isset($data['comments'])) {
1241            foreach ($data['comments'] as $key => $value) {
1242                $event->data[1] .= $this->_addCommentWords($key, $data);
1243            }
1244        }
1245    }
1246
1247    /**
1248     * Adds the words of a given comment to the index
1249     */
1250    function _addCommentWords($cid, &$data, $parent = '') {
1251
1252        if (!isset($data['comments'][$cid])) return ''; // comment was removed
1253        $comment = $data['comments'][$cid];
1254
1255        if (!is_array($comment)) return '';             // corrupt datatype
1256        if ($comment['parent'] != $parent) return '';   // reply to an other comment
1257        if (!$comment['show']) return '';               // hidden comment
1258
1259        $text = $comment['raw'];                        // we only add the raw comment text
1260        if (is_array($comment['replies'])) {             // and the replies
1261            foreach ($comment['replies'] as $rid) {
1262                $text .= $this->_addCommentWords($rid, $data, $cid);
1263            }
1264        }
1265        return ' '.$text;
1266    }
1267
1268    /**
1269     * Only allow http(s) URLs and append http:// to URLs if needed
1270     */
1271    function _checkURL($url) {
1272        if(preg_match("#^http://|^https://#", $url)) {
1273            return hsc($url);
1274        } elseif(substr($url, 0, 4) == 'www.') {
1275            return hsc('http://' . $url);
1276        } else {
1277            return '';
1278        }
1279    }
1280}
1281
1282function _sortCallback($a, $b) {
1283    if (is_array($a['date'])) { // new format
1284        $createdA  = $a['date']['created'];
1285    } else {                         // old format
1286        $createdA  = $a['date'];
1287    }
1288
1289    if (is_array($b['date'])) { // new format
1290        $createdB  = $b['date']['created'];
1291    } else {                         // old format
1292        $createdB  = $b['date'];
1293    }
1294
1295    if ($createdA == $createdB)
1296        return 0;
1297    else
1298        return ($createdA < $createdB) ? -1 : 1;
1299}
1300
1301// vim:ts=4:sw=4:et:enc=utf-8:
1302