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