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