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