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