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