xref: /plugin/discussion/action.php (revision 5886c85b1a39171e64cac46e45b2f5bfc77b7bbc)
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 != 'unsubscribe' && $event->data != 'confirmsubscribe') return;
189
190        if ($event->data == 'unsubscribe' or $event->data == '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 == 'unsubscribe') {
211                        unset($data['subscribers'][$mail]);
212                        msg(sprintf($lang['unsubscribe_success'], $mail, $ID), 1);
213                    } elseif($event->data == '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 ($raw) {
495            global $TEXT;
496
497            $otxt = $TEXT; // set $TEXT to comment text for wordblock check
498            $TEXT = $raw;
499
500            // spamcheck against the DokuWiki blacklist
501            if (checkwordblock()) {
502                msg($this->getLang('wordblock'), -1);
503                return false;
504            }
505
506            $TEXT = $otxt; // restore global $TEXT
507        }
508
509        // get discussion meta file name
510        $file = metaFN($ID, '.comments');
511        $data = unserialize(io_readFile($file, false));
512
513        if (!is_array($cids)) $cids = array($cids);
514        foreach ($cids as $cid) {
515
516            if (is_array($data['comments'][$cid]['user'])) {
517                $user    = $data['comments'][$cid]['user']['id'];
518                $convert = false;
519            } else {
520                $user    = $data['comments'][$cid]['user'];
521                $convert = true;
522            }
523
524            // someone else was trying to edit our comment -> abort
525            if (($user != $_SERVER['REMOTE_USER']) && (!auth_ismanager())) return false;
526
527            $date = time();
528
529            // need to convert to new format?
530            if ($convert) {
531                $data['comments'][$cid]['user'] = array(
532                        'id'      => $user,
533                        'name'    => $data['comments'][$cid]['name'],
534                        'mail'    => $data['comments'][$cid]['mail'],
535                        'url'     => $data['comments'][$cid]['url'],
536                        'address' => $data['comments'][$cid]['address'],
537                        );
538                $data['comments'][$cid]['date'] = array(
539                        'created' => $data['comments'][$cid]['date']
540                        );
541            }
542
543            if ($act == 'toogle') {     // toogle visibility
544                $now = $data['comments'][$cid]['show'];
545                $data['comments'][$cid]['show'] = !$now;
546                $data['number'] = $this->_count($data);
547
548                $type = ($data['comments'][$cid]['show'] ? 'sc' : 'hc');
549
550            } elseif ($act == 'show') { // show comment
551                $data['comments'][$cid]['show'] = true;
552                $data['number'] = $this->_count($data);
553
554                $type = 'sc'; // show comment
555
556            } elseif ($act == 'hide') { // hide comment
557                $data['comments'][$cid]['show'] = false;
558                $data['number'] = $this->_count($data);
559
560                $type = 'hc'; // hide comment
561
562            } elseif (!$raw) {          // remove the comment
563                $data['comments'] = $this->_removeComment($cid, $data['comments']);
564                $data['number'] = $this->_count($data);
565
566                $type = 'dc'; // delete comment
567
568            } else {                   // save changed comment
569                $xhtml = $this->_render($raw);
570
571                // now change the comment's content
572                $data['comments'][$cid]['date']['modified'] = $date;
573                $data['comments'][$cid]['raw']              = $raw;
574                $data['comments'][$cid]['xhtml']            = $xhtml;
575
576                $type = 'ec'; // edit comment
577            }
578        }
579
580        // save the comment metadata file
581        io_saveFile($file, serialize($data));
582        $this->_addLogEntry($date, $ID, $type, '', $cid);
583
584        $this->_redirect($cid);
585        return true;
586    }
587
588    /**
589     * Recursive function to remove a comment
590     */
591    function _removeComment($cid, $comments) {
592        if (is_array($comments[$cid]['replies'])) {
593            foreach ($comments[$cid]['replies'] as $rid) {
594                $comments = $this->_removeComment($rid, $comments);
595            }
596        }
597        unset($comments[$cid]);
598        return $comments;
599    }
600
601    /**
602     * Prints an individual comment
603     */
604    function _print($cid, &$data, $parent = '', $reply = '', $visible = true) {
605
606        if (!isset($data['comments'][$cid])) return false; // comment was removed
607        $comment = $data['comments'][$cid];
608
609        if (!is_array($comment)) return false;             // corrupt datatype
610
611        if ($comment['parent'] != $parent) return true;    // reply to an other comment
612
613        if (!$comment['show']) {                            // comment hidden
614            if (auth_ismanager()) $hidden = ' comment_hidden';
615            else return true;
616        } else {
617            $hidden = '';
618        }
619
620        if($this->getConf('newestfirst')) {
621            // reply form
622            $this->_print_form($cid, $reply);
623            // replies to this comment entry?
624            $this->_print_replies($cid, $data, $reply, $visible);
625            // print the actual comment
626            $this->_print_comment($cid, $data, $parent, $reply, $visible, $hidden);
627        } else {
628            // print the actual comment
629            $this->_print_comment($cid, $data, $parent, $reply, $visible, $hidden);
630            // replies to this comment entry?
631            $this->_print_replies($cid, $data, $reply, $visible);
632            // reply form
633            $this->_print_form($cid, $reply);
634        }
635    }
636
637    function _print_comment($cid, &$data, $parent, $reply, $visible, $hidden)
638    {
639        global $conf, $lang, $ID, $HIGH;
640        $comment = $data['comments'][$cid];
641
642        // comment head with date and user data
643        ptln('<div class="hentry'.$hidden.'">', 4);
644        ptln('<div class="comment_head">', 6);
645        ptln('<a name="comment_'.$cid.'" id="comment_'.$cid.'"></a>', 8);
646        $head = '<span class="vcard author">';
647
648        // prepare variables
649        if (is_array($comment['user'])) { // new format
650            $user    = $comment['user']['id'];
651            $name    = $comment['user']['name'];
652            $mail    = $comment['user']['mail'];
653            $url     = $comment['user']['url'];
654            $address = $comment['user']['address'];
655        } else {                         // old format
656            $user    = $comment['user'];
657            $name    = $comment['name'];
658            $mail    = $comment['mail'];
659            $url     = $comment['url'];
660            $address = $comment['address'];
661        }
662        if (is_array($comment['date'])) { // new format
663            $created  = $comment['date']['created'];
664            $modified = $comment['date']['modified'];
665        } else {                         // old format
666            $created  = $comment['date'];
667            $modified = $comment['edited'];
668        }
669
670        // show avatar image?
671        if ($this->_use_avatar()) {
672            if(!$mail) $mail = $name;
673            $avatar = $this->avatar->getXHTML($mail, $name, 'left');
674            if($avatar) $head .= $avatar;
675        }
676
677        if ($this->getConf('linkemail') && $mail) {
678            $head .= $this->email($mail, $name, 'email fn');
679        } elseif ($url) {
680            $head .= $this->external_link($this->_checkURL($url), $name, 'urlextern url fn');
681        } else {
682            $head .= '<span class="fn">'.$name.'</span>';
683        }
684        if ($address) $head .= ', <span class="adr">'.$address.'</span>';
685        $head .= '</span>, '.
686            '<abbr class="published" title="'.strftime('%Y-%m-%dT%H:%M:%SZ', $created).'">'.
687            strftime($conf['dformat'], $created).'</abbr>';
688        if ($comment['edited']) $head .= ' (<abbr class="updated" title="'.
689                strftime('%Y-%m-%dT%H:%M:%SZ', $modified).'">'.strftime($conf['dformat'], $modified).
690                '</abbr>)';
691        ptln($head, 8);
692        ptln('</div>', 6); // class="comment_head"
693
694        // main comment content
695        ptln('<div class="comment_body entry-content"'.
696                ($this->getConf('useavatar') ? $this->_get_style() : '').'>', 6);
697        echo ($HIGH?html_hilight($comment['xhtml'],$HIGH):$comment['xhtml']).DOKU_LF;
698        ptln('</div>', 6); // class="comment_body"
699
700        if ($visible) {
701            ptln('<div class="comment_buttons">', 6);
702
703            // show reply button?
704            if (($data['status'] == 1) && !$reply && $comment['show']
705                    && ($this->getConf('allowguests') || $_SERVER['REMOTE_USER']) && $this->getConf('usethreading'))
706                $this->_button($cid, $this->getLang('btn_reply'), 'reply', true);
707
708            // show edit, show/hide and delete button?
709            if ((($user == $_SERVER['REMOTE_USER']) && ($user != '')) || (auth_ismanager())) {
710                $this->_button($cid, $lang['btn_secedit'], 'edit', true);
711                $label = ($comment['show'] ? $this->getLang('btn_hide') : $this->getLang('btn_show'));
712                $this->_button($cid, $label, 'toogle');
713                $this->_button($cid, $lang['btn_delete'], 'delete');
714            }
715            ptln('</div>', 6); // class="comment_buttons"
716        }
717        ptln('</div>', 4); // class="hentry"
718    }
719
720    function _print_form($cid, $reply)
721    {
722        if ($this->getConf('usethreading') && $reply == $cid) {
723            ptln('<div class="comment_replies">', 4);
724            $this->_form('', 'add', $cid);
725            ptln('</div>', 4); // class="comment_replies"
726        }
727    }
728
729    function _print_replies($cid, &$data, $reply, &$visible)
730    {
731        $comment = $data['comments'][$cid];
732        if (!count($comment['replies'])) {
733            return;
734        }
735        ptln('<div class="comment_replies"'.$this->_get_style().'>', 4);
736        $visible = ($comment['show'] && $visible);
737        foreach ($comment['replies'] as $rid) {
738            $this->_print($rid, $data, $cid, $reply, $visible);
739        }
740        ptln('</div>', 4);
741    }
742
743    function _use_avatar()
744    {
745        if (is_null($this->use_avatar)) {
746            $this->use_avatar = $this->getConf('useavatar')
747                    && (!plugin_isdisabled('avatar'))
748                    && ($this->avatar =& plugin_load('helper', 'avatar'));
749        }
750        return $this->use_avatar;
751    }
752
753    function _get_style()
754    {
755        if (is_null($this->style)){
756            if ($this->_use_avatar()) {
757                $this->style = ' style="margin-left: '.($this->avatar->getConf('size') + 14).'px;"';
758            } else {
759                $this->style = ' style="margin-left: 20px;"';
760            }
761        }
762        return $this->style;
763    }
764
765    /**
766     * Outputs the comment form
767     */
768    function _form($raw = '', $act = 'add', $cid = NULL) {
769        global $lang;
770        global $conf;
771        global $ID;
772        global $INFO;
773
774        // not for unregistered users when guest comments aren't allowed
775        if (!$_SERVER['REMOTE_USER'] && !$this->getConf('allowguests')) return false;
776
777        // fill $raw with $_REQUEST['text'] if it's empty (for failed CAPTCHA check)
778        if (!$raw && ($_REQUEST['comment'] == 'show')) $raw = $_REQUEST['text'];
779        ?>
780
781        <div class="comment_form">
782          <form id="discussion__comment_form" method="post" action="<?php echo script() ?>" accept-charset="<?php echo $lang['encoding'] ?>">
783            <div class="no">
784              <input type="hidden" name="id" value="<?php echo $ID ?>" />
785              <input type="hidden" name="do" value="show" />
786              <input type="hidden" name="comment" value="<?php echo $act ?>" />
787        <?php
788        // for adding a comment
789        if ($act == 'add') {
790        ?>
791              <input type="hidden" name="reply" value="<?php echo $cid ?>" />
792        <?php
793        // for guest/adminimport: show name, e-mail and subscribe to comments fields
794        if(!$_SERVER['REMOTE_USER'] or ($this->getConf('adminimport') && auth_ismanager())) {
795        ?>
796              <input type="hidden" name="user" value="<?php echo clientIP() ?>" />
797              <div class="comment_name">
798                <label class="block" for="discussion__comment_name">
799                  <span><?php echo $lang['fullname'] ?>:</span>
800                  <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'])?>" />
801                </label>
802              </div>
803              <div class="comment_mail">
804                <label class="block" for="discussion__comment_mail">
805                  <span><?php echo $lang['email'] ?>:</span>
806                  <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'])?>" />
807                </label>
808              </div>
809        <?php
810        }
811
812        // allow entering an URL
813        if ($this->getConf('urlfield')) {
814        ?>
815              <div class="comment_url">
816                <label class="block" for="discussion__comment_url">
817                  <span><?php echo $this->getLang('url') ?>:</span>
818                  <input type="text" class="edit" name="url" id="discussion__comment_url" size="50" tabindex="3" value="<?php echo hsc($_REQUEST['url'])?>" />
819                </label>
820              </div>
821        <?php
822        }
823
824        // allow entering an address
825        if ($this->getConf('addressfield')) {
826        ?>
827              <div class="comment_address">
828                <label class="block" for="discussion__comment_address">
829                  <span><?php echo $this->getLang('address') ?>:</span>
830                  <input type="text" class="edit" name="address" id="discussion__comment_address" size="50" tabindex="4" value="<?php echo hsc($_REQUEST['address'])?>" />
831                </label>
832              </div>
833        <?php
834        }
835
836        // allow setting the comment date
837        if ($this->getConf('adminimport') && (auth_ismanager())) {
838        ?>
839              <div class="comment_date">
840                <label class="block" for="discussion__comment_date">
841                  <span><?php echo $this->getLang('date') ?>:</span>
842                  <input type="text" class="edit" name="date" id="discussion__comment_date" size="50" />
843                </label>
844              </div>
845        <?php
846        }
847
848        // for saving a comment
849        } else {
850        ?>
851              <input type="hidden" name="cid" value="<?php echo $cid ?>" />
852        <?php
853        }
854        ?>
855              <div class="comment_text">
856                <div id="discussion__comment_toolbar">
857                  <?php echo $this->getLang('entercomment')?>
858                  <?php if($this->getLang('wikisyntaxok')) echo ', ' . $this->getLang('wikisyntax') . ':';?>
859                </div>
860                <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
861                  if($raw) {
862                      echo formText($raw);
863                  } else {
864                      echo $_REQUEST['text'];
865                  }
866                ?></textarea>
867              </div>
868        <?php //bad and dirty event insert hook
869        $evdata = array('writable' => true);
870        trigger_event('HTML_EDITFORM_INJECTION', $evdata);
871        ?>
872              <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" />
873              <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]" />
874
875        <?php if((!$_SERVER['REMOTE_USER'] || $_SERVER['REMOTE_USER'] && !$conf['subscribers']) && $this->getConf('subscribe')) { ?>
876              <div class="comment_subscribe">
877                <input type="checkbox" id="discussion__comment_subscribe" name="subscribe" tabindex="6" />
878                <label class="block" for="discussion__comment_subscribe">
879                  <span><?php echo $this->getLang('subscribe') ?></span>
880                </label>
881              </div>
882        <?php } ?>
883
884              <div class="clearer"></div>
885              <div id="discussion__comment_preview">&nbsp;</div>
886            </div>
887          </form>
888        </div>
889        <?php
890        if ($this->getConf('usecocomment')) echo $this->_coComment();
891    }
892
893    /**
894     * Adds a javascript to interact with coComments
895     */
896    function _coComment() {
897        global $ID;
898        global $conf;
899        global $INFO;
900
901        $user = $_SERVER['REMOTE_USER'];
902
903        ?>
904        <script type="text/javascript"><!--//--><![CDATA[//><!--
905          var blogTool  = "DokuWiki";
906          var blogURL   = "<?php echo DOKU_URL ?>";
907          var blogTitle = "<?php echo $conf['title'] ?>";
908          var postURL   = "<?php echo wl($ID, '', true) ?>";
909          var postTitle = "<?php echo tpl_pagetitle($ID, true) ?>";
910        <?php
911        if ($user) {
912        ?>
913          var commentAuthor = "<?php echo $INFO['userinfo']['name'] ?>";
914        <?php
915        } else {
916        ?>
917          var commentAuthorFieldName = "name";
918        <?php
919        }
920        ?>
921          var commentAuthorLoggedIn = <?php echo ($user ? 'true' : 'false') ?>;
922          var commentFormID         = "discussion__comment_form";
923          var commentTextFieldName  = "text";
924          var commentButtonName     = "submit";
925          var cocomment_force       = false;
926        //--><!]]></script>
927        <script type="text/javascript" src="http://www.cocomment.com/js/cocomment.js">
928        </script>
929        <?php
930    }
931
932    /**
933     * General button function
934     */
935    function _button($cid, $label, $act, $jump = false) {
936        global $ID;
937
938        $anchor = ($jump ? '#discussion__comment_form' : '' );
939
940        ?>
941        <form class="button discussion__<?php echo $act?>" method="get" action="<?php echo script().$anchor ?>">
942          <div class="no">
943            <input type="hidden" name="id" value="<?php echo $ID ?>" />
944            <input type="hidden" name="do" value="show" />
945            <input type="hidden" name="comment" value="<?php echo $act ?>" />
946            <input type="hidden" name="cid" value="<?php echo $cid ?>" />
947            <input type="submit" value="<?php echo $label ?>" class="button" title="<?php echo $label ?>" />
948          </div>
949        </form>
950        <?php
951        return true;
952    }
953
954    /**
955     * Adds an entry to the comments changelog
956     *
957     * @author Esther Brunner <wikidesign@gmail.com>
958     * @author Ben Coburn <btcoburn@silicodon.net>
959     */
960    function _addLogEntry($date, $id, $type = 'cc', $summary = '', $extra = '') {
961        global $conf;
962
963        $changelog = $conf['metadir'].'/_comments.changes';
964
965        if(!$date) $date = time(); //use current time if none supplied
966        $remote = $_SERVER['REMOTE_ADDR'];
967        $user   = $_SERVER['REMOTE_USER'];
968
969        $strip = array("\t", "\n");
970        $logline = array(
971                'date'  => $date,
972                'ip'    => $remote,
973                'type'  => str_replace($strip, '', $type),
974                'id'    => $id,
975                'user'  => $user,
976                'sum'   => str_replace($strip, '', $summary),
977                'extra' => str_replace($strip, '', $extra)
978                );
979
980        // add changelog line
981        $logline = implode("\t", $logline)."\n";
982        io_saveFile($changelog, $logline, true); //global changelog cache
983        $this->_trimRecentCommentsLog($changelog);
984
985        // tell the indexer to re-index the page
986        @unlink(metaFN($id, '.indexed'));
987    }
988
989    /**
990     * Trims the recent comments cache to the last $conf['changes_days'] recent
991     * changes or $conf['recent'] items, which ever is larger.
992     * The trimming is only done once a day.
993     *
994     * @author Ben Coburn <btcoburn@silicodon.net>
995     */
996    function _trimRecentCommentsLog($changelog) {
997        global $conf;
998
999        if (@file_exists($changelog) &&
1000                (filectime($changelog) + 86400) < time() &&
1001                !@file_exists($changelog.'_tmp')) {
1002
1003            io_lock($changelog);
1004            $lines = file($changelog);
1005            if (count($lines)<$conf['recent']) {
1006                // nothing to trim
1007                io_unlock($changelog);
1008                return true;
1009            }
1010
1011            io_saveFile($changelog.'_tmp', '');                  // presave tmp as 2nd lock
1012            $trim_time = time() - $conf['recent_days']*86400;
1013            $out_lines = array();
1014
1015            $num = count($lines);
1016            for ($i=0; $i<$num; $i++) {
1017                $log = parseChangelogLine($lines[$i]);
1018                if ($log === false) continue;                      // discard junk
1019                if ($log['date'] < $trim_time) {
1020                    $old_lines[$log['date'].".$i"] = $lines[$i];     // keep old lines for now (append .$i to prevent key collisions)
1021                } else {
1022                    $out_lines[$log['date'].".$i"] = $lines[$i];     // definitely keep these lines
1023                }
1024            }
1025
1026            // sort the final result, it shouldn't be necessary,
1027            // however the extra robustness in making the changelog cache self-correcting is worth it
1028            ksort($out_lines);
1029            $extra = $conf['recent'] - count($out_lines);        // do we need extra lines do bring us up to minimum
1030            if ($extra > 0) {
1031                ksort($old_lines);
1032                $out_lines = array_merge(array_slice($old_lines,-$extra),$out_lines);
1033            }
1034
1035            // save trimmed changelog
1036            io_saveFile($changelog.'_tmp', implode('', $out_lines));
1037            @unlink($changelog);
1038            if (!rename($changelog.'_tmp', $changelog)) {
1039                // rename failed so try another way...
1040                io_unlock($changelog);
1041                io_saveFile($changelog, implode('', $out_lines));
1042                @unlink($changelog.'_tmp');
1043            } else {
1044                io_unlock($changelog);
1045            }
1046            return true;
1047        }
1048    }
1049
1050    /**
1051     * Sends a notify mail on new comment
1052     *
1053     * @param  array  $comment  data array of the new comment
1054     *
1055     * @author Andreas Gohr <andi@splitbrain.org>
1056     * @author Esther Brunner <wikidesign@gmail.com>
1057     */
1058    function _notify($comment, &$subscribers) {
1059        global $conf;
1060        global $ID;
1061
1062        $notify_text = io_readfile($this->localfn('subscribermail'));
1063        $confirm_text = io_readfile($this->localfn('confirmsubscribe'));
1064        $subject_notify = '['.$conf['title'].'] '.$this->getLang('mail_newcomment');
1065        $subject_subscribe = '['.$conf['title'].'] '.$this->getLang('subscribe');
1066
1067        $search = array(
1068                '@PAGE@',
1069                '@TITLE@',
1070                '@DATE@',
1071                '@NAME@',
1072                '@TEXT@',
1073                '@COMMENTURL@',
1074                '@UNSUBSCRIBE@',
1075                '@DOKUWIKIURL@',
1076                );
1077
1078        // notify page subscribers
1079        if ($conf['subscribers'] || $conf['notify']) {
1080            $list = explode(',', subscriber_addresslist($ID));
1081            $to   = (!empty($conf['notify'])) ? $conf['notify'] : array_pop($list);
1082            $bcc  = implode(',', $list);
1083
1084            $replace = array(
1085                    $ID,
1086                    $conf['title'],
1087                    strftime($conf['dformat'], $comment['date']['created']),
1088                    $comment['user']['name'],
1089                    $comment['raw'],
1090                    wl($ID, '', true) . '#comment_' . $comment['cid'],
1091                    wl($ID, 'do=unsubscribe', true, '&'),
1092                    DOKU_URL,
1093                    );
1094
1095                $body = str_replace($search, $replace, $notify_text);
1096                mail_send($to, $subject_notify, $body, $conf['mailfrom'], '', $bcc);
1097        }
1098
1099        // notify comment subscribers
1100        if (!empty($subscribers)) {
1101
1102            foreach($subscribers as $mail => $data) {
1103                $to = $mail;
1104
1105                if($data['active']) {
1106                    $replace = array(
1107                            $ID,
1108                            $conf['title'],
1109                            strftime($conf['dformat'], $comment['date']['created']),
1110                            $comment['user']['name'],
1111                            $comment['raw'],
1112                            wl($ID, '', true) . '#comment_' . $comment['cid'],
1113                            wl($ID, 'do=unsubscribe&hash=' . $data['hash'], true, '&'),
1114                            DOKU_URL,
1115                            );
1116
1117                    $body = str_replace($search, $replace, $notify_text);
1118                    mail_send($to, $subject_notify, $body, $conf['mailfrom']);
1119                } elseif(!$data['active'] && !$data['confirmsent']) {
1120                    $search = array(
1121                            '@PAGE@',
1122                            '@TITLE@',
1123                            '@SUBSCRIBE@',
1124                            '@DOKUWIKIURL@',
1125                            );
1126                    $replace = array(
1127                            $ID,
1128                            $conf['title'],
1129                            wl($ID, 'do=confirmsubscribe&hash=' . $data['hash'], true, '&'),
1130                            DOKU_URL,
1131                            );
1132
1133                    $body = str_replace($search, $replace, $confirm_text);
1134                    mail_send($to, $subject_subscribe, $body, $conf['mailfrom']);
1135                    $subscribers[$mail]['confirmsent'] = true;
1136                }
1137            }
1138        }
1139    }
1140
1141    /**
1142     * Counts the number of visible comments
1143     */
1144    function _count($data) {
1145        $number = 0;
1146        foreach ($data['comments'] as $cid => $comment) {
1147            if ($comment['parent']) continue;
1148            if (!$comment['show']) continue;
1149            $number++;
1150            $rids = $comment['replies'];
1151            if (count($rids)) $number = $number + $this->_countReplies($data, $rids);
1152        }
1153        return $number;
1154    }
1155
1156    function _countReplies(&$data, $rids) {
1157        $number = 0;
1158        foreach ($rids as $rid) {
1159            if (!isset($data['comments'][$rid])) continue; // reply was removed
1160            if (!$data['comments'][$rid]['show']) continue;
1161            $number++;
1162            $rids = $data['comments'][$rid]['replies'];
1163            if (count($rids)) $number = $number + $this->_countReplies($data, $rids);
1164        }
1165        return $number;
1166    }
1167
1168    /**
1169     * Renders the comment text
1170     */
1171    function _render($raw) {
1172        if ($this->getConf('wikisyntaxok')) {
1173            $xhtml = $this->render($raw);
1174        } else { // wiki syntax not allowed -> just encode special chars
1175            $xhtml = hsc(trim($raw));
1176            $xhtml = str_replace("\n", '<br />', $xhtml);
1177        }
1178        return $xhtml;
1179    }
1180
1181    /**
1182     * Finds out whether there is a discussion section for the current page
1183     */
1184    function _hasDiscussion(&$title) {
1185        global $ID;
1186
1187        $cfile = metaFN($ID, '.comments');
1188
1189        if (!@file_exists($cfile)) {
1190            if ($this->getConf('automatic')) {
1191                return true;
1192            } else {
1193                return false;
1194            }
1195        }
1196
1197        $comments = unserialize(io_readFile($cfile, false));
1198
1199        if ($comments['title']) $title = hsc($comments['title']);
1200        $num = $comments['number'];
1201        if ((!$comments['status']) || (($comments['status'] == 2) && (!$num))) return false;
1202        else return true;
1203    }
1204
1205    /**
1206     * Creates a new thread page
1207     */
1208    function _newThread() {
1209        global $ID, $INFO;
1210
1211        $ns    = cleanID($_REQUEST['ns']);
1212        $title = str_replace(':', '', $_REQUEST['title']);
1213        $back  = $ID;
1214        $ID    = ($ns ? $ns.':' : '').cleanID($title);
1215        $INFO  = pageinfo();
1216
1217        // check if we are allowed to create this file
1218        if ($INFO['perm'] >= AUTH_CREATE) {
1219
1220            //check if locked by anyone - if not lock for my self
1221            if ($INFO['locked']) return 'locked';
1222            else lock($ID);
1223
1224            // prepare the new thread file with default stuff
1225            if (!@file_exists($INFO['filepath'])) {
1226                global $TEXT;
1227
1228                $TEXT = pageTemplate(array(($ns ? $ns.':' : '').$title));
1229                if (!$TEXT) {
1230                    $data = array('id' => $ID, 'ns' => $ns, 'title' => $title, 'back' => $back);
1231                    $TEXT = $this->_pageTemplate($data);
1232                }
1233                return 'preview';
1234            } else {
1235                return 'edit';
1236            }
1237        } else {
1238            return 'show';
1239        }
1240    }
1241
1242    /**
1243     * Adapted version of pageTemplate() function
1244     */
1245    function _pageTemplate($data) {
1246        global $conf, $INFO;
1247
1248        $id   = $data['id'];
1249        $user = $_SERVER['REMOTE_USER'];
1250        $tpl  = io_readFile(DOKU_PLUGIN.'discussion/_template.txt');
1251
1252        // standard replacements
1253        $replace = array(
1254                '@NS@'   => $data['ns'],
1255                '@PAGE@' => strtr(noNS($id),'_',' '),
1256                '@USER@' => $user,
1257                '@NAME@' => $INFO['userinfo']['name'],
1258                '@MAIL@' => $INFO['userinfo']['mail'],
1259                '@DATE@' => strftime($conf['dformat']),
1260                );
1261
1262        // additional replacements
1263        $replace['@BACK@']  = $data['back'];
1264        $replace['@TITLE@'] = $data['title'];
1265
1266        // avatar if useavatar and avatar plugin available
1267        if ($this->getConf('useavatar')
1268                && (@file_exists(DOKU_PLUGIN.'avatar/syntax.php'))
1269                && (!plugin_isdisabled('avatar'))) {
1270            $replace['@AVATAR@'] = '{{avatar>'.$user.' }} ';
1271        } else {
1272            $replace['@AVATAR@'] = '';
1273        }
1274
1275        // tag if tag plugin is available
1276        if ((@file_exists(DOKU_PLUGIN.'tag/syntax/tag.php'))
1277                && (!plugin_isdisabled('tag'))) {
1278            $replace['@TAG@'] = "\n\n{{tag>}}";
1279        } else {
1280            $replace['@TAG@'] = '';
1281        }
1282
1283        // do the replace
1284        $tpl = str_replace(array_keys($replace), array_values($replace), $tpl);
1285        return $tpl;
1286    }
1287
1288    /**
1289     * Checks if the CAPTCHA string submitted is valid
1290     *
1291     * @author     Andreas Gohr <gohr@cosmocode.de>
1292     * @adaption   Esther Brunner <wikidesign@gmail.com>
1293     */
1294    function _captchaCheck() {
1295        if (plugin_isdisabled('captcha') || (!$captcha = plugin_load('helper', 'captcha')))
1296            return; // CAPTCHA is disabled or not available
1297
1298        // do nothing if logged in user and no CAPTCHA required
1299        if (!$captcha->getConf('forusers') && $_SERVER['REMOTE_USER']) return;
1300
1301        // compare provided string with decrypted captcha
1302        $rand = PMA_blowfish_decrypt($_REQUEST['plugin__captcha_secret'], auth_cookiesalt());
1303        $code = $captcha->_generateCAPTCHA($captcha->_fixedIdent(), $rand);
1304
1305        if (!$_REQUEST['plugin__captcha_secret'] ||
1306                !$_REQUEST['plugin__captcha'] ||
1307                strtoupper($_REQUEST['plugin__captcha']) != $code) {
1308
1309            // CAPTCHA test failed! Continue to edit instead of saving
1310            msg($captcha->getLang('testfailed'), -1);
1311            if ($_REQUEST['comment'] == 'save') $_REQUEST['comment'] = 'edit';
1312            elseif ($_REQUEST['comment'] == 'add') $_REQUEST['comment'] = 'show';
1313        }
1314        // if we arrive here it was a valid save
1315    }
1316
1317    /**
1318     * Adds the comments to the index
1319     */
1320    function idx_add_discussion(&$event, $param) {
1321
1322        // get .comments meta file name
1323        $file = metaFN($event->data[0], '.comments');
1324
1325        if (@file_exists($file)) $data = unserialize(io_readFile($file, false));
1326        if ((!$data['status']) || ($data['number'] == 0)) return; // comments are turned off
1327
1328        // now add the comments
1329        if (isset($data['comments'])) {
1330            foreach ($data['comments'] as $key => $value) {
1331                $event->data[1] .= $this->_addCommentWords($key, $data);
1332            }
1333        }
1334    }
1335
1336    /**
1337     * Adds the words of a given comment to the index
1338     */
1339    function _addCommentWords($cid, &$data, $parent = '') {
1340
1341        if (!isset($data['comments'][$cid])) return ''; // comment was removed
1342        $comment = $data['comments'][$cid];
1343
1344        if (!is_array($comment)) return '';             // corrupt datatype
1345        if ($comment['parent'] != $parent) return '';   // reply to an other comment
1346        if (!$comment['show']) return '';               // hidden comment
1347
1348        $text = $comment['raw'];                        // we only add the raw comment text
1349        if (is_array($comment['replies'])) {             // and the replies
1350            foreach ($comment['replies'] as $rid) {
1351                $text .= $this->_addCommentWords($rid, $data, $cid);
1352            }
1353        }
1354        return ' '.$text;
1355    }
1356
1357    /**
1358     * Only allow http(s) URLs and append http:// to URLs if needed
1359     */
1360    function _checkURL($url) {
1361        if(preg_match("#^http://|^https://#", $url)) {
1362            return hsc($url);
1363        } elseif(substr($url, 0, 4) == 'www.') {
1364            return hsc('http://' . $url);
1365        } else {
1366            return '';
1367        }
1368    }
1369}
1370
1371function _sortCallback($a, $b) {
1372    if (is_array($a['date'])) { // new format
1373        $createdA  = $a['date']['created'];
1374    } else {                         // old format
1375        $createdA  = $a['date'];
1376    }
1377
1378    if (is_array($b['date'])) { // new format
1379        $createdB  = $b['date']['created'];
1380    } else {                         // old format
1381        $createdB  = $b['date'];
1382    }
1383
1384    if ($createdA == $createdB)
1385        return 0;
1386    else
1387        return ($createdA < $createdB) ? -1 : 1;
1388}
1389
1390// vim:ts=4:sw=4:et:enc=utf-8:
1391