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