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