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