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