xref: /plugin/discussion/action.php (revision a15998500c98ea06cebea4d5a42e0d1bbc1d6570)
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        // show discussion wrapper only on certain circumstances
335        $cnt = count($data['comments']);
336        $keys = array_keys($data['comments']);
337        if($cnt > 1 || ($cnt == 1 && $data['comments'][$keys[0]]['show'] == 1) || $this->getConf('allowguests') || isset($_SERVER['REMOTE_USER'])) {
338            $show = true;
339            // section title
340            $title = ($data['title'] ? hsc($data['title']) : $this->getLang('discussion'));
341            ptln('<div class="comment_wrapper">');
342            ptln('<h2><a name="discussion__section" id="discussion__section">', 2);
343            ptln($title, 4);
344            ptln('</a></h2>', 2);
345            ptln('<div class="level2 hfeed">', 2);
346        }
347
348        // now display the comments
349        if (isset($data['comments'])) {
350            if (!$this->getConf('usethreading')) {
351                $data['comments'] = $this->_flattenThreads($data['comments']);
352                uasort($data['comments'], '_sortCallBack');
353            }
354            if($this->getConf('newestfirst')) {
355                $data['comments'] = array_reverse($data['comments']);
356            }
357            foreach ($data['comments'] as $key => $value) {
358                if ($key == $edit) $this->_form($value['raw'], 'save', $edit); // edit form
359                else $this->_print($key, $data, '', $reply);
360            }
361        }
362
363        // comment form
364        if (($data['status'] == 1) && (!$reply || !$this->getConf('usethreading')) && !$edit) $this->_form('');
365
366        if($show) {
367            ptln('</div>', 2); // level2 hfeed
368            ptln('</div>'); // comment_wrapper
369        }
370
371        return true;
372    }
373
374    function _flattenThreads($comments, $keys = null) {
375        if (is_null($keys))
376            $keys = array_keys($comments);
377
378        foreach($keys as $cid) {
379            if (!empty($comments[$cid]['replies'])) {
380                $rids = $comments[$cid]['replies'];
381                $comments = $this->_flattenThreads($comments, $rids);
382                $comments[$cid]['replies'] = array();
383            }
384            $comments[$cid]['parent'] = '';
385        }
386        return $comments;
387    }
388
389    /**
390     * Adds a new comment and then displays all comments
391     */
392    function _add($comment, $parent) {
393        global $lang;
394        global $ID;
395        global $TEXT;
396
397        $otxt = $TEXT; // set $TEXT to comment text for wordblock check
398        $TEXT = $comment['raw'];
399
400        // spamcheck against the DokuWiki blacklist
401        if (checkwordblock()) {
402            msg($this->getLang('wordblock'), -1);
403            return false;
404        }
405
406        if ((!$this->getConf('allowguests'))
407                && ($comment['user']['id'] != $_SERVER['REMOTE_USER']))
408            return false; // guest comments not allowed
409
410        $TEXT = $otxt; // restore global $TEXT
411
412        // get discussion meta file name
413        $file = metaFN($ID, '.comments');
414
415        // create comments file if it doesn't exist yet
416        if(!@file_exists($file)) {
417            $data = array('status' => 1, 'number' => 0);
418            io_saveFile($file, serialize($data));
419        } else {
420            $data = array();
421            $data = unserialize(io_readFile($file, false));
422            if ($data['status'] != 1) return false; // comments off or closed
423        }
424
425        if ($comment['date']['created']) {
426            $date = strtotime($comment['date']['created']);
427        } else {
428            $date = time();
429        }
430
431        if ($date == -1) {
432            $date = time();
433        }
434
435        $cid  = md5($comment['user']['id'].$date); // create a unique id
436
437        if (!is_array($data['comments'][$parent])) {
438            $parent = NULL; // invalid parent comment
439        }
440
441        // render the comment
442        $xhtml = $this->_render($comment['raw']);
443
444        // fill in the new comment
445        $data['comments'][$cid] = array(
446                'user'    => $comment['user'],
447                'date'    => array('created' => $date),
448                'show'    => true,
449                'raw'     => $comment['raw'],
450                'xhtml'   => $xhtml,
451                'parent'  => $parent,
452                'replies' => array(),
453                'show'    => $comment['show']
454                );
455
456        if($comment['subscribe']) {
457            $mail = $comment['user']['mail'];
458            if($data['subscribers']) {
459                if(!$data['subscribers'][$mail]) {
460                    $data['subscribers'][$mail]['hash'] = md5($mail . mt_rand());
461                    $data['subscribers'][$mail]['active'] = false;
462                    $data['subscribers'][$mail]['confirmsent'] = false;
463                } else {
464                    // convert old style subscribers and set them active
465                    if(!is_array($data['subscribers'][$mail])) {
466                        $hash = $data['subscribers'][$mail];
467                        $data['subscribers'][$mail]['hash'] = $hash;
468                        $data['subscribers'][$mail]['active'] = true;
469                        $data['subscribers'][$mail]['confirmsent'] = true;
470                    }
471                }
472            } else {
473                $data['subscribers'][$mail]['hash']   = md5($mail . mt_rand());
474                $data['subscribers'][$mail]['active'] = false;
475                $data['subscribers'][$mail]['confirmsent'] = false;
476            }
477        }
478
479        // update parent comment
480        if ($parent) $data['comments'][$parent]['replies'][] = $cid;
481
482        // update the number of comments
483        $data['number']++;
484
485        // notify subscribers of the page
486        $data['comments'][$cid]['cid'] = $cid;
487        $this->_notify($data['comments'][$cid], $data['subscribers']);
488
489        // save the comment metadata file
490        io_saveFile($file, serialize($data));
491        $this->_addLogEntry($date, $ID, 'cc', '', $cid);
492
493        $this->_redirect($cid);
494        return true;
495    }
496
497    /**
498     * Saves the comment with the given ID and then displays all comments
499     */
500    function _save($cids, $raw, $act = NULL) {
501        global $ID;
502
503        if(!$cids) return; // do nothing if we get no comment id
504
505        if ($raw) {
506            global $TEXT;
507
508            $otxt = $TEXT; // set $TEXT to comment text for wordblock check
509            $TEXT = $raw;
510
511            // spamcheck against the DokuWiki blacklist
512            if (checkwordblock()) {
513                msg($this->getLang('wordblock'), -1);
514                return false;
515            }
516
517            $TEXT = $otxt; // restore global $TEXT
518        }
519
520        // get discussion meta file name
521        $file = metaFN($ID, '.comments');
522        $data = unserialize(io_readFile($file, false));
523
524        if (!is_array($cids)) $cids = array($cids);
525        foreach ($cids as $cid) {
526
527            if (is_array($data['comments'][$cid]['user'])) {
528                $user    = $data['comments'][$cid]['user']['id'];
529                $convert = false;
530            } else {
531                $user    = $data['comments'][$cid]['user'];
532                $convert = true;
533            }
534
535            // someone else was trying to edit our comment -> abort
536            if (($user != $_SERVER['REMOTE_USER']) && (!auth_ismanager())) return false;
537
538            $date = time();
539
540            // need to convert to new format?
541            if ($convert) {
542                $data['comments'][$cid]['user'] = array(
543                        'id'      => $user,
544                        'name'    => $data['comments'][$cid]['name'],
545                        'mail'    => $data['comments'][$cid]['mail'],
546                        'url'     => $data['comments'][$cid]['url'],
547                        'address' => $data['comments'][$cid]['address'],
548                        );
549                $data['comments'][$cid]['date'] = array(
550                        'created' => $data['comments'][$cid]['date']
551                        );
552            }
553
554            if ($act == 'toogle') {     // toogle visibility
555                $now = $data['comments'][$cid]['show'];
556                $data['comments'][$cid]['show'] = !$now;
557                $data['number'] = $this->_count($data);
558
559                $type = ($data['comments'][$cid]['show'] ? 'sc' : 'hc');
560
561            } elseif ($act == 'show') { // show comment
562                $data['comments'][$cid]['show'] = true;
563                $data['number'] = $this->_count($data);
564
565                $type = 'sc'; // show comment
566
567            } elseif ($act == 'hide') { // hide comment
568                $data['comments'][$cid]['show'] = false;
569                $data['number'] = $this->_count($data);
570
571                $type = 'hc'; // hide comment
572
573            } elseif (!$raw) {          // remove the comment
574                $data['comments'] = $this->_removeComment($cid, $data['comments']);
575                $data['number'] = $this->_count($data);
576
577                $type = 'dc'; // delete comment
578
579            } else {                   // save changed comment
580                $xhtml = $this->_render($raw);
581
582                // now change the comment's content
583                $data['comments'][$cid]['date']['modified'] = $date;
584                $data['comments'][$cid]['raw']              = $raw;
585                $data['comments'][$cid]['xhtml']            = $xhtml;
586
587                $type = 'ec'; // edit comment
588            }
589        }
590
591        // save the comment metadata file
592        io_saveFile($file, serialize($data));
593        $this->_addLogEntry($date, $ID, $type, '', $cid);
594
595        $this->_redirect($cid);
596        return true;
597    }
598
599    /**
600     * Recursive function to remove a comment
601     */
602    function _removeComment($cid, $comments) {
603        if (is_array($comments[$cid]['replies'])) {
604            foreach ($comments[$cid]['replies'] as $rid) {
605                $comments = $this->_removeComment($rid, $comments);
606            }
607        }
608        unset($comments[$cid]);
609        return $comments;
610    }
611
612    /**
613     * Prints an individual comment
614     */
615    function _print($cid, &$data, $parent = '', $reply = '', $visible = true) {
616
617        if (!isset($data['comments'][$cid])) return false; // comment was removed
618        $comment = $data['comments'][$cid];
619
620        if (!is_array($comment)) return false;             // corrupt datatype
621
622        if ($comment['parent'] != $parent) return true;    // reply to an other comment
623
624        if (!$comment['show']) {                            // comment hidden
625            if (auth_ismanager()) $hidden = ' comment_hidden';
626            else return true;
627        } else {
628            $hidden = '';
629        }
630
631        // print the actual comment
632        $this->_print_comment($cid, $data, $parent, $reply, $visible, $hidden);
633        // replies to this comment entry?
634        $this->_print_replies($cid, $data, $reply, $visible);
635        // reply form
636        $this->_print_form($cid, $reply);
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        global $INFO;
1071
1072        $notify_text = io_readfile($this->localfn('subscribermail'));
1073        $confirm_text = io_readfile($this->localfn('confirmsubscribe'));
1074        $subject_notify = '['.$conf['title'].'] '.$this->getLang('mail_newcomment');
1075        $subject_subscribe = '['.$conf['title'].'] '.$this->getLang('subscribe');
1076        $from = $conf['mailfrom'];
1077        $from = str_replace('@USER@',$_SERVER['REMOTE_USER'],$from);
1078        $from = str_replace('@NAME@',$INFO['userinfo']['name'],$from);
1079        $from = str_replace('@MAIL@',$INFO['userinfo']['mail'],$from);
1080
1081        $search = array(
1082                '@PAGE@',
1083                '@TITLE@',
1084                '@DATE@',
1085                '@NAME@',
1086                '@TEXT@',
1087                '@COMMENTURL@',
1088                '@UNSUBSCRIBE@',
1089                '@DOKUWIKIURL@',
1090                );
1091
1092        // notify page subscribers
1093        if ($conf['subscribers'] || $conf['notify']) {
1094            $list = explode(',', subscriber_addresslist($ID));
1095            $to   = (!empty($conf['notify'])) ? $conf['notify'] : array_pop($list);
1096            $bcc  = implode(',', $list);
1097
1098            $replace = array(
1099                    $ID,
1100                    $conf['title'],
1101                    strftime($conf['dformat'], $comment['date']['created']),
1102                    $comment['user']['name'],
1103                    $comment['raw'],
1104                    wl($ID, '', true) . '#comment_' . $comment['cid'],
1105                    wl($ID, 'do=unsubscribe', true, '&'),
1106                    DOKU_URL,
1107                    );
1108
1109                $body = str_replace($search, $replace, $notify_text);
1110                mail_send($to, $subject_notify, $body, $from, '', $bcc);
1111        }
1112
1113        // notify comment subscribers
1114        if (!empty($subscribers)) {
1115
1116            foreach($subscribers as $mail => $data) {
1117                $to = $mail;
1118
1119                if($data['active']) {
1120                    $replace = array(
1121                            $ID,
1122                            $conf['title'],
1123                            strftime($conf['dformat'], $comment['date']['created']),
1124                            $comment['user']['name'],
1125                            $comment['raw'],
1126                            wl($ID, '', true) . '#comment_' . $comment['cid'],
1127                            wl($ID, 'do=discussion_unsubscribe&hash=' . $data['hash'], true, '&'),
1128                            DOKU_URL,
1129                            );
1130
1131                    $body = str_replace($search, $replace, $notify_text);
1132                    mail_send($to, $subject_notify, $body, $from);
1133                } elseif(!$data['active'] && !$data['confirmsent']) {
1134                    $search = array(
1135                            '@PAGE@',
1136                            '@TITLE@',
1137                            '@SUBSCRIBE@',
1138                            '@DOKUWIKIURL@',
1139                            );
1140                    $replace = array(
1141                            $ID,
1142                            $conf['title'],
1143                            wl($ID, 'do=discussion_confirmsubscribe&hash=' . $data['hash'], true, '&'),
1144                            DOKU_URL,
1145                            );
1146
1147                    $body = str_replace($search, $replace, $confirm_text);
1148                    mail_send($to, $subject_subscribe, $body, $from);
1149                    $subscribers[$mail]['confirmsent'] = true;
1150                }
1151            }
1152        }
1153    }
1154
1155    /**
1156     * Counts the number of visible comments
1157     */
1158    function _count($data) {
1159        $number = 0;
1160        foreach ($data['comments'] as $cid => $comment) {
1161            if ($comment['parent']) continue;
1162            if (!$comment['show']) continue;
1163            $number++;
1164            $rids = $comment['replies'];
1165            if (count($rids)) $number = $number + $this->_countReplies($data, $rids);
1166        }
1167        return $number;
1168    }
1169
1170    function _countReplies(&$data, $rids) {
1171        $number = 0;
1172        foreach ($rids as $rid) {
1173            if (!isset($data['comments'][$rid])) continue; // reply was removed
1174            if (!$data['comments'][$rid]['show']) continue;
1175            $number++;
1176            $rids = $data['comments'][$rid]['replies'];
1177            if (count($rids)) $number = $number + $this->_countReplies($data, $rids);
1178        }
1179        return $number;
1180    }
1181
1182    /**
1183     * Renders the comment text
1184     */
1185    function _render($raw) {
1186        if ($this->getConf('wikisyntaxok')) {
1187            $xhtml = $this->render($raw);
1188        } else { // wiki syntax not allowed -> just encode special chars
1189            $xhtml = hsc(trim($raw));
1190            $xhtml = str_replace("\n", '<br />', $xhtml);
1191        }
1192        return $xhtml;
1193    }
1194
1195    /**
1196     * Finds out whether there is a discussion section for the current page
1197     */
1198    function _hasDiscussion(&$title) {
1199        global $ID;
1200
1201        $cfile = metaFN($ID, '.comments');
1202
1203        if (!@file_exists($cfile)) {
1204            if ($this->getConf('automatic')) {
1205                return true;
1206            } else {
1207                return false;
1208            }
1209        }
1210
1211        $comments = unserialize(io_readFile($cfile, false));
1212
1213        if ($comments['title']) $title = hsc($comments['title']);
1214        $num = $comments['number'];
1215        if ((!$comments['status']) || (($comments['status'] == 2) && (!$num))) return false;
1216        else return true;
1217    }
1218
1219    /**
1220     * Creates a new thread page
1221     */
1222    function _newThread() {
1223        global $ID, $INFO;
1224
1225        $ns    = cleanID($_REQUEST['ns']);
1226        $title = str_replace(':', '', $_REQUEST['title']);
1227        $back  = $ID;
1228        $ID    = ($ns ? $ns.':' : '').cleanID($title);
1229        $INFO  = pageinfo();
1230
1231        // check if we are allowed to create this file
1232        if ($INFO['perm'] >= AUTH_CREATE) {
1233
1234            //check if locked by anyone - if not lock for my self
1235            if ($INFO['locked']) return 'locked';
1236            else lock($ID);
1237
1238            // prepare the new thread file with default stuff
1239            if (!@file_exists($INFO['filepath'])) {
1240                global $TEXT;
1241
1242                $TEXT = pageTemplate(array(($ns ? $ns.':' : '').$title));
1243                if (!$TEXT) {
1244                    $data = array('id' => $ID, 'ns' => $ns, 'title' => $title, 'back' => $back);
1245                    $TEXT = $this->_pageTemplate($data);
1246                }
1247                return 'preview';
1248            } else {
1249                return 'edit';
1250            }
1251        } else {
1252            return 'show';
1253        }
1254    }
1255
1256    /**
1257     * Adapted version of pageTemplate() function
1258     */
1259    function _pageTemplate($data) {
1260        global $conf, $INFO;
1261
1262        $id   = $data['id'];
1263        $user = $_SERVER['REMOTE_USER'];
1264        $tpl  = io_readFile(DOKU_PLUGIN.'discussion/_template.txt');
1265
1266        // standard replacements
1267        $replace = array(
1268                '@NS@'   => $data['ns'],
1269                '@PAGE@' => strtr(noNS($id),'_',' '),
1270                '@USER@' => $user,
1271                '@NAME@' => $INFO['userinfo']['name'],
1272                '@MAIL@' => $INFO['userinfo']['mail'],
1273                '@DATE@' => strftime($conf['dformat']),
1274                );
1275
1276        // additional replacements
1277        $replace['@BACK@']  = $data['back'];
1278        $replace['@TITLE@'] = $data['title'];
1279
1280        // avatar if useavatar and avatar plugin available
1281        if ($this->getConf('useavatar')
1282                && (@file_exists(DOKU_PLUGIN.'avatar/syntax.php'))
1283                && (!plugin_isdisabled('avatar'))) {
1284            $replace['@AVATAR@'] = '{{avatar>'.$user.' }} ';
1285        } else {
1286            $replace['@AVATAR@'] = '';
1287        }
1288
1289        // tag if tag plugin is available
1290        if ((@file_exists(DOKU_PLUGIN.'tag/syntax/tag.php'))
1291                && (!plugin_isdisabled('tag'))) {
1292            $replace['@TAG@'] = "\n\n{{tag>}}";
1293        } else {
1294            $replace['@TAG@'] = '';
1295        }
1296
1297        // do the replace
1298        $tpl = str_replace(array_keys($replace), array_values($replace), $tpl);
1299        return $tpl;
1300    }
1301
1302    /**
1303     * Checks if the CAPTCHA string submitted is valid
1304     *
1305     * @author     Andreas Gohr <gohr@cosmocode.de>
1306     * @adaption   Esther Brunner <wikidesign@gmail.com>
1307     */
1308    function _captchaCheck() {
1309        if (plugin_isdisabled('captcha') || (!$captcha = plugin_load('helper', 'captcha')))
1310            return; // CAPTCHA is disabled or not available
1311
1312        // do nothing if logged in user and no CAPTCHA required
1313        if (!$captcha->getConf('forusers') && $_SERVER['REMOTE_USER']) return;
1314
1315        // compare provided string with decrypted captcha
1316        $rand = PMA_blowfish_decrypt($_REQUEST['plugin__captcha_secret'], auth_cookiesalt());
1317        $code = $captcha->_generateCAPTCHA($captcha->_fixedIdent(), $rand);
1318
1319        if (!$_REQUEST['plugin__captcha_secret'] ||
1320                !$_REQUEST['plugin__captcha'] ||
1321                strtoupper($_REQUEST['plugin__captcha']) != $code) {
1322
1323            // CAPTCHA test failed! Continue to edit instead of saving
1324            msg($captcha->getLang('testfailed'), -1);
1325            if ($_REQUEST['comment'] == 'save') $_REQUEST['comment'] = 'edit';
1326            elseif ($_REQUEST['comment'] == 'add') $_REQUEST['comment'] = 'show';
1327        }
1328        // if we arrive here it was a valid save
1329    }
1330
1331    /**
1332     * Adds the comments to the index
1333     */
1334    function idx_add_discussion(&$event, $param) {
1335
1336        // get .comments meta file name
1337        $file = metaFN($event->data[0], '.comments');
1338
1339        if (@file_exists($file)) $data = unserialize(io_readFile($file, false));
1340        if ((!$data['status']) || ($data['number'] == 0)) return; // comments are turned off
1341
1342        // now add the comments
1343        if (isset($data['comments'])) {
1344            foreach ($data['comments'] as $key => $value) {
1345                $event->data[1] .= $this->_addCommentWords($key, $data);
1346            }
1347        }
1348    }
1349
1350    /**
1351     * Adds the words of a given comment to the index
1352     */
1353    function _addCommentWords($cid, &$data, $parent = '') {
1354
1355        if (!isset($data['comments'][$cid])) return ''; // comment was removed
1356        $comment = $data['comments'][$cid];
1357
1358        if (!is_array($comment)) return '';             // corrupt datatype
1359        if ($comment['parent'] != $parent) return '';   // reply to an other comment
1360        if (!$comment['show']) return '';               // hidden comment
1361
1362        $text = $comment['raw'];                        // we only add the raw comment text
1363        if (is_array($comment['replies'])) {             // and the replies
1364            foreach ($comment['replies'] as $rid) {
1365                $text .= $this->_addCommentWords($rid, $data, $cid);
1366            }
1367        }
1368        return ' '.$text;
1369    }
1370
1371    /**
1372     * Only allow http(s) URLs and append http:// to URLs if needed
1373     */
1374    function _checkURL($url) {
1375        if(preg_match("#^http://|^https://#", $url)) {
1376            return hsc($url);
1377        } elseif(substr($url, 0, 4) == 'www.') {
1378            return hsc('http://' . $url);
1379        } else {
1380            return '';
1381        }
1382    }
1383}
1384
1385function _sortCallback($a, $b) {
1386    if (is_array($a['date'])) { // new format
1387        $createdA  = $a['date']['created'];
1388    } else {                         // old format
1389        $createdA  = $a['date'];
1390    }
1391
1392    if (is_array($b['date'])) { // new format
1393        $createdB  = $b['date']['created'];
1394    } else {                         // old format
1395        $createdB  = $b['date'];
1396    }
1397
1398    if ($createdA == $createdB)
1399        return 0;
1400    else
1401        return ($createdA < $createdB) ? -1 : 1;
1402}
1403
1404// vim:ts=4:sw=4:et:enc=utf-8:
1405