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