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