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