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