xref: /plugin/discussion/action.php (revision aaa25a9013cf387184d256815040ed1f3c5cad6f)
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
10/**
11 * Class action_plugin_discussion
12 */
13class action_plugin_discussion extends DokuWiki_Action_Plugin{
14
15    /** @var helper_plugin_avatar */
16    var $avatar = null;
17    var $style = null;
18    var $use_avatar = null;
19    /** @var helper_plugin_discussion */
20    var $helper = null;
21
22    /**
23     * load helper
24     */
25    public function __construct() {
26        $this->helper = plugin_load('helper', 'discussion');
27    }
28
29    /**
30     * Register the handlers
31     *
32     * @param Doku_Event_Handler $contr DokuWiki's event controller object.
33     */
34    public function register(Doku_Event_Handler $contr) {
35        $contr->register_hook(
36                'ACTION_ACT_PREPROCESS',
37                'BEFORE',
38                $this,
39                'handle_act_preprocess',
40                array()
41                );
42        $contr->register_hook(
43                'TPL_ACT_RENDER',
44                'AFTER',
45                $this,
46                'comments',
47                array()
48                );
49        $contr->register_hook(
50                'INDEXER_PAGE_ADD',
51                'AFTER',
52                $this,
53                'idx_add_discussion',
54                array()
55                );
56        $contr->register_hook(
57                'INDEXER_VERSION_GET',
58                'BEFORE',
59                $this,
60                'idx_version',
61                array()
62                );
63        $contr->register_hook(
64                'PARSER_METADATA_RENDER',
65                'AFTER',
66                $this,
67                'update_comment_status',
68                array()
69        );
70        $contr->register_hook(
71                'TPL_METAHEADER_OUTPUT',
72                'BEFORE',
73                $this,
74                'handle_tpl_metaheader_output',
75                array()
76                );
77        $contr->register_hook(
78                'TOOLBAR_DEFINE',
79                'AFTER',
80                $this,
81                'handle_toolbar_define',
82                array()
83                );
84        $contr->register_hook(
85                'AJAX_CALL_UNKNOWN',
86                'BEFORE',
87                $this,
88                'handle_ajax_call',
89                array()
90                );
91        $contr->register_hook(
92                'TPL_TOC_RENDER',
93                'BEFORE',
94                $this,
95                'handle_toc_render',
96                array()
97                );
98    }
99
100    /**
101     * Preview Comments
102     *
103     * @author Michael Klier <chi@chimeric.de>
104     *
105     * @param Doku_Event $event
106     * @param $params
107     */
108    public function handle_ajax_call(Doku_Event $event, $params) {
109        if($event->data != 'discussion_preview') return;
110        $event->preventDefault();
111        $event->stopPropagation();
112        print p_locale_xhtml('preview');
113        print '<div class="comment_preview">';
114        if(!$_SERVER['REMOTE_USER'] && !$this->getConf('allowguests')) {
115            print p_locale_xhtml('denied');
116        } else {
117            print $this->_render($_REQUEST['comment']);
118        }
119        print '</div>';
120    }
121
122    /**
123     * Adds a TOC item if a discussion exists
124     *
125     * @author Michael Klier <chi@chimeric.de>
126     *
127     * @param Doku_Event $event
128     * @param $params
129     */
130    public function handle_toc_render(Doku_Event $event, $params) {
131        global $ACT;
132        if($this->_hasDiscussion($title) && $event->data && $ACT != 'admin') {
133            $tocitem = array( 'hid' => 'discussion__section',
134                              'title' => $this->getLang('discussion'),
135                              'type' => 'ul',
136                              'level' => 1 );
137
138            array_push($event->data, $tocitem);
139        }
140    }
141
142    /**
143     * Modify Tollbar for use with discussion plugin
144     *
145     * @author Michael Klier <chi@chimeric.de>
146     *
147     * @param Doku_Event $event
148     * @param $param
149     */
150    public function handle_toolbar_define(Doku_Event $event, $param) {
151        global $ACT;
152        if($ACT != 'show') return;
153
154        if($this->_hasDiscussion($title) && $this->getConf('wikisyntaxok')) {
155            $toolbar = array();
156            foreach($event->data as $btn) {
157                if($btn['type'] == 'mediapopup') continue;
158                if($btn['type'] == 'signature') continue;
159                if($btn['type'] == 'linkwiz') continue;
160                if($btn['type'] == 'NewTable') continue; //skip button for Edittable Plugin
161                if(preg_match("/=+?/", $btn['open'])) continue;
162                array_push($toolbar, $btn);
163            }
164            $event->data = $toolbar;
165        }
166    }
167
168    /**
169     * Dirty workaround to add a toolbar to the discussion plugin
170     *
171     * @author Michael Klier <chi@chimeric.de>
172     *
173     * @param Doku_Event $event
174     * @param $param
175     */
176    public function handle_tpl_metaheader_output(Doku_Event $event, $param) {
177        global $ACT;
178        global $ID;
179        if($ACT != 'show') return;
180
181        if($this->_hasDiscussion($title) && $this->getConf('wikisyntaxok')) {
182            // FIXME ugly workaround, replace this once DW the toolbar code is more flexible
183            @require_once(DOKU_INC.'inc/toolbar.php');
184            ob_start();
185            print 'NS = "' . getNS($ID) . '";'; // we have to define NS, otherwise we get get JS errors
186            toolbar_JSdefines('toolbar');
187            $script = ob_get_clean();
188            array_push($event->data['script'], array('type' => 'text/javascript', 'charset' => "utf-8", '_data' => $script));
189        }
190    }
191
192    /**
193     * Handles comment actions, dispatches data processing routines
194     *
195     * @param Doku_Event $event
196     * @param $param
197     * @return bool
198     */
199    public function handle_act_preprocess(Doku_Event $event, $param) {
200        global $ID;
201        global $INFO;
202        global $lang;
203
204        // handle newthread ACTs
205        if ($event->data == 'newthread') {
206            // we can handle it -> prevent others
207            $event->preventDefault();
208            $event->data = $this->_newThread();
209        }
210
211        // enable captchas
212        if (in_array($_REQUEST['comment'], array('add', 'save'))) {
213            if (@file_exists(DOKU_PLUGIN.'captcha/action.php')) {
214                $this->_captchaCheck();
215            }
216            if (@file_exists(DOKU_PLUGIN.'recaptcha/action.php')) {
217                $this->_recaptchaCheck();
218            }
219        }
220
221        // if we are not in show mode or someone wants to unsubscribe, that was all for now
222        if ($event->data != 'show' && $event->data != 'discussion_unsubscribe' && $event->data != 'discussion_confirmsubscribe') return;
223
224        if ($event->data == 'discussion_unsubscribe' or $event->data == 'discussion_confirmsubscribe') {
225            // ok we can handle it prevent others
226            $event->preventDefault();
227
228            if (!isset($_REQUEST['hash'])) {
229                return;
230            } else {
231                $file = metaFN($ID, '.comments');
232                $data = unserialize(io_readFile($file));
233                $themail = '';
234                foreach($data['subscribers'] as $mail => $info)  {
235                    // convert old style subscribers just in case
236                    if(!is_array($info)) {
237                        $hash = $data['subscribers'][$mail];
238                        $data['subscribers'][$mail]['hash']   = $hash;
239                        $data['subscribers'][$mail]['active'] = true;
240                        $data['subscribers'][$mail]['confirmsent'] = true;
241                    }
242
243                    if ($data['subscribers'][$mail]['hash'] == $_REQUEST['hash']) {
244                        $themail = $mail;
245                    }
246                }
247
248                if($themail != '') {
249                    if($event->data == 'discussion_unsubscribe') {
250                        unset($data['subscribers'][$themail]);
251                        msg(sprintf($lang['subscr_unsubscribe_success'], $themail, $ID), 1);
252                    } elseif($event->data == 'discussion_confirmsubscribe') {
253                        $data['subscribers'][$themail]['active'] = true;
254                        msg(sprintf($lang['subscr_subscribe_success'], $themail, $ID), 1);
255                    }
256                    io_saveFile($file, serialize($data));
257                    $event->data = 'show';
258                }
259                return;
260
261            }
262        } else {
263            // do the data processing for comments
264            $cid  = $_REQUEST['cid'];
265            switch ($_REQUEST['comment']) {
266                case 'add':
267                    if(empty($_REQUEST['text'])) return; // don't add empty comments
268                    if(isset($_SERVER['REMOTE_USER']) && !$this->getConf('adminimport')) {
269                        $comment['user']['id'] = $_SERVER['REMOTE_USER'];
270                        $comment['user']['name'] = $INFO['userinfo']['name'];
271                        $comment['user']['mail'] = $INFO['userinfo']['mail'];
272                    } elseif((isset($_SERVER['REMOTE_USER']) && $this->getConf('adminimport') && $this->helper->isDiscussionMod()) || !isset($_SERVER['REMOTE_USER'])) {
273                        if(empty($_REQUEST['name']) or empty($_REQUEST['mail'])) return; // don't add anonymous comments
274                        if(!mail_isvalid($_REQUEST['mail'])) {
275                            msg($lang['regbadmail'], -1);
276                            return;
277                        } else {
278                            $comment['user']['id'] = 'test'.hsc($_REQUEST['user']);
279                            $comment['user']['name'] = hsc($_REQUEST['name']);
280                            $comment['user']['mail'] = hsc($_REQUEST['mail']);
281                        }
282                    }
283                    $comment['user']['address'] = ($this->getConf('addressfield')) ? hsc($_REQUEST['address']) : '';
284                    $comment['user']['url'] = ($this->getConf('urlfield')) ? $this->_checkURL($_REQUEST['url']) : '';
285                    $comment['subscribe'] = ($this->getConf('subscribe')) ? $_REQUEST['subscribe'] : '';
286                    $comment['date'] = array('created' => $_REQUEST['date']);
287                    $comment['raw'] = cleanText($_REQUEST['text']);
288                    $repl = $_REQUEST['reply'];
289                    if($this->getConf('moderate') && !$this->helper->isDiscussionMod()) {
290                        $comment['show'] = false;
291                    } else {
292                        $comment['show'] = true;
293                    }
294                    $this->_add($comment, $repl);
295                    break;
296
297                case 'save':
298                    $raw  = cleanText($_REQUEST['text']);
299                    $this->save(array($cid), $raw);
300                    break;
301
302                case 'delete':
303                    $this->save(array($cid), '');
304                    break;
305
306                case 'toogle':
307                    $this->save(array($cid), '', 'toogle');
308                    break;
309            }
310        }
311    }
312
313    /**
314     * Main function; dispatches the visual comment actions
315     */
316    public function comments(Doku_Event $event, $param) {
317        if ($event->data != 'show') return; // nothing to do for us
318
319        $cid  = $_REQUEST['cid'];
320        if(!$cid) {
321            $cid = $_REQUEST['reply'];
322        }
323        switch ($_REQUEST['comment']) {
324            case 'edit':
325                $this->_show(NULL, $cid);
326                break;
327            default:
328                $this->_show($cid);
329                break;
330        }
331    }
332
333    /**
334     * Redirects browser to given comment anchor
335     */
336    protected function _redirect($cid) {
337        global $ID;
338        global $ACT;
339
340        if ($ACT !== 'show') return;
341
342        if($this->getConf('moderate') && !$this->helper->isDiscussionMod()) {
343            msg($this->getLang('moderation'), 1);
344            @session_start();
345            global $MSG;
346            $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
347            session_write_close();
348            $url = wl($ID);
349        } else {
350            $url = wl($ID) . '#comment_' . $cid;
351        }
352
353        if (function_exists('send_redirect')) {
354            send_redirect($url);
355        } else {
356            header('Location: ' . $url);
357        }
358        exit();
359    }
360
361    /**
362     * Shows all comments of the current page
363     */
364    protected function _show($reply = null, $edit = null) {
365        global $ID;
366        global $INFO;
367
368        // get .comments meta file name
369        $file = metaFN($ID, '.comments');
370
371        if (!$INFO['exists']) return false;
372        if (!@file_exists($file) && !$this->getConf('automatic')) return false;
373        if (!$_SERVER['REMOTE_USER'] && !$this->getConf('showguests')) return false;
374
375        // load data
376        if (@file_exists($file)) {
377            $data = unserialize(io_readFile($file, false));
378            if (!$data['status']) return false; // comments are turned off
379        } elseif (!@file_exists($file) && $this->getConf('automatic') && $INFO['exists']) {
380            // set status to show the comment form
381            $data['status'] = 1;
382            $data['number'] = 0;
383        }
384
385        // show discussion wrapper only on certain circumstances
386        $cnt = count($data['comments']);
387        $keys = @array_keys($data['comments']);
388        $show = false;
389        if($cnt > 1 || ($cnt == 1 && $data['comments'][$keys[0]]['show'] == 1) || $this->getConf('allowguests') || isset($_SERVER['REMOTE_USER'])) {
390            $show = true;
391            // section title
392            $title = ($data['title'] ? hsc($data['title']) : $this->getLang('discussion'));
393            ptln('<div class="comment_wrapper" id="comment_wrapper">'); // the id value is used for visibility toggling the section
394            ptln('<h2><a name="discussion__section" id="discussion__section">', 2);
395            ptln($title, 4);
396            ptln('</a></h2>', 2);
397            ptln('<div class="level2 hfeed">', 2);
398        }
399
400        // now display the comments
401        if (isset($data['comments'])) {
402            if (!$this->getConf('usethreading')) {
403                $data['comments'] = $this->_flattenThreads($data['comments']);
404                uasort($data['comments'], '_sortCallback');
405            }
406            if($this->getConf('newestfirst')) {
407                $data['comments'] = array_reverse($data['comments']);
408            }
409            foreach ($data['comments'] as $key => $value) {
410                if ($key == $edit) $this->_form($value['raw'], 'save', $edit); // edit form
411                else $this->_print($key, $data, '', $reply);
412            }
413        }
414
415        // comment form
416        if (($data['status'] == 1) && (!$reply || !$this->getConf('usethreading')) && !$edit) $this->_form('');
417
418        if($show) {
419            ptln('</div>', 2); // level2 hfeed
420            ptln('</div>'); // comment_wrapper
421        }
422
423        // check for toggle print configuration
424        if($this->getConf('visibilityButton')) {
425            // print the hide/show discussion section button
426            $this->_print_toggle_button();
427        }
428
429        return true;
430    }
431
432    /**
433     * @param array      $comments
434     * @param null|array $keys
435     * @return array
436     */
437    protected function _flattenThreads($comments, $keys = null) {
438        if (is_null($keys))
439            $keys = array_keys($comments);
440
441        foreach($keys as $cid) {
442            if (!empty($comments[$cid]['replies'])) {
443                $rids = $comments[$cid]['replies'];
444                $comments = $this->_flattenThreads($comments, $rids);
445                $comments[$cid]['replies'] = array();
446            }
447            $comments[$cid]['parent'] = '';
448        }
449        return $comments;
450    }
451
452    /**
453     * Adds a new comment and then displays all comments
454     *
455     * @param array $comment
456     * @param string $parent
457     * @return bool
458     */
459    protected function _add($comment, $parent) {
460        global $ID;
461        global $TEXT;
462
463        $otxt = $TEXT; // set $TEXT to comment text for wordblock check
464        $TEXT = $comment['raw'];
465
466        // spamcheck against the DokuWiki blacklist
467        if (checkwordblock()) {
468            msg($this->getLang('wordblock'), -1);
469            return false;
470        }
471
472        if ((!$this->getConf('allowguests'))
473                && ($comment['user']['id'] != $_SERVER['REMOTE_USER']))
474            return false; // guest comments not allowed
475
476        $TEXT = $otxt; // restore global $TEXT
477
478        // get discussion meta file name
479        $file = metaFN($ID, '.comments');
480
481        // create comments file if it doesn't exist yet
482        if(!@file_exists($file)) {
483            $data = array('status' => 1, 'number' => 0);
484            io_saveFile($file, serialize($data));
485        } else {
486            $data = unserialize(io_readFile($file, false));
487            if ($data['status'] != 1) return false; // comments off or closed
488        }
489
490        if ($comment['date']['created']) {
491            $date = strtotime($comment['date']['created']);
492        } else {
493            $date = time();
494        }
495
496        if ($date == -1) {
497            $date = time();
498        }
499
500        $cid  = md5($comment['user']['id'].$date); // create a unique id
501
502        if (!is_array($data['comments'][$parent])) {
503            $parent = NULL; // invalid parent comment
504        }
505
506        // render the comment
507        $xhtml = $this->_render($comment['raw']);
508
509        // fill in the new comment
510        $data['comments'][$cid] = array(
511                'user'    => $comment['user'],
512                'date'    => array('created' => $date),
513                'raw'     => $comment['raw'],
514                'xhtml'   => $xhtml,
515                'parent'  => $parent,
516                'replies' => array(),
517                'show'    => $comment['show']
518                );
519
520        if($comment['subscribe']) {
521            $mail = $comment['user']['mail'];
522            if($data['subscribers']) {
523                if(!$data['subscribers'][$mail]) {
524                    $data['subscribers'][$mail]['hash'] = md5($mail . mt_rand());
525                    $data['subscribers'][$mail]['active'] = false;
526                    $data['subscribers'][$mail]['confirmsent'] = false;
527                } else {
528                    // convert old style subscribers and set them active
529                    if(!is_array($data['subscribers'][$mail])) {
530                        $hash = $data['subscribers'][$mail];
531                        $data['subscribers'][$mail]['hash'] = $hash;
532                        $data['subscribers'][$mail]['active'] = true;
533                        $data['subscribers'][$mail]['confirmsent'] = true;
534                    }
535                }
536            } else {
537                $data['subscribers'][$mail]['hash']   = md5($mail . mt_rand());
538                $data['subscribers'][$mail]['active'] = false;
539                $data['subscribers'][$mail]['confirmsent'] = false;
540            }
541        }
542
543        // update parent comment
544        if ($parent) $data['comments'][$parent]['replies'][] = $cid;
545
546        // update the number of comments
547        $data['number']++;
548
549        // notify subscribers of the page
550        $data['comments'][$cid]['cid'] = $cid;
551        $this->_notify($data['comments'][$cid], $data['subscribers']);
552
553        // save the comment metadata file
554        io_saveFile($file, serialize($data));
555        $this->_addLogEntry($date, $ID, 'cc', '', $cid);
556
557        $this->_redirect($cid);
558        return true;
559    }
560
561    /**
562     * Saves the comment with the given ID and then displays all comments
563     *
564     * @param array|string $cids
565     * @param string $raw
566     * @param string $act
567     * @return bool
568     */
569    public function save($cids, $raw, $act = NULL) {
570        global $ID;
571
572        if(!$cids) return false; // do nothing if we get no comment id
573
574        if ($raw) {
575            global $TEXT;
576
577            $otxt = $TEXT; // set $TEXT to comment text for wordblock check
578            $TEXT = $raw;
579
580            // spamcheck against the DokuWiki blacklist
581            if (checkwordblock()) {
582                msg($this->getLang('wordblock'), -1);
583                return false;
584            }
585
586            $TEXT = $otxt; // restore global $TEXT
587        }
588
589        // get discussion meta file name
590        $file = metaFN($ID, '.comments');
591        $data = unserialize(io_readFile($file, false));
592
593        if (!is_array($cids)) $cids = array($cids);
594        foreach ($cids as $cid) {
595
596            if (is_array($data['comments'][$cid]['user'])) {
597                $user    = $data['comments'][$cid]['user']['id'];
598                $convert = false;
599            } else {
600                $user    = $data['comments'][$cid]['user'];
601                $convert = true;
602            }
603
604            // someone else was trying to edit our comment -> abort
605            if (($user != $_SERVER['REMOTE_USER']) && (!$this->helper->isDiscussionMod())) return false;
606
607            $date = time();
608
609            // need to convert to new format?
610            if ($convert) {
611                $data['comments'][$cid]['user'] = array(
612                        'id'      => $user,
613                        'name'    => $data['comments'][$cid]['name'],
614                        'mail'    => $data['comments'][$cid]['mail'],
615                        'url'     => $data['comments'][$cid]['url'],
616                        'address' => $data['comments'][$cid]['address'],
617                        );
618                $data['comments'][$cid]['date'] = array(
619                        'created' => $data['comments'][$cid]['date']
620                        );
621            }
622
623            if ($act == 'toogle') {     // toogle visibility
624                $now = $data['comments'][$cid]['show'];
625                $data['comments'][$cid]['show'] = !$now;
626                $data['number'] = $this->_count($data);
627
628                $type = ($data['comments'][$cid]['show'] ? 'sc' : 'hc');
629
630            } elseif ($act == 'show') { // show comment
631                $data['comments'][$cid]['show'] = true;
632                $data['number'] = $this->_count($data);
633
634                $type = 'sc'; // show comment
635
636            } elseif ($act == 'hide') { // hide comment
637                $data['comments'][$cid]['show'] = false;
638                $data['number'] = $this->_count($data);
639
640                $type = 'hc'; // hide comment
641
642            } elseif (!$raw) {          // remove the comment
643                $data['comments'] = $this->_removeComment($cid, $data['comments']);
644                $data['number'] = $this->_count($data);
645
646                $type = 'dc'; // delete comment
647
648            } else {                   // save changed comment
649                $xhtml = $this->_render($raw);
650
651                // now change the comment's content
652                $data['comments'][$cid]['date']['modified'] = $date;
653                $data['comments'][$cid]['raw']              = $raw;
654                $data['comments'][$cid]['xhtml']            = $xhtml;
655
656                $type = 'ec'; // edit comment
657            }
658        }
659
660        // save the comment metadata file
661        io_saveFile($file, serialize($data));
662        $this->_addLogEntry($date, $ID, $type, '', $cid);
663
664        $this->_redirect($cid);
665        return true;
666    }
667
668    /**
669     * Recursive function to remove a comment
670     */
671    protected function _removeComment($cid, $comments) {
672        if (is_array($comments[$cid]['replies'])) {
673            foreach ($comments[$cid]['replies'] as $rid) {
674                $comments = $this->_removeComment($rid, $comments);
675            }
676        }
677        unset($comments[$cid]);
678        return $comments;
679    }
680
681    /**
682     * Prints an individual comment
683     *
684     * @param string $cid
685     * @param array $data
686     * @param string $parent
687     * @param string $reply
688     * @param bool $visible
689     * @return bool
690     */
691    protected function _print($cid, &$data, $parent = '', $reply = '', $visible = true) {
692        if (!isset($data['comments'][$cid])) return false; // comment was removed
693        $comment = $data['comments'][$cid];
694
695        if (!is_array($comment)) return false;             // corrupt datatype
696
697        if ($comment['parent'] != $parent) return true;    // reply to an other comment
698
699        if (!$comment['show']) {                            // comment hidden
700            if ($this->helper->isDiscussionMod()) $hidden = ' comment_hidden';
701            else return true;
702        } else {
703            $hidden = '';
704        }
705
706        // print the actual comment
707        $this->_print_comment($cid, $data, $parent, $reply, $visible, $hidden);
708        // replies to this comment entry?
709        $this->_print_replies($cid, $data, $reply, $visible);
710        // reply form
711        $this->_print_form($cid, $reply);
712        return true;
713    }
714
715    /**
716     * @param $cid
717     * @param $data
718     * @param $parent
719     * @param $reply
720     * @param $visible
721     * @param $hidden
722     */
723    protected function _print_comment($cid, &$data, $parent, $reply, $visible, $hidden) {
724        global $conf, $lang, $HIGH;
725        $comment = $data['comments'][$cid];
726
727        // comment head with date and user data
728        ptln('<div class="hentry'.$hidden.'">', 4);
729        ptln('<div class="comment_head">', 6);
730        ptln('<a name="comment_'.$cid.'" id="comment_'.$cid.'"></a>', 8);
731        $head = '<span class="vcard author">';
732
733        // prepare variables
734        if (is_array($comment['user'])) { // new format
735            $user    = $comment['user']['id'];
736            $name    = $comment['user']['name'];
737            $mail    = $comment['user']['mail'];
738            $url     = $comment['user']['url'];
739            $address = $comment['user']['address'];
740        } else {                         // old format
741            $user    = $comment['user'];
742            $name    = $comment['name'];
743            $mail    = $comment['mail'];
744            $url     = $comment['url'];
745            $address = $comment['address'];
746        }
747        if (is_array($comment['date'])) { // new format
748            $created  = $comment['date']['created'];
749            $modified = $comment['date']['modified'];
750        } else {                         // old format
751            $created  = $comment['date'];
752            $modified = $comment['edited'];
753        }
754
755        // show username or real name?
756        if ((!$this->getConf('userealname')) && ($user)) {
757            $showname = $user;
758        } else {
759            $showname = $name;
760        }
761
762        // show avatar image?
763        if ($this->_use_avatar()) {
764            $user_data['name'] = $name;
765            $user_data['user'] = $user;
766            $user_data['mail'] = $mail;
767            $avatar = $this->avatar->getXHTML($user_data, $name, 'left');
768            if($avatar) $head .= $avatar;
769        }
770
771        if ($this->getConf('linkemail') && $mail) {
772            $head .= $this->email($mail, $showname, 'email fn');
773        } elseif ($url) {
774            $head .= $this->external_link($this->_checkURL($url), $showname, 'urlextern url fn');
775        } else {
776            $head .= '<span class="fn">'.$showname.'</span>';
777        }
778
779        if ($address) $head .= ', <span class="adr">'.$address.'</span>';
780        $head .= '</span>, '.
781            '<abbr class="published" title="'. strftime('%Y-%m-%dT%H:%M:%SZ', $created) .'">'.
782            dformat($created, $conf['dformat']).'</abbr>';
783        if ($comment['edited']) $head .= ' (<abbr class="updated" title="'.
784                strftime('%Y-%m-%dT%H:%M:%SZ', $modified).'">'.dformat($modified, $conf['dformat']).
785                '</abbr>)';
786        ptln($head, 8);
787        ptln('</div>', 6); // class="comment_head"
788
789        // main comment content
790        ptln('<div class="comment_body entry-content"'.
791                ($this->_use_avatar() ? $this->_get_style() : '').'>', 6);
792        echo ($HIGH?html_hilight($comment['xhtml'],$HIGH):$comment['xhtml']).DOKU_LF;
793        ptln('</div>', 6); // class="comment_body"
794
795        if ($visible) {
796            ptln('<div class="comment_buttons">', 6);
797
798            // show reply button?
799            if (($data['status'] == 1) && !$reply && $comment['show']
800                    && ($this->getConf('allowguests') || $_SERVER['REMOTE_USER']) && $this->getConf('usethreading'))
801                $this->_button($cid, $this->getLang('btn_reply'), 'reply', true);
802
803            // show edit, show/hide and delete button?
804            if ((($user == $_SERVER['REMOTE_USER']) && ($user != '')) || ($this->helper->isDiscussionMod())) {
805                $this->_button($cid, $lang['btn_secedit'], 'edit', true);
806                $label = ($comment['show'] ? $this->getLang('btn_hide') : $this->getLang('btn_show'));
807                $this->_button($cid, $label, 'toogle');
808                $this->_button($cid, $lang['btn_delete'], 'delete');
809            }
810            ptln('</div>', 6); // class="comment_buttons"
811        }
812        ptln('</div>', 4); // class="hentry"
813    }
814
815    /**
816     * @param string $cid
817     * @param string $reply
818     */
819    protected function _print_form($cid, $reply)
820    {
821        if ($this->getConf('usethreading') && $reply == $cid) {
822            ptln('<div class="comment_replies">', 4);
823            $this->_form('', 'add', $cid);
824            ptln('</div>', 4); // class="comment_replies"
825        }
826    }
827
828    /**
829     * @param string $cid
830     * @param array  $data
831     * @param string $reply
832     * @param bool $visible
833     */
834    protected function _print_replies($cid, &$data, $reply, &$visible)
835    {
836        $comment = $data['comments'][$cid];
837        if (!count($comment['replies'])) {
838            return;
839        }
840        ptln('<div class="comment_replies"'.$this->_get_style().'>', 4);
841        $visible = ($comment['show'] && $visible);
842        foreach ($comment['replies'] as $rid) {
843            $this->_print($rid, $data, $cid, $reply, $visible);
844        }
845        ptln('</div>', 4);
846    }
847
848    /**
849     * Is an avatar displayed?
850     *
851     * @return bool
852     */
853    protected function _use_avatar()
854    {
855        if (is_null($this->use_avatar)) {
856            $this->use_avatar = $this->getConf('useavatar')
857                    && (!plugin_isdisabled('avatar'))
858                    && ($this->avatar =& plugin_load('helper', 'avatar'));
859        }
860        return $this->use_avatar;
861    }
862
863    /**
864     * Calculate width of indent
865     *
866     * @return string
867     */
868    protected function _get_style()
869    {
870        if (is_null($this->style)){
871            if ($this->_use_avatar()) {
872                $this->style = ' style="margin-left: '.($this->avatar->getConf('size') + 14).'px;"';
873            } else {
874                $this->style = ' style="margin-left: 20px;"';
875            }
876        }
877        return $this->style;
878    }
879
880    /**
881     * Show the button which toggle the visibility of the discussion section
882     */
883    protected function _print_toggle_button() {
884        ptln('<div id="toggle_button" class="toggle_button" style="text-align: right;">');
885        ptln('<input type="submit" id="discussion__btn_toggle_visibility" title="Toggle Visibiliy" class="button" value="'.$this->getLang('toggle_display').'">');
886        ptln('</div>');
887    }
888
889    /**
890     * Outputs the comment form
891     */
892    protected function _form($raw = '', $act = 'add', $cid = NULL) {
893        global $lang;
894        global $conf;
895        global $ID;
896
897        // not for unregistered users when guest comments aren't allowed
898        if (!$_SERVER['REMOTE_USER'] && !$this->getConf('allowguests')) {
899            ?>
900            <div class="comment_form">
901                <?php echo $this->getLang('noguests'); ?>
902            </div>
903            <?php
904            return;
905        }
906
907        // fill $raw with $_REQUEST['text'] if it's empty (for failed CAPTCHA check)
908        if (!$raw && ($_REQUEST['comment'] == 'show')) $raw = $_REQUEST['text'];
909        ?>
910
911        <div class="comment_form">
912          <form id="discussion__comment_form" method="post" action="<?php echo script() ?>" accept-charset="<?php echo $lang['encoding'] ?>">
913            <div class="no">
914              <input type="hidden" name="id" value="<?php echo $ID ?>" />
915              <input type="hidden" name="do" value="show" />
916              <input type="hidden" name="comment" value="<?php echo $act ?>" />
917        <?php
918        // for adding a comment
919        if ($act == 'add') {
920        ?>
921              <input type="hidden" name="reply" value="<?php echo $cid ?>" />
922        <?php
923        // for guest/adminimport: show name, e-mail and subscribe to comments fields
924        if(!$_SERVER['REMOTE_USER'] or ($this->getConf('adminimport') && $this->helper->isDiscussionMod())) {
925        ?>
926              <input type="hidden" name="user" value="<?php echo clientIP() ?>" />
927              <div class="comment_name">
928                <label class="block" for="discussion__comment_name">
929                  <span><?php echo $lang['fullname'] ?>:</span>
930                  <input type="text" class="edit<?php if($_REQUEST['comment'] == 'add' && empty($_REQUEST['name'])) echo ' error'?>" name="name" id="discussion__comment_name" size="50" tabindex="1" value="<?php echo hsc($_REQUEST['name'])?>" />
931                </label>
932              </div>
933              <div class="comment_mail">
934                <label class="block" for="discussion__comment_mail">
935                  <span><?php echo $lang['email'] ?>:</span>
936                  <input type="text" class="edit<?php if($_REQUEST['comment'] == 'add' && empty($_REQUEST['mail'])) echo ' error'?>" name="mail" id="discussion__comment_mail" size="50" tabindex="2" value="<?php echo hsc($_REQUEST['mail'])?>" />
937                </label>
938              </div>
939        <?php
940        }
941
942        // allow entering an URL
943        if ($this->getConf('urlfield')) {
944        ?>
945              <div class="comment_url">
946                <label class="block" for="discussion__comment_url">
947                  <span><?php echo $this->getLang('url') ?>:</span>
948                  <input type="text" class="edit" name="url" id="discussion__comment_url" size="50" tabindex="3" value="<?php echo hsc($_REQUEST['url'])?>" />
949                </label>
950              </div>
951        <?php
952        }
953
954        // allow entering an address
955        if ($this->getConf('addressfield')) {
956        ?>
957              <div class="comment_address">
958                <label class="block" for="discussion__comment_address">
959                  <span><?php echo $this->getLang('address') ?>:</span>
960                  <input type="text" class="edit" name="address" id="discussion__comment_address" size="50" tabindex="4" value="<?php echo hsc($_REQUEST['address'])?>" />
961                </label>
962              </div>
963        <?php
964        }
965
966        // allow setting the comment date
967        if ($this->getConf('adminimport') && ($this->helper->isDiscussionMod())) {
968        ?>
969              <div class="comment_date">
970                <label class="block" for="discussion__comment_date">
971                  <span><?php echo $this->getLang('date') ?>:</span>
972                  <input type="text" class="edit" name="date" id="discussion__comment_date" size="50" />
973                </label>
974              </div>
975        <?php
976        }
977
978        // for saving a comment
979        } else {
980        ?>
981              <input type="hidden" name="cid" value="<?php echo $cid ?>" />
982        <?php
983        }
984        ?>
985                <div class="comment_text">
986                  <?php echo $this->getLang('entercomment'); echo ($this->getConf('wikisyntaxok') ? "" : ":");
987                        if($this->getConf('wikisyntaxok')) echo '. ' . $this->getLang('wikisyntax') . ':'; ?>
988
989                  <!-- Fix for disable the toolbar when wikisyntaxok is set to false. See discussion's script.jss -->
990                  <?php if($this->getConf('wikisyntaxok')) { ?>
991                    <div id="discussion__comment_toolbar" class="toolbar group">
992                  <?php } else { ?>
993                    <div id="discussion__comment_toolbar_disabled">
994                  <?php } ?>
995                </div>
996                <textarea class="edit<?php if($_REQUEST['comment'] == 'add' && empty($_REQUEST['text'])) echo ' error'?>" name="text" cols="80" rows="10" id="discussion__comment_text" tabindex="5"><?php
997                  if($raw) {
998                      echo formText($raw);
999                  } else {
1000                      echo hsc($_REQUEST['text']);
1001                  }
1002                ?></textarea>
1003              </div>
1004        <?php //bad and dirty event insert hook
1005        $evdata = array('writable' => true);
1006        trigger_event('HTML_EDITFORM_INJECTION', $evdata);
1007        ?>
1008              <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" />
1009              <input class="button comment_preview_button" id="discussion__btn_preview" type="button" name="preview" accesskey="p" value="<?php echo $lang['btn_preview'] ?>" title="<?php echo $lang['btn_preview']?> [P]" />
1010
1011        <?php if((!$_SERVER['REMOTE_USER'] || $_SERVER['REMOTE_USER'] && !$conf['subscribers']) && $this->getConf('subscribe')) { ?>
1012              <div class="comment_subscribe">
1013                <input type="checkbox" id="discussion__comment_subscribe" name="subscribe" tabindex="6" />
1014                <label class="block" for="discussion__comment_subscribe">
1015                  <span><?php echo $this->getLang('subscribe') ?></span>
1016                </label>
1017              </div>
1018        <?php } ?>
1019
1020              <div class="clearer"></div>
1021              <div id="discussion__comment_preview">&nbsp;</div>
1022            </div>
1023          </form>
1024        </div>
1025        <?php
1026        if ($this->getConf('usecocomment')){
1027            $this->_coComment();
1028        }
1029    }
1030
1031    /**
1032     * Adds a javascript to interact with coComments
1033     */
1034    protected function _coComment() {
1035        global $ID;
1036        global $conf;
1037        global $INFO;
1038
1039        $user = $_SERVER['REMOTE_USER'];
1040
1041        ?>
1042        <script type="text/javascript"><!--//--><![CDATA[//><!--
1043          var blogTool  = "DokuWiki";
1044          var blogURL   = "<?php echo DOKU_URL ?>";
1045          var blogTitle = "<?php echo $conf['title'] ?>";
1046          var postURL   = "<?php echo wl($ID, '', true) ?>";
1047          var postTitle = "<?php echo tpl_pagetitle($ID, true) ?>";
1048        <?php
1049        if ($user) {
1050        ?>
1051          var commentAuthor = "<?php echo $INFO['userinfo']['name'] ?>";
1052        <?php
1053        } else {
1054        ?>
1055          var commentAuthorFieldName = "name";
1056        <?php
1057        }
1058        ?>
1059          var commentAuthorLoggedIn = <?php echo ($user ? 'true' : 'false') ?>;
1060          var commentFormID         = "discussion__comment_form";
1061          var commentTextFieldName  = "text";
1062          var commentButtonName     = "submit";
1063          var cocomment_force       = false;
1064        //--><!]]></script>
1065        <script type="text/javascript" src="http://www.cocomment.com/js/cocomment.js">
1066        </script>
1067        <?php
1068    }
1069
1070    /**
1071     * General button function
1072     *
1073     * @param string $cid
1074     * @param string $label
1075     * @param string $act
1076     * @param bool $jump
1077     * @return bool
1078     */
1079    protected function _button($cid, $label, $act, $jump = false) {
1080        global $ID;
1081
1082        $anchor = ($jump ? '#discussion__comment_form' : '' );
1083
1084        ?>
1085        <form class="button discussion__<?php echo $act?>" method="get" action="<?php echo script().$anchor ?>">
1086          <div class="no">
1087            <input type="hidden" name="id" value="<?php echo $ID ?>" />
1088            <input type="hidden" name="do" value="show" />
1089            <input type="hidden" name="comment" value="<?php echo $act ?>" />
1090            <input type="hidden" name="cid" value="<?php echo $cid ?>" />
1091            <input type="submit" value="<?php echo $label ?>" class="button" title="<?php echo $label ?>" />
1092          </div>
1093        </form>
1094        <?php
1095        return true;
1096    }
1097
1098    /**
1099     * Adds an entry to the comments changelog
1100     *
1101     * @author Esther Brunner <wikidesign@gmail.com>
1102     * @author Ben Coburn <btcoburn@silicodon.net>
1103     *
1104     * @param int    $date
1105     * @param string $id page id
1106     * @param string $type
1107     * @param string $summary
1108     * @param string $extra
1109     */
1110    protected function _addLogEntry($date, $id, $type = 'cc', $summary = '', $extra = '') {
1111        global $conf;
1112
1113        $changelog = $conf['metadir'].'/_comments.changes';
1114
1115        if(!$date) $date = time(); //use current time if none supplied
1116        $remote = $_SERVER['REMOTE_ADDR'];
1117        $user   = $_SERVER['REMOTE_USER'];
1118
1119        $strip = array("\t", "\n");
1120        $logline = array(
1121                'date'  => $date,
1122                'ip'    => $remote,
1123                'type'  => str_replace($strip, '', $type),
1124                'id'    => $id,
1125                'user'  => $user,
1126                'sum'   => str_replace($strip, '', $summary),
1127                'extra' => str_replace($strip, '', $extra)
1128                );
1129
1130        // add changelog line
1131        $logline = implode("\t", $logline)."\n";
1132        io_saveFile($changelog, $logline, true); //global changelog cache
1133        $this->_trimRecentCommentsLog($changelog);
1134
1135        // tell the indexer to re-index the page
1136        @unlink(metaFN($id, '.indexed'));
1137    }
1138
1139    /**
1140     * Trims the recent comments cache to the last $conf['changes_days'] recent
1141     * changes or $conf['recent'] items, which ever is larger.
1142     * The trimming is only done once a day.
1143     *
1144     * @author Ben Coburn <btcoburn@silicodon.net>
1145     *
1146     * @param string $changelog file path
1147     * @return bool
1148     */
1149    protected function _trimRecentCommentsLog($changelog) {
1150        global $conf;
1151
1152        if (@file_exists($changelog) &&
1153                (filectime($changelog) + 86400) < time() &&
1154                !@file_exists($changelog.'_tmp')) {
1155
1156            io_lock($changelog);
1157            $lines = file($changelog);
1158            if (count($lines)<$conf['recent']) {
1159                // nothing to trim
1160                io_unlock($changelog);
1161                return true;
1162            }
1163
1164            io_saveFile($changelog.'_tmp', '');                  // presave tmp as 2nd lock
1165            $trim_time = time() - $conf['recent_days']*86400;
1166            $out_lines = array();
1167
1168            $num = count($lines);
1169            for ($i=0; $i<$num; $i++) {
1170                $log = parseChangelogLine($lines[$i]);
1171                if ($log === false) continue;                      // discard junk
1172                if ($log['date'] < $trim_time) {
1173                    $old_lines[$log['date'].".$i"] = $lines[$i];     // keep old lines for now (append .$i to prevent key collisions)
1174                } else {
1175                    $out_lines[$log['date'].".$i"] = $lines[$i];     // definitely keep these lines
1176                }
1177            }
1178
1179            // sort the final result, it shouldn't be necessary,
1180            // however the extra robustness in making the changelog cache self-correcting is worth it
1181            ksort($out_lines);
1182            $extra = $conf['recent'] - count($out_lines);        // do we need extra lines do bring us up to minimum
1183            if ($extra > 0) {
1184                ksort($old_lines);
1185                $out_lines = array_merge(array_slice($old_lines,-$extra),$out_lines);
1186            }
1187
1188            // save trimmed changelog
1189            io_saveFile($changelog.'_tmp', implode('', $out_lines));
1190            @unlink($changelog);
1191            if (!rename($changelog.'_tmp', $changelog)) {
1192                // rename failed so try another way...
1193                io_unlock($changelog);
1194                io_saveFile($changelog, implode('', $out_lines));
1195                @unlink($changelog.'_tmp');
1196            } else {
1197                io_unlock($changelog);
1198            }
1199            return true;
1200        }
1201        return true;
1202    }
1203
1204    /**
1205     * Sends a notify mail on new comment
1206     *
1207     * @param  array  $comment  data array of the new comment
1208     * @param  array  $subscribers data of the subscribers
1209     *
1210     * @author Andreas Gohr <andi@splitbrain.org>
1211     * @author Esther Brunner <wikidesign@gmail.com>
1212     */
1213    protected function _notify($comment, &$subscribers) {
1214        global $conf;
1215        global $ID;
1216
1217        $notify_text = io_readfile($this->localfn('subscribermail'));
1218        $confirm_text = io_readfile($this->localfn('confirmsubscribe'));
1219        $subject_notify = '['.$conf['title'].'] '.$this->getLang('mail_newcomment');
1220        $subject_subscribe = '['.$conf['title'].'] '.$this->getLang('subscribe');
1221
1222        $mailer = new Mailer();
1223        if (empty($_SERVER['REMOTE_USER'])) {
1224            $mailer->from($conf['mailfromnobody']);
1225        }
1226
1227        $replace = array(
1228            'PAGE' => $ID,
1229            'TITLE' => $conf['title'],
1230            'DATE' => dformat($comment['date']['created'], $conf['dformat']),
1231            'NAME' => $comment['user']['name'],
1232            'TEXT' => $comment['raw'],
1233            'COMMENTURL' => wl($ID, '', true) . '#comment_' . $comment['cid'],
1234            'UNSUBSCRIBE' => wl($ID, 'do=subscribe', true, '&'),
1235            'DOKUWIKIURL' => DOKU_URL
1236        );
1237
1238        $confirm_replace = array(
1239            'PAGE' => $ID,
1240            'TITLE' => $conf['title'],
1241            'DOKUWIKIURL' => DOKU_URL
1242        );
1243
1244
1245        $mailer->subject($subject_notify);
1246        $mailer->setBody($notify_text, $replace);
1247
1248        // send mail to notify address
1249        if ($conf['notify']) {
1250            $mailer->bcc($conf['notify']);
1251            $mailer->send();
1252        }
1253
1254        // notify page subscribers
1255        if (actionOK('subscribe')) {
1256            $data = array('id' => $ID, 'addresslist' => '', 'self' => false);
1257            if (class_exists('Subscription')) { /* Introduced in DokuWiki 2013-05-10 */
1258                trigger_event(
1259                    'COMMON_NOTIFY_ADDRESSLIST', $data,
1260                    array(new Subscription(), 'notifyaddresses')
1261                );
1262            } else { /* Old, deprecated default handler */
1263                trigger_event(
1264                    'COMMON_NOTIFY_ADDRESSLIST', $data,
1265                    'subscription_addresslist'
1266                );
1267            }
1268            $to = $data['addresslist'];
1269            if(!empty($to)) {
1270                $mailer->bcc($to);
1271                $mailer->send();
1272            }
1273        }
1274
1275        // notify comment subscribers
1276        if (!empty($subscribers)) {
1277
1278            foreach($subscribers as $mail => $data) {
1279                $mailer->bcc($mail);
1280                if($data['active']) {
1281                    $replace['UNSUBSCRIBE'] = wl($ID, 'do=discussion_unsubscribe&hash=' . $data['hash'], true, '&');
1282
1283                    $mailer->subject($subject_notify);
1284                    $mailer->setBody($notify_text, $replace);
1285                    $mailer->send();
1286                } elseif(!$data['active'] && !$data['confirmsent']) {
1287                    $confirm_replace['SUBSCRIBE'] = wl($ID, 'do=discussion_confirmsubscribe&hash=' . $data['hash'], true, '&');
1288
1289                    $mailer->subject($subject_subscribe);
1290                    $mailer->setBody($confirm_text, $confirm_replace);
1291                    $mailer->send();
1292                    $subscribers[$mail]['confirmsent'] = true;
1293                }
1294            }
1295        }
1296    }
1297
1298    /**
1299     * Counts the number of visible comments
1300     *
1301     * @param array $data
1302     * @return int
1303     */
1304    protected function _count($data) {
1305        $number = 0;
1306        foreach ($data['comments'] as $comment) {
1307            if ($comment['parent']) continue;
1308            if (!$comment['show']) continue;
1309            $number++;
1310            $rids = $comment['replies'];
1311            if (count($rids)) $number = $number + $this->_countReplies($data, $rids);
1312        }
1313        return $number;
1314    }
1315
1316    /**
1317     * @param array $data
1318     * @param array $rids
1319     * @return int
1320     */
1321    protected function _countReplies(&$data, $rids) {
1322        $number = 0;
1323        foreach ($rids as $rid) {
1324            if (!isset($data['comments'][$rid])) continue; // reply was removed
1325            if (!$data['comments'][$rid]['show']) continue;
1326            $number++;
1327            $rids = $data['comments'][$rid]['replies'];
1328            if (count($rids)) $number = $number + $this->_countReplies($data, $rids);
1329        }
1330        return $number;
1331    }
1332
1333    /**
1334     * Renders the comment text
1335     *
1336     * @param string $raw
1337     * @return null|string
1338     */
1339    protected function _render($raw) {
1340        if ($this->getConf('wikisyntaxok')) {
1341            $xhtml = $this->render_text($raw);
1342        } else { // wiki syntax not allowed -> just encode special chars
1343            $xhtml = hsc(trim($raw));
1344            $xhtml = str_replace("\n", '<br />', $xhtml);
1345        }
1346        return $xhtml;
1347    }
1348
1349    /**
1350     * Finds out whether there is a discussion section for the current page
1351     *
1352     * @param string $title
1353     * @return bool
1354     */
1355    protected function _hasDiscussion(&$title) {
1356        global $ID;
1357
1358        $cfile = metaFN($ID, '.comments');
1359
1360        if (!@file_exists($cfile)) {
1361            if ($this->getConf('automatic')) {
1362                return true;
1363            } else {
1364                return false;
1365            }
1366        }
1367
1368        $comments = unserialize(io_readFile($cfile, false));
1369
1370        if ($comments['title']) $title = hsc($comments['title']);
1371        $num = $comments['number'];
1372        if ((!$comments['status']) || (($comments['status'] == 2) && (!$num))) return false;
1373        else return true;
1374    }
1375
1376    /**
1377     * Creates a new thread page
1378     *
1379     * @return string
1380     */
1381    protected function _newThread() {
1382        global $ID, $INFO;
1383
1384        $ns    = cleanID($_REQUEST['ns']);
1385        $title = str_replace(':', '', $_REQUEST['title']);
1386        $back  = $ID;
1387        $ID    = ($ns ? $ns.':' : '').cleanID($title);
1388        $INFO  = pageinfo();
1389
1390        // check if we are allowed to create this file
1391        if ($INFO['perm'] >= AUTH_CREATE) {
1392
1393            //check if locked by anyone - if not lock for my self
1394            if ($INFO['locked']) return 'locked';
1395            else lock($ID);
1396
1397            // prepare the new thread file with default stuff
1398            if (!@file_exists($INFO['filepath'])) {
1399                global $TEXT;
1400
1401                $TEXT = pageTemplate(array(($ns ? $ns.':' : '').$title));
1402                if (!$TEXT) {
1403                    $data = array('id' => $ID, 'ns' => $ns, 'title' => $title, 'back' => $back);
1404                    $TEXT = $this->_pageTemplate($data);
1405                }
1406                return 'preview';
1407            } else {
1408                return 'edit';
1409            }
1410        } else {
1411            return 'show';
1412        }
1413    }
1414
1415    /**
1416     * Adapted version of pageTemplate() function
1417     *
1418     * @param array $data
1419     * @return string
1420     */
1421    protected function _pageTemplate($data) {
1422        global $conf, $INFO;
1423
1424        $id   = $data['id'];
1425        $user = $_SERVER['REMOTE_USER'];
1426        $tpl  = io_readFile(DOKU_PLUGIN.'discussion/_template.txt');
1427
1428        // standard replacements
1429        $replace = array(
1430                '@NS@'   => $data['ns'],
1431                '@PAGE@' => strtr(noNS($id),'_',' '),
1432                '@USER@' => $user,
1433                '@NAME@' => $INFO['userinfo']['name'],
1434                '@MAIL@' => $INFO['userinfo']['mail'],
1435                '@DATE@' => dformat(time(), $conf['dformat']),
1436                );
1437
1438        // additional replacements
1439        $replace['@BACK@']  = $data['back'];
1440        $replace['@TITLE@'] = $data['title'];
1441
1442        // avatar if useavatar and avatar plugin available
1443        if ($this->getConf('useavatar')
1444                && (@file_exists(DOKU_PLUGIN.'avatar/syntax.php'))
1445                && (!plugin_isdisabled('avatar'))) {
1446            $replace['@AVATAR@'] = '{{avatar>'.$user.' }} ';
1447        } else {
1448            $replace['@AVATAR@'] = '';
1449        }
1450
1451        // tag if tag plugin is available
1452        if ((@file_exists(DOKU_PLUGIN.'tag/syntax/tag.php'))
1453                && (!plugin_isdisabled('tag'))) {
1454            $replace['@TAG@'] = "\n\n{{tag>}}";
1455        } else {
1456            $replace['@TAG@'] = '';
1457        }
1458
1459        // do the replace
1460        $tpl = str_replace(array_keys($replace), array_values($replace), $tpl);
1461        return $tpl;
1462    }
1463
1464    /**
1465     * Checks if the CAPTCHA string submitted is valid
1466     */
1467    protected function _captchaCheck() {
1468        /** @var helper_plugin_captcha $captcha */
1469        if (plugin_isdisabled('captcha') || (!$captcha = plugin_load('helper', 'captcha')))
1470            return; // CAPTCHA is disabled or not available
1471
1472        if ($captcha->isEnabled() && !$captcha->check()) {
1473            if ($_REQUEST['comment'] == 'save') $_REQUEST['comment'] = 'edit';
1474            elseif ($_REQUEST['comment'] == 'add') $_REQUEST['comment'] = 'show';
1475        }
1476    }
1477
1478    /**
1479     * checks if the submitted reCAPTCHA string is valid
1480     *
1481     * @author Adrian Schlegel <adrian@liip.ch>
1482     */
1483    protected function _recaptchaCheck() {
1484        /** @var $recaptcha helper_plugin_recaptcha */
1485        if (plugin_isdisabled('recaptcha') || (!$recaptcha = plugin_load('helper', 'recaptcha')))
1486            return; // reCAPTCHA is disabled or not available
1487
1488        // do nothing if logged in user and no reCAPTCHA required
1489        if (!$recaptcha->getConf('forusers') && $_SERVER['REMOTE_USER']) return;
1490
1491        $resp = $recaptcha->check();
1492        if (!$resp->is_valid) {
1493            msg($recaptcha->getLang('testfailed'),-1);
1494            if ($_REQUEST['comment'] == 'save') $_REQUEST['comment'] = 'edit';
1495            elseif ($_REQUEST['comment'] == 'add') $_REQUEST['comment'] = 'show';
1496        }
1497    }
1498
1499    /**
1500     * Add discussion plugin version to the indexer version
1501     * This means that all pages will be indexed again in order to add the comments
1502     * to the index whenever there has been a change that concerns the index content.
1503     *
1504     * @param Doku_Event $event
1505     * @param $param
1506     */
1507    public function idx_version(Doku_Event $event, $param) {
1508        $event->data['discussion'] = '0.1';
1509    }
1510
1511    /**
1512     * Adds the comments to the index
1513     *
1514     * @param Doku_Event $event
1515     * @param $param
1516     */
1517    public function idx_add_discussion(Doku_Event $event, $param) {
1518
1519        // get .comments meta file name
1520        $file = metaFN($event->data['page'], '.comments');
1521
1522        if (!@file_exists($file)) return;
1523        $data = unserialize(io_readFile($file, false));
1524        if ((!$data['status']) || ($data['number'] == 0)) return; // comments are turned off
1525
1526        // now add the comments
1527        if (isset($data['comments'])) {
1528            foreach ($data['comments'] as $key => $value) {
1529                $event->data['body'] .= $this->_addCommentWords($key, $data);
1530            }
1531        }
1532    }
1533
1534    /**
1535     * Saves the current comment status and title in the .comments file
1536     *
1537     * @param Doku_Event $event
1538     * @param $param
1539     */
1540    public function update_comment_status(Doku_Event $event, $param) {
1541        global $ID;
1542
1543        $meta = $event->data['current'];
1544        $file = metaFN($ID, '.comments');
1545        $status = ($this->getConf('automatic') ? 1 : 0);
1546        $title = NULL;
1547        if (isset($meta['plugin_discussion'])) {
1548            $status = $meta['plugin_discussion']['status'];
1549            $title = $meta['plugin_discussion']['title'];
1550        } else if ($status == 1) {
1551            // Don't enable comments when automatic comments are on - this already happens automatically
1552            // and if comments are turned off in the admin this only updates the .comments file
1553            return;
1554        }
1555
1556        if ($status || @file_exists($file)) {
1557            $data = array();
1558            if (@file_exists($file)) {
1559                $data = unserialize(io_readFile($file, false));
1560            }
1561
1562            if (!array_key_exists('title', $data) || $data['title'] !== $title || !isset($data['status']) || $data['status'] !== $status) {
1563                $data['title']  = $title;
1564                $data['status'] = $status;
1565                if (!isset($data['number']))
1566                    $data['number'] = 0;
1567                io_saveFile($file, serialize($data));
1568            }
1569        }
1570    }
1571
1572    /**
1573     * Adds the words of a given comment to the index
1574     *
1575     * @param string $cid
1576     * @param array  $data
1577     * @param string $parent
1578     * @return string
1579     */
1580    protected function _addCommentWords($cid, &$data, $parent = '') {
1581
1582        if (!isset($data['comments'][$cid])) return ''; // comment was removed
1583        $comment = $data['comments'][$cid];
1584
1585        if (!is_array($comment)) return '';             // corrupt datatype
1586        if ($comment['parent'] != $parent) return '';   // reply to an other comment
1587        if (!$comment['show']) return '';               // hidden comment
1588
1589        $text = $comment['raw'];                        // we only add the raw comment text
1590        if (is_array($comment['replies'])) {             // and the replies
1591            foreach ($comment['replies'] as $rid) {
1592                $text .= $this->_addCommentWords($rid, $data, $cid);
1593            }
1594        }
1595        return ' '.$text;
1596    }
1597
1598    /**
1599     * Only allow http(s) URLs and append http:// to URLs if needed
1600     *
1601     * @param string $url
1602     * @return string
1603     */
1604    protected function _checkURL($url) {
1605        if(preg_match("#^http://|^https://#", $url)) {
1606            return hsc($url);
1607        } elseif(substr($url, 0, 4) == 'www.') {
1608            return hsc('http://' . $url);
1609        } else {
1610            return '';
1611        }
1612    }
1613}
1614
1615/**
1616 * Sort threads
1617 *
1618 * @param $a
1619 * @param $b
1620 * @return int
1621 */
1622    function _sortCallback($a, $b) {
1623        if (is_array($a['date'])) { // new format
1624            $createdA  = $a['date']['created'];
1625        } else {                         // old format
1626            $createdA  = $a['date'];
1627        }
1628
1629        if (is_array($b['date'])) { // new format
1630            $createdB  = $b['date']['created'];
1631        } else {                         // old format
1632            $createdB  = $b['date'];
1633        }
1634
1635        if ($createdA == $createdB)
1636            return 0;
1637        else
1638            return ($createdA < $createdB) ? -1 : 1;
1639    }
1640
1641// vim:ts=4:sw=4:et:enc=utf-8:
1642