xref: /plugin/discussion/action.php (revision 2feceb676459c0068310e5d98ac437a8533669af)
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
716        if ($address) $head .= ', <span class="adr">'.$address.'</span>';
717        $head .= '</span>, '.
718            '<abbr class="published" title="'. strftime('%Y-%m-%dT%H:%M:%SZ', $created) .'">'.
719            dformat($created, $conf['dformat']).'</abbr>';
720        if ($comment['edited']) $head .= ' (<abbr class="updated" title="'.
721                strftime('%Y-%m-%dT%H:%M:%SZ', $modified).'">'.dformat($modified, $conf['dformat']).
722                '</abbr>)';
723        ptln($head, 8);
724        ptln('</div>', 6); // class="comment_head"
725
726        // main comment content
727        ptln('<div class="comment_body entry-content"'.
728                ($this->getConf('useavatar') ? $this->_get_style() : '').'>', 6);
729        echo ($HIGH?html_hilight($comment['xhtml'],$HIGH):$comment['xhtml']).DOKU_LF;
730        ptln('</div>', 6); // class="comment_body"
731
732        if ($visible) {
733            ptln('<div class="comment_buttons">', 6);
734
735            // show reply button?
736            if (($data['status'] == 1) && !$reply && $comment['show']
737                    && ($this->getConf('allowguests') || $_SERVER['REMOTE_USER']) && $this->getConf('usethreading'))
738                $this->_button($cid, $this->getLang('btn_reply'), 'reply', true);
739
740            // show edit, show/hide and delete button?
741            if ((($user == $_SERVER['REMOTE_USER']) && ($user != '')) || (auth_ismanager())) {
742                $this->_button($cid, $lang['btn_secedit'], 'edit', true);
743                $label = ($comment['show'] ? $this->getLang('btn_hide') : $this->getLang('btn_show'));
744                $this->_button($cid, $label, 'toogle');
745                $this->_button($cid, $lang['btn_delete'], 'delete');
746            }
747            ptln('</div>', 6); // class="comment_buttons"
748        }
749        ptln('</div>', 4); // class="hentry"
750    }
751
752    function _print_form($cid, $reply)
753    {
754        if ($this->getConf('usethreading') && $reply == $cid) {
755            ptln('<div class="comment_replies">', 4);
756            $this->_form('', 'add', $cid);
757            ptln('</div>', 4); // class="comment_replies"
758        }
759    }
760
761    function _print_replies($cid, &$data, $reply, &$visible)
762    {
763        $comment = $data['comments'][$cid];
764        if (!count($comment['replies'])) {
765            return;
766        }
767        ptln('<div class="comment_replies"'.$this->_get_style().'>', 4);
768        $visible = ($comment['show'] && $visible);
769        foreach ($comment['replies'] as $rid) {
770            $this->_print($rid, $data, $cid, $reply, $visible);
771        }
772        ptln('</div>', 4);
773    }
774
775    function _use_avatar()
776    {
777        if (is_null($this->use_avatar)) {
778            $this->use_avatar = $this->getConf('useavatar')
779                    && (!plugin_isdisabled('avatar'))
780                    && ($this->avatar =& plugin_load('helper', 'avatar'));
781        }
782        return $this->use_avatar;
783    }
784
785    function _get_style()
786    {
787        if (is_null($this->style)){
788            if ($this->_use_avatar()) {
789                $this->style = ' style="margin-left: '.($this->avatar->getConf('size') + 14).'px;"';
790            } else {
791                $this->style = ' style="margin-left: 20px;"';
792            }
793        }
794        return $this->style;
795    }
796
797    /**
798     * Outputs the comment form
799     */
800    function _form($raw = '', $act = 'add', $cid = NULL) {
801        global $lang;
802        global $conf;
803        global $ID;
804        global $INFO;
805
806        // not for unregistered users when guest comments aren't allowed
807        if (!$_SERVER['REMOTE_USER'] && !$this->getConf('allowguests')) {
808            ?>
809            <div class="comment_form">
810                <?php echo $this->getLang('noguests'); ?>
811            </div>
812            <?php
813            return false;
814        }
815
816        // fill $raw with $_REQUEST['text'] if it's empty (for failed CAPTCHA check)
817        if (!$raw && ($_REQUEST['comment'] == 'show')) $raw = $_REQUEST['text'];
818        ?>
819
820        <div class="comment_form">
821          <form id="discussion__comment_form" method="post" action="<?php echo script() ?>" accept-charset="<?php echo $lang['encoding'] ?>">
822            <div class="no">
823              <input type="hidden" name="id" value="<?php echo $ID ?>" />
824              <input type="hidden" name="do" value="show" />
825              <input type="hidden" name="comment" value="<?php echo $act ?>" />
826        <?php
827        // for adding a comment
828        if ($act == 'add') {
829        ?>
830              <input type="hidden" name="reply" value="<?php echo $cid ?>" />
831        <?php
832        // for guest/adminimport: show name, e-mail and subscribe to comments fields
833        if(!$_SERVER['REMOTE_USER'] or ($this->getConf('adminimport') && auth_ismanager())) {
834        ?>
835              <input type="hidden" name="user" value="<?php echo clientIP() ?>" />
836              <div class="comment_name">
837                <label class="block" for="discussion__comment_name">
838                  <span><?php echo $lang['fullname'] ?>:</span>
839                  <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'])?>" />
840                </label>
841              </div>
842              <div class="comment_mail">
843                <label class="block" for="discussion__comment_mail">
844                  <span><?php echo $lang['email'] ?>:</span>
845                  <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'])?>" />
846                </label>
847              </div>
848        <?php
849        }
850
851        // allow entering an URL
852        if ($this->getConf('urlfield')) {
853        ?>
854              <div class="comment_url">
855                <label class="block" for="discussion__comment_url">
856                  <span><?php echo $this->getLang('url') ?>:</span>
857                  <input type="text" class="edit" name="url" id="discussion__comment_url" size="50" tabindex="3" value="<?php echo hsc($_REQUEST['url'])?>" />
858                </label>
859              </div>
860        <?php
861        }
862
863        // allow entering an address
864        if ($this->getConf('addressfield')) {
865        ?>
866              <div class="comment_address">
867                <label class="block" for="discussion__comment_address">
868                  <span><?php echo $this->getLang('address') ?>:</span>
869                  <input type="text" class="edit" name="address" id="discussion__comment_address" size="50" tabindex="4" value="<?php echo hsc($_REQUEST['address'])?>" />
870                </label>
871              </div>
872        <?php
873        }
874
875        // allow setting the comment date
876        if ($this->getConf('adminimport') && (auth_ismanager())) {
877        ?>
878              <div class="comment_date">
879                <label class="block" for="discussion__comment_date">
880                  <span><?php echo $this->getLang('date') ?>:</span>
881                  <input type="text" class="edit" name="date" id="discussion__comment_date" size="50" />
882                </label>
883              </div>
884        <?php
885        }
886
887        // for saving a comment
888        } else {
889        ?>
890              <input type="hidden" name="cid" value="<?php echo $cid ?>" />
891        <?php
892        }
893        ?>
894                <div class="comment_text">
895                  <?php echo $this->getLang('entercomment'); echo ($this->getConf('wikisyntaxok') ? "" : ":");
896                        if($this->getConf('wikisyntaxok')) echo '. ' . $this->getLang('wikisyntax') . ':'; ?>
897
898                  <!-- Fix for disable the toolbar when wikisyntaxok is set to false. See discussion's script.jss -->
899                  <?php if($this->getConf('wikisyntaxok')) { ?>
900                    <div id="discussion__comment_toolbar">
901                  <?php } else { ?>
902                    <div id="discussion__comment_toolbar_disabled">
903                  <?php } ?>
904                </div>
905                <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
906                  if($raw) {
907                      echo formText($raw);
908                  } else {
909                      echo $_REQUEST['text'];
910                  }
911                ?></textarea>
912              </div>
913        <?php //bad and dirty event insert hook
914        $evdata = array('writable' => true);
915        trigger_event('HTML_EDITFORM_INJECTION', $evdata);
916        ?>
917              <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" />
918              <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]" />
919
920        <?php if((!$_SERVER['REMOTE_USER'] || $_SERVER['REMOTE_USER'] && !$conf['subscribers']) && $this->getConf('subscribe')) { ?>
921              <div class="comment_subscribe">
922                <input type="checkbox" id="discussion__comment_subscribe" name="subscribe" tabindex="6" />
923                <label class="block" for="discussion__comment_subscribe">
924                  <span><?php echo $this->getLang('subscribe') ?></span>
925                </label>
926              </div>
927        <?php } ?>
928
929              <div class="clearer"></div>
930              <div id="discussion__comment_preview">&nbsp;</div>
931            </div>
932          </form>
933        </div>
934        <?php
935        if ($this->getConf('usecocomment')) echo $this->_coComment();
936    }
937
938    /**
939     * Adds a javascript to interact with coComments
940     */
941    function _coComment() {
942        global $ID;
943        global $conf;
944        global $INFO;
945
946        $user = $_SERVER['REMOTE_USER'];
947
948        ?>
949        <script type="text/javascript"><!--//--><![CDATA[//><!--
950          var blogTool  = "DokuWiki";
951          var blogURL   = "<?php echo DOKU_URL ?>";
952          var blogTitle = "<?php echo $conf['title'] ?>";
953          var postURL   = "<?php echo wl($ID, '', true) ?>";
954          var postTitle = "<?php echo tpl_pagetitle($ID, true) ?>";
955        <?php
956        if ($user) {
957        ?>
958          var commentAuthor = "<?php echo $INFO['userinfo']['name'] ?>";
959        <?php
960        } else {
961        ?>
962          var commentAuthorFieldName = "name";
963        <?php
964        }
965        ?>
966          var commentAuthorLoggedIn = <?php echo ($user ? 'true' : 'false') ?>;
967          var commentFormID         = "discussion__comment_form";
968          var commentTextFieldName  = "text";
969          var commentButtonName     = "submit";
970          var cocomment_force       = false;
971        //--><!]]></script>
972        <script type="text/javascript" src="http://www.cocomment.com/js/cocomment.js">
973        </script>
974        <?php
975    }
976
977    /**
978     * General button function
979     */
980    function _button($cid, $label, $act, $jump = false) {
981        global $ID;
982
983        $anchor = ($jump ? '#discussion__comment_form' : '' );
984
985        ?>
986        <form class="button discussion__<?php echo $act?>" method="get" action="<?php echo script().$anchor ?>">
987          <div class="no">
988            <input type="hidden" name="id" value="<?php echo $ID ?>" />
989            <input type="hidden" name="do" value="show" />
990            <input type="hidden" name="comment" value="<?php echo $act ?>" />
991            <input type="hidden" name="cid" value="<?php echo $cid ?>" />
992            <input type="submit" value="<?php echo $label ?>" class="button" title="<?php echo $label ?>" />
993          </div>
994        </form>
995        <?php
996        return true;
997    }
998
999    /**
1000     * Adds an entry to the comments changelog
1001     *
1002     * @author Esther Brunner <wikidesign@gmail.com>
1003     * @author Ben Coburn <btcoburn@silicodon.net>
1004     */
1005    function _addLogEntry($date, $id, $type = 'cc', $summary = '', $extra = '') {
1006        global $conf;
1007
1008        $changelog = $conf['metadir'].'/_comments.changes';
1009
1010        if(!$date) $date = time(); //use current time if none supplied
1011        $remote = $_SERVER['REMOTE_ADDR'];
1012        $user   = $_SERVER['REMOTE_USER'];
1013
1014        $strip = array("\t", "\n");
1015        $logline = array(
1016                'date'  => $date,
1017                'ip'    => $remote,
1018                'type'  => str_replace($strip, '', $type),
1019                'id'    => $id,
1020                'user'  => $user,
1021                'sum'   => str_replace($strip, '', $summary),
1022                'extra' => str_replace($strip, '', $extra)
1023                );
1024
1025        // add changelog line
1026        $logline = implode("\t", $logline)."\n";
1027        io_saveFile($changelog, $logline, true); //global changelog cache
1028        $this->_trimRecentCommentsLog($changelog);
1029
1030        // tell the indexer to re-index the page
1031        @unlink(metaFN($id, '.indexed'));
1032    }
1033
1034    /**
1035     * Trims the recent comments cache to the last $conf['changes_days'] recent
1036     * changes or $conf['recent'] items, which ever is larger.
1037     * The trimming is only done once a day.
1038     *
1039     * @author Ben Coburn <btcoburn@silicodon.net>
1040     */
1041    function _trimRecentCommentsLog($changelog) {
1042        global $conf;
1043
1044        if (@file_exists($changelog) &&
1045                (filectime($changelog) + 86400) < time() &&
1046                !@file_exists($changelog.'_tmp')) {
1047
1048            io_lock($changelog);
1049            $lines = file($changelog);
1050            if (count($lines)<$conf['recent']) {
1051                // nothing to trim
1052                io_unlock($changelog);
1053                return true;
1054            }
1055
1056            io_saveFile($changelog.'_tmp', '');                  // presave tmp as 2nd lock
1057            $trim_time = time() - $conf['recent_days']*86400;
1058            $out_lines = array();
1059
1060            $num = count($lines);
1061            for ($i=0; $i<$num; $i++) {
1062                $log = parseChangelogLine($lines[$i]);
1063                if ($log === false) continue;                      // discard junk
1064                if ($log['date'] < $trim_time) {
1065                    $old_lines[$log['date'].".$i"] = $lines[$i];     // keep old lines for now (append .$i to prevent key collisions)
1066                } else {
1067                    $out_lines[$log['date'].".$i"] = $lines[$i];     // definitely keep these lines
1068                }
1069            }
1070
1071            // sort the final result, it shouldn't be necessary,
1072            // however the extra robustness in making the changelog cache self-correcting is worth it
1073            ksort($out_lines);
1074            $extra = $conf['recent'] - count($out_lines);        // do we need extra lines do bring us up to minimum
1075            if ($extra > 0) {
1076                ksort($old_lines);
1077                $out_lines = array_merge(array_slice($old_lines,-$extra),$out_lines);
1078            }
1079
1080            // save trimmed changelog
1081            io_saveFile($changelog.'_tmp', implode('', $out_lines));
1082            @unlink($changelog);
1083            if (!rename($changelog.'_tmp', $changelog)) {
1084                // rename failed so try another way...
1085                io_unlock($changelog);
1086                io_saveFile($changelog, implode('', $out_lines));
1087                @unlink($changelog.'_tmp');
1088            } else {
1089                io_unlock($changelog);
1090            }
1091            return true;
1092        }
1093    }
1094
1095    /**
1096     * Sends a notify mail on new comment
1097     *
1098     * @param  array  $comment  data array of the new comment
1099     *
1100     * @author Andreas Gohr <andi@splitbrain.org>
1101     * @author Esther Brunner <wikidesign@gmail.com>
1102     */
1103    function _notify($comment, &$subscribers) {
1104        global $conf;
1105        global $ID;
1106        global $INFO;
1107
1108        $notify_text = io_readfile($this->localfn('subscribermail'));
1109        $confirm_text = io_readfile($this->localfn('confirmsubscribe'));
1110        $subject_notify = '['.$conf['title'].'] '.$this->getLang('mail_newcomment');
1111        $subject_subscribe = '['.$conf['title'].'] '.$this->getLang('subscribe');
1112        $from = $conf['mailfrom'];
1113        $from = str_replace('@USER@',$_SERVER['REMOTE_USER'],$from);
1114        $from = str_replace('@NAME@',$INFO['userinfo']['name'],$from);
1115        $from = str_replace('@MAIL@',$INFO['userinfo']['mail'],$from);
1116
1117        $search = array(
1118                '@PAGE@',
1119                '@TITLE@',
1120                '@DATE@',
1121                '@NAME@',
1122                '@TEXT@',
1123                '@COMMENTURL@',
1124                '@UNSUBSCRIBE@',
1125                '@DOKUWIKIURL@',
1126        );
1127
1128        // prepare email body
1129        if($conf['notify'] || $conf['subscribers']) {
1130            $replace = array(
1131                    $ID,
1132                    $conf['title'],
1133                    dformat($comment['date']['created'], $conf['dformat']),
1134                    $comment['user']['name'],
1135                    $comment['raw'],
1136                    wl($ID, '', true) . '#comment_' . $comment['cid'],
1137                    wl($ID, 'do=unsubscribe', true, '&'),
1138                    DOKU_URL,
1139                    );
1140            $body = str_replace($search, $replace, $notify_text);
1141        }
1142
1143        // send mail to notify address
1144        if ($conf['notify']) {
1145            $to = $conf['notify'];
1146            mail_send($to, $subject_notify, $body, $from, '', '');
1147        }
1148
1149        // notify page subscribers
1150        if ($conf['subscribers']) {
1151            $to   = ''; // put all recipients in bcc field
1152            $data = array('id' => $ID, 'addresslist' => '', 'self' => false);
1153            trigger_event('COMMON_NOTIFY_ADDRESSLIST', $data, 'subscription_addresslist');
1154            $bcc = $data['addresslist'];
1155            mail_send($to, $subject_notify, $body, $from, '', $bcc);
1156        }
1157
1158        // notify comment subscribers
1159        if (!empty($subscribers)) {
1160
1161            foreach($subscribers as $mail => $data) {
1162                $to = $mail;
1163
1164                if($data['active']) {
1165                    $replace = array(
1166                            $ID,
1167                            $conf['title'],
1168                            dformat($comment['date']['created'], $conf['dformat']),
1169                            $comment['user']['name'],
1170                            $comment['raw'],
1171                            wl($ID, '', true) . '#comment_' . $comment['cid'],
1172                            wl($ID, 'do=discussion_unsubscribe&hash=' . $data['hash'], true, '&'),
1173                            DOKU_URL,
1174                            );
1175
1176                    $body = str_replace($search, $replace, $notify_text);
1177                    mail_send($to, $subject_notify, $body, $from);
1178                } elseif(!$data['active'] && !$data['confirmsent']) {
1179                    $search = array(
1180                            '@PAGE@',
1181                            '@TITLE@',
1182                            '@SUBSCRIBE@',
1183                            '@DOKUWIKIURL@',
1184                            );
1185                    $replace = array(
1186                            $ID,
1187                            $conf['title'],
1188                            wl($ID, 'do=discussion_confirmsubscribe&hash=' . $data['hash'], true, '&'),
1189                            DOKU_URL,
1190                            );
1191
1192                    $body = str_replace($search, $replace, $confirm_text);
1193                    mail_send($to, $subject_subscribe, $body, $from);
1194                    $subscribers[$mail]['confirmsent'] = true;
1195                }
1196            }
1197        }
1198    }
1199
1200    /**
1201     * Counts the number of visible comments
1202     */
1203    function _count($data) {
1204        $number = 0;
1205        foreach ($data['comments'] as $cid => $comment) {
1206            if ($comment['parent']) continue;
1207            if (!$comment['show']) continue;
1208            $number++;
1209            $rids = $comment['replies'];
1210            if (count($rids)) $number = $number + $this->_countReplies($data, $rids);
1211        }
1212        return $number;
1213    }
1214
1215    function _countReplies(&$data, $rids) {
1216        $number = 0;
1217        foreach ($rids as $rid) {
1218            if (!isset($data['comments'][$rid])) continue; // reply was removed
1219            if (!$data['comments'][$rid]['show']) continue;
1220            $number++;
1221            $rids = $data['comments'][$rid]['replies'];
1222            if (count($rids)) $number = $number + $this->_countReplies($data, $rids);
1223        }
1224        return $number;
1225    }
1226
1227    /**
1228     * Renders the comment text
1229     */
1230    function _render($raw) {
1231        if ($this->getConf('wikisyntaxok')) {
1232            $xhtml = $this->render($raw);
1233        } else { // wiki syntax not allowed -> just encode special chars
1234            $xhtml = hsc(trim($raw));
1235            $xhtml = str_replace("\n", '<br />', $xhtml);
1236        }
1237        return $xhtml;
1238    }
1239
1240    /**
1241     * Finds out whether there is a discussion section for the current page
1242     */
1243    function _hasDiscussion(&$title) {
1244        global $ID;
1245
1246        $cfile = metaFN($ID, '.comments');
1247
1248        if (!@file_exists($cfile)) {
1249            if ($this->getConf('automatic')) {
1250                return true;
1251            } else {
1252                return false;
1253            }
1254        }
1255
1256        $comments = unserialize(io_readFile($cfile, false));
1257
1258        if ($comments['title']) $title = hsc($comments['title']);
1259        $num = $comments['number'];
1260        if ((!$comments['status']) || (($comments['status'] == 2) && (!$num))) return false;
1261        else return true;
1262    }
1263
1264    /**
1265     * Creates a new thread page
1266     */
1267    function _newThread() {
1268        global $ID, $INFO;
1269
1270        $ns    = cleanID($_REQUEST['ns']);
1271        $title = str_replace(':', '', $_REQUEST['title']);
1272        $back  = $ID;
1273        $ID    = ($ns ? $ns.':' : '').cleanID($title);
1274        $INFO  = pageinfo();
1275
1276        // check if we are allowed to create this file
1277        if ($INFO['perm'] >= AUTH_CREATE) {
1278
1279            //check if locked by anyone - if not lock for my self
1280            if ($INFO['locked']) return 'locked';
1281            else lock($ID);
1282
1283            // prepare the new thread file with default stuff
1284            if (!@file_exists($INFO['filepath'])) {
1285                global $TEXT;
1286
1287                $TEXT = pageTemplate(array(($ns ? $ns.':' : '').$title));
1288                if (!$TEXT) {
1289                    $data = array('id' => $ID, 'ns' => $ns, 'title' => $title, 'back' => $back);
1290                    $TEXT = $this->_pageTemplate($data);
1291                }
1292                return 'preview';
1293            } else {
1294                return 'edit';
1295            }
1296        } else {
1297            return 'show';
1298        }
1299    }
1300
1301    /**
1302     * Adapted version of pageTemplate() function
1303     */
1304    function _pageTemplate($data) {
1305        global $conf, $INFO;
1306
1307        $id   = $data['id'];
1308        $user = $_SERVER['REMOTE_USER'];
1309        $tpl  = io_readFile(DOKU_PLUGIN.'discussion/_template.txt');
1310
1311        // standard replacements
1312        $replace = array(
1313                '@NS@'   => $data['ns'],
1314                '@PAGE@' => strtr(noNS($id),'_',' '),
1315                '@USER@' => $user,
1316                '@NAME@' => $INFO['userinfo']['name'],
1317                '@MAIL@' => $INFO['userinfo']['mail'],
1318                '@DATE@' => dformat($conf['dformat']),
1319                );
1320
1321        // additional replacements
1322        $replace['@BACK@']  = $data['back'];
1323        $replace['@TITLE@'] = $data['title'];
1324
1325        // avatar if useavatar and avatar plugin available
1326        if ($this->getConf('useavatar')
1327                && (@file_exists(DOKU_PLUGIN.'avatar/syntax.php'))
1328                && (!plugin_isdisabled('avatar'))) {
1329            $replace['@AVATAR@'] = '{{avatar>'.$user.' }} ';
1330        } else {
1331            $replace['@AVATAR@'] = '';
1332        }
1333
1334        // tag if tag plugin is available
1335        if ((@file_exists(DOKU_PLUGIN.'tag/syntax/tag.php'))
1336                && (!plugin_isdisabled('tag'))) {
1337            $replace['@TAG@'] = "\n\n{{tag>}}";
1338        } else {
1339            $replace['@TAG@'] = '';
1340        }
1341
1342        // do the replace
1343        $tpl = str_replace(array_keys($replace), array_values($replace), $tpl);
1344        return $tpl;
1345    }
1346
1347    /**
1348     * Checks if the CAPTCHA string submitted is valid
1349     *
1350     * @author     Andreas Gohr <gohr@cosmocode.de>
1351     * @adaption   Esther Brunner <wikidesign@gmail.com>
1352     */
1353    function _captchaCheck() {
1354        if (plugin_isdisabled('captcha') || (!$captcha = plugin_load('helper', 'captcha')))
1355            return; // CAPTCHA is disabled or not available
1356
1357        // do nothing if logged in user and no CAPTCHA required
1358        if (!$captcha->getConf('forusers') && $_SERVER['REMOTE_USER']) return;
1359
1360        // compare provided string with decrypted captcha
1361        $rand = PMA_blowfish_decrypt($_REQUEST['plugin__captcha_secret'], auth_cookiesalt());
1362        $code = $captcha->_generateCAPTCHA($captcha->_fixedIdent(), $rand);
1363
1364        if (!$_REQUEST['plugin__captcha_secret'] ||
1365                !$_REQUEST['plugin__captcha'] ||
1366                strtoupper($_REQUEST['plugin__captcha']) != $code) {
1367
1368            // CAPTCHA test failed! Continue to edit instead of saving
1369            msg($captcha->getLang('testfailed'), -1);
1370            if ($_REQUEST['comment'] == 'save') $_REQUEST['comment'] = 'edit';
1371            elseif ($_REQUEST['comment'] == 'add') $_REQUEST['comment'] = 'show';
1372        }
1373        // if we arrive here it was a valid save
1374    }
1375
1376    /**
1377     * checks if the submitted reCAPTCHA string is valid
1378     *
1379     * @author Adrian Schlegel <adrian@liip.ch>
1380     */
1381    function _recaptchaCheck() {
1382        if (plugin_isdisabled('recaptcha') || (!$recaptcha = plugin_load('helper', 'recaptcha')))
1383            return; // reCAPTCHA is disabled or not available
1384
1385        // do nothing if logged in user and no reCAPTCHA required
1386        if (!$recaptcha->getConf('forusers') && $_SERVER['REMOTE_USER']) return;
1387
1388        $resp = $recaptcha->check();
1389        if (!$resp->is_valid) {
1390            msg($recaptcha->getLang('testfailed'),-1);
1391            if ($_REQUEST['comment'] == 'save') $_REQUEST['comment'] = 'edit';
1392            elseif ($_REQUEST['comment'] == 'add') $_REQUEST['comment'] = 'show';
1393        }
1394    }
1395
1396    /**
1397     * Adds the comments to the index
1398     */
1399    function idx_add_discussion(&$event, $param) {
1400
1401        // get .comments meta file name
1402        $file = metaFN($event->data[0], '.comments');
1403
1404        if (@file_exists($file)) $data = unserialize(io_readFile($file, false));
1405        if ((!$data['status']) || ($data['number'] == 0)) return; // comments are turned off
1406
1407        // now add the comments
1408        if (isset($data['comments'])) {
1409            foreach ($data['comments'] as $key => $value) {
1410                $event->data[1] .= $this->_addCommentWords($key, $data);
1411            }
1412        }
1413    }
1414
1415    /**
1416     * Adds the words of a given comment to the index
1417     */
1418    function _addCommentWords($cid, &$data, $parent = '') {
1419
1420        if (!isset($data['comments'][$cid])) return ''; // comment was removed
1421        $comment = $data['comments'][$cid];
1422
1423        if (!is_array($comment)) return '';             // corrupt datatype
1424        if ($comment['parent'] != $parent) return '';   // reply to an other comment
1425        if (!$comment['show']) return '';               // hidden comment
1426
1427        $text = $comment['raw'];                        // we only add the raw comment text
1428        if (is_array($comment['replies'])) {             // and the replies
1429            foreach ($comment['replies'] as $rid) {
1430                $text .= $this->_addCommentWords($rid, $data, $cid);
1431            }
1432        }
1433        return ' '.$text;
1434    }
1435
1436    /**
1437     * Only allow http(s) URLs and append http:// to URLs if needed
1438     */
1439    function _checkURL($url) {
1440        if(preg_match("#^http://|^https://#", $url)) {
1441            return hsc($url);
1442        } elseif(substr($url, 0, 4) == 'www.') {
1443            return hsc('http://' . $url);
1444        } else {
1445            return '';
1446        }
1447    }
1448}
1449
1450function _sortCallback($a, $b) {
1451    if (is_array($a['date'])) { // new format
1452        $createdA  = $a['date']['created'];
1453    } else {                         // old format
1454        $createdA  = $a['date'];
1455    }
1456
1457    if (is_array($b['date'])) { // new format
1458        $createdB  = $b['date']['created'];
1459    } else {                         // old format
1460        $createdB  = $b['date'];
1461    }
1462
1463    if ($createdA == $createdB)
1464        return 0;
1465    else
1466        return ($createdA < $createdB) ? -1 : 1;
1467}
1468
1469// vim:ts=4:sw=4:et:enc=utf-8:
1470