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