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