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