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