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