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