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