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