xref: /plugin/discussion/action.php (revision 3648fb3e7657174cb0a1405e801873dfebb1f5cf)
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    function getInfo() {
19        return array(
20                'author' => 'Gina Häußge, Michael Klier, Esther Brunner',
21                'email'  => 'dokuwiki@chimeric.de',
22                'date'   => @file_get_contents(DOKU_PLUGIN.'discussion/VERSION'),
23                'name'   => 'Discussion Plugin (action component)',
24                'desc'   => 'Enables discussion features',
25                'url'    => 'http://wiki.splitbrain.org/plugin:discussion',
26                );
27    }
28
29    function register(&$contr) {
30        $contr->register_hook(
31                'ACTION_ACT_PREPROCESS',
32                'BEFORE',
33                $this,
34                'handle_act_preprocess',
35                array()
36                );
37        $contr->register_hook(
38                'TPL_ACT_RENDER',
39                'AFTER',
40                $this,
41                'comments',
42                array()
43                );
44        $contr->register_hook(
45                'INDEXER_PAGE_ADD',
46                'AFTER',
47                $this,
48                'idx_add_discussion',
49                array()
50                );
51    }
52
53    /**
54     * Handles comment actions, dispatches data processing routines
55     */
56    function handle_act_preprocess(&$event, $param) {
57        global $ID;
58        global $conf;
59        global $lang;
60
61        // handle newthread ACTs
62        if ($event->data == 'newthread') {
63            // we can handle it -> prevent others
64            $event->preventDefault();
65
66            $event->data = $this->_newThread();
67        }
68
69        // enable captchas
70        if ((in_array($_REQUEST['comment'], array('add', 'save')))
71                && (@file_exists(DOKU_PLUGIN.'captcha/action.php'))) {
72            $this->_captchaCheck();
73        }
74
75        // if we are not in show mode or someone wants to unsubscribe, that was all for now
76        if ($event->data != 'show' && $event->data != 'unsubscribe') return;
77
78        if ($event->data == 'unsubscribe') {
79            if (!isset($_REQUEST['hash'])) {
80                return;
81            } else {
82                $file = metaFN($ID, '.comments');
83                $data = unserialize(io_readFile($file));
84                foreach($data['subscribers'] as $mail => $hash)  {
85                    if($hash == $_REQUEST['hash']) {
86                        // ok we can handle it prevent others
87                        $event->preventDefault();
88                        unset($data['subscribers'][$mail]);
89                        io_saveFile($file, serialize($data));
90                        msg(sprintf($lang['unsubscribe_success'], $mail, $ID), 1);
91                        $event->data = 'show';
92                        return true;
93                    }
94                }
95                return false;
96            }
97        } else {
98            // do the data processing for comments
99            $cid  = $_REQUEST['cid'];
100            switch ($_REQUEST['comment']) {
101                case 'add':
102                    $comment = array(
103                            'user'    => array(
104                            'id'      => hsc($_REQUEST['user']),
105                            'name'    => hsc($_REQUEST['name']),
106                            'mail'    => hsc($_REQUEST['mail']),
107                            'url'     => hsc($_REQUEST['url']),
108                            'address' => hsc($_REQUEST['address'])),
109                            'subscribe' => $_REQUEST['subscribe'],
110                            'date'    => array('created' => $_REQUEST['date']),
111                            'raw'     => cleanText($_REQUEST['text'])
112                            );
113                    $repl = $_REQUEST['reply'];
114                    $this->_add($comment, $repl);
115                    break;
116
117                case 'save':
118                    $raw  = cleanText($_REQUEST['text']);
119                    $this->_save(array($cid), $raw);
120                    break;
121
122                case 'delete':
123                    $this->_save(array($cid), '');
124                    break;
125
126                case 'toogle':
127                    $this->_save(array($cid), '', 'toogle');
128                    break;
129            }
130        }
131
132        // FIXME use new TPL_TOC_RENDER event in the future
133        $tocmeta = p_get_metadata($ID, 'description tableofcontents');
134        if(count($tocmeta) >= ($conf['maxtoclevel']-1)) {
135
136            $TOC = array();
137            global $TOC;
138            $TOC = $tocmeta;
139
140            $tocitem = array( 'hid' => 'discussion__section',
141                              'title' => $this->getLang('discussion'),
142                              'type' => 'ul',
143                              'level' => 1 );
144
145            $file = metaFN($ID, '.comments');
146            if(@file_exists($file)) {
147                $data = unserialize(io_readFile($file));
148                if($data['status'] != 0 && !empty($TOC)) {
149                    $TOC[] = $tocitem;
150                }
151            }
152        }
153    }
154
155    /**
156     * Main function; dispatches the visual comment actions
157     */
158    function comments(&$event, $param) {
159        if ($event->data != 'show') return; // nothing to do for us
160
161        $cid  = $_REQUEST['cid'];
162        switch ($_REQUEST['comment']) {
163            case 'edit':
164                $this->_show(NULL, $cid);
165                break;
166            default:
167                $this->_show($cid);
168                break;
169        }
170    }
171
172    /**
173     * Redirects browser to given comment anchor
174     */
175    function _redirect($cid) {
176        global $ID;
177        global $ACT;
178
179        if ($ACT !== 'show') return;
180        header('Location: ' . wl($ID) . '#comment__' . $cid);
181    }
182
183    /**
184     * Shows all comments of the current page
185     */
186    function _show($reply = NULL, $edit = NULL) {
187        global $ID;
188        global $INFO;
189        global $ACT;
190
191        // get .comments meta file name
192        $file = metaFN($ID, '.comments');
193
194        if (!@file_exists($file) && !$this->getConf('automatic')) return false;
195
196        // load data
197        if (@file_exists($file)) {
198            $data = unserialize(io_readFile($file, false));
199            if (!$data['status']) return false; // comments are turned off
200        } elseif (!@file_exists($file) && $this->getConf('automatic') && $INFO['exists']) {
201            // set status to show the comment form
202            $data['status'] = 1;
203            $data['number'] = 0;
204        }
205
206        // section title
207        $title = ($data['title'] ? hsc($data['title']) : $this->getLang('discussion'));
208        ptln('<div class="comment_wrapper">');
209        ptln('<h2><a name="discussion__section" id="discussion__section">', 2);
210        ptln($title, 4);
211        ptln('</a></h2>', 2);
212        ptln('<div class="level2 hfeed">', 2);
213        // now display the comments
214        if (isset($data['comments'])) {
215            foreach ($data['comments'] as $key => $value) {
216                if ($key == $edit) $this->_form($value['raw'], 'save', $edit); // edit form
217                else $this->_print($key, $data, '', $reply);
218            }
219        }
220
221        // comment form
222        if (($data['status'] == 1) && !$reply && !$edit) $this->_form('');
223
224        ptln('</div>', 2); // level2 hfeed
225        ptln('</div>'); // comment_wrapper
226
227        return true;
228    }
229
230    /**
231     * Adds a new comment and then displays all comments
232     */
233    function _add($comment, $parent) {
234        global $lang;
235        global $ID;
236        global $TEXT;
237
238        $otxt = $TEXT; // set $TEXT to comment text for wordblock check
239        $TEXT = $comment['raw'];
240
241        // spamcheck against the DokuWiki blacklist
242        if (checkwordblock()) {
243            msg($this->getLang('wordblock'), -1);
244            return false;
245        }
246
247        if ((!$this->getConf('allowguests'))
248                && ($comment['user']['id'] != $_SERVER['REMOTE_USER']))
249            return false; // guest comments not allowed
250
251        $TEXT = $otxt; // restore global $TEXT
252
253        // get discussion meta file name
254        $file = metaFN($ID, '.comments');
255
256        // create comments file if it doesn't exist yet
257        if(!@file_exists($file)) {
258            $data = array('status' => 1, 'number' => 0);
259            io_saveFile($file, serialize($data));
260        } else {
261            $data = array();
262            $data = unserialize(io_readFile($file, false));
263            if ($data['status'] != 1) return false; // comments off or closed
264        }
265
266        if ($comment['date']['created']) {
267            $date = strtotime($comment['date']['created']);
268        } else {
269            $date = time();
270        }
271
272        if ($date == -1) {
273            $date = time();
274        }
275
276        $cid  = md5($comment['user']['id'].$date); // create a unique id
277
278        if (!is_array($data['comments'][$parent])) {
279            $parent = NULL; // invalid parent comment
280        }
281
282        // render the comment
283        $xhtml = $this->_render($comment['raw']);
284
285        // fill in the new comment
286        $data['comments'][$cid] = array(
287                'user'    => $comment['user'],
288                'date'    => array('created' => $date),
289                'show'    => true,
290                'raw'     => $comment['raw'],
291                'xhtml'   => $xhtml,
292                'parent'  => $parent,
293                'replies' => array()
294                );
295
296        if($comment['subscribe']) {
297            $mail = $comment['user']['mail'];
298            if($data['subscribers']) {
299                if(!$data['subscribers'][$mail]) {
300                    $data['subscribers'][$mail] = md5($mail . mt_rand());
301                }
302            } else {
303                $data['subscribers'][$mail] = md5($mail . mt_rand());
304            }
305        }
306
307        // update parent comment
308        if ($parent) $data['comments'][$parent]['replies'][] = $cid;
309
310        // update the number of comments
311        $data['number']++;
312
313        // save the comment metadata file
314        io_saveFile($file, serialize($data));
315        $this->_addLogEntry($date, $ID, 'cc', '', $cid);
316
317        // notify subscribers of the page
318        $data['comments'][$cid]['cid'] = $cid;
319        $this->_notify($data['comments'][$cid], $data['subscribers']);
320
321        $this->_redirect($cid);
322        return true;
323    }
324
325    /**
326     * Saves the comment with the given ID and then displays all comments
327     */
328    function _save($cids, $raw, $act = NULL) {
329        global $ID;
330
331        if ($raw) {
332            global $TEXT;
333
334            $otxt = $TEXT; // set $TEXT to comment text for wordblock check
335            $TEXT = $raw;
336
337            // spamcheck against the DokuWiki blacklist
338            if (checkwordblock()) {
339                msg($this->getLang('wordblock'), -1);
340                return false;
341            }
342
343            $TEXT = $otxt; // restore global $TEXT
344        }
345
346        // get discussion meta file name
347        $file = metaFN($ID, '.comments');
348        $data = unserialize(io_readFile($file, false));
349
350        if (!is_array($cids)) $cids = array($cids);
351        foreach ($cids as $cid) {
352
353            if (is_array($data['comments'][$cid]['user'])) {
354                $user    = $data['comments'][$cid]['user']['id'];
355                $convert = false;
356            } else {
357                $user    = $data['comments'][$cid]['user'];
358                $convert = true;
359            }
360
361            // someone else was trying to edit our comment -> abort
362            if (($user != $_SERVER['REMOTE_USER']) && (!auth_ismanager())) return false;
363
364            $date = time();
365
366            // need to convert to new format?
367            if ($convert) {
368                $data['comments'][$cid]['user'] = array(
369                        'id'      => $user,
370                        'name'    => $data['comments'][$cid]['name'],
371                        'mail'    => $data['comments'][$cid]['mail'],
372                        'url'     => $data['comments'][$cid]['url'],
373                        'address' => $data['comments'][$cid]['address'],
374                        );
375                $data['comments'][$cid]['date'] = array(
376                        'created' => $data['comments'][$cid]['date']
377                        );
378            }
379
380            if ($act == 'toogle') {     // toogle visibility
381                $now = $data['comments'][$cid]['show'];
382                $data['comments'][$cid]['show'] = !$now;
383                $data['number'] = $this->_count($data);
384
385                $type = ($data['comments'][$cid]['show'] ? 'sc' : 'hc');
386
387            } elseif ($act == 'show') { // show comment
388                $data['comments'][$cid]['show'] = true;
389                $data['number'] = $this->_count($data);
390
391                $type = 'sc'; // show comment
392
393            } elseif ($act == 'hide') { // hide comment
394                $data['comments'][$cid]['show'] = false;
395                $data['number'] = $this->_count($data);
396
397                $type = 'hc'; // hide comment
398
399            } elseif (!$raw) {          // remove the comment
400                $data['comments'] = $this->_removeComment($cid, $data['comments']);
401                $data['number'] = $this->_count($data);
402
403                $type = 'dc'; // delete comment
404
405            } else {                   // save changed comment
406                $xhtml = $this->_render($raw);
407
408                // now change the comment's content
409                $data['comments'][$cid]['date']['modified'] = $date;
410                $data['comments'][$cid]['raw']              = $raw;
411                $data['comments'][$cid]['xhtml']            = $xhtml;
412
413                $type = 'ec'; // edit comment
414            }
415        }
416
417        // save the comment metadata file
418        io_saveFile($file, serialize($data));
419        $this->_addLogEntry($date, $ID, $type, '', $cid);
420
421        $this->_redirect($cid);
422        return true;
423    }
424
425    /**
426     * Recursive function to remove a comment
427     */
428    function _removeComment($cid, $comments) {
429        if (is_array($comments[$cid]['replies'])) {
430            foreach ($comments[$cid]['replies'] as $rid) {
431                $comments = $this->_removeComment($rid, $comments);
432            }
433        }
434        unset($comments[$cid]);
435        return $comments;
436    }
437
438    /**
439     * Prints an individual comment
440     */
441    function _print($cid, &$data, $parent = '', $reply = '', $visible = true) {
442        global $conf, $lang, $ID;
443
444        if (!isset($data['comments'][$cid])) return false; // comment was removed
445        $comment = $data['comments'][$cid];
446
447        if (!is_array($comment)) return false;             // corrupt datatype
448
449        if ($comment['parent'] != $parent) return true;    // reply to an other comment
450
451        if (!$comment['show']) {                            // comment hidden
452            if (auth_ismanager()) $hidden = ' comment_hidden';
453            else return true;
454        } else {
455            $hidden = '';
456        }
457
458        // comment head with date and user data
459        ptln('<div class="hentry'.$hidden.'">', 4);
460        ptln('<div class="comment_head">', 6);
461        ptln('<a name="comment__'.$cid.'" id="comment__'.$cid.'"></a>', 8);
462        $head = '<span class="vcard author">';
463
464        // prepare variables
465        if (is_array($comment['user'])) { // new format
466            $user    = $comment['user']['id'];
467            $name    = $comment['user']['name'];
468            $mail    = $comment['user']['mail'];
469            $url     = $comment['user']['url'];
470            $address = $comment['user']['address'];
471        } else {                         // old format
472            $user    = $comment['user'];
473            $name    = $comment['name'];
474            $mail    = $comment['mail'];
475            $url     = $comment['url'];
476            $address = $comment['address'];
477        }
478        if (is_array($comment['date'])) { // new format
479            $created  = $comment['date']['created'];
480            $modified = $comment['date']['modified'];
481        } else {                         // old format
482            $created  = $comment['date'];
483            $modified = $comment['edited'];
484        }
485
486        // show avatar image?
487        if ($this->getConf('useavatar')
488                && (!plugin_isdisabled('avatar'))
489                && ($avatar =& plugin_load('helper', 'avatar'))) {
490            if ($mail) $head .= $avatar->getXHTML($mail, $name, 'left');
491            else $head .= $avatar->getXHTML($user, $name, 'left');
492            $style = ' style="margin-left: '.($avatar->getConf('size') + 14).'px;"';
493        } else {
494            $style = ' style="margin-left: 20px;"';
495        }
496
497        if ($this->getConf('linkemail') && $mail) {
498            $head .= $this->email($mail, $name, 'email fn');
499        } elseif ($url) {
500            $head .= $this->external_link($url, $name, 'urlextern url fn');
501        } else {
502            $head .= '<span class="fn">'.$name.'</span>';
503        }
504        if ($address) $head .= ', <span class="adr">'.$address.'</span>';
505        $head .= '</span>, '.
506            '<abbr class="published" title="'.strftime('%Y-%m-%dT%H:%M:%SZ', $created).'">'.
507            strftime($conf['dformat'], $created).'</abbr>';
508        if ($comment['edited']) $head .= ' (<abbr class="updated" title="'.
509                strftime('%Y-%m-%dT%H:%M:%SZ', $modified).'">'.strftime($conf['dformat'], $modified).
510                '</abbr>)';
511        ptln($head, 8);
512        ptln('</div>', 6); // class="comment_head"
513
514        // main comment content
515        ptln('<div class="comment_body entry-content"'.
516                ($this->getConf('useavatar') ? $style : '').'>', 6);
517        echo $comment['xhtml'].DOKU_LF;
518        ptln('</div>', 6); // class="comment_body"
519
520        if ($visible) {
521            ptln('<div class="comment_buttons">', 6);
522
523            // show reply button?
524            if (($data['status'] == 1) && !$reply && $comment['show']
525                    && ($this->getConf('allowguests') || $_SERVER['REMOTE_USER']))
526                $this->_button($cid, $this->getLang('btn_reply'), 'reply', true);
527
528            // show edit, show/hide and delete button?
529            if ((($user == $_SERVER['REMOTE_USER']) && ($user != '')) || (auth_ismanager())) {
530                $this->_button($cid, $lang['btn_secedit'], 'edit', true);
531                $label = ($comment['show'] ? $this->getLang('btn_hide') : $this->getLang('btn_show'));
532                $this->_button($cid, $label, 'toogle');
533                $this->_button($cid, $lang['btn_delete'], 'delete');
534            }
535            ptln('</div>', 6); // class="comment_buttons"
536        }
537        ptln('</div>', 4); // class="hentry"
538
539        // replies to this comment entry?
540        if (count($comment['replies'])) {
541            ptln('<div class="comment_replies"'.$style.'>', 4);
542            $visible = ($comment['show'] && $visible);
543            foreach ($comment['replies'] as $rid) {
544                $this->_print($rid, $data, $cid, $reply, $visible);
545            }
546            ptln('</div>', 4); // class="comment_replies"
547        }
548
549        // reply form
550        if ($reply == $cid) {
551            ptln('<div class="comment_replies">', 4);
552            $this->_form('', 'add', $cid);
553            ptln('</div>', 4); // class="comment_replies"
554        }
555    }
556
557    /**
558     * Outputs the comment form
559     */
560    function _form($raw = '', $act = 'add', $cid = NULL) {
561        global $lang;
562        global $conf;
563        global $ID;
564        global $INFO;
565
566        // not for unregistered users when guest comments aren't allowed
567        if (!$_SERVER['REMOTE_USER'] && !$this->getConf('allowguests')) return false;
568
569        // fill $raw with $_REQUEST['text'] if it's empty (for failed CAPTCHA check)
570        if (!$raw && ($_REQUEST['comment'] == 'show')) $raw = $_REQUEST['text'];
571        ?>
572
573        <div class="comment_form">
574          <form id="discussion__comment_form" method="post" action="<?php echo script() ?>" accept-charset="<?php echo $lang['encoding'] ?>" onsubmit="return validate(this);">
575            <div class="no">
576              <input type="hidden" name="id" value="<?php echo $ID ?>" />
577              <input type="hidden" name="do" value="show" />
578              <input type="hidden" name="comment" value="<?php echo $act ?>" />
579
580        <?php
581        // for adding a comment
582        if ($act == 'add') {
583        ?>
584              <input type="hidden" name="reply" value="<?php echo $cid ?>" />
585        <?php
586        // for registered user (and we're not in admin import mode)
587        if ($conf['useacl'] && $_SERVER['REMOTE_USER']
588                && (!($this->getConf('adminimport') && (auth_ismanager())))) {
589        ?>
590              <input type="hidden" name="user" value="<?php echo hsc($_SERVER['REMOTE_USER']) ?>" />
591              <input type="hidden" name="name" value="<?php echo hsc($INFO['userinfo']['name']) ?>" />
592              <input type="hidden" name="mail" value="<?php echo hsc($INFO['userinfo']['mail']) ?>" />
593        <?php
594        // for guest: show name, e-mail and subscribe to comments fields
595        } else {
596        ?>
597              <input type="hidden" name="user" value="<?php echo clientIP() ?>" />
598              <div class="comment_name">
599                <label class="block" for="discussion__comment_name">
600                  <span><?php echo $lang['fullname'] ?>:</span>
601                  <input type="text" class="edit" name="name" id="discussion__comment_name" size="50" tabindex="1" value="<?php echo hsc($_REQUEST['name'])?>" />
602                </label>
603              </div>
604              <div class="comment_mail">
605                <label class="block" for="discussion__comment_mail">
606                  <span><?php echo $lang['email'] ?>:</span>
607                  <input type="text" class="edit" name="mail" id="discussion__comment_mail" size="50" tabindex="2" value="<?php echo hsc($_REQUEST['mail'])?>" />
608                </label>
609              </div>
610        <?php
611        }
612
613        // allow entering an URL
614        if ($this->getConf('urlfield')) {
615        ?>
616              <div class="comment_url">
617                <label class="block" for="discussion__comment_url">
618                  <span><?php echo $this->getLang('url') ?>:</span>
619                  <input type="text" class="edit" name="url" id="discussion__comment_url" size="50" tabindex="3" value="<?php echo hsc($_REQUEST['url'])?>" />
620                </label>
621              </div>
622        <?php
623        }
624
625        // allow entering an address
626        if ($this->getConf('addressfield')) {
627        ?>
628              <div class="comment_address">
629                <label class="block" for="discussion__comment_address">
630                  <span><?php echo $this->getLang('address') ?>:</span>
631                  <input type="text" class="edit" name="address" id="discussion__comment_address" size="50" tabindex="4" value="<?php echo hsc($_REQUEST['address'])?>" />
632                </label>
633              </div>
634        <?php
635        }
636
637        // allow setting the comment date
638        if ($this->getConf('adminimport') && (auth_ismanager())) {
639        ?>
640              <div class="comment_date">
641                <label class="block" for="discussion__comment_date">
642                  <span><?php echo $this->getLang('date') ?>:</span>
643                  <input type="text" class="edit" name="date" id="discussion__comment_date" size="50" />
644                </label>
645              </div>
646        <?php
647        }
648
649        // for saving a comment
650        } else {
651        ?>
652              <input type="hidden" name="cid" value="<?php echo $cid ?>" />
653        <?php
654        }
655        ?>
656              <div class="comment_text">
657        <?php
658        echo $this->getLang('entercomment');
659        if ($this->getConf('wikisyntaxok')) echo ' ('.$this->getLang('wikisyntax').')';
660        echo ':<br />'.DOKU_LF;
661        ?>
662                <textarea class="edit" name="text" cols="80" rows="10" id="discussion__comment_text" tabindex="5"><?php echo formText($raw) ?></textarea>
663              </div>
664        <?php //bad and dirty event insert hook
665        $evdata = array('writable' => true);
666        trigger_event('HTML_EDITFORM_INJECTION', $evdata);
667        ?>
668              <input class="button comment_submit" type="submit" name="submit" accesskey="s" value="<?php echo $lang['btn_save'] ?>" title="<?php echo $lang['btn_save']?> [ALt+S]" tabindex="7" />
669
670        <?php if(!$_SERVER['REMOTE_USER']) { ?>
671              <div class="comment_subscribe">
672                <input type="checkbox" id="discussion__comment_subscribe" name="subscribe" tabindex=="6" />
673                <label class="block" for="discussion__comment_subscribe">
674                  <span><?php echo $this->getLang('subscribe') ?></span>
675                </label>
676              </div>
677        <?php } ?>
678
679              <div class="clearer"></div>
680
681            </div>
682          </form>
683        </div>
684        <?php
685        if ($this->getConf('usecocomment')) echo $this->_coComment();
686    }
687
688    /**
689     * Adds a javascript to interact with coComments
690     */
691    function _coComment() {
692        global $ID;
693        global $conf;
694        global $INFO;
695
696        $user = $_SERVER['REMOTE_USER'];
697
698        ?>
699        <script type="text/javascript"><!--//--><![CDATA[//><!--
700          var blogTool  = "DokuWiki";
701          var blogURL   = "<?php echo DOKU_URL ?>";
702          var blogTitle = "<?php echo $conf['title'] ?>";
703          var postURL   = "<?php echo wl($ID, '', true) ?>";
704          var postTitle = "<?php echo tpl_pagetitle($ID, true) ?>";
705        <?php
706        if ($user) {
707        ?>
708          var commentAuthor = "<?php echo $INFO['userinfo']['name'] ?>";
709        <?php
710        } else {
711        ?>
712          var commentAuthorFieldName = "name";
713        <?php
714        }
715        ?>
716          var commentAuthorLoggedIn = <?php echo ($user ? 'true' : 'false') ?>;
717          var commentFormID         = "discussion__comment_form";
718          var commentTextFieldName  = "text";
719          var commentButtonName     = "submit";
720          var cocomment_force       = false;
721        //--><!]]></script>
722        <script type="text/javascript" src="http://www.cocomment.com/js/cocomment.js">
723        </script>
724        <?php
725    }
726
727    /**
728     * General button function
729     */
730    function _button($cid, $label, $act, $jump = false) {
731        global $ID;
732
733        $anchor = ($jump ? '#discussion__comment_form' : '' );
734
735        ?>
736        <form class="button discussion__<?php echo $act?>" method="post" action="<?php echo script().$anchor ?>">
737          <div class="no">
738            <input type="hidden" name="id" value="<?php echo $ID ?>" />
739            <input type="hidden" name="do" value="show" />
740            <input type="hidden" name="comment" value="<?php echo $act ?>" />
741            <input type="hidden" name="cid" value="<?php echo $cid ?>" />
742            <input type="submit" value="<?php echo $label ?>" class="button" title="<?php echo $label ?>" />
743          </div>
744        </form>
745        <?php
746        return true;
747    }
748
749    /**
750     * Adds an entry to the comments changelog
751     *
752     * @author Esther Brunner <wikidesign@gmail.com>
753     * @author Ben Coburn <btcoburn@silicodon.net>
754     */
755    function _addLogEntry($date, $id, $type = 'cc', $summary = '', $extra = '') {
756        global $conf;
757
758        $changelog = $conf['metadir'].'/_comments.changes';
759
760        if(!$date) $date = time(); //use current time if none supplied
761        $remote = $_SERVER['REMOTE_ADDR'];
762        $user   = $_SERVER['REMOTE_USER'];
763
764        $strip = array("\t", "\n");
765        $logline = array(
766                'date'  => $date,
767                'ip'    => $remote,
768                'type'  => str_replace($strip, '', $type),
769                'id'    => $id,
770                'user'  => $user,
771                'sum'   => str_replace($strip, '', $summary),
772                'extra' => str_replace($strip, '', $extra)
773                );
774
775        // add changelog line
776        $logline = implode("\t", $logline)."\n";
777        io_saveFile($changelog, $logline, true); //global changelog cache
778        $this->_trimRecentCommentsLog($changelog);
779
780        // tell the indexer to re-index the page
781        @unlink(metaFN($id, '.indexed'));
782    }
783
784    /**
785     * Trims the recent comments cache to the last $conf['changes_days'] recent
786     * changes or $conf['recent'] items, which ever is larger.
787     * The trimming is only done once a day.
788     *
789     * @author Ben Coburn <btcoburn@silicodon.net>
790     */
791    function _trimRecentCommentsLog($changelog) {
792        global $conf;
793
794        if (@file_exists($changelog) &&
795                (filectime($changelog) + 86400) < time() &&
796                !@file_exists($changelog.'_tmp')) {
797
798            io_lock($changelog);
799            $lines = file($changelog);
800            if (count($lines)<$conf['recent']) {
801                // nothing to trim
802                io_unlock($changelog);
803                return true;
804            }
805
806            io_saveFile($changelog.'_tmp', '');                  // presave tmp as 2nd lock
807            $trim_time = time() - $conf['recent_days']*86400;
808            $out_lines = array();
809
810            $num = count($lines);
811            for ($i=0; $i<$num; $i++) {
812                $log = parseChangelogLine($lines[$i]);
813                if ($log === false) continue;                      // discard junk
814                if ($log['date'] < $trim_time) {
815                    $old_lines[$log['date'].".$i"] = $lines[$i];     // keep old lines for now (append .$i to prevent key collisions)
816                } else {
817                    $out_lines[$log['date'].".$i"] = $lines[$i];     // definitely keep these lines
818                }
819            }
820
821            // sort the final result, it shouldn't be necessary,
822            // however the extra robustness in making the changelog cache self-correcting is worth it
823            ksort($out_lines);
824            $extra = $conf['recent'] - count($out_lines);        // do we need extra lines do bring us up to minimum
825            if ($extra > 0) {
826                ksort($old_lines);
827                $out_lines = array_merge(array_slice($old_lines,-$extra),$out_lines);
828            }
829
830            // save trimmed changelog
831            io_saveFile($changelog.'_tmp', implode('', $out_lines));
832            @unlink($changelog);
833            if (!rename($changelog.'_tmp', $changelog)) {
834                // rename failed so try another way...
835                io_unlock($changelog);
836                io_saveFile($changelog, implode('', $out_lines));
837                @unlink($changelog.'_tmp');
838            } else {
839                io_unlock($changelog);
840            }
841            return true;
842        }
843    }
844
845    /**
846     * Sends a notify mail on new comment
847     *
848     * @param  array  $comment  data array of the new comment
849     *
850     * @author Andreas Gohr <andi@splitbrain.org>
851     * @author Esther Brunner <wikidesign@gmail.com>
852     */
853    function _notify($comment, $subscribers) {
854        global $conf;
855        global $ID;
856
857        $text = io_readfile($this->localfn('subscribermail'));
858        $subject = '['.$conf['title'].'] '.$this->getLang('mail_newcomment');
859
860        $search = array(
861                '@PAGE@',
862                '@TITLE@',
863                '@DATE@',
864                '@NAME@',
865                '@TEXT@',
866                '@COMMENTURL@',
867                '@UNSUBSCRIBE@',
868                '@DOKUWIKIURL@',
869                );
870
871        // notify page subscribers
872        if (($conf['subscribers']) && ($conf['notify'])) {
873            $bcc = subscriber_addresslist($ID);
874            $to = $conf['notify'];
875
876            $replace = array(
877                    $ID,
878                    $conf['title'],
879                    strftime($conf['dformat'], $comment['date']['created']),
880                    $comment['user']['name'],
881                    $comment['raw'],
882                    wl($ID, '', true) . '#comment__' . $comment['cid'],
883                    wl($ID, 'do=unsubscribe', true, '&'),
884                    DOKU_URL,
885                    );
886
887                $body = str_replace($search, $replace, $text);
888                mail_send($to, $subject, $body, $conf['mailfrom'], '', $bcc);
889        }
890
891        // notify comment subscribers
892        if (!empty($subscribers)) {
893
894            foreach($subscribers as $mail => $hash) {
895                $to = $mail;
896
897                $replace = array(
898                        $ID,
899                        $conf['title'],
900                        strftime($conf['dformat'], $comment['date']['created']),
901                        $comment['user']['name'],
902                        $comment['raw'],
903                        wl($ID, '', true) . '#comment__' . $comment['cid'],
904                        wl($ID, 'do=unsubscribe&hash=' . $hash, true, '&'),
905                        DOKU_URL,
906                        );
907
908                $body = str_replace($search, $replace, $text);
909                mail_send($to, $subject, $body, $conf['mailfrom']);
910            }
911        }
912    }
913
914    /**
915     * Counts the number of visible comments
916     */
917    function _count($data) {
918        $number = 0;
919        foreach ($data['comments'] as $cid => $comment) {
920            if ($comment['parent']) continue;
921            if (!$comment['show']) continue;
922            $number++;
923            $rids = $comment['replies'];
924            if (count($rids)) $number = $number + $this->_countReplies($data, $rids);
925        }
926        return $number;
927    }
928
929    function _countReplies(&$data, $rids) {
930        $number = 0;
931        foreach ($rids as $rid) {
932            if (!isset($data['comments'][$rid])) continue; // reply was removed
933            if (!$data['comments'][$rid]['show']) continue;
934            $number++;
935            $rids = $data['comments'][$rid]['replies'];
936            if (count($rids)) $number = $number + $this->_countReplies($data, $rids);
937        }
938        return $number;
939    }
940
941    /**
942     * Renders the comment text
943     */
944    function _render($raw) {
945        if ($this->getConf('wikisyntaxok')) {
946            $xhtml = $this->render($raw);
947        } else { // wiki syntax not allowed -> just encode special chars
948            $xhtml = htmlspecialchars(trim($raw));
949        }
950        return $xhtml;
951    }
952
953    /**
954     * Finds out whether there is a discussion section for the current page
955     */
956    function _hasDiscussion(&$title) {
957        global $ID;
958
959        $cfile = metaFN($ID, '.comments');
960
961        if (!@file_exists($cfile)) {
962            if ($this->getConf('automatic')) {
963                return true;
964            } else {
965                return false;
966            }
967        }
968
969        $comments = unserialize(io_readFile($cfile, false));
970
971        if ($comments['title']) $title = hsc($comments['title']);
972        $num = $comments['number'];
973        if ((!$comments['status']) || (($comments['status'] == 2) && (!$num))) return false;
974        else return true;
975    }
976
977    /**
978     * Creates a new thread page
979     */
980    function _newThread() {
981        global $ID, $INFO;
982
983        $ns    = cleanID($_REQUEST['ns']);
984        $title = str_replace(':', '', $_REQUEST['title']);
985        $back  = $ID;
986        $ID    = ($ns ? $ns.':' : '').cleanID($title);
987        $INFO  = pageinfo();
988
989        // check if we are allowed to create this file
990        if ($INFO['perm'] >= AUTH_CREATE) {
991
992            //check if locked by anyone - if not lock for my self
993            if ($INFO['locked']) return 'locked';
994            else lock($ID);
995
996            // prepare the new thread file with default stuff
997            if (!@file_exists($INFO['filepath'])) {
998                global $TEXT;
999
1000                $TEXT = pageTemplate(array(($ns ? $ns.':' : '').$title));
1001                if (!$TEXT) {
1002                    $data = array('id' => $ID, 'ns' => $ns, 'title' => $title, 'back' => $back);
1003                    $TEXT = $this->_pageTemplate($data);
1004                }
1005                return 'preview';
1006            } else {
1007                return 'edit';
1008            }
1009        } else {
1010            return 'show';
1011        }
1012    }
1013
1014    /**
1015     * Adapted version of pageTemplate() function
1016     */
1017    function _pageTemplate($data) {
1018        global $conf, $INFO;
1019
1020        $id   = $data['id'];
1021        $user = $_SERVER['REMOTE_USER'];
1022        $tpl  = io_readFile(DOKU_PLUGIN.'discussion/_template.txt');
1023
1024        // standard replacements
1025        $replace = array(
1026                '@NS@'   => $data['ns'],
1027                '@PAGE@' => strtr(noNS($id),'_',' '),
1028                '@USER@' => $user,
1029                '@NAME@' => $INFO['userinfo']['name'],
1030                '@MAIL@' => $INFO['userinfo']['mail'],
1031                '@DATE@' => strftime($conf['dformat']),
1032                );
1033
1034        // additional replacements
1035        $replace['@BACK@']  = $data['back'];
1036        $replace['@TITLE@'] = $data['title'];
1037
1038        // avatar if useavatar and avatar plugin available
1039        if ($this->getConf('useavatar')
1040                && (@file_exists(DOKU_PLUGIN.'avatar/syntax.php'))
1041                && (!plugin_isdisabled('avatar'))) {
1042            $replace['@AVATAR@'] = '{{avatar>'.$user.' }} ';
1043        } else {
1044            $replace['@AVATAR@'] = '';
1045        }
1046
1047        // tag if tag plugin is available
1048        if ((@file_exists(DOKU_PLUGIN.'tag/syntax/tag.php'))
1049                && (!plugin_isdisabled('tag'))) {
1050            $replace['@TAG@'] = "\n\n{{tag>}}";
1051        } else {
1052            $replace['@TAG@'] = '';
1053        }
1054
1055        // do the replace
1056        $tpl = str_replace(array_keys($replace), array_values($replace), $tpl);
1057        return $tpl;
1058    }
1059
1060    /**
1061     * Checks if the CAPTCHA string submitted is valid
1062     *
1063     * @author     Andreas Gohr <gohr@cosmocode.de>
1064     * @adaption   Esther Brunner <wikidesign@gmail.com>
1065     */
1066    function _captchaCheck() {
1067        if (@file_exists(DOKU_PLUGIN.'captcha/disabled')) return; // CAPTCHA is disabled
1068
1069        require_once(DOKU_PLUGIN.'captcha/action.php');
1070        $captcha = new action_plugin_captcha;
1071
1072        // do nothing if logged in user and no CAPTCHA required
1073        if (!$captcha->getConf('forusers') && $_SERVER['REMOTE_USER']) return;
1074
1075        // compare provided string with decrypted captcha
1076        $rand = PMA_blowfish_decrypt($_REQUEST['plugin__captcha_secret'], auth_cookiesalt());
1077        $code = $captcha->_generateCAPTCHA($captcha->_fixedIdent(), $rand);
1078
1079        if (!$_REQUEST['plugin__captcha_secret'] ||
1080                !$_REQUEST['plugin__captcha'] ||
1081                strtoupper($_REQUEST['plugin__captcha']) != $code) {
1082
1083            // CAPTCHA test failed! Continue to edit instead of saving
1084            msg($captcha->getLang('testfailed'), -1);
1085            if ($_REQUEST['comment'] == 'save') $_REQUEST['comment'] = 'edit';
1086            elseif ($_REQUEST['comment'] == 'add') $_REQUEST['comment'] = 'show';
1087        }
1088        // if we arrive here it was a valid save
1089    }
1090
1091    /**
1092     * Adds the comments to the index
1093     */
1094    function idx_add_discussion(&$event, $param) {
1095
1096        // get .comments meta file name
1097        $file = metaFN($event->data[0], '.comments');
1098
1099        if (@file_exists($file)) $data = unserialize(io_readFile($file, false));
1100        if ((!$data['status']) || ($data['number'] == 0)) return; // comments are turned off
1101
1102        // now add the comments
1103        if (isset($data['comments'])) {
1104            foreach ($data['comments'] as $key => $value) {
1105                $event->data[1] .= $this->_addCommentWords($key, $data);
1106            }
1107        }
1108    }
1109
1110    /**
1111     * Adds the words of a given comment to the index
1112     */
1113    function _addCommentWords($cid, &$data, $parent = '') {
1114
1115        if (!isset($data['comments'][$cid])) return ''; // comment was removed
1116        $comment = $data['comments'][$cid];
1117
1118        if (!is_array($comment)) return '';             // corrupt datatype
1119        if ($comment['parent'] != $parent) return '';   // reply to an other comment
1120        if (!$comment['show']) return '';               // hidden comment
1121
1122        $text = $comment['raw'];                        // we only add the raw comment text
1123        if (is_array($comment['replies'])) {             // and the replies
1124            foreach ($comment['replies'] as $rid) {
1125                $text .= $this->_addCommentWords($rid, $data, $cid);
1126            }
1127        }
1128        return ' '.$text;
1129    }
1130}
1131// vim:ts=4:sw=4:et:enc=utf-8:
1132