xref: /plugin/discussion/action.php (revision 83f28d9be95bf97b59ef0466563d65a5d5698fa1)
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 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, 'update_comment_status', []);
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' => $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'] = 'test' . hsc($INPUT->str('user'));
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        }
418
419        // show discussion wrapper only on certain circumstances
420        if (empty($data['comments']) || !is_array($data['comments'])) {
421            $cnt = 0;
422            $keys = [];
423        } else {
424            $cnt = count($data['comments']);
425            $keys = array_keys($data['comments']);
426        }
427
428        $show = false;
429        if ($cnt > 1 || ($cnt == 1 && $data['comments'][$keys[0]]['show'] == 1)
430            || $this->getConf('allowguests') || $INPUT->server->has('REMOTE_USER')) {
431            $show = true;
432            // section title
433            $title = ($data['title'] ? hsc($data['title']) : $this->getLang('discussion'));
434            ptln('<div class="comment_wrapper" id="comment_wrapper">'); // the id value is used for visibility toggling the section
435            ptln('<h2><a name="discussion__section" id="discussion__section">', 2);
436            ptln($title, 4);
437            ptln('</a></h2>', 2);
438            ptln('<div class="level2 hfeed">', 2);
439        }
440
441        // now display the comments
442        if (isset($data['comments'])) {
443            if (!$this->getConf('usethreading')) {
444                $data['comments'] = $this->flattenThreads($data['comments']);
445                uasort($data['comments'], [$this, 'sortThreadsOnCreation']);
446            }
447            if ($this->getConf('newestfirst')) {
448                $data['comments'] = array_reverse($data['comments']);
449            }
450            foreach ($data['comments'] as $cid => $value) {
451                if ($cid == $edit) { // edit form
452                    $this->showCommentForm($value['raw'], 'save', $edit);
453                } else {
454                    $this->showCommentWithReplies($cid, $data, '', $reply);
455                }
456            }
457        }
458
459        // comment form shown on the end, if no comment form of $reply or $edit is requested before
460        if ($data['status'] == 1 && (!$reply || !$this->getConf('usethreading')) && !$edit) {
461            $this->showCommentForm('', 'add');
462        }
463
464        if ($show) {
465            ptln('</div>', 2); // level2 hfeed
466            ptln('</div>'); // comment_wrapper
467        }
468
469        // check for toggle print configuration
470        if ($this->getConf('visibilityButton')) {
471            // print the hide/show discussion section button
472            $this->showDiscussionToggleButton();
473        }
474    }
475
476    /**
477     * Remove the parent-child relation, such that the comment structure becomes flat
478     *
479     * @param array $comments array with all comments
480     * @param null|array $cids comment ids of replies, which should be flatten
481     * @return array returned array with flattened comment structure
482     */
483    protected function flattenThreads($comments, $cids = null)
484    {
485        if (is_null($cids)) {
486            $cids = array_keys($comments);
487        }
488
489        foreach ($cids as $cid) {
490            if (!empty($comments[$cid]['replies'])) {
491                $rids = $comments[$cid]['replies'];
492                $comments = $this->flattenThreads($comments, $rids);
493                $comments[$cid]['replies'] = [];
494            }
495            $comments[$cid]['parent'] = '';
496        }
497        return $comments;
498    }
499
500    /**
501     * Adds a new comment and then displays all comments
502     *
503     * @param array $comment with
504     *  'raw' => string comment text,
505     *  'user' => [
506     *      'id' => string,
507     *      'name' => string,
508     *      'mail' => string
509     *  ],
510     *  'date' => [
511     *      'created' => int timestamp
512     *  ]
513     *  'show' => bool
514     *  'subscribe' => bool
515     * @param string $parent comment id of parent
516     * @return bool
517     */
518    protected function add($comment, $parent)
519    {
520        global $ID, $TEXT, $INPUT;
521
522        $originalTxt = $TEXT; // set $TEXT to comment text for wordblock check
523        $TEXT = $comment['raw'];
524
525        // spamcheck against the DokuWiki blacklist
526        if (checkwordblock()) {
527            msg($this->getLang('wordblock'), -1);
528            return false;
529        }
530
531        if (!$this->getConf('allowguests')
532            && $comment['user']['id'] != $INPUT->server->str('REMOTE_USER')
533        ) {
534            return false; // guest comments not allowed
535        }
536
537        $TEXT = $originalTxt; // restore global $TEXT
538
539        // get discussion meta file name
540        $file = metaFN($ID, '.comments');
541
542        // create comments file if it doesn't exist yet
543        if (!@file_exists($file)) {
544            $data = ['status' => 1, 'number' => 0];
545            io_saveFile($file, serialize($data));
546        } else {
547            $data = unserialize(io_readFile($file, false));
548            // comments off or closed
549            if ($data['status'] != 1) {
550                return false;
551            }
552        }
553
554        if ($comment['date']['created']) {
555            $date = strtotime($comment['date']['created']);
556        } else {
557            $date = time();
558        }
559
560        if ($date == -1) {
561            $date = time();
562        }
563
564        $cid = md5($comment['user']['id'] . $date); // create a unique id
565
566        if (!is_array($data['comments'][$parent])) {
567            $parent = null; // invalid parent comment
568        }
569
570        // render the comment
571        $xhtml = $this->renderComment($comment['raw']);
572
573        // fill in the new comment
574        $data['comments'][$cid] = [
575            'user' => $comment['user'],
576            'date' => ['created' => $date],
577            'raw' => $comment['raw'],
578            'xhtml' => $xhtml,
579            'parent' => $parent,
580            'replies' => [],
581            'show' => $comment['show']
582        ];
583
584        if ($comment['subscribe']) {
585            $mail = $comment['user']['mail'];
586            if ($data['subscribers']) {
587                if (!$data['subscribers'][$mail]) {
588                    $data['subscribers'][$mail]['hash'] = md5($mail . mt_rand());
589                    $data['subscribers'][$mail]['active'] = false;
590                    $data['subscribers'][$mail]['confirmsent'] = false;
591                } else {
592                    // convert old style subscribers and set them active
593                    if (!is_array($data['subscribers'][$mail])) {
594                        $hash = $data['subscribers'][$mail];
595                        $data['subscribers'][$mail]['hash'] = $hash;
596                        $data['subscribers'][$mail]['active'] = true;
597                        $data['subscribers'][$mail]['confirmsent'] = true;
598                    }
599                }
600            } else {
601                $data['subscribers'][$mail]['hash'] = md5($mail . mt_rand());
602                $data['subscribers'][$mail]['active'] = false;
603                $data['subscribers'][$mail]['confirmsent'] = false;
604            }
605        }
606
607        // update parent comment
608        if ($parent) {
609            $data['comments'][$parent]['replies'][] = $cid;
610        }
611
612        // update the number of comments
613        $data['number']++;
614
615        // notify subscribers of the page
616        $data['comments'][$cid]['cid'] = $cid;
617        $this->notify($data['comments'][$cid], $data['subscribers']);
618
619        // save the comment metadata file
620        io_saveFile($file, serialize($data));
621        $this->addLogEntry($date, $ID, 'cc', '', $cid);
622
623        $this->redirect($cid);
624        return true;
625    }
626
627    /**
628     * Saves the comment with the given ID and then displays all comments
629     *
630     * @param array|string $cids array with comment ids to save, or a single string comment id
631     * @param string $raw if empty comment is deleted, otherwise edited text is stored (note: storing is per one cid!)
632     * @param string|null $act 'toogle', 'show', 'hide', null. If null, it depends on $raw
633     * @return bool succeed?
634     */
635    public function save($cids, $raw, $act = null)
636    {
637        global $ID, $INPUT;
638
639        if (empty($cids)) return false; // do nothing if we get no comment id
640
641        if ($raw) {
642            global $TEXT;
643
644            $otxt = $TEXT; // set $TEXT to comment text for wordblock check
645            $TEXT = $raw;
646
647            // spamcheck against the DokuWiki blacklist
648            if (checkwordblock()) {
649                msg($this->getLang('wordblock'), -1);
650                return false;
651            }
652
653            $TEXT = $otxt; // restore global $TEXT
654        }
655
656        // get discussion meta file name
657        $file = metaFN($ID, '.comments');
658        $data = unserialize(io_readFile($file, false));
659
660        if (!is_array($cids)) {
661            $cids = [$cids];
662        }
663        foreach ($cids as $cid) {
664
665            if (is_array($data['comments'][$cid]['user'])) {
666                $user = $data['comments'][$cid]['user']['id'];
667                $convert = false;
668            } else {
669                $user = $data['comments'][$cid]['user'];
670                $convert = true;
671            }
672
673            // someone else was trying to edit our comment -> abort
674            if ($user != $INPUT->server->str('REMOTE_USER') && !$this->helper->isDiscussionModerator()) {
675                return false;
676            }
677
678            $date = time();
679
680            // need to convert to new format?
681            if ($convert) {
682                $data['comments'][$cid]['user'] = [
683                    'id' => $user,
684                    'name' => $data['comments'][$cid]['name'],
685                    'mail' => $data['comments'][$cid]['mail'],
686                    'url' => $data['comments'][$cid]['url'],
687                    'address' => $data['comments'][$cid]['address'],
688                ];
689                $data['comments'][$cid]['date'] = [
690                    'created' => $data['comments'][$cid]['date']
691                ];
692            }
693
694            if ($act == 'toogle') {     // toogle visibility
695                $now = $data['comments'][$cid]['show'];
696                $data['comments'][$cid]['show'] = !$now;
697                $data['number'] = $this->countVisibleComments($data);
698
699                $type = ($data['comments'][$cid]['show'] ? 'sc' : 'hc');
700
701            } elseif ($act == 'show') { // show comment
702                $data['comments'][$cid]['show'] = true;
703                $data['number'] = $this->countVisibleComments($data);
704
705                $type = 'sc'; // show comment
706
707            } elseif ($act == 'hide') { // hide comment
708                $data['comments'][$cid]['show'] = false;
709                $data['number'] = $this->countVisibleComments($data);
710
711                $type = 'hc'; // hide comment
712
713            } elseif (!$raw) {          // remove the comment
714                $data['comments'] = $this->removeComment($cid, $data['comments']);
715                $data['number'] = $this->countVisibleComments($data);
716
717                $type = 'dc'; // delete comment
718
719            } else {                   // save changed comment
720                $xhtml = $this->renderComment($raw);
721
722                // now change the comment's content
723                $data['comments'][$cid]['date']['modified'] = $date;
724                $data['comments'][$cid]['raw'] = $raw;
725                $data['comments'][$cid]['xhtml'] = $xhtml;
726
727                $type = 'ec'; // edit comment
728            }
729        }
730
731        // save the comment metadata file
732        io_saveFile($file, serialize($data));
733        $this->addLogEntry($date, $ID, $type, '', $cid);
734
735        $this->redirect($cid);
736        return true;
737    }
738
739    /**
740     * Recursive function to remove a comment from the data array
741     *
742     * @param string $cid comment id to be removed
743     * @param array $comments array with all comments
744     * @return array returns modified array with all remaining comments
745     */
746    protected function removeComment($cid, $comments)
747    {
748        if (is_array($comments[$cid]['replies'])) {
749            foreach ($comments[$cid]['replies'] as $rid) {
750                $comments = $this->removeComment($rid, $comments);
751            }
752        }
753        unset($comments[$cid]);
754        return $comments;
755    }
756
757    /**
758     * Prints an individual comment
759     *
760     * @param string $cid comment id
761     * @param array $data array with all comments by reference
762     * @param string $parent comment id of parent
763     * @param string $reply comment id on which the user requested a reply
764     * @param bool $isVisible is marked as visible
765     */
766    protected function showCommentWithReplies($cid, &$data, $parent = '', $reply = '', $isVisible = true)
767    {
768        // comment was removed
769        if (!isset($data['comments'][$cid])) {
770            return;
771        }
772        $comment = $data['comments'][$cid];
773
774        // corrupt datatype
775        if (!is_array($comment)) {
776            return;
777        }
778
779        // handle only replies to given parent comment
780        if ($comment['parent'] != $parent) {
781            return;
782        }
783
784        // comment hidden
785        if (!$comment['show']) {
786            if ($this->helper->isDiscussionModerator()) {
787                $hidden = ' comment_hidden';
788            } else {
789                return;
790            }
791        } else {
792            $hidden = '';
793        }
794
795        // print the actual comment
796        $this->showComment($cid, $data, $reply, $isVisible, $hidden);
797        // replies to this comment entry?
798        $this->showReplies($cid, $data, $reply, $isVisible);
799        // reply form
800        $this->showReplyForm($cid, $reply);
801    }
802
803    /**
804     * Print the comment
805     *
806     * @param string $cid comment id
807     * @param array $data array with all comments
808     * @param string $reply comment id on which the user requested a reply
809     * @param bool $isVisible is marked as visible
810     * @param string $hidden extra class, for the admin only hidden view
811     */
812    protected function showComment($cid, $data, $reply, $isVisible, $hidden)
813    {
814        global $conf, $lang, $HIGH, $INPUT;
815        $comment = $data['comments'][$cid];
816
817        // comment head with date and user data
818        ptln('<div class="hentry' . $hidden . '">', 4);
819        ptln('<div class="comment_head">', 6);
820        ptln('<a name="comment_' . $cid . '" id="comment_' . $cid . '"></a>', 8);
821        $head = '<span class="vcard author">';
822
823        // prepare variables
824        if (is_array($comment['user'])) { // new format
825            $user = $comment['user']['id'];
826            $name = $comment['user']['name'];
827            $mail = $comment['user']['mail'];
828            $url = $comment['user']['url'];
829            $address = $comment['user']['address'];
830        } else {                         // old format
831            $user = $comment['user'];
832            $name = $comment['name'];
833            $mail = $comment['mail'];
834            $url = $comment['url'];
835            $address = $comment['address'];
836        }
837        if (is_array($comment['date'])) { // new format
838            $created = $comment['date']['created'];
839            $modified = $comment['date']['modified'] ?? null;
840        } else {                         // old format
841            $created = $comment['date'];
842            $modified = $comment['edited'];
843        }
844
845        // show username or real name?
846        if (!$this->getConf('userealname') && $user) {
847            $showname = $user;
848        } else {
849            $showname = $name;
850        }
851
852        // show avatar image?
853        if ($this->useAvatar()) {
854            $user_data['name'] = $name;
855            $user_data['user'] = $user;
856            $user_data['mail'] = $mail;
857            $avatar = $this->avatar->getXHTML($user_data, $name, 'left');
858            if ($avatar) {
859                $head .= $avatar;
860            }
861        }
862
863        if ($this->getConf('linkemail') && $mail) {
864            $head .= $this->email($mail, $showname, 'email fn');
865        } elseif ($url) {
866            $head .= $this->external_link($this->checkURL($url), $showname, 'urlextern url fn');
867        } else {
868            $head .= '<span class="fn">' . $showname . '</span>';
869        }
870
871        if ($address) {
872            $head .= ', <span class="adr">' . $address . '</span>';
873        }
874        $head .= '</span>, ' .
875            '<abbr class="published" title="' . strftime('%Y-%m-%dT%H:%M:%SZ', $created) . '">' .
876            dformat($created, $conf['dformat']) . '</abbr>';
877        if ($modified) {
878            $head .= ', <abbr class="updated" title="' .
879                strftime('%Y-%m-%dT%H:%M:%SZ', $modified) . '">' . dformat($modified, $conf['dformat']) .
880                '</abbr>';
881        }
882        ptln($head, 8);
883        ptln('</div>', 6); // class="comment_head"
884
885        // main comment content
886        ptln('<div class="comment_body entry-content"' .
887            ($this->useAvatar() ? $this->getWidthStyle() : '') . '>', 6);
888        echo ($HIGH ? html_hilight($comment['xhtml'], $HIGH) : $comment['xhtml']) . DOKU_LF;
889        ptln('</div>', 6); // class="comment_body"
890
891        if ($isVisible) {
892            ptln('<div class="comment_buttons">', 6);
893
894            // show reply button?
895            if ($data['status'] == 1 && !$reply && $comment['show']
896                && ($this->getConf('allowguests') || $INPUT->server->has('REMOTE_USER'))
897                && $this->getConf('usethreading')
898            ) {
899                $this->showButton($cid, $this->getLang('btn_reply'), 'reply', true);
900            }
901
902            // show edit, show/hide and delete button?
903            if (($user == $INPUT->server->str('REMOTE_USER') && $user != '') || $this->helper->isDiscussionModerator()) {
904                $this->showButton($cid, $lang['btn_secedit'], 'edit', true);
905                $label = ($comment['show'] ? $this->getLang('btn_hide') : $this->getLang('btn_show'));
906                $this->showButton($cid, $label, 'toogle');
907                $this->showButton($cid, $lang['btn_delete'], 'delete');
908            }
909            ptln('</div>', 6); // class="comment_buttons"
910        }
911        ptln('</div>', 4); // class="hentry"
912    }
913
914    /**
915     * If requested by user, show comment form to write a reply
916     *
917     * @param string $cid current comment id
918     * @param string $reply comment id on which the user requested a reply
919     */
920    protected function showReplyForm($cid, $reply)
921    {
922        if ($this->getConf('usethreading') && $reply == $cid) {
923            ptln('<div class="comment_replies">', 4);
924            $this->showCommentForm('', 'add', $cid);
925            ptln('</div>', 4); // class="comment_replies"
926        }
927    }
928
929    /**
930     * Show the replies to the given comment
931     *
932     * @param string $cid comment id
933     * @param array $data array with all comments by reference
934     * @param string $reply comment id on which the user requested a reply
935     * @param bool $isVisible is marked as visible by reference
936     */
937    protected function showReplies($cid, &$data, $reply, &$isVisible)
938    {
939        $comment = $data['comments'][$cid];
940        if (!count($comment['replies'])) {
941            return;
942        }
943        ptln('<div class="comment_replies"' . $this->getWidthStyle() . '>', 4);
944        $isVisible = ($comment['show'] && $isVisible);
945        foreach ($comment['replies'] as $rid) {
946            $this->showCommentWithReplies($rid, $data, $cid, $reply, $isVisible);
947        }
948        ptln('</div>', 4);
949    }
950
951    /**
952     * Is an avatar displayed?
953     *
954     * @return bool
955     */
956    protected function useAvatar()
957    {
958        if (is_null($this->useAvatar)) {
959            $this->useAvatar = $this->getConf('useavatar')
960                && ($this->avatar = $this->loadHelper('avatar', false));
961        }
962        return $this->useAvatar;
963    }
964
965    /**
966     * Calculate width of indent
967     *
968     * @return string
969     */
970    protected function getWidthStyle()
971    {
972        if (is_null($this->style)) {
973            if ($this->useAvatar()) {
974                $this->style = ' style="margin-left: ' . ($this->avatar->getConf('size') + 14) . 'px;"';
975            } else {
976                $this->style = ' style="margin-left: 20px;"';
977            }
978        }
979        return $this->style;
980    }
981
982    /**
983     * Show the button which toggles between show/hide of the entire discussion section
984     */
985    protected function showDiscussionToggleButton()
986    {
987        ptln('<div id="toggle_button" class="toggle_button" style="text-align: right;">');
988        ptln('<input type="submit" id="discussion__btn_toggle_visibility" title="Toggle Visibiliy" class="button"'
989            . 'value="' . $this->getLang('toggle_display') . '">');
990        ptln('</div>');
991    }
992
993    /**
994     * Outputs the comment form
995     *
996     * @param string $raw the existing comment text in case of edit
997     * @param string $act action 'add' or 'save'
998     * @param string|null $cid comment id to be responded to or null
999     */
1000    protected function showCommentForm($raw, $act, $cid = null)
1001    {
1002        global $lang, $conf, $ID, $INPUT;
1003
1004        // not for unregistered users when guest comments aren't allowed
1005        if (!$INPUT->server->has('REMOTE_USER') && !$this->getConf('allowguests')) {
1006            ?>
1007            <div class="comment_form">
1008                <?php echo $this->getLang('noguests'); ?>
1009            </div>
1010            <?php
1011            return;
1012        }
1013
1014        // fill $raw with $INPUT->str('text') if it's empty (for failed CAPTCHA check)
1015        if (!$raw && $INPUT->str('comment') == 'show') {
1016            $raw = $INPUT->str('text');
1017        }
1018        ?>
1019
1020        <div class="comment_form">
1021            <form id="discussion__comment_form" method="post" action="<?php echo script() ?>"
1022                  accept-charset="<?php echo $lang['encoding'] ?>">
1023                <div class="no">
1024                    <input type="hidden" name="id" value="<?php echo $ID ?>"/>
1025                    <input type="hidden" name="do" value="show"/>
1026                    <input type="hidden" name="comment" value="<?php echo $act ?>"/>
1027                    <?php
1028                    // for adding a comment
1029                    if ($act == 'add') {
1030                        ?>
1031                        <input type="hidden" name="reply" value="<?php echo $cid ?>"/>
1032                        <?php
1033                        // for guest/adminimport: show name, e-mail and subscribe to comments fields
1034                        if (!$INPUT->server->has('REMOTE_USER') or ($this->getConf('adminimport') && $this->helper->isDiscussionModerator())) {
1035                            ?>
1036                            <input type="hidden" name="user" value="<?php echo clientIP() ?>"/>
1037                            <div class="comment_name">
1038                                <label class="block" for="discussion__comment_name">
1039                                    <span><?php echo $lang['fullname'] ?>:</span>
1040                                    <input type="text"
1041                                           class="edit<?php if ($INPUT->str('comment') == 'add' && empty($INPUT->str('name'))) echo ' error' ?>"
1042                                           name="name" id="discussion__comment_name" size="50" tabindex="1"
1043                                           value="<?php echo hsc($INPUT->str('name')) ?>"/>
1044                                </label>
1045                            </div>
1046                            <div class="comment_mail">
1047                                <label class="block" for="discussion__comment_mail">
1048                                    <span><?php echo $lang['email'] ?>:</span>
1049                                    <input type="text"
1050                                           class="edit<?php if ($INPUT->str('comment') == 'add' && empty($INPUT->str('mail'))) echo ' error' ?>"
1051                                           name="mail" id="discussion__comment_mail" size="50" tabindex="2"
1052                                           value="<?php echo hsc($INPUT->str('mail')) ?>"/>
1053                                </label>
1054                            </div>
1055                            <?php
1056                        }
1057
1058                        // allow entering an URL
1059                        if ($this->getConf('urlfield')) {
1060                            ?>
1061                            <div class="comment_url">
1062                                <label class="block" for="discussion__comment_url">
1063                                    <span><?php echo $this->getLang('url') ?>:</span>
1064                                    <input type="text" class="edit" name="url" id="discussion__comment_url" size="50"
1065                                           tabindex="3" value="<?php echo hsc($INPUT->str('url')) ?>"/>
1066                                </label>
1067                            </div>
1068                            <?php
1069                        }
1070
1071                        // allow entering an address
1072                        if ($this->getConf('addressfield')) {
1073                            ?>
1074                            <div class="comment_address">
1075                                <label class="block" for="discussion__comment_address">
1076                                    <span><?php echo $this->getLang('address') ?>:</span>
1077                                    <input type="text" class="edit" name="address" id="discussion__comment_address"
1078                                           size="50" tabindex="4" value="<?php echo hsc($INPUT->str('address')) ?>"/>
1079                                </label>
1080                            </div>
1081                            <?php
1082                        }
1083
1084                        // allow setting the comment date
1085                        if ($this->getConf('adminimport') && ($this->helper->isDiscussionModerator())) {
1086                            ?>
1087                            <div class="comment_date">
1088                                <label class="block" for="discussion__comment_date">
1089                                    <span><?php echo $this->getLang('date') ?>:</span>
1090                                    <input type="text" class="edit" name="date" id="discussion__comment_date"
1091                                           size="50"/>
1092                                </label>
1093                            </div>
1094                            <?php
1095                        }
1096
1097                        // for saving a comment
1098                    } else {
1099                        ?>
1100                        <input type="hidden" name="cid" value="<?php echo $cid ?>"/>
1101                        <?php
1102                    }
1103                    ?>
1104                    <div class="comment_text">
1105                        <?php echo $this->getLang('entercomment');
1106                        echo($this->getConf('wikisyntaxok') ? "" : ":");
1107                        if ($this->getConf('wikisyntaxok')) echo '. ' . $this->getLang('wikisyntax') . ':'; ?>
1108
1109                        <!-- Fix for disable the toolbar when wikisyntaxok is set to false. See discussion's script.jss -->
1110                        <?php if ($this->getConf('wikisyntaxok')) { ?>
1111                        <div id="discussion__comment_toolbar" class="toolbar group">
1112                            <?php } else { ?>
1113                            <div id="discussion__comment_toolbar_disabled">
1114                                <?php } ?>
1115                            </div>
1116                            <textarea
1117                                class="edit<?php if ($INPUT->str('comment') == 'add' && empty($INPUT->str('text'))) echo ' error' ?>"
1118                                name="text" cols="80" rows="10" id="discussion__comment_text" tabindex="5"><?php
1119                                if ($raw) {
1120                                    echo formText($raw);
1121                                } else {
1122                                    echo hsc($INPUT->str('text'));
1123                                }
1124                                ?></textarea>
1125                        </div>
1126
1127                        <?php
1128                        /** @var helper_plugin_captcha $captcha */
1129                        $captcha = $this->loadHelper('captcha', false);
1130                        if ($captcha && $captcha->isEnabled()) {
1131                            echo $captcha->getHTML();
1132                        }
1133
1134                        /** @var helper_plugin_recaptcha $recaptcha */
1135                        $recaptcha = $this->loadHelper('recaptcha', false);
1136                        if ($recaptcha && $recaptcha->isEnabled()) {
1137                            echo $recaptcha->getHTML();
1138                        }
1139                        ?>
1140
1141                        <input class="button comment_submit" id="discussion__btn_submit" type="submit" name="submit"
1142                               accesskey="s" value="<?php echo $lang['btn_save'] ?>"
1143                               title="<?php echo $lang['btn_save'] ?> [S]" tabindex="7"/>
1144                        <input class="button comment_preview_button" id="discussion__btn_preview" type="button"
1145                               name="preview" accesskey="p" value="<?php echo $lang['btn_preview'] ?>"
1146                               title="<?php echo $lang['btn_preview'] ?> [P]"/>
1147
1148                        <?php if ((!$INPUT->server->has('REMOTE_USER')
1149                                || $INPUT->server->has('REMOTE_USER') && !$conf['subscribers'])
1150                                && $this->getConf('subscribe')) { ?>
1151                            <div class="comment_subscribe">
1152                                <input type="checkbox" id="discussion__comment_subscribe" name="subscribe"
1153                                       tabindex="6"/>
1154                                <label class="block" for="discussion__comment_subscribe">
1155                                    <span><?php echo $this->getLang('subscribe') ?></span>
1156                                </label>
1157                            </div>
1158                        <?php } ?>
1159
1160                        <div class="clearer"></div>
1161                        <div id="discussion__comment_preview">&nbsp;</div>
1162                    </div>
1163            </form>
1164        </div>
1165        <?php
1166    }
1167
1168    /**
1169     * Action button below a comment
1170     *
1171     * @param string $cid comment id
1172     * @param string $label translated label
1173     * @param string $act action
1174     * @param bool $jump whether to scroll to the commentform
1175     */
1176    protected function showButton($cid, $label, $act, $jump = false)
1177    {
1178        global $ID;
1179
1180        $anchor = ($jump ? '#discussion__comment_form' : '');
1181
1182        ?>
1183        <form class="button discussion__<?php echo $act ?>" method="get" action="<?php echo script() . $anchor ?>">
1184            <div class="no">
1185                <input type="hidden" name="id" value="<?php echo $ID ?>"/>
1186                <input type="hidden" name="do" value="show"/>
1187                <input type="hidden" name="comment" value="<?php echo $act ?>"/>
1188                <input type="hidden" name="cid" value="<?php echo $cid ?>"/>
1189                <input type="submit" value="<?php echo $label ?>" class="button" title="<?php echo $label ?>"/>
1190            </div>
1191        </form>
1192        <?php
1193    }
1194
1195    /**
1196     * Adds an entry to the comments changelog
1197     *
1198     * @param int $date
1199     * @param string $id page id
1200     * @param string $type create/edit/delete/show/hide comment 'cc', 'ec', 'dc', 'sc', 'hc'
1201     * @param string $summary
1202     * @param string $extra
1203     * @author Ben Coburn <btcoburn@silicodon.net>
1204     *
1205     * @author Esther Brunner <wikidesign@gmail.com>
1206     */
1207    protected function addLogEntry($date, $id, $type = 'cc', $summary = '', $extra = '')
1208    {
1209        global $conf, $INPUT;
1210
1211        $changelog = $conf['metadir'] . '/_comments.changes';
1212
1213        //use current time if none supplied
1214        if (!$date) {
1215            $date = time();
1216        }
1217        $remote = $INPUT->server->str('REMOTE_ADDR');
1218        $user = $INPUT->server->str('REMOTE_USER');
1219
1220        $strip = ["\t", "\n"];
1221        $logline = [
1222            'date' => $date,
1223            'ip' => $remote,
1224            'type' => str_replace($strip, '', $type),
1225            'id' => $id,
1226            'user' => $user,
1227            'sum' => str_replace($strip, '', $summary),
1228            'extra' => str_replace($strip, '', $extra)
1229        ];
1230
1231        // add changelog line
1232        $logline = implode("\t", $logline) . "\n";
1233        io_saveFile($changelog, $logline, true); //global changelog cache
1234        $this->trimRecentCommentsLog($changelog);
1235
1236        // tell the indexer to re-index the page
1237        @unlink(metaFN($id, '.indexed'));
1238    }
1239
1240    /**
1241     * Trims the recent comments cache to the last $conf['changes_days'] recent
1242     * changes or $conf['recent'] items, which ever is larger.
1243     * The trimming is only done once a day.
1244     *
1245     * @param string $changelog file path
1246     * @return bool
1247     * @author Ben Coburn <btcoburn@silicodon.net>
1248     *
1249     */
1250    protected function trimRecentCommentsLog($changelog)
1251    {
1252        global $conf;
1253
1254        if (@file_exists($changelog)
1255            && (filectime($changelog) + 86400) < time()
1256            && !@file_exists($changelog . '_tmp')
1257        ) {
1258
1259            io_lock($changelog);
1260            $lines = file($changelog);
1261            if (count($lines) < $conf['recent']) {
1262                // nothing to trim
1263                io_unlock($changelog);
1264                return true;
1265            }
1266
1267            // presave tmp as 2nd lock
1268            io_saveFile($changelog . '_tmp', '');
1269            $trim_time = time() - $conf['recent_days'] * 86400;
1270            $out_lines = [];
1271
1272            $num = count($lines);
1273            for ($i = 0; $i < $num; $i++) {
1274                $log = parseChangelogLine($lines[$i]);
1275                if ($log === false) continue;                      // discard junk
1276                if ($log['date'] < $trim_time) {
1277                    $old_lines[$log['date'] . ".$i"] = $lines[$i]; // keep old lines for now (append .$i to prevent key collisions)
1278                } else {
1279                    $out_lines[$log['date'] . ".$i"] = $lines[$i]; // definitely keep these lines
1280                }
1281            }
1282
1283            // sort the final result, it shouldn't be necessary,
1284            // however the extra robustness in making the changelog cache self-correcting is worth it
1285            ksort($out_lines);
1286            $extra = $conf['recent'] - count($out_lines);        // do we need extra lines do bring us up to minimum
1287            if ($extra > 0) {
1288                ksort($old_lines);
1289                $out_lines = array_merge(array_slice($old_lines, -$extra), $out_lines);
1290            }
1291
1292            // save trimmed changelog
1293            io_saveFile($changelog . '_tmp', implode('', $out_lines));
1294            @unlink($changelog);
1295            if (!rename($changelog . '_tmp', $changelog)) {
1296                // rename failed so try another way...
1297                io_unlock($changelog);
1298                io_saveFile($changelog, implode('', $out_lines));
1299                @unlink($changelog . '_tmp');
1300            } else {
1301                io_unlock($changelog);
1302            }
1303            return true;
1304        }
1305        return true;
1306    }
1307
1308    /**
1309     * Sends a notify mail on new comment
1310     *
1311     * @param array $comment data array of the new comment
1312     * @param array $subscribers data of the subscribers by reference
1313     *
1314     * @author Andreas Gohr <andi@splitbrain.org>
1315     * @author Esther Brunner <wikidesign@gmail.com>
1316     */
1317    protected function notify($comment, &$subscribers)
1318    {
1319        global $conf, $ID, $INPUT, $auth;
1320
1321        $notify_text = io_readfile($this->localfn('subscribermail'));
1322        $confirm_text = io_readfile($this->localfn('confirmsubscribe'));
1323        $subject_notify = '[' . $conf['title'] . '] ' . $this->getLang('mail_newcomment');
1324        $subject_subscribe = '[' . $conf['title'] . '] ' . $this->getLang('subscribe');
1325
1326        $mailer = new Mailer();
1327        if (!$INPUT->server->has('REMOTE_USER')) {
1328            $mailer->from($conf['mailfromnobody']);
1329        }
1330
1331        $replace = [
1332            'PAGE' => $ID,
1333            'TITLE' => $conf['title'],
1334            'DATE' => dformat($comment['date']['created'], $conf['dformat']),
1335            'NAME' => $comment['user']['name'],
1336            'TEXT' => $comment['raw'],
1337            'COMMENTURL' => wl($ID, '', true) . '#comment_' . $comment['cid'],
1338            'UNSUBSCRIBE' => wl($ID, 'do=subscribe', true, '&'),
1339            'DOKUWIKIURL' => DOKU_URL
1340        ];
1341
1342        $confirm_replace = [
1343            'PAGE' => $ID,
1344            'TITLE' => $conf['title'],
1345            'DOKUWIKIURL' => DOKU_URL
1346        ];
1347
1348
1349        $mailer->subject($subject_notify);
1350        $mailer->setBody($notify_text, $replace);
1351
1352        // send mail to notify address
1353        if ($conf['notify']) {
1354            $mailer->bcc($conf['notify']);
1355            $mailer->send();
1356        }
1357
1358        // send email to moderators
1359        if ($this->getConf('moderatorsnotify')) {
1360            $moderatorgrpsString = trim($this->getConf('moderatorgroups'));
1361            if (!empty($moderatorgrpsString)) {
1362                // create a clean mods list
1363                $moderatorgroups = explode(',', $moderatorgrpsString);
1364                $moderatorgroups = array_map('trim', $moderatorgroups);
1365                $moderatorgroups = array_unique($moderatorgroups);
1366                $moderatorgroups = array_filter($moderatorgroups);
1367                // search for moderators users
1368                foreach ($moderatorgroups as $moderatorgroup) {
1369                    if (!$auth->isCaseSensitive()) {
1370                        $moderatorgroup = PhpString::strtolower($moderatorgroup);
1371                    }
1372                    // create a clean mailing list
1373                    $bccs = [];
1374                    if ($moderatorgroup[0] == '@') {
1375                        foreach ($auth->retrieveUsers(0, 0, ['grps' => $auth->cleanGroup(substr($moderatorgroup, 1))]) as $user) {
1376                            if (!empty($user['mail'])) {
1377                                $bccs[] = $user['mail'];
1378                            }
1379                        }
1380                    } else {
1381                        //it is an user
1382                        $userdata = $auth->getUserData($auth->cleanUser($moderatorgroup));
1383                        if (!empty($userdata['mail'])) {
1384                            $bccs[] = $userdata['mail'];
1385                        }
1386                    }
1387                    $bccs = array_unique($bccs);
1388                    // notify the users
1389                    $mailer->bcc(implode(',', $bccs));
1390                    $mailer->send();
1391                }
1392            }
1393        }
1394
1395        // notify page subscribers
1396        if (actionOK('subscribe')) {
1397            $data = ['id' => $ID, 'addresslist' => '', 'self' => false];
1398            //FIXME default callback, needed to mentioned it again?
1399            Event::createAndTrigger(
1400                'COMMON_NOTIFY_ADDRESSLIST', $data,
1401                [new SubscriberManager(), 'notifyAddresses']
1402            );
1403
1404            $to = $data['addresslist'];
1405            if (!empty($to)) {
1406                $mailer->bcc($to);
1407                $mailer->send();
1408            }
1409        }
1410
1411        // notify comment subscribers
1412        if (!empty($subscribers)) {
1413
1414            foreach ($subscribers as $mail => $data) {
1415                $mailer->bcc($mail);
1416                if ($data['active']) {
1417                    $replace['UNSUBSCRIBE'] = wl($ID, 'do=discussion_unsubscribe&hash=' . $data['hash'], true, '&');
1418
1419                    $mailer->subject($subject_notify);
1420                    $mailer->setBody($notify_text, $replace);
1421                    $mailer->send();
1422                } elseif (!$data['confirmsent']) {
1423                    $confirm_replace['SUBSCRIBE'] = wl($ID, 'do=discussion_confirmsubscribe&hash=' . $data['hash'], true, '&');
1424
1425                    $mailer->subject($subject_subscribe);
1426                    $mailer->setBody($confirm_text, $confirm_replace);
1427                    $mailer->send();
1428                    $subscribers[$mail]['confirmsent'] = true;
1429                }
1430            }
1431        }
1432    }
1433
1434    /**
1435     * Counts the number of visible comments
1436     *
1437     * @param array $data array with all comments
1438     * @return int
1439     */
1440    protected function countVisibleComments($data)
1441    {
1442        $number = 0;
1443        foreach ($data['comments'] as $comment) {
1444            if ($comment['parent']) continue;
1445            if (!$comment['show']) continue;
1446
1447            $number++;
1448            $rids = $comment['replies'];
1449            if (count($rids)) {
1450                $number = $number + $this->countVisibleReplies($data, $rids);
1451            }
1452        }
1453        return $number;
1454    }
1455
1456    /**
1457     * Count visible replies on the comments
1458     *
1459     * @param array $data
1460     * @param array $rids
1461     * @return int counted replies
1462     */
1463    protected function countVisibleReplies(&$data, $rids)
1464    {
1465        $number = 0;
1466        foreach ($rids as $rid) {
1467            if (!isset($data['comments'][$rid])) continue; // reply was removed
1468            if (!$data['comments'][$rid]['show']) continue;
1469
1470            $number++;
1471            $rids = $data['comments'][$rid]['replies'];
1472            if (count($rids)) {
1473                $number = $number + $this->countVisibleReplies($data, $rids);
1474            }
1475        }
1476        return $number;
1477    }
1478
1479    /**
1480     * Renders the raw comment (wiki)text to html
1481     *
1482     * @param string $raw comment text
1483     * @return null|string
1484     */
1485    protected function renderComment($raw)
1486    {
1487        if ($this->getConf('wikisyntaxok')) {
1488            // Note the warning for render_text:
1489            //   "very ineffecient for small pieces of data - try not to use"
1490            // in dokuwiki/inc/plugin.php
1491            $xhtml = $this->render_text($raw);
1492        } else { // wiki syntax not allowed -> just encode special chars
1493            $xhtml = hsc(trim($raw));
1494            $xhtml = str_replace("\n", '<br />', $xhtml);
1495        }
1496        return $xhtml;
1497    }
1498
1499    /**
1500     * Finds out whether there is a discussion section for the current page
1501     *
1502     * @param string $title
1503     * @return bool
1504     */
1505    protected function hasDiscussion(&$title)
1506    {
1507        global $ID;
1508
1509        $file = metaFN($ID, '.comments');
1510
1511        if (!@file_exists($file)) {
1512            if ($this->isDiscussionEnabled()) {
1513                return true;
1514            } else {
1515                return false;
1516            }
1517        }
1518
1519        $comments = unserialize(io_readFile($file, false));
1520
1521        if ($comments['title']) {
1522            $title = hsc($comments['title']);
1523        }
1524        $num = $comments['number'];
1525        if (!$comments['status'] || ($comments['status'] == 2 && $num == 0)) {
1526            //disabled, or closed and no comments
1527            return false;
1528        } else {
1529            return true;
1530        }
1531    }
1532
1533    /**
1534     * Creates a new thread page
1535     *
1536     * @return string
1537     */
1538    protected function newThread()
1539    {
1540        global $ID, $INFO, $INPUT;
1541
1542        $ns = cleanID($INPUT->str('ns'));
1543        $title = str_replace(':', '', $INPUT->str('title'));
1544        $back = $ID;
1545        $ID = ($ns ? $ns . ':' : '') . cleanID($title);
1546        $INFO = pageinfo();
1547
1548        // check if we are allowed to create this file
1549        if ($INFO['perm'] >= AUTH_CREATE) {
1550
1551            //check if locked by anyone - if not lock for my self
1552            if ($INFO['locked']) {
1553                return 'locked';
1554            } else {
1555                lock($ID);
1556            }
1557
1558            // prepare the new thread file with default stuff
1559            if (!@file_exists($INFO['filepath'])) {
1560                global $TEXT;
1561
1562                $TEXT = pageTemplate(($ns ? $ns . ':' : '') . $title);
1563                if (!$TEXT) {
1564                    $data = ['id' => $ID, 'ns' => $ns, 'title' => $title, 'back' => $back];
1565                    $TEXT = $this->pageTemplate($data);
1566                }
1567                return 'preview';
1568            } else {
1569                return 'edit';
1570            }
1571        } else {
1572            return 'show';
1573        }
1574    }
1575
1576    /**
1577     * Adapted version of pageTemplate() function
1578     *
1579     * @param array $data
1580     * @return string
1581     */
1582    protected function pageTemplate($data)
1583    {
1584        global $conf, $INFO, $INPUT;
1585
1586        $id = $data['id'];
1587        $user = $INPUT->server->str('REMOTE_USER');
1588        $tpl = io_readFile(DOKU_PLUGIN . 'discussion/_template.txt');
1589
1590        // standard replacements
1591        $replace = [
1592            '@NS@' => $data['ns'],
1593            '@PAGE@' => strtr(noNS($id), '_', ' '),
1594            '@USER@' => $user,
1595            '@NAME@' => $INFO['userinfo']['name'],
1596            '@MAIL@' => $INFO['userinfo']['mail'],
1597            '@DATE@' => dformat(time(), $conf['dformat']),
1598        ];
1599
1600        // additional replacements
1601        $replace['@BACK@'] = $data['back'];
1602        $replace['@TITLE@'] = $data['title'];
1603
1604        // avatar if useavatar and avatar plugin available
1605        if ($this->getConf('useavatar') && !plugin_isdisabled('avatar')) {
1606            $replace['@AVATAR@'] = '{{avatar>' . $user . ' }} ';
1607        } else {
1608            $replace['@AVATAR@'] = '';
1609        }
1610
1611        // tag if tag plugin is available
1612        if (!plugin_isdisabled('tag')) {
1613            $replace['@TAG@'] = "\n\n{{tag>}}";
1614        } else {
1615            $replace['@TAG@'] = '';
1616        }
1617
1618        // perform the replacements in tpl
1619        return str_replace(array_keys($replace), array_values($replace), $tpl);
1620    }
1621
1622    /**
1623     * Checks if the CAPTCHA string submitted is valid, modifies action if needed
1624     */
1625    protected function captchaCheck()
1626    {
1627        global $INPUT;
1628        /** @var helper_plugin_captcha $captcha */
1629        if (!$captcha = $this->loadHelper('captcha', false)) {
1630            // CAPTCHA is disabled or not available
1631            return;
1632        }
1633
1634        if ($captcha->isEnabled() && !$captcha->check()) {
1635            if ($INPUT->str('comment') == 'save') {
1636                $INPUT->set('comment', 'edit');
1637            } elseif ($INPUT->str('comment') == 'add') {
1638                $INPUT->set('comment', 'show');
1639            }
1640        }
1641    }
1642
1643    /**
1644     * checks if the submitted reCAPTCHA string is valid, modifies action if needed
1645     *
1646     * @author Adrian Schlegel <adrian@liip.ch>
1647     */
1648    protected function recaptchaCheck()
1649    {
1650        global $INPUT;
1651        /** @var helper_plugin_recaptcha $recaptcha */
1652        if (!$recaptcha = plugin_load('helper', 'recaptcha'))
1653            return; // reCAPTCHA is disabled or not available
1654
1655        // do nothing if logged in user and no reCAPTCHA required
1656        if (!$recaptcha->getConf('forusers') && $INPUT->server->has('REMOTE_USER')) return;
1657
1658        $response = $recaptcha->check();
1659        if (!$response->is_valid) {
1660            msg($recaptcha->getLang('testfailed'), -1);
1661            if ($INPUT->str('comment') == 'save') {
1662                $INPUT->str('comment', 'edit');
1663            } elseif ($INPUT->str('comment') == 'add') {
1664                $INPUT->str('comment', 'show');
1665            }
1666        }
1667    }
1668
1669    /**
1670     * Add discussion plugin version to the indexer version
1671     * This means that all pages will be indexed again in order to add the comments
1672     * to the index whenever there has been a change that concerns the index content.
1673     *
1674     * @param Doku_Event $event
1675     */
1676    public function addIndexVersion(Doku_Event $event)
1677    {
1678        $event->data['discussion'] = '0.1';
1679    }
1680
1681    /**
1682     * Adds the comments to the index
1683     *
1684     * @param Doku_Event $event
1685     * @param array $param with
1686     *  'id' => string 'page'/'id' for respectively INDEXER_PAGE_ADD and FULLTEXT_SNIPPET_CREATE event
1687     *  'text' => string 'body'/'text'
1688     */
1689    public function addCommentsToIndex(Doku_Event $event, $param)
1690    {
1691        // get .comments meta file name
1692        $file = metaFN($event->data[$param['id']], '.comments');
1693
1694        if (!@file_exists($file)) return;
1695        $data = unserialize(io_readFile($file, false));
1696
1697        // comments are turned off or no comments available to index
1698        if (!$data['status'] || $data['number'] == 0) return;
1699
1700        // now add the comments
1701        if (isset($data['comments'])) {
1702            foreach ($data['comments'] as $key => $value) {
1703                $event->data[$param['text']] .= DOKU_LF . $this->addCommentWords($key, $data);
1704            }
1705        }
1706    }
1707
1708    /**
1709     * Checks if the phrase occurs in the comments and return event result true if matching
1710     *
1711     * @param Doku_Event $event
1712     */
1713    public function fulltextPhraseMatchInComments(Doku_Event $event)
1714    {
1715        if ($event->result === true) return;
1716
1717        // get .comments meta file name
1718        $file = metaFN($event->data['id'], '.comments');
1719
1720        if (!@file_exists($file)) return;
1721        $data = unserialize(io_readFile($file, false));
1722
1723        // comments are turned off or no comments available to match
1724        if (!$data['status'] || $data['number'] == 0) return;
1725
1726        $matched = false;
1727
1728        // now add the comments
1729        if (isset($data['comments'])) {
1730            foreach ($data['comments'] as $cid => $value) {
1731                $matched = $this->phraseMatchInComment($event->data['phrase'], $cid, $data);
1732                if ($matched) break;
1733            }
1734        }
1735
1736        if ($matched) {
1737            $event->result = true;
1738        }
1739    }
1740
1741    /**
1742     * Match the phrase in the comment and its replies
1743     *
1744     * @param string $phrase phrase to search
1745     * @param string $cid comment id
1746     * @param array $data array with all comments by reference
1747     * @param string $parent cid of parent
1748     * @return bool if match true, otherwise false
1749     */
1750    protected function phraseMatchInComment($phrase, $cid, &$data, $parent = '')
1751    {
1752        if (!isset($data['comments'][$cid])) return false; // comment was removed
1753
1754        $comment = $data['comments'][$cid];
1755
1756        if (!is_array($comment)) return false;             // corrupt datatype
1757        if ($comment['parent'] != $parent) return false;   // reply to an other comment
1758        if (!$comment['show']) return false;               // hidden comment
1759
1760        $text = PhpString::strtolower($comment['raw']);
1761        if (strpos($text, $phrase) !== false) {
1762            return true;
1763        }
1764
1765        if (is_array($comment['replies'])) {               // and the replies
1766            foreach ($comment['replies'] as $rid) {
1767                if ($this->phraseMatchInComment($phrase, $rid, $data, $cid)) {
1768                    return true;
1769                }
1770            }
1771        }
1772        return false;
1773    }
1774
1775    /**
1776     * Saves the current comment status and title from metadata into the .comments file
1777     *
1778     * @param Doku_Event $event
1779     */
1780    public function update_comment_status(Doku_Event $event)
1781    {
1782        global $ID;
1783
1784        $meta = $event->data['current'];
1785        $file = metaFN($ID, '.comments');
1786        $status = ($this->isDiscussionEnabled() ? 1 : 0);
1787        $title = null;
1788        if (isset($meta['plugin_discussion'])) {
1789            $status = $meta['plugin_discussion']['status']; // 0, 1 or 2
1790            $title = $meta['plugin_discussion']['title'];
1791        } elseif ($status == 1) {
1792            // Don't enable comments when automatic comments are on - this already happens automatically
1793            // and if comments are turned off in the admin this only updates the .comments file
1794            return;
1795        }
1796
1797        if ($status || @file_exists($file)) {
1798            $data = [];
1799            if (@file_exists($file)) {
1800                $data = unserialize(io_readFile($file, false));
1801            }
1802
1803            if (!array_key_exists('title', $data) || $data['title'] !== $title || !isset($data['status']) || $data['status'] !== $status) {
1804                $data['title'] = $title;
1805                $data['status'] = $status;
1806                if (!isset($data['number'])) {
1807                    $data['number'] = 0;
1808                }
1809                io_saveFile($file, serialize($data));
1810            }
1811        }
1812    }
1813
1814    /**
1815     * Return words of a given comment and its replies, suitable to be added to the index
1816     *
1817     * @param string $cid comment id
1818     * @param array $data array with all comments by reference
1819     * @param string $parent cid of parent
1820     * @return string
1821     */
1822    protected function addCommentWords($cid, &$data, $parent = '')
1823    {
1824
1825        if (!isset($data['comments'][$cid])) return ''; // comment was removed
1826
1827        $comment = $data['comments'][$cid];
1828
1829        if (!is_array($comment)) return '';             // corrupt datatype
1830        if ($comment['parent'] != $parent) return '';   // reply to an other comment
1831        if (!$comment['show']) return '';               // hidden comment
1832
1833        $text = $comment['raw'];                        // we only add the raw comment text
1834        if (is_array($comment['replies'])) {            // and the replies
1835            foreach ($comment['replies'] as $rid) {
1836                $text .= $this->addCommentWords($rid, $data, $cid);
1837            }
1838        }
1839        return ' ' . $text;
1840    }
1841
1842    /**
1843     * Only allow http(s) URLs and append http:// to URLs if needed
1844     *
1845     * @param string $url
1846     * @return string
1847     */
1848    protected function checkURL($url)
1849    {
1850        if (preg_match("#^http://|^https://#", $url)) {
1851            return hsc($url);
1852        } elseif (substr($url, 0, 4) == 'www.') {
1853            return hsc('https://' . $url);
1854        } else {
1855            return '';
1856        }
1857    }
1858
1859    /**
1860     * Sort threads
1861     *
1862     * @param array $a array with comment properties
1863     * @param array $b array with comment properties
1864     * @return int
1865     */
1866    function sortThreadsOnCreation($a, $b)
1867    {
1868        if (is_array($a['date'])) {
1869            // new format
1870            $createdA = $a['date']['created'];
1871        } else {
1872            // old format
1873            $createdA = $a['date'];
1874        }
1875
1876        if (is_array($b['date'])) {
1877            // new format
1878            $createdB = $b['date']['created'];
1879        } else {
1880            // old format
1881            $createdB = $b['date'];
1882        }
1883
1884        if ($createdA == $createdB) {
1885            return 0;
1886        } else {
1887            return ($createdA < $createdB) ? -1 : 1;
1888        }
1889    }
1890
1891}
1892
1893
1894