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