xref: /plugin/discussion/action.php (revision f0bcde1826a4bfab27fa38eb1c5dc4f8a96129cd)
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     *
363     * @return bool
364     */
365    public function isDiscussionEnabled() {
366        global $INFO;
367
368        // handle excluded_ns
369        $isNamespaceExcluded = preg_match($this->getConf('excluded_ns'), $INFO['namespace']);
370
371        if($this->getConf('automatic')) {
372            if($isNamespaceExcluded) {
373                return false;
374            } else {
375                return true;
376            }
377        } else {
378            if($isNamespaceExcluded) {
379                return true;
380            } else {
381                return false;
382            }
383        }
384    }
385
386    /**
387     * Shows all comments of the current page
388     */
389    protected function _show($reply = null, $edit = null) {
390        global $ID;
391        global $INFO;
392
393        // get .comments meta file name
394        $file = metaFN($ID, '.comments');
395
396        if (!$INFO['exists']) return false;
397        if (!@file_exists($file) && !$this->isDiscussionEnabled()) return false;
398        if (!$_SERVER['REMOTE_USER'] && !$this->getConf('showguests')) return false;
399
400        // load data
401        if (@file_exists($file)) {
402            $data = unserialize(io_readFile($file, false));
403            if (!$data['status']) return false; // comments are turned off
404        } elseif (!@file_exists($file) && $this->isDiscussionEnabled() && $INFO['exists']) {
405            // set status to show the comment form
406            $data['status'] = 1;
407            $data['number'] = 0;
408        }
409
410        // show discussion wrapper only on certain circumstances
411        $cnt = count($data['comments']);
412        $keys = @array_keys($data['comments']);
413        $show = false;
414        if($cnt > 1 || ($cnt == 1 && $data['comments'][$keys[0]]['show'] == 1) || $this->getConf('allowguests') || isset($_SERVER['REMOTE_USER'])) {
415            $show = true;
416            // section title
417            $title = ($data['title'] ? hsc($data['title']) : $this->getLang('discussion'));
418            ptln('<div class="comment_wrapper" id="comment_wrapper">'); // the id value is used for visibility toggling the section
419            ptln('<h2><a name="discussion__section" id="discussion__section">', 2);
420            ptln($title, 4);
421            ptln('</a></h2>', 2);
422            ptln('<div class="level2 hfeed">', 2);
423        }
424
425        // now display the comments
426        if (isset($data['comments'])) {
427            if (!$this->getConf('usethreading')) {
428                $data['comments'] = $this->_flattenThreads($data['comments']);
429                uasort($data['comments'], '_sortCallback');
430            }
431            if($this->getConf('newestfirst')) {
432                $data['comments'] = array_reverse($data['comments']);
433            }
434            foreach ($data['comments'] as $key => $value) {
435                if ($key == $edit) $this->_form($value['raw'], 'save', $edit); // edit form
436                else $this->_print($key, $data, '', $reply);
437            }
438        }
439
440        // comment form
441        if (($data['status'] == 1) && (!$reply || !$this->getConf('usethreading')) && !$edit) $this->_form('');
442
443        if($show) {
444            ptln('</div>', 2); // level2 hfeed
445            ptln('</div>'); // comment_wrapper
446        }
447
448        // check for toggle print configuration
449        if($this->getConf('visibilityButton')) {
450            // print the hide/show discussion section button
451            $this->_print_toggle_button();
452        }
453
454        return true;
455    }
456
457    /**
458     * @param array      $comments
459     * @param null|array $keys
460     * @return array
461     */
462    protected function _flattenThreads($comments, $keys = null) {
463        if (is_null($keys))
464            $keys = array_keys($comments);
465
466        foreach($keys as $cid) {
467            if (!empty($comments[$cid]['replies'])) {
468                $rids = $comments[$cid]['replies'];
469                $comments = $this->_flattenThreads($comments, $rids);
470                $comments[$cid]['replies'] = array();
471            }
472            $comments[$cid]['parent'] = '';
473        }
474        return $comments;
475    }
476
477    /**
478     * Adds a new comment and then displays all comments
479     *
480     * @param array $comment
481     * @param string $parent
482     * @return bool
483     */
484    protected function _add($comment, $parent) {
485        global $ID;
486        global $TEXT;
487
488        $otxt = $TEXT; // set $TEXT to comment text for wordblock check
489        $TEXT = $comment['raw'];
490
491        // spamcheck against the DokuWiki blacklist
492        if (checkwordblock()) {
493            msg($this->getLang('wordblock'), -1);
494            return false;
495        }
496
497        if ((!$this->getConf('allowguests'))
498                && ($comment['user']['id'] != $_SERVER['REMOTE_USER']))
499            return false; // guest comments not allowed
500
501        $TEXT = $otxt; // restore global $TEXT
502
503        // get discussion meta file name
504        $file = metaFN($ID, '.comments');
505
506        // create comments file if it doesn't exist yet
507        if(!@file_exists($file)) {
508            $data = array('status' => 1, 'number' => 0);
509            io_saveFile($file, serialize($data));
510        } else {
511            $data = unserialize(io_readFile($file, false));
512            if ($data['status'] != 1) return false; // comments off or closed
513        }
514
515        if ($comment['date']['created']) {
516            $date = strtotime($comment['date']['created']);
517        } else {
518            $date = time();
519        }
520
521        if ($date == -1) {
522            $date = time();
523        }
524
525        $cid  = md5($comment['user']['id'].$date); // create a unique id
526
527        if (!is_array($data['comments'][$parent])) {
528            $parent = NULL; // invalid parent comment
529        }
530
531        // render the comment
532        $xhtml = $this->_render($comment['raw']);
533
534        // fill in the new comment
535        $data['comments'][$cid] = array(
536                'user'    => $comment['user'],
537                'date'    => array('created' => $date),
538                'raw'     => $comment['raw'],
539                'xhtml'   => $xhtml,
540                'parent'  => $parent,
541                'replies' => array(),
542                'show'    => $comment['show']
543                );
544
545        if($comment['subscribe']) {
546            $mail = $comment['user']['mail'];
547            if($data['subscribers']) {
548                if(!$data['subscribers'][$mail]) {
549                    $data['subscribers'][$mail]['hash'] = md5($mail . mt_rand());
550                    $data['subscribers'][$mail]['active'] = false;
551                    $data['subscribers'][$mail]['confirmsent'] = false;
552                } else {
553                    // convert old style subscribers and set them active
554                    if(!is_array($data['subscribers'][$mail])) {
555                        $hash = $data['subscribers'][$mail];
556                        $data['subscribers'][$mail]['hash'] = $hash;
557                        $data['subscribers'][$mail]['active'] = true;
558                        $data['subscribers'][$mail]['confirmsent'] = true;
559                    }
560                }
561            } else {
562                $data['subscribers'][$mail]['hash']   = md5($mail . mt_rand());
563                $data['subscribers'][$mail]['active'] = false;
564                $data['subscribers'][$mail]['confirmsent'] = false;
565            }
566        }
567
568        // update parent comment
569        if ($parent) $data['comments'][$parent]['replies'][] = $cid;
570
571        // update the number of comments
572        $data['number']++;
573
574        // notify subscribers of the page
575        $data['comments'][$cid]['cid'] = $cid;
576        $this->_notify($data['comments'][$cid], $data['subscribers']);
577
578        // save the comment metadata file
579        io_saveFile($file, serialize($data));
580        $this->_addLogEntry($date, $ID, 'cc', '', $cid);
581
582        $this->_redirect($cid);
583        return true;
584    }
585
586    /**
587     * Saves the comment with the given ID and then displays all comments
588     *
589     * @param array|string $cids
590     * @param string $raw
591     * @param string $act
592     * @return bool
593     */
594    public function save($cids, $raw, $act = NULL) {
595        global $ID;
596
597        if(!$cids) return false; // do nothing if we get no comment id
598
599        if ($raw) {
600            global $TEXT;
601
602            $otxt = $TEXT; // set $TEXT to comment text for wordblock check
603            $TEXT = $raw;
604
605            // spamcheck against the DokuWiki blacklist
606            if (checkwordblock()) {
607                msg($this->getLang('wordblock'), -1);
608                return false;
609            }
610
611            $TEXT = $otxt; // restore global $TEXT
612        }
613
614        // get discussion meta file name
615        $file = metaFN($ID, '.comments');
616        $data = unserialize(io_readFile($file, false));
617
618        if (!is_array($cids)) $cids = array($cids);
619        foreach ($cids as $cid) {
620
621            if (is_array($data['comments'][$cid]['user'])) {
622                $user    = $data['comments'][$cid]['user']['id'];
623                $convert = false;
624            } else {
625                $user    = $data['comments'][$cid]['user'];
626                $convert = true;
627            }
628
629            // someone else was trying to edit our comment -> abort
630            if (($user != $_SERVER['REMOTE_USER']) && (!$this->helper->isDiscussionMod())) return false;
631
632            $date = time();
633
634            // need to convert to new format?
635            if ($convert) {
636                $data['comments'][$cid]['user'] = array(
637                        'id'      => $user,
638                        'name'    => $data['comments'][$cid]['name'],
639                        'mail'    => $data['comments'][$cid]['mail'],
640                        'url'     => $data['comments'][$cid]['url'],
641                        'address' => $data['comments'][$cid]['address'],
642                        );
643                $data['comments'][$cid]['date'] = array(
644                        'created' => $data['comments'][$cid]['date']
645                        );
646            }
647
648            if ($act == 'toogle') {     // toogle visibility
649                $now = $data['comments'][$cid]['show'];
650                $data['comments'][$cid]['show'] = !$now;
651                $data['number'] = $this->_count($data);
652
653                $type = ($data['comments'][$cid]['show'] ? 'sc' : 'hc');
654
655            } elseif ($act == 'show') { // show comment
656                $data['comments'][$cid]['show'] = true;
657                $data['number'] = $this->_count($data);
658
659                $type = 'sc'; // show comment
660
661            } elseif ($act == 'hide') { // hide comment
662                $data['comments'][$cid]['show'] = false;
663                $data['number'] = $this->_count($data);
664
665                $type = 'hc'; // hide comment
666
667            } elseif (!$raw) {          // remove the comment
668                $data['comments'] = $this->_removeComment($cid, $data['comments']);
669                $data['number'] = $this->_count($data);
670
671                $type = 'dc'; // delete comment
672
673            } else {                   // save changed comment
674                $xhtml = $this->_render($raw);
675
676                // now change the comment's content
677                $data['comments'][$cid]['date']['modified'] = $date;
678                $data['comments'][$cid]['raw']              = $raw;
679                $data['comments'][$cid]['xhtml']            = $xhtml;
680
681                $type = 'ec'; // edit comment
682            }
683        }
684
685        // save the comment metadata file
686        io_saveFile($file, serialize($data));
687        $this->_addLogEntry($date, $ID, $type, '', $cid);
688
689        $this->_redirect($cid);
690        return true;
691    }
692
693    /**
694     * Recursive function to remove a comment
695     */
696    protected function _removeComment($cid, $comments) {
697        if (is_array($comments[$cid]['replies'])) {
698            foreach ($comments[$cid]['replies'] as $rid) {
699                $comments = $this->_removeComment($rid, $comments);
700            }
701        }
702        unset($comments[$cid]);
703        return $comments;
704    }
705
706    /**
707     * Prints an individual comment
708     *
709     * @param string $cid
710     * @param array $data
711     * @param string $parent
712     * @param string $reply
713     * @param bool $visible
714     * @return bool
715     */
716    protected function _print($cid, &$data, $parent = '', $reply = '', $visible = true) {
717        if (!isset($data['comments'][$cid])) return false; // comment was removed
718        $comment = $data['comments'][$cid];
719
720        if (!is_array($comment)) return false;             // corrupt datatype
721
722        if ($comment['parent'] != $parent) return true;    // reply to an other comment
723
724        if (!$comment['show']) {                            // comment hidden
725            if ($this->helper->isDiscussionMod()) $hidden = ' comment_hidden';
726            else return true;
727        } else {
728            $hidden = '';
729        }
730
731        // print the actual comment
732        $this->_print_comment($cid, $data, $parent, $reply, $visible, $hidden);
733        // replies to this comment entry?
734        $this->_print_replies($cid, $data, $reply, $visible);
735        // reply form
736        $this->_print_form($cid, $reply);
737        return true;
738    }
739
740    /**
741     * @param $cid
742     * @param $data
743     * @param $parent
744     * @param $reply
745     * @param $visible
746     * @param $hidden
747     */
748    protected function _print_comment($cid, &$data, $parent, $reply, $visible, $hidden) {
749        global $conf, $lang, $HIGH;
750        $comment = $data['comments'][$cid];
751
752        // comment head with date and user data
753        ptln('<div class="hentry'.$hidden.'">', 4);
754        ptln('<div class="comment_head">', 6);
755        ptln('<a name="comment_'.$cid.'" id="comment_'.$cid.'"></a>', 8);
756        $head = '<span class="vcard author">';
757
758        // prepare variables
759        if (is_array($comment['user'])) { // new format
760            $user    = $comment['user']['id'];
761            $name    = $comment['user']['name'];
762            $mail    = $comment['user']['mail'];
763            $url     = $comment['user']['url'];
764            $address = $comment['user']['address'];
765        } else {                         // old format
766            $user    = $comment['user'];
767            $name    = $comment['name'];
768            $mail    = $comment['mail'];
769            $url     = $comment['url'];
770            $address = $comment['address'];
771        }
772        if (is_array($comment['date'])) { // new format
773            $created  = $comment['date']['created'];
774            $modified = $comment['date']['modified'];
775        } else {                         // old format
776            $created  = $comment['date'];
777            $modified = $comment['edited'];
778        }
779
780        // show username or real name?
781        if ((!$this->getConf('userealname')) && ($user)) {
782            $showname = $user;
783        } else {
784            $showname = $name;
785        }
786
787        // show avatar image?
788        if ($this->_use_avatar()) {
789            $user_data['name'] = $name;
790            $user_data['user'] = $user;
791            $user_data['mail'] = $mail;
792            $avatar = $this->avatar->getXHTML($user_data, $name, 'left');
793            if($avatar) $head .= $avatar;
794        }
795
796        if ($this->getConf('linkemail') && $mail) {
797            $head .= $this->email($mail, $showname, 'email fn');
798        } elseif ($url) {
799            $head .= $this->external_link($this->_checkURL($url), $showname, 'urlextern url fn');
800        } else {
801            $head .= '<span class="fn">'.$showname.'</span>';
802        }
803
804        if ($address) $head .= ', <span class="adr">'.$address.'</span>';
805        $head .= '</span>, '.
806            '<abbr class="published" title="'. strftime('%Y-%m-%dT%H:%M:%SZ', $created) .'">'.
807            dformat($created, $conf['dformat']).'</abbr>';
808        if ($comment['edited']) $head .= ' (<abbr class="updated" title="'.
809                strftime('%Y-%m-%dT%H:%M:%SZ', $modified).'">'.dformat($modified, $conf['dformat']).
810                '</abbr>)';
811        ptln($head, 8);
812        ptln('</div>', 6); // class="comment_head"
813
814        // main comment content
815        ptln('<div class="comment_body entry-content"'.
816                ($this->_use_avatar() ? $this->_get_style() : '').'>', 6);
817        echo ($HIGH?html_hilight($comment['xhtml'],$HIGH):$comment['xhtml']).DOKU_LF;
818        ptln('</div>', 6); // class="comment_body"
819
820        if ($visible) {
821            ptln('<div class="comment_buttons">', 6);
822
823            // show reply button?
824            if (($data['status'] == 1) && !$reply && $comment['show']
825                    && ($this->getConf('allowguests') || $_SERVER['REMOTE_USER']) && $this->getConf('usethreading'))
826                $this->_button($cid, $this->getLang('btn_reply'), 'reply', true);
827
828            // show edit, show/hide and delete button?
829            if ((($user == $_SERVER['REMOTE_USER']) && ($user != '')) || ($this->helper->isDiscussionMod())) {
830                $this->_button($cid, $lang['btn_secedit'], 'edit', true);
831                $label = ($comment['show'] ? $this->getLang('btn_hide') : $this->getLang('btn_show'));
832                $this->_button($cid, $label, 'toogle');
833                $this->_button($cid, $lang['btn_delete'], 'delete');
834            }
835            ptln('</div>', 6); // class="comment_buttons"
836        }
837        ptln('</div>', 4); // class="hentry"
838    }
839
840    /**
841     * @param string $cid
842     * @param string $reply
843     */
844    protected function _print_form($cid, $reply)
845    {
846        if ($this->getConf('usethreading') && $reply == $cid) {
847            ptln('<div class="comment_replies">', 4);
848            $this->_form('', 'add', $cid);
849            ptln('</div>', 4); // class="comment_replies"
850        }
851    }
852
853    /**
854     * @param string $cid
855     * @param array  $data
856     * @param string $reply
857     * @param bool $visible
858     */
859    protected function _print_replies($cid, &$data, $reply, &$visible)
860    {
861        $comment = $data['comments'][$cid];
862        if (!count($comment['replies'])) {
863            return;
864        }
865        ptln('<div class="comment_replies"'.$this->_get_style().'>', 4);
866        $visible = ($comment['show'] && $visible);
867        foreach ($comment['replies'] as $rid) {
868            $this->_print($rid, $data, $cid, $reply, $visible);
869        }
870        ptln('</div>', 4);
871    }
872
873    /**
874     * Is an avatar displayed?
875     *
876     * @return bool
877     */
878    protected function _use_avatar()
879    {
880        if (is_null($this->use_avatar)) {
881            $this->use_avatar = $this->getConf('useavatar')
882                    && (!plugin_isdisabled('avatar'))
883                    && ($this->avatar =& plugin_load('helper', 'avatar'));
884        }
885        return $this->use_avatar;
886    }
887
888    /**
889     * Calculate width of indent
890     *
891     * @return string
892     */
893    protected function _get_style()
894    {
895        if (is_null($this->style)){
896            if ($this->_use_avatar()) {
897                $this->style = ' style="margin-left: '.($this->avatar->getConf('size') + 14).'px;"';
898            } else {
899                $this->style = ' style="margin-left: 20px;"';
900            }
901        }
902        return $this->style;
903    }
904
905    /**
906     * Show the button which toggle the visibility of the discussion section
907     */
908    protected function _print_toggle_button() {
909        ptln('<div id="toggle_button" class="toggle_button" style="text-align: right;">');
910        ptln('<input type="submit" id="discussion__btn_toggle_visibility" title="Toggle Visibiliy" class="button" value="'.$this->getLang('toggle_display').'">');
911        ptln('</div>');
912    }
913
914    /**
915     * Outputs the comment form
916     */
917    protected function _form($raw = '', $act = 'add', $cid = NULL) {
918        global $lang;
919        global $conf;
920        global $ID;
921
922        // not for unregistered users when guest comments aren't allowed
923        if (!$_SERVER['REMOTE_USER'] && !$this->getConf('allowguests')) {
924            ?>
925            <div class="comment_form">
926                <?php echo $this->getLang('noguests'); ?>
927            </div>
928            <?php
929            return;
930        }
931
932        // fill $raw with $_REQUEST['text'] if it's empty (for failed CAPTCHA check)
933        if (!$raw && ($_REQUEST['comment'] == 'show')) $raw = $_REQUEST['text'];
934        ?>
935
936        <div class="comment_form">
937          <form id="discussion__comment_form" method="post" action="<?php echo script() ?>" accept-charset="<?php echo $lang['encoding'] ?>">
938            <div class="no">
939              <input type="hidden" name="id" value="<?php echo $ID ?>" />
940              <input type="hidden" name="do" value="show" />
941              <input type="hidden" name="comment" value="<?php echo $act ?>" />
942        <?php
943        // for adding a comment
944        if ($act == 'add') {
945        ?>
946              <input type="hidden" name="reply" value="<?php echo $cid ?>" />
947        <?php
948        // for guest/adminimport: show name, e-mail and subscribe to comments fields
949        if(!$_SERVER['REMOTE_USER'] or ($this->getConf('adminimport') && $this->helper->isDiscussionMod())) {
950        ?>
951              <input type="hidden" name="user" value="<?php echo clientIP() ?>" />
952              <div class="comment_name">
953                <label class="block" for="discussion__comment_name">
954                  <span><?php echo $lang['fullname'] ?>:</span>
955                  <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'])?>" />
956                </label>
957              </div>
958              <div class="comment_mail">
959                <label class="block" for="discussion__comment_mail">
960                  <span><?php echo $lang['email'] ?>:</span>
961                  <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'])?>" />
962                </label>
963              </div>
964        <?php
965        }
966
967        // allow entering an URL
968        if ($this->getConf('urlfield')) {
969        ?>
970              <div class="comment_url">
971                <label class="block" for="discussion__comment_url">
972                  <span><?php echo $this->getLang('url') ?>:</span>
973                  <input type="text" class="edit" name="url" id="discussion__comment_url" size="50" tabindex="3" value="<?php echo hsc($_REQUEST['url'])?>" />
974                </label>
975              </div>
976        <?php
977        }
978
979        // allow entering an address
980        if ($this->getConf('addressfield')) {
981        ?>
982              <div class="comment_address">
983                <label class="block" for="discussion__comment_address">
984                  <span><?php echo $this->getLang('address') ?>:</span>
985                  <input type="text" class="edit" name="address" id="discussion__comment_address" size="50" tabindex="4" value="<?php echo hsc($_REQUEST['address'])?>" />
986                </label>
987              </div>
988        <?php
989        }
990
991        // allow setting the comment date
992        if ($this->getConf('adminimport') && ($this->helper->isDiscussionMod())) {
993        ?>
994              <div class="comment_date">
995                <label class="block" for="discussion__comment_date">
996                  <span><?php echo $this->getLang('date') ?>:</span>
997                  <input type="text" class="edit" name="date" id="discussion__comment_date" size="50" />
998                </label>
999              </div>
1000        <?php
1001        }
1002
1003        // for saving a comment
1004        } else {
1005        ?>
1006              <input type="hidden" name="cid" value="<?php echo $cid ?>" />
1007        <?php
1008        }
1009        ?>
1010                <div class="comment_text">
1011                  <?php echo $this->getLang('entercomment'); echo ($this->getConf('wikisyntaxok') ? "" : ":");
1012                        if($this->getConf('wikisyntaxok')) echo '. ' . $this->getLang('wikisyntax') . ':'; ?>
1013
1014                  <!-- Fix for disable the toolbar when wikisyntaxok is set to false. See discussion's script.jss -->
1015                  <?php if($this->getConf('wikisyntaxok')) { ?>
1016                    <div id="discussion__comment_toolbar" class="toolbar group">
1017                  <?php } else { ?>
1018                    <div id="discussion__comment_toolbar_disabled">
1019                  <?php } ?>
1020                </div>
1021                <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
1022                  if($raw) {
1023                      echo formText($raw);
1024                  } else {
1025                      echo hsc($_REQUEST['text']);
1026                  }
1027                ?></textarea>
1028              </div>
1029        <?php //bad and dirty event insert hook
1030        $evdata = array('writable' => true);
1031        trigger_event('HTML_EDITFORM_INJECTION', $evdata);
1032        ?>
1033              <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" />
1034              <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]" />
1035
1036        <?php if((!$_SERVER['REMOTE_USER'] || $_SERVER['REMOTE_USER'] && !$conf['subscribers']) && $this->getConf('subscribe')) { ?>
1037              <div class="comment_subscribe">
1038                <input type="checkbox" id="discussion__comment_subscribe" name="subscribe" tabindex="6" />
1039                <label class="block" for="discussion__comment_subscribe">
1040                  <span><?php echo $this->getLang('subscribe') ?></span>
1041                </label>
1042              </div>
1043        <?php } ?>
1044
1045              <div class="clearer"></div>
1046              <div id="discussion__comment_preview">&nbsp;</div>
1047            </div>
1048          </form>
1049        </div>
1050        <?php
1051        if ($this->getConf('usecocomment')){
1052            $this->_coComment();
1053        }
1054    }
1055
1056    /**
1057     * Adds a javascript to interact with coComments
1058     */
1059    protected function _coComment() {
1060        global $ID;
1061        global $conf;
1062        global $INFO;
1063
1064        $user = $_SERVER['REMOTE_USER'];
1065
1066        ?>
1067        <script type="text/javascript"><!--//--><![CDATA[//><!--
1068          var blogTool  = "DokuWiki";
1069          var blogURL   = "<?php echo DOKU_URL ?>";
1070          var blogTitle = "<?php echo $conf['title'] ?>";
1071          var postURL   = "<?php echo wl($ID, '', true) ?>";
1072          var postTitle = "<?php echo tpl_pagetitle($ID, true) ?>";
1073        <?php
1074        if ($user) {
1075        ?>
1076          var commentAuthor = "<?php echo $INFO['userinfo']['name'] ?>";
1077        <?php
1078        } else {
1079        ?>
1080          var commentAuthorFieldName = "name";
1081        <?php
1082        }
1083        ?>
1084          var commentAuthorLoggedIn = <?php echo ($user ? 'true' : 'false') ?>;
1085          var commentFormID         = "discussion__comment_form";
1086          var commentTextFieldName  = "text";
1087          var commentButtonName     = "submit";
1088          var cocomment_force       = false;
1089        //--><!]]></script>
1090        <script type="text/javascript" src="http://www.cocomment.com/js/cocomment.js">
1091        </script>
1092        <?php
1093    }
1094
1095    /**
1096     * General button function
1097     *
1098     * @param string $cid
1099     * @param string $label
1100     * @param string $act
1101     * @param bool $jump
1102     * @return bool
1103     */
1104    protected function _button($cid, $label, $act, $jump = false) {
1105        global $ID;
1106
1107        $anchor = ($jump ? '#discussion__comment_form' : '' );
1108
1109        ?>
1110        <form class="button discussion__<?php echo $act?>" method="get" action="<?php echo script().$anchor ?>">
1111          <div class="no">
1112            <input type="hidden" name="id" value="<?php echo $ID ?>" />
1113            <input type="hidden" name="do" value="show" />
1114            <input type="hidden" name="comment" value="<?php echo $act ?>" />
1115            <input type="hidden" name="cid" value="<?php echo $cid ?>" />
1116            <input type="submit" value="<?php echo $label ?>" class="button" title="<?php echo $label ?>" />
1117          </div>
1118        </form>
1119        <?php
1120        return true;
1121    }
1122
1123    /**
1124     * Adds an entry to the comments changelog
1125     *
1126     * @author Esther Brunner <wikidesign@gmail.com>
1127     * @author Ben Coburn <btcoburn@silicodon.net>
1128     *
1129     * @param int    $date
1130     * @param string $id page id
1131     * @param string $type
1132     * @param string $summary
1133     * @param string $extra
1134     */
1135    protected function _addLogEntry($date, $id, $type = 'cc', $summary = '', $extra = '') {
1136        global $conf;
1137
1138        $changelog = $conf['metadir'].'/_comments.changes';
1139
1140        if(!$date) $date = time(); //use current time if none supplied
1141        $remote = $_SERVER['REMOTE_ADDR'];
1142        $user   = $_SERVER['REMOTE_USER'];
1143
1144        $strip = array("\t", "\n");
1145        $logline = array(
1146                'date'  => $date,
1147                'ip'    => $remote,
1148                'type'  => str_replace($strip, '', $type),
1149                'id'    => $id,
1150                'user'  => $user,
1151                'sum'   => str_replace($strip, '', $summary),
1152                'extra' => str_replace($strip, '', $extra)
1153                );
1154
1155        // add changelog line
1156        $logline = implode("\t", $logline)."\n";
1157        io_saveFile($changelog, $logline, true); //global changelog cache
1158        $this->_trimRecentCommentsLog($changelog);
1159
1160        // tell the indexer to re-index the page
1161        @unlink(metaFN($id, '.indexed'));
1162    }
1163
1164    /**
1165     * Trims the recent comments cache to the last $conf['changes_days'] recent
1166     * changes or $conf['recent'] items, which ever is larger.
1167     * The trimming is only done once a day.
1168     *
1169     * @author Ben Coburn <btcoburn@silicodon.net>
1170     *
1171     * @param string $changelog file path
1172     * @return bool
1173     */
1174    protected function _trimRecentCommentsLog($changelog) {
1175        global $conf;
1176
1177        if (@file_exists($changelog) &&
1178                (filectime($changelog) + 86400) < time() &&
1179                !@file_exists($changelog.'_tmp')) {
1180
1181            io_lock($changelog);
1182            $lines = file($changelog);
1183            if (count($lines)<$conf['recent']) {
1184                // nothing to trim
1185                io_unlock($changelog);
1186                return true;
1187            }
1188
1189            io_saveFile($changelog.'_tmp', '');                  // presave tmp as 2nd lock
1190            $trim_time = time() - $conf['recent_days']*86400;
1191            $out_lines = array();
1192
1193            $num = count($lines);
1194            for ($i=0; $i<$num; $i++) {
1195                $log = parseChangelogLine($lines[$i]);
1196                if ($log === false) continue;                      // discard junk
1197                if ($log['date'] < $trim_time) {
1198                    $old_lines[$log['date'].".$i"] = $lines[$i];     // keep old lines for now (append .$i to prevent key collisions)
1199                } else {
1200                    $out_lines[$log['date'].".$i"] = $lines[$i];     // definitely keep these lines
1201                }
1202            }
1203
1204            // sort the final result, it shouldn't be necessary,
1205            // however the extra robustness in making the changelog cache self-correcting is worth it
1206            ksort($out_lines);
1207            $extra = $conf['recent'] - count($out_lines);        // do we need extra lines do bring us up to minimum
1208            if ($extra > 0) {
1209                ksort($old_lines);
1210                $out_lines = array_merge(array_slice($old_lines,-$extra),$out_lines);
1211            }
1212
1213            // save trimmed changelog
1214            io_saveFile($changelog.'_tmp', implode('', $out_lines));
1215            @unlink($changelog);
1216            if (!rename($changelog.'_tmp', $changelog)) {
1217                // rename failed so try another way...
1218                io_unlock($changelog);
1219                io_saveFile($changelog, implode('', $out_lines));
1220                @unlink($changelog.'_tmp');
1221            } else {
1222                io_unlock($changelog);
1223            }
1224            return true;
1225        }
1226        return true;
1227    }
1228
1229    /**
1230     * Sends a notify mail on new comment
1231     *
1232     * @param  array  $comment  data array of the new comment
1233     * @param  array  $subscribers data of the subscribers
1234     *
1235     * @author Andreas Gohr <andi@splitbrain.org>
1236     * @author Esther Brunner <wikidesign@gmail.com>
1237     */
1238    protected function _notify($comment, &$subscribers) {
1239        global $conf;
1240        global $ID;
1241
1242        $notify_text = io_readfile($this->localfn('subscribermail'));
1243        $confirm_text = io_readfile($this->localfn('confirmsubscribe'));
1244        $subject_notify = '['.$conf['title'].'] '.$this->getLang('mail_newcomment');
1245        $subject_subscribe = '['.$conf['title'].'] '.$this->getLang('subscribe');
1246
1247        $mailer = new Mailer();
1248        if (empty($_SERVER['REMOTE_USER'])) {
1249            $mailer->from($conf['mailfromnobody']);
1250        }
1251
1252        $replace = array(
1253            'PAGE' => $ID,
1254            'TITLE' => $conf['title'],
1255            'DATE' => dformat($comment['date']['created'], $conf['dformat']),
1256            'NAME' => $comment['user']['name'],
1257            'TEXT' => $comment['raw'],
1258            'COMMENTURL' => wl($ID, '', true) . '#comment_' . $comment['cid'],
1259            'UNSUBSCRIBE' => wl($ID, 'do=subscribe', true, '&'),
1260            'DOKUWIKIURL' => DOKU_URL
1261        );
1262
1263        $confirm_replace = array(
1264            'PAGE' => $ID,
1265            'TITLE' => $conf['title'],
1266            'DOKUWIKIURL' => DOKU_URL
1267        );
1268
1269
1270        $mailer->subject($subject_notify);
1271        $mailer->setBody($notify_text, $replace);
1272
1273        // send mail to notify address
1274        if ($conf['notify']) {
1275            $mailer->bcc($conf['notify']);
1276            $mailer->send();
1277        }
1278
1279        // notify page subscribers
1280        if (actionOK('subscribe')) {
1281            $data = array('id' => $ID, 'addresslist' => '', 'self' => false);
1282            if (class_exists('Subscription')) { /* Introduced in DokuWiki 2013-05-10 */
1283                trigger_event(
1284                    'COMMON_NOTIFY_ADDRESSLIST', $data,
1285                    array(new Subscription(), 'notifyaddresses')
1286                );
1287            } else { /* Old, deprecated default handler */
1288                trigger_event(
1289                    'COMMON_NOTIFY_ADDRESSLIST', $data,
1290                    'subscription_addresslist'
1291                );
1292            }
1293            $to = $data['addresslist'];
1294            if(!empty($to)) {
1295                $mailer->bcc($to);
1296                $mailer->send();
1297            }
1298        }
1299
1300        // notify comment subscribers
1301        if (!empty($subscribers)) {
1302
1303            foreach($subscribers as $mail => $data) {
1304                $mailer->bcc($mail);
1305                if($data['active']) {
1306                    $replace['UNSUBSCRIBE'] = wl($ID, 'do=discussion_unsubscribe&hash=' . $data['hash'], true, '&');
1307
1308                    $mailer->subject($subject_notify);
1309                    $mailer->setBody($notify_text, $replace);
1310                    $mailer->send();
1311                } elseif(!$data['active'] && !$data['confirmsent']) {
1312                    $confirm_replace['SUBSCRIBE'] = wl($ID, 'do=discussion_confirmsubscribe&hash=' . $data['hash'], true, '&');
1313
1314                    $mailer->subject($subject_subscribe);
1315                    $mailer->setBody($confirm_text, $confirm_replace);
1316                    $mailer->send();
1317                    $subscribers[$mail]['confirmsent'] = true;
1318                }
1319            }
1320        }
1321    }
1322
1323    /**
1324     * Counts the number of visible comments
1325     *
1326     * @param array $data
1327     * @return int
1328     */
1329    protected function _count($data) {
1330        $number = 0;
1331        foreach ($data['comments'] as $comment) {
1332            if ($comment['parent']) continue;
1333            if (!$comment['show']) continue;
1334            $number++;
1335            $rids = $comment['replies'];
1336            if (count($rids)) $number = $number + $this->_countReplies($data, $rids);
1337        }
1338        return $number;
1339    }
1340
1341    /**
1342     * @param array $data
1343     * @param array $rids
1344     * @return int
1345     */
1346    protected function _countReplies(&$data, $rids) {
1347        $number = 0;
1348        foreach ($rids as $rid) {
1349            if (!isset($data['comments'][$rid])) continue; // reply was removed
1350            if (!$data['comments'][$rid]['show']) continue;
1351            $number++;
1352            $rids = $data['comments'][$rid]['replies'];
1353            if (count($rids)) $number = $number + $this->_countReplies($data, $rids);
1354        }
1355        return $number;
1356    }
1357
1358    /**
1359     * Renders the comment text
1360     *
1361     * @param string $raw
1362     * @return null|string
1363     */
1364    protected function _render($raw) {
1365        if ($this->getConf('wikisyntaxok')) {
1366            $xhtml = $this->render_text($raw);
1367        } else { // wiki syntax not allowed -> just encode special chars
1368            $xhtml = hsc(trim($raw));
1369            $xhtml = str_replace("\n", '<br />', $xhtml);
1370        }
1371        return $xhtml;
1372    }
1373
1374    /**
1375     * Finds out whether there is a discussion section for the current page
1376     *
1377     * @param string $title
1378     * @return bool
1379     */
1380    protected function _hasDiscussion(&$title) {
1381        global $ID;
1382
1383        $cfile = metaFN($ID, '.comments');
1384
1385        if (!@file_exists($cfile)) {
1386            if ($this->isDiscussionEnabled()) {
1387                return true;
1388            } else {
1389                return false;
1390            }
1391        }
1392
1393        $comments = unserialize(io_readFile($cfile, false));
1394
1395        if ($comments['title']) $title = hsc($comments['title']);
1396        $num = $comments['number'];
1397        if ((!$comments['status']) || (($comments['status'] == 2) && (!$num))) return false;
1398        else return true;
1399    }
1400
1401    /**
1402     * Creates a new thread page
1403     *
1404     * @return string
1405     */
1406    protected function _newThread() {
1407        global $ID, $INFO;
1408
1409        $ns    = cleanID($_REQUEST['ns']);
1410        $title = str_replace(':', '', $_REQUEST['title']);
1411        $back  = $ID;
1412        $ID    = ($ns ? $ns.':' : '').cleanID($title);
1413        $INFO  = pageinfo();
1414
1415        // check if we are allowed to create this file
1416        if ($INFO['perm'] >= AUTH_CREATE) {
1417
1418            //check if locked by anyone - if not lock for my self
1419            if ($INFO['locked']) return 'locked';
1420            else lock($ID);
1421
1422            // prepare the new thread file with default stuff
1423            if (!@file_exists($INFO['filepath'])) {
1424                global $TEXT;
1425
1426                $TEXT = pageTemplate(array(($ns ? $ns.':' : '').$title));
1427                if (!$TEXT) {
1428                    $data = array('id' => $ID, 'ns' => $ns, 'title' => $title, 'back' => $back);
1429                    $TEXT = $this->_pageTemplate($data);
1430                }
1431                return 'preview';
1432            } else {
1433                return 'edit';
1434            }
1435        } else {
1436            return 'show';
1437        }
1438    }
1439
1440    /**
1441     * Adapted version of pageTemplate() function
1442     *
1443     * @param array $data
1444     * @return string
1445     */
1446    protected function _pageTemplate($data) {
1447        global $conf, $INFO;
1448
1449        $id   = $data['id'];
1450        $user = $_SERVER['REMOTE_USER'];
1451        $tpl  = io_readFile(DOKU_PLUGIN.'discussion/_template.txt');
1452
1453        // standard replacements
1454        $replace = array(
1455                '@NS@'   => $data['ns'],
1456                '@PAGE@' => strtr(noNS($id),'_',' '),
1457                '@USER@' => $user,
1458                '@NAME@' => $INFO['userinfo']['name'],
1459                '@MAIL@' => $INFO['userinfo']['mail'],
1460                '@DATE@' => dformat(time(), $conf['dformat']),
1461                );
1462
1463        // additional replacements
1464        $replace['@BACK@']  = $data['back'];
1465        $replace['@TITLE@'] = $data['title'];
1466
1467        // avatar if useavatar and avatar plugin available
1468        if ($this->getConf('useavatar')
1469                && (@file_exists(DOKU_PLUGIN.'avatar/syntax.php'))
1470                && (!plugin_isdisabled('avatar'))) {
1471            $replace['@AVATAR@'] = '{{avatar>'.$user.' }} ';
1472        } else {
1473            $replace['@AVATAR@'] = '';
1474        }
1475
1476        // tag if tag plugin is available
1477        if ((@file_exists(DOKU_PLUGIN.'tag/syntax/tag.php'))
1478                && (!plugin_isdisabled('tag'))) {
1479            $replace['@TAG@'] = "\n\n{{tag>}}";
1480        } else {
1481            $replace['@TAG@'] = '';
1482        }
1483
1484        // do the replace
1485        $tpl = str_replace(array_keys($replace), array_values($replace), $tpl);
1486        return $tpl;
1487    }
1488
1489    /**
1490     * Checks if the CAPTCHA string submitted is valid
1491     */
1492    protected function _captchaCheck() {
1493        /** @var helper_plugin_captcha $captcha */
1494        if (plugin_isdisabled('captcha') || (!$captcha = plugin_load('helper', 'captcha')))
1495            return; // CAPTCHA is disabled or not available
1496
1497        if ($captcha->isEnabled() && !$captcha->check()) {
1498            if ($_REQUEST['comment'] == 'save') $_REQUEST['comment'] = 'edit';
1499            elseif ($_REQUEST['comment'] == 'add') $_REQUEST['comment'] = 'show';
1500        }
1501    }
1502
1503    /**
1504     * checks if the submitted reCAPTCHA string is valid
1505     *
1506     * @author Adrian Schlegel <adrian@liip.ch>
1507     */
1508    protected function _recaptchaCheck() {
1509        /** @var $recaptcha helper_plugin_recaptcha */
1510        if (plugin_isdisabled('recaptcha') || (!$recaptcha = plugin_load('helper', 'recaptcha')))
1511            return; // reCAPTCHA is disabled or not available
1512
1513        // do nothing if logged in user and no reCAPTCHA required
1514        if (!$recaptcha->getConf('forusers') && $_SERVER['REMOTE_USER']) return;
1515
1516        $resp = $recaptcha->check();
1517        if (!$resp->is_valid) {
1518            msg($recaptcha->getLang('testfailed'),-1);
1519            if ($_REQUEST['comment'] == 'save') $_REQUEST['comment'] = 'edit';
1520            elseif ($_REQUEST['comment'] == 'add') $_REQUEST['comment'] = 'show';
1521        }
1522    }
1523
1524    /**
1525     * Add discussion plugin version to the indexer version
1526     * This means that all pages will be indexed again in order to add the comments
1527     * to the index whenever there has been a change that concerns the index content.
1528     *
1529     * @param Doku_Event $event
1530     * @param $param
1531     */
1532    public function idx_version(Doku_Event $event, $param) {
1533        $event->data['discussion'] = '0.1';
1534    }
1535
1536    /**
1537     * Adds the comments to the index
1538     *
1539     * @param Doku_Event $event
1540     * @param $param
1541     */
1542    public function idx_add_discussion(Doku_Event $event, $param) {
1543
1544        // get .comments meta file name
1545        $file = metaFN($event->data['page'], '.comments');
1546
1547        if (!@file_exists($file)) return;
1548        $data = unserialize(io_readFile($file, false));
1549        if ((!$data['status']) || ($data['number'] == 0)) return; // comments are turned off
1550
1551        // now add the comments
1552        if (isset($data['comments'])) {
1553            foreach ($data['comments'] as $key => $value) {
1554                $event->data['body'] .= $this->_addCommentWords($key, $data);
1555            }
1556        }
1557    }
1558
1559    /**
1560     * Saves the current comment status and title in the .comments file
1561     *
1562     * @param Doku_Event $event
1563     * @param $param
1564     */
1565    public function update_comment_status(Doku_Event $event, $param) {
1566        global $ID;
1567
1568        $meta = $event->data['current'];
1569        $file = metaFN($ID, '.comments');
1570        $status = ($this->isDiscussionEnabled() ? 1 : 0);
1571        $title = NULL;
1572        if (isset($meta['plugin_discussion'])) {
1573            $status = $meta['plugin_discussion']['status'];
1574            $title = $meta['plugin_discussion']['title'];
1575        } else if ($status == 1) {
1576            // Don't enable comments when automatic comments are on - this already happens automatically
1577            // and if comments are turned off in the admin this only updates the .comments file
1578            return;
1579        }
1580
1581        if ($status || @file_exists($file)) {
1582            $data = array();
1583            if (@file_exists($file)) {
1584                $data = unserialize(io_readFile($file, false));
1585            }
1586
1587            if (!array_key_exists('title', $data) || $data['title'] !== $title || !isset($data['status']) || $data['status'] !== $status) {
1588                $data['title']  = $title;
1589                $data['status'] = $status;
1590                if (!isset($data['number']))
1591                    $data['number'] = 0;
1592                io_saveFile($file, serialize($data));
1593            }
1594        }
1595    }
1596
1597    /**
1598     * Adds the words of a given comment to the index
1599     *
1600     * @param string $cid
1601     * @param array  $data
1602     * @param string $parent
1603     * @return string
1604     */
1605    protected function _addCommentWords($cid, &$data, $parent = '') {
1606
1607        if (!isset($data['comments'][$cid])) return ''; // comment was removed
1608        $comment = $data['comments'][$cid];
1609
1610        if (!is_array($comment)) return '';             // corrupt datatype
1611        if ($comment['parent'] != $parent) return '';   // reply to an other comment
1612        if (!$comment['show']) return '';               // hidden comment
1613
1614        $text = $comment['raw'];                        // we only add the raw comment text
1615        if (is_array($comment['replies'])) {             // and the replies
1616            foreach ($comment['replies'] as $rid) {
1617                $text .= $this->_addCommentWords($rid, $data, $cid);
1618            }
1619        }
1620        return ' '.$text;
1621    }
1622
1623    /**
1624     * Only allow http(s) URLs and append http:// to URLs if needed
1625     *
1626     * @param string $url
1627     * @return string
1628     */
1629    protected function _checkURL($url) {
1630        if(preg_match("#^http://|^https://#", $url)) {
1631            return hsc($url);
1632        } elseif(substr($url, 0, 4) == 'www.') {
1633            return hsc('http://' . $url);
1634        } else {
1635            return '';
1636        }
1637    }
1638}
1639
1640/**
1641 * Sort threads
1642 *
1643 * @param $a
1644 * @param $b
1645 * @return int
1646 */
1647    function _sortCallback($a, $b) {
1648        if (is_array($a['date'])) { // new format
1649            $createdA  = $a['date']['created'];
1650        } else {                         // old format
1651            $createdA  = $a['date'];
1652        }
1653
1654        if (is_array($b['date'])) { // new format
1655            $createdB  = $b['date']['created'];
1656        } else {                         // old format
1657            $createdB  = $b['date'];
1658        }
1659
1660        if ($createdA == $createdB)
1661            return 0;
1662        else
1663            return ($createdA < $createdB) ? -1 : 1;
1664    }
1665
1666// vim:ts=4:sw=4:et:enc=utf-8:
1667