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