aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/ForumEntry.php
blob: 7ac5306eb62e73198569d87a3e7755b4b68a2bd1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
<?php
/**
 * ForumEntry.php - Allows the retrieval and handling of forum-entrys
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of
 * the License, or (at your option) any later version.
 *
 * @author      Till Glöggler <tgloeggl@uos.de>
 * @license     http://www.gnu.org/licenses/gpl-3.0.html GPL version 3
 * @category    Stud.IP
 */

class ForumEntry  implements PrivacyObject
{
    const WITH_CHILDS = true;
    const WITHOUT_CHILDS = false;
    const THREAD_PREVIEW_LENGTH = 100;
    const POSTINGS_PER_PAGE = 10;
    const FEED_POSTINGS = 100;


    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     * H   E   L   P   E   R   -   F   U   N   C   T   I   O   N   S *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    /**
     * is used for posting-preview. replaces all newlines with spaces
     *
     * @param string $text the text to work on
     * @returns string
     */
    public static function br2space($text)
    {
        return str_replace("\n", ' ', str_replace("\r", '', $text));
    }

    /**
     * remove the edit-html from a posting
     *
     * @param string $description the posting-content
     * @return string the content stripped by the edit-mark
     */
    public static function killEdit($description)
    {
        // wurde schon mal editiert
        if (preg_match('/^(.*)(<admin_msg.*?)$/s', $description, $match)) {
            return $match[1];
        }
        return $description;
    }

    /**
     * add the edit-html to a posting
     *
     * @param string $description the posting-content
     * @return string the content with the edit-mark
     */
    public static function appendEdit($description)
    {
        $edit = "<admin_msg autor=\"" . addslashes(get_fullname()) . "\" chdate=\"" . time() . "\">";
        return $description . $edit;
    }

    /**
     * convert the edit-html to raw text
     *
     * @param string $description the posting-content
     * @return string the content with the raw text version of the edit-mark
     */
    public static function parseEdit($description, $anonymous = false)
    {
        // TODO figure out if this function can be removed
        //      has been replaced with getContentAsHTML in core code
        $content = ForumEntry::killEdit($description);
        $comment = ForumEntry::getEditComment($description, $anonymous);
        return $content . ($comment ? "\n\n%%" . $comment .'%%' : '');
    }

    /**
     * Get content with appended edit comment as HTML.
     *
     * @param string  $description  Database entry of forum entry's body.
     * @param bool    $anonymous    True, if only root is allowed to see
     *                              authors.
     * @return string  Content and edit comment as HTML.
     */
    public static function getContentAsHtml($description, $anonymous = false)
    {
        $raw_content = ForumEntry::killEdit($description);

        $comment = ForumEntry::getEditComment($description, $anonymous);
        $content = formatReady($raw_content);

        if ($comment) {
            $content .= '<br><em>' . htmlReady($comment) . '</em>';
        }

        return $content;
    }

    /**
     * Get author and time of an edited forum entry as a string.
     *
     * @param string  $description  Database entry of forum entry's body.
     * @param bool    $anonymous    True, if only root is allowed to see
     *                              authors.
     * @return string  Author and time or empty string if not edited.
     */
    public static function getEditComment($description, $anonymous = false)
    {
        $info = ForumEntry::getEditInfo($description);
        if ($info) {
            $root = $GLOBALS['perm']->have_perm('root');
            $author = ($anonymous && !$root) ? _('Anonym') : $info['author'];
            $time = date('d.m.y - H:i', $info['time']);
            return '[' . _('Zuletzt editiert von') . " $author - $time]";
        }
        return '';
    }

    /**
     * Get author and time of an edited forum entry.
     *
     * @param string  $description  Database entry of forum entry's body.
     * @return array    Associative array containing author and time.
     *         boolean  False if edit tag was not found.
     */
    public static function getEditInfo($description) {
        if (preg_match('/<admin_msg autor="([^"]*)" chdate="([^"]*)">\s*$/i', $description, $matches)) {
            // wurde schon mal editiert
            return ['author' => $matches[1], 'time' => $matches[2]];
        }
        return false;
    }

    /**
     * Remove all quote blocks AND the quoted text from a forum post.
     *
     * @param String $string The string to remove the quote blocks from
     * @return String the posting without the [quote]-blocks (not just tags!)
     */
    public static function removeQuotes($description)
    {
        if (Studip\Markup::isHtml($description)) {
            // remove all blockquote tags
            $dom = new DOMDocument();
            $old_libxml_error = libxml_use_internal_errors(true);
            $dom->loadHtml($description, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
            libxml_use_internal_errors($old_libxml_error);
            $nodes = iterator_to_array($dom->getElementsByTagName('blockquote'));

            foreach ($nodes as $node) {
                $node->parentNode->removeChild($node);
            }

            return $dom->saveHTML();
        } else {
            $description = preg_replace('/\[quote(=.*)\].*\[\/quote\]/isU', '', $description);
            $description = str_replace('[/quote]', '', $description);
        }
        return $description;
    }


    /**
     * calls Stud.IP's kill_format
     *
     * @param string $text the text to parse
     * @return string the text without format-tags
     */
    public static function killFormat($text)
    {
        return kill_format($text);
    }

    /**
     * returns the entry for the passed topic_id
     *
     * @param  string  $topic_id
     * @return array   array('lft' => ..., 'rgt' => ..., seminar_id => ...)
     *
     * @throws Exception
     */
    public static function getConstraints($topic_id)
    {
        //very bad performance if topic_id is 0 or false
        if (!$topic_id) return false;

        // look up the range of postings
        $range_stmt = DBManager::get()->prepare("SELECT *
            FROM forum_entries WHERE topic_id = ?");
        $range_stmt->execute([$topic_id]);
        if (!$data = $range_stmt->fetch(PDO::FETCH_ASSOC)) {
            return false;
            // throw new Exception("Could not find entry with id >>$topic_id<< in forum_entries, " . __FILE__ . " on line " . __LINE__);
        }

        if ($data['depth'] == 1) {
            $data['area'] = 1;
        }

        return $data;
    }

    /**
     * return the topic_id of the parent element, false if there is none (ie the
     * passed topic_id is already the upper-most node in the tree)
     *
     * @param string $topic_id the topic_id for which the parent shall be found
     *
     * @return string the topic_id of the parent element or false
     */
    public static function getParentTopicId($topic_id)
    {
        $path = ForumEntry::getPathToPosting($topic_id);
        array_pop($path);
        $data = array_pop($path);

        return $data['id'] ?? false;
    }


    /**
     * get the topic_ids of all childs of the passed topic including itself
     *
     * @param string $topic_id the topic_id to find the childs for
     * @return array a list if topic_ids
     */
    public static function getChildTopicIds($topic_id)
    {
        $constraints = ForumEntry::getConstraints($topic_id);

        $stmt = DBManager::get()->prepare("SELECT topic_id
            FROM forum_entries WHERE lft >= ? AND rgt <= ?
                AND seminar_id = ?");
        $stmt->execute([$constraints['lft'], $constraints['rgt'], $constraints['seminar_id']]);

        return $stmt->fetchAll(PDO::FETCH_COLUMN);
    }

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     * D   A   T   A   -   R   E   T   R   I   E   V   A   L *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

     /**
      * get the page the passed posting is on
      *
      * @param  string  $topic_id
      * @return  int
      */
    public static function getPostingPage($topic_id, $constraint = null)
    {
        if (!$constraint) {
            $constraint = ForumEntry::getConstraints($topic_id);
        }

        // this calculation only works for postings
        if ($constraint['depth'] <= 2) return ForumHelpers::getPage();

        if ($parent_id = ForumEntry::getParentTopicId($topic_id)) {
            $parent_constraint = ForumEntry::getConstraints($parent_id);

            return ceil((($constraint['lft'] - $parent_constraint['lft'] + 3) / 2) / ForumEntry::POSTINGS_PER_PAGE);
        }

        return 0;
    }

    /**
     * return the id for the oldest unread child-posting for the passed topic.
     *
     * @param string $parent_id
     * @return string  id of oldest unread posting
     */
    public static function getLastUnread($parent_id)
    {
        $constraint = ForumEntry::getConstraints($parent_id);

        // take users visitdate into account
        $visitdate = ForumVisit::getLastVisit($constraint['seminar_id']);

        // get the first unread entry
        $stmt = DBManager::get()->prepare("SELECT * FROM forum_entries
            WHERE lft > ? AND rgt < ? AND seminar_id = ?
                AND mkdate >= ?
            ORDER BY mkdate ASC LIMIT 1");
        $stmt->execute([$constraint['lft'], $constraint['rgt'], $constraint['seminar_id'], $visitdate]);
        $last_unread = $stmt->fetch(PDO::FETCH_ASSOC);

        return $last_unread ? $last_unread['topic_id'] : null;
    }

    /**
     * retrieve the the latest posting under $parent_id
     * or false if the postings itself is the latest
     *
     * @param string $parent_id the node to lookup the childs in
     * @return mixed the data for the latest postings or false
     */
    public static function getLatestPosting($parent_id)
    {
        $constraint = ForumEntry::getConstraints($parent_id);

        // get last entry
        $stmt = DBManager::get()->prepare("SELECT * FROM forum_entries
            WHERE lft > ? AND rgt < ? AND seminar_id = ?
            ORDER BY mkdate DESC LIMIT 1");
        $stmt->execute([$constraint['lft'], $constraint['rgt'], $constraint['seminar_id']]);

        if (!$data = $stmt->fetch(PDO::FETCH_ASSOC)) {
            return false;
        }

        return $data;
    }

    /**
     * returns a hashmap with arrays containing id and name with the entries
     * which lead to the passed topic
     *
     * @param string $topic_id the topic to get the path for
     *
     * @return array
     */
    public static function getPathToPosting($topic_id)
    {
        $data = ForumEntry::getConstraints($topic_id);
        $ret = [];

        $stmt = DBManager::get()->prepare("SELECT * FROM forum_entries
            WHERE lft <= ? AND rgt >= ? AND seminar_id = ? ORDER BY lft ASC");
        $stmt->execute([$data['lft'], $data['rgt'], $data['seminar_id']]);

        while ($data = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $ret[$data['topic_id']] = $data;
            $ret[$data['topic_id']]['id'] = $data['topic_id'];
        }

        // set the name of the first entry to the name of the category the entry is in
        if (sizeof($ret) > 1) {
            reset($ret);
            $tmp = array_slice($ret, 1, 1);
            $area = array_pop($tmp);
            $top  = current($ret);
            $ret[$top['id']]['name'] = ForumCat::getCategoryNameForArea($area['id']) ?: _('Allgemein');
        }

        return $ret;
    }

    /**
     * returns a hashmap where key is topic_id and value a posting-title from the
     * entries which lead to the passed topic.
     *
     * WARNING: This function ommits postings with an empty title. For a full
     * list please use ForumEntry::getPathToPosting()!
     *
     * @param string $topic_id the topic to get the path for
     *
     * @return array
     */
    public static function getFlatPathToPosting($topic_id)
    {
        // use only the part of the path until the thread, no posting title
        $postings = array_slice(self::getPathToPosting($topic_id), 0, 3);

        // var_dump($postings);

        foreach ($postings as $post) {
            if ($post['name']) {
                $ret[$post['id']] = $post['name'];
            }
        }

        return $ret;
    }

    /**
     * fill the passed postings with additional data
     *
     * @param  array $postings
     * @return array
     */
    public static function parseEntries($postings)
    {
        $posting_list = [];

        // retrieve the postings
        foreach ($postings as $data) {
            // we throw away all formatting stuff, tags, etc, leaving the important bit of information
            $desc_short = ForumEntry::br2space(ForumEntry::killFormat($data['content']));
            if (mb_strlen($desc_short) > (ForumEntry::THREAD_PREVIEW_LENGTH + 2)) {
                $desc_short = mb_substr($desc_short, 0, ForumEntry::THREAD_PREVIEW_LENGTH) . '...';
            } else {
                $desc_short = $desc_short;
            }

            $posting_list[$data['topic_id']] = [
                'author'          => $data['author'],
                'topic_id'        => $data['topic_id'],
                'name'            => formatReady($data['name']),
                'name_raw'        => $data['name'],
                'content'         => ForumEntry::getContentAsHtml($data['content'], $data['anonymous']),
                'content_raw'     => ForumEntry::killEdit($data['content']),
                'content_short'   => $desc_short,
                'chdate'          => $data['chdate'],
                'mkdate'          => $data['mkdate'],
                'user_id'        => $data['user_id'],
                'raw_title'       => $data['name'],
                'raw_description' => ForumEntry::killEdit($data['content']),
                'fav'             => (!empty($data['fav']) && ($data['fav'] == 'fav')),
                'depth'           => $data['depth'],
                'anonymous'       => $data['anonymous'],
                'closed'          => $data['closed'],
                'sticky'          => $data['sticky'],
                'seminar_id'      => $data['seminar_id']
            ];
        } // retrieve the postings

        return $posting_list;
    }

    /**
     * Get all entries for the passed parent_id.
     * Returns an array of the following structure:
     * Array (
     *     'list'  => Array (
     *         'author'          =>
     *         'topic_id'        =>
     *         'name'            => formatReady()
     *         'name_raw'        =>
     *         'content'         => formatReady()
     *         'content_raw'     =>
     *         'content_short'   =>
     *         'chdate'          =>
     *         'mkdate'          =>
     *         'user_id'        =>
     *         'raw_title'       =>
     *         'raw_description' =>
     *         'fav'             =>
     *         'depth'           =>
     *         'sticky'          =>
     *         'closed'          =>
     *         'seminar_id'      =>
     *     )
     *     'count' =>
     * )
     *
     * @param string $parent_id    id of parent-element to get entries for.
     * @param boolean $with_childs  if true, the whole subtree is fetched
     * @param string $add          for additional constraints in the WHERE-part of the query
     * @param string $sort_order   can be ASC or DESC
     * @param int $start        can be used for pagination, is used for the LIMIT-part of the query
     * @param int $limit        number of entries to fetch, defaults to ForumEntry::POSTINGS_PER_PAGE
     *
     * @return array
     *
     * @throws Exception  if the retrieval failed, an Exception is thrown
     */
    public static function getEntries($parent_id, $with_childs = false, $add = '',
        $sort_order = 'DESC', $start = 0, $limit = ForumEntry::POSTINGS_PER_PAGE)
    {
        $constraint = ForumEntry::getConstraints($parent_id);
        $seminar_id = $constraint['seminar_id'];
        $depth      = $constraint['depth'] + 1;

        // count the entries and set correct page if necessary
        if ($with_childs) {
            $count_stmt = DBManager::get()->prepare("SELECT COUNT(*) FROM forum_entries
                LEFT JOIN forum_favorites as ou ON (ou.topic_id = forum_entries.topic_id AND ou.user_id = ?)
                WHERE (forum_entries.seminar_id = ?
                    AND forum_entries.seminar_id != forum_entries.topic_id
                    AND lft > ? AND rgt < ?) "
                . ($depth > 2 ? " OR forum_entries.topic_id = ". DBManager::get()->quote($parent_id) : '')
                . $add
                . " ORDER BY forum_entries.mkdate $sort_order");
            $count_stmt->execute([$GLOBALS['user']->id, $seminar_id, $constraint['lft'], $constraint['rgt']]);
            $count = $count_stmt->fetchColumn();
        } else {
            $count_stmt = DBManager::get()->prepare("SELECT COUNT(*) FROM forum_entries
                LEFT JOIN forum_favorites as ou ON (ou.topic_id = forum_entries.topic_id AND ou.user_id = ?)
                WHERE ((depth = ? AND forum_entries.seminar_id = ?
                    AND forum_entries.seminar_id != forum_entries.topic_id
                    AND lft > ? AND rgt < ?) "
                . ($depth > 2 ? " OR forum_entries.topic_id = ". DBManager::get()->quote($parent_id) : '')
                . ') '. $add
                . " ORDER BY forum_entries.mkdate $sort_order");
            $count_stmt->execute([$GLOBALS['user']->id, $depth, $seminar_id, $constraint['lft'], $constraint['rgt']]);
            $count = $count_stmt->fetchColumn();
        }

        // use the last page if the requested page does not exist
        if ($start > $count) {
            $page = ceil($count / ForumEntry::POSTINGS_PER_PAGE);
            ForumHelpers::setPage($page);
            $start = max(1, $page - 1) * ForumEntry::POSTINGS_PER_PAGE;
        }

        if ($with_childs) {
            $stmt = DBManager::get()->prepare("SELECT forum_entries.*, IF(ou.topic_id IS NOT NULL, 'fav', NULL) as fav
                    FROM forum_entries
                LEFT JOIN forum_favorites as ou ON (ou.topic_id = forum_entries.topic_id AND ou.user_id = ?)
                WHERE (forum_entries.seminar_id = ?
                    AND forum_entries.seminar_id != forum_entries.topic_id
                    AND lft > ? AND rgt < ?) "
                . ($depth > 2 ? " OR forum_entries.topic_id = ". DBManager::get()->quote($parent_id) : '')
                . $add
                . " ORDER BY forum_entries.mkdate $sort_order"
                . ($limit ? " LIMIT $start, $limit" : ''));
            $stmt->execute([$GLOBALS['user']->id, $seminar_id, $constraint['lft'], $constraint['rgt']]);
        } else {
            $stmt = DBManager::get()->prepare("SELECT forum_entries.*, IF(ou.topic_id IS NOT NULL, 'fav', NULL) as fav
                    FROM forum_entries
                LEFT JOIN forum_favorites as ou ON (ou.topic_id = forum_entries.topic_id AND ou.user_id = ?)
                WHERE ((depth = ? AND forum_entries.seminar_id = ?
                    AND lft > ? AND rgt < ?) "
                . ($depth > 2 ? " OR forum_entries.topic_id = ". DBManager::get()->quote($parent_id) : '')
                . ') '. $add
                . " ORDER BY forum_entries.mkdate $sort_order"
                . ($limit ? " LIMIT $start, $limit" : ''));
            $stmt->execute([$GLOBALS['user']->id, $depth, $seminar_id, $constraint['lft'], $constraint['rgt']]);
        }

        if (!$stmt) {
            throw new Exception("Error while retrieving postings in " . __FILE__ . " on line " . __LINE__);
        }

        return ['list' => ForumEntry::parseEntries($stmt->fetchAll(PDO::FETCH_ASSOC)), 'count' => $count];
    }


    /**
     * Takes a posting-array like the one generated by ForumEntry::getList()
     * and adds the child-posting with the freshest creation-date to it.
     *
     * @param array $postings
     * @return array
     */
    public static function getLastPostings($postings)
    {
        foreach ($postings as $key => $posting)
        {
            $last_posting = [];

            if ($data = ForumEntry::getLatestPosting($posting['topic_id'])) {
                $last_posting['topic_id']      = $data['topic_id'];
                $last_posting['date']          = $data['mkdate'];
                $last_posting['user_id']       = $data['user_id'];
                $last_posting['user_fullname'] = $data['author'];
                $last_posting['username']      = get_username($data['user_id']);
                $last_posting['anonymous']     = $data['anonymous'];

                // we throw away all formatting stuff, tags, etc, so we have just the important bit of information
                $text = ForumEntry::removeQuotes($data['name']);
                $text = ForumEntry::br2space(ForumEntry::killFormat($text));

                if (mb_strlen($text) > 42) {
                    $text = mb_substr($text, 0, 40) . '...';
                }

                $last_posting['text'] = $text;
            }

            $postings[$key]['last_posting'] = $last_posting;
            if (!$postings[$key]['last_unread']  = ForumEntry::getLastUnread($posting['topic_id'])) {
                $postings[$key]['last_unread'] = $last_posting['topic_id'] ?? '';
            }
            $postings[$key]['num_postings'] = ForumEntry::countEntries($posting['topic_id']);

            unset($last_posting);
        }

        return $postings;
    }

    /**
     * get a list of postings of a special type
     *
     * @param string $type one of 'area', 'list', 'postings', 'latest', 'favorites', 'dump', 'flat'
     * @param string $parent_id the are to fetch from
     * @return array array('list' => ..., 'count' => ...);
     */
    public static function getList($type, $parent_id)
    {
        $start = (ForumHelpers::getPage() - 1) * ForumEntry::POSTINGS_PER_PAGE;
        switch ($type) {
            case 'area':
                $list = ForumEntry::getEntries($parent_id, ForumEntry::WITHOUT_CHILDS, '', 'DESC', 0, 1000);
                $postings = $list['list'];

                $postings = ForumEntry::getLastPostings($postings);
                return ['list' => $postings, 'count' => $list['count']];

            case 'list':
                $constraint = ForumEntry::getConstraints($parent_id);

                // purpose of the following query is to retrieve the threads
                // for an area ordered by the mkdate of their latest posting
                $stmt = DBManager::get()->prepare("SELECT SQL_CALC_FOUND_ROWS
                        fe.*, IF(ou.topic_id IS NOT NULL, 'fav', NULL) as fav
                    FROM forum_entries AS fe
                    LEFT JOIN forum_favorites as ou ON (ou.topic_id = fe.topic_id AND ou.user_id = :user_id)
                    WHERE fe.seminar_id = :seminar_id AND fe.lft > :left
                        AND fe.rgt < :right AND fe.depth = 2
                    ORDER BY sticky DESC, latest_chdate DESC
                    LIMIT $start, ". ForumEntry::POSTINGS_PER_PAGE);
                $stmt->bindParam(':seminar_id', $constraint['seminar_id']);
                $stmt->bindParam(':left', $constraint['lft'], PDO::PARAM_INT);
                $stmt->bindParam(':right', $constraint['rgt'], PDO::PARAM_INT);
                $stmt->bindParam(':user_id', $GLOBALS['user']->id);
                $stmt->execute();

                $postings = $stmt->fetchAll(PDO::FETCH_ASSOC);
                $count = DBManager::get()->query("SELECT FOUND_ROWS()")->fetchColumn();
                $postings = ForumEntry::parseEntries($postings);
                $postings = ForumEntry::getLastPostings($postings);

                return ['list' => $postings, 'count' => $count];

            case 'postings':
                return ForumEntry::getEntries($parent_id, ForumEntry::WITH_CHILDS, '', 'ASC', $start);

            case 'newest':
                $constraint = ForumEntry::getConstraints($parent_id);
                $last_visit_date = ForumVisit::getLastVisit($constraint['seminar_id']);

                // get postings
                $stmt = DBManager::get()->prepare("SELECT forum_entries.*, IF(ou.topic_id IS NOT NULL, 'fav', NULL) as fav
                    FROM forum_entries
                    LEFT JOIN forum_favorites as ou ON (ou.topic_id = forum_entries.topic_id AND ou.user_id = :user_id)
                    WHERE seminar_id = :seminar_id AND lft > :left
                        AND rgt < :right AND (mkdate >= :mkdate OR chdate >= :mkdate)
                    ORDER BY mkdate ASC
                    LIMIT $start, ". ForumEntry::POSTINGS_PER_PAGE);

                $stmt->bindParam(':seminar_id', $constraint['seminar_id']);
                $stmt->bindParam(':left', $constraint['lft']);
                $stmt->bindParam(':right', $constraint['rgt']);
                $stmt->bindParam(':mkdate', $last_visit_date);
                $stmt->bindParam(':user_id', $GLOBALS['user']->id);
                $stmt->execute();

                $postings = $stmt->fetchAll(PDO::FETCH_ASSOC);

                $postings = ForumEntry::parseEntries($postings);

                // count found postings
                $stmt_count = DBManager::get()->prepare("SELECT COUNT(*)
                    FROM forum_entries
                    WHERE seminar_id = :seminar_id AND lft > :left
                        AND rgt < :right AND mkdate >= :mkdate
                    ORDER BY mkdate ASC");

                $stmt_count->bindParam(':seminar_id', $constraint['seminar_id']);
                $stmt_count->bindParam(':left', $constraint['lft']);
                $stmt_count->bindParam(':right', $constraint['rgt']);
                $stmt_count->bindParam(':mkdate', $last_visit_date);
                $stmt_count->execute();


                // return results
                return ['list' => $postings, 'count' => $stmt_count->fetchColumn()];

            case 'latest':
                return ForumEntry::getEntries($parent_id, ForumEntry::WITH_CHILDS, '', 'DESC', $start);

            case 'favorites':
                $add = "AND ou.topic_id IS NOT NULL";
                return ForumEntry::getEntries($parent_id, ForumEntry::WITH_CHILDS, $add, 'DESC', $start);

            case 'dump':
                $constraint = ForumEntry::getConstraints($parent_id);
                $seminar_id = $constraint['seminar_id'];
                $depth      = $constraint['depth'] + 1;

                $stmt = DBManager::get()->prepare("SELECT * FROM forum_entries
                    WHERE (forum_entries.seminar_id = ?
                        AND forum_entries.seminar_id != forum_entries.topic_id
                        AND lft > ? AND rgt < ?) "
                    . ($depth > 2 ? " OR forum_entries.topic_id = ". DBManager::get()->quote($parent_id) : '')
                    . " ORDER BY forum_entries.lft ASC");
                $stmt->execute([$seminar_id, $constraint['lft'], $constraint['rgt']]);

                return ForumEntry::parseEntries($stmt->fetchAll(PDO::FETCH_ASSOC));

            case 'flat':
                $constraint = ForumEntry::getConstraints($parent_id);

                $stmt = DBManager::get()->prepare("SELECT SQL_CALC_FOUND_ROWS * FROM forum_entries
                    WHERE lft > ? AND rgt < ? AND seminar_id = ? AND depth = ?
                    ORDER BY name ASC");
                $stmt->execute([$constraint['lft'], $constraint['rgt'], $constraint['seminar_id'], $constraint['depth'] + 1]);

                $count = DBManager::get()->query("SELECT FOUND_ROWS()")->fetchColumn();

                $posting_list = [];

                // speed up things a bit by leaving out the formatReady fields
                foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $data) {
                    // we throw away all formatting stuff, tags, etc, leaving the important bit of information
                    $desc_short = ForumEntry::br2space(ForumEntry::killFormat($data['content']));
                    if (mb_strlen($desc_short) > (ForumEntry::THREAD_PREVIEW_LENGTH + 2)) {
                        $desc_short = mb_substr($desc_short, 0, ForumEntry::THREAD_PREVIEW_LENGTH) . '...';
                    } else {
                        $desc_short = $desc_short;
                    }
                    $posting_list[$data['topic_id']] = [
                        'author'          => $data['author'],
                        'topic_id'        => $data['topic_id'],
                        'name_raw'        => $data['name'],
                        'content_raw'     => ForumEntry::killEdit($data['content']),
                        'content_short'   => $desc_short,
                        'chdate'          => $data['chdate'],
                        'mkdate'          => $data['mkdate'],
                        'user_id'         => $data['user_id'],
                        'raw_title'       => $data['name'],
                        'raw_description' => ForumEntry::killEdit($data['content']),
                        'fav'             => (!empty($data['fav']) && $data['fav'] == 'fav'),
                        'depth'           => $data['depth'],
                        'seminar_id'      => $data['seminar_id']
                    ];
                }

                return ['list' => $posting_list, 'count' => $count];

            case 'depth_to_large':
                $constraint = ForumEntry::getConstraints($parent_id);

                $stmt = DBManager::get()->prepare("SELECT SQL_CALC_FOUND_ROWS * FROM forum_entries
                    WHERE lft > ? AND rgt < ? AND seminar_id = ? AND depth > 3
                    ORDER BY name ASC");
                $stmt->execute([$constraint['lft'], $constraint['rgt'], $constraint['seminar_id']]);

                $count = DBManager::get()->query("SELECT FOUND_ROWS()")->fetchColumn();

                return ['list' => $stmt->fetchAll(PDO::FETCH_ASSOC), 'count' => $count];
        }

        throw new InvalidArgumentException("Invalid type {$type}");
    }

    /**
     * Get the latest forum entries for the passed entries childs
     *
     * @param string $parent_id
     * @param int $start_date  timestamp
     * @param int $end_date    timestamp
     *
     * @return array list of postings
     */
    public static function getLatestSince($parent_id, $start_date, $end_date)
    {
        $constraint = ForumEntry::getConstraints($parent_id);

        $stmt = DBManager::get()->prepare("SELECT SQL_CALC_FOUND_ROWS * FROM forum_entries
            WHERE lft > ? AND rgt < ? AND seminar_id = ?
                AND mkdate BETWEEN ? AND ?
            ORDER BY name ASC");
        $stmt->execute([$constraint['lft'], $constraint['rgt'], $constraint['seminar_id'], $start_date, $end_date]);

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     ** returns a list of postings for the passed search-term
     *
     * @param string $parent_id the area to search in (can be a whole seminar)
     * @param string $_searchfor the term to search for
     * @param array $options filter-options: search_title, search_content, search_author
     * @return array array('list' => ..., 'count' => ...);
     */
    public static function getSearchResults($parent_id, $_searchfor, $options)
    {
        $start = (ForumHelpers::getPage() - 1) * ForumEntry::POSTINGS_PER_PAGE;

        // if there are quoted parts, they should not be separated
        $suchmuster = '/".*"/U';
        preg_match_all($suchmuster, $_searchfor, $treffer);
        array_walk($treffer[0], function(&$value) { $value = trim($value, '"'); });

        // remove the quoted parts from $_searchfor
        $_searchfor = trim(preg_replace($suchmuster, '', $_searchfor));

        // split the searchstring $_searchfor at every space
        $parts = explode(' ', $_searchfor);

        foreach ($parts as $key => $val) {
            if ($val == '') {
                unset($parts[$key]);
            }
        }

        if (!empty($parts)) {
            $_searchfor = array_merge($parts, $treffer[0]);
        } else  {
            $_searchfor = $treffer[0];
        }

        // make an SQL-statement out of the searchstring
        $search_string = [];
        foreach ($_searchfor as $key => $val) {
            if (!$val) {
                unset($_searchfor[$key]);
            } else {
                $search_word = '%'. $val .'%';
                $zw_search_string = [];
                if ($options['search_title']) {
                    $zw_search_string[] = "name LIKE " . DBManager::get()->quote($search_word);
                }

                if ($options['search_content']) {
                    $zw_search_string[] = "content LIKE " . DBManager::get()->quote($search_word);
                }

                if ($options['search_author']) {
                    $zw_search_string[] = "(anonymous = 0 AND author LIKE " . DBManager::get()->quote($search_word) . ')';
                }

                if (!empty($zw_search_string)) {
                    $search_string[] = '(' . implode(' OR ', $zw_search_string) . ')';
                }
            }
        }

        if (!empty($search_string)) {
            $add = "AND (" . implode(' AND ', $search_string) . ")";
            return array_merge(
                ['highlight' => $_searchfor],
                ForumEntry::getEntries($parent_id, ForumEntry::WITH_CHILDS, $add, 'DESC', $start)
            );
        }

        return ['num_postings' => 0, 'list' => []];
    }

    /**
     * returns the entry for the passed topic_id
     *
     * @param string $topic_id
     * @return array hash-array with the entries fields
     */
    public static function getEntry($topic_id)
    {
        return ForumEntry::getConstraints($topic_id);
    }

    /**
     * Count the number of child-elements that the passed entry has and return it.
     *
     * @param string $parent_id
     *
     * @return int  the number of child entries for the passed entry
     */
    public static function countEntries($parent_id)
    {
        $data = ForumEntry::getConstraints($parent_id);
        return max((($data['rgt'] - $data['lft'] - 1) / 2) + 1, 0);
    }

    /**
    * Count the number of postings in a given course and return it.
    *
    * @param string $course_id the id of the given course
    *
    * @return int the number of postings in the course
    */
    public static function countPostings($course_id)
    {
        $stmt = DBManager::get()->prepare("SELECT COUNT(*) FROM forum_entries
            WHERE seminar_id = ? AND depth >= 2");
        $stmt->execute([$course_id]);

        return $stmt->fetchColumn(0);
    }

    /**
     * Count all entries the passed user has ever written and return the result
     *
     * @staticvar type $entries
     *
     * @param string $user_id
     *
     * @return int  number of entries user has ever written
     */
    public static function countUserEntries($user_id, $seminar_id = null)
    {
        static $entries;

        if (empty($entries[$user_id])) {
            $stmt = DBManager::get()->prepare("SELECT COUNT(*)
                FROM forum_entries
                WHERE user_id = ? AND seminar_id = IFNULL(?, seminar_id)");
            $stmt->execute([$user_id, $seminar_id]);

            $entries[$user_id] = $stmt->fetchColumn();
        }

        return $entries[$user_id];
    }

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *   D   A   T   A   -   C   R   E   A   T   I   O   N   *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    /**
     * insert a node into the table
     *
     * @param array $data an array containing the following fields:
     *     topic_id     the id of the new topic
     *     seminar_id   the id of the seminar to add the topic to
     *     user_id      the id of the user who created the topic
     *     name         the title of the entry
     *     content      the content of the entry
     *     author       the author's name as a plaintext string
     *     author_host  ip-address of creator
     * @param string $parent_id the node to add the topic to
     *
     * @return void
     */
    public static function insert($data, $parent_id)
    {
        $constraint = ForumEntry::getConstraints($parent_id);

        // #TODO: Zusammenfassen in eine Transaktion!!!
        DBManager::get()->exec('UPDATE forum_entries SET lft = lft + 2
            WHERE lft > '. $constraint['rgt'] ." AND seminar_id = '". $constraint['seminar_id'] ."'");
        DBManager::get()->exec('UPDATE forum_entries SET rgt = rgt + 2
            WHERE rgt >= '. $constraint['rgt'] ." AND seminar_id = '". $constraint['seminar_id'] ."'");

        $stmt = DBManager::get()->prepare("INSERT INTO forum_entries
            (topic_id, seminar_id, user_id, name, content, mkdate, latest_chdate,
                chdate, author, author_host, lft, rgt, depth, anonymous)
            VALUES (? ,?, ?, ?, ?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$data['topic_id'], $data['seminar_id'], $data['user_id'],
            $data['name'], $data['content'], $data['author'], $data['author_host'],
            $constraint['rgt'], $constraint['rgt'] + 1, $constraint['depth'] + 1, $data['anonymous'] ?? 0]);

        // update "latest_chdate" for easier sorting of actual threads
        DBManager::get()->exec("UPDATE forum_entries SET latest_chdate = UNIX_TIMESTAMP()
            WHERE topic_id = '" . $constraint['topic_id'] . "'");

        NotificationCenter::postNotification('ForumAfterInsert', $data['topic_id'], $data);
    }


    /**
     * update the passed topic
     *
     * @param string $topic_id the id of the topic to update
     * @param string $name the new name
     * @param string $content the new content
     *
     * @return void
     */
    public static function update($topic_id, $name, $content)
    {
        $post = ForumEntry::getConstraints($topic_id);

        if (time() - $post['mkdate'] > 5 * 60) {
            $content = ForumEntry::appendEdit($content);
        }

        $stmt = DBManager::get()->prepare("UPDATE forum_entries
            SET name = ?, content = ?, chdate = UNIX_TIMESTAMP(), latest_chdate = UNIX_TIMESTAMP()
            WHERE topic_id = ?");
        $stmt->execute([$name, $content, $topic_id]);

        // update "latest_chdate" for easier sorting of actual threads
        $parent_id = ForumEntry::getParentTopicId($topic_id);
        DBManager::get()->exec("UPDATE forum_entries SET latest_chdate = UNIX_TIMESTAMP()
            WHERE topic_id = '" . $parent_id . "'");

        $post['name']    = $name;
        $post['content'] = $content;

        NotificationCenter::postNotification('ForumAfterUpdate', $topic_id, $post);
    }

    /**
     * delete an entry and all his descendants from the mptt-table
     *
     * @param string $topic_id the id of the entry to delete
     *
     * @return void
     */
    public static function delete($topic_id)
    {
        $post   = ForumEntry::getConstraints($topic_id);
        $parent = ForumEntry::getConstraints(ForumEntry::getParentTopicId($topic_id));

        NotificationCenter::postNotification('ForumBeforeDelete', $topic_id, $post);

        // #TODO: Zusammenfassen in eine Transaktion!!!
        // get all entry-ids to delete them from the category-reference-table
        $stmt = DBManager::get()->prepare("SELECT topic_id FROM forum_entries
            WHERE seminar_id = ? AND lft >= ? AND rgt <= ? AND depth = 1");
        $stmt->execute([$post['seminar_id'], $post['lft'], $post['rgt']]);
        $ids = $stmt->fetchAll(PDO::FETCH_COLUMN);

        if ($ids != false && !is_array($ids)) $ids = [$ids];

        if (!empty($ids)) {
            $stmt = DBManager::get()->prepare("DELETE FROM forum_categories_entries
                WHERE topic_id IN (:ids)");
            $stmt->bindParam(':ids', $ids, StudipPDO::PARAM_ARRAY);
            $stmt->execute();
        }

        // delete all entries
        $stmt = DBManager::get()->prepare("DELETE FROM forum_entries
            WHERE seminar_id = ? AND lft >= ? AND rgt <= ?");

        $stmt->execute([$post['seminar_id'], $post['lft'], $post['rgt']]);

        // update lft and rgt
        $diff = $post['rgt'] - $post['lft'] + 1;
        $stmt = DBManager::get()->prepare("UPDATE forum_entries SET lft = lft - $diff
            WHERE lft > ? AND seminar_id = ?");
        $stmt->execute([$post['rgt'], $post['seminar_id']]);

        $stmt = DBManager::get()->prepare("UPDATE forum_entries SET rgt = rgt - $diff
            WHERE rgt > ? AND seminar_id = ?");
        $stmt->execute([$post['rgt'], $post['seminar_id']]);


        // set the latest_chdate to the latest child's chdate
        $stmt = DBManager::get()->prepare("SELECT chdate FROM forum_entries
            WHERE lft > ? AND rgt < ? AND seminar_id = ?
            ORDER BY chdate DESC LIMIT 1");
        $stmt->execute([$parent['lft'] ?? null, $parent['rgt'] ?? null, $parent['seminar_id'] ?? null]);
        $chdate = $stmt->fetchColumn();

        $stmt_insert = DBManager::get()->prepare("UPDATE forum_entries
            SET chdate = ? WHERE topic_id = ?");
        if ($chdate) {
            $stmt_insert->execute([$chdate, $parent['topic_id']]);
        } else {
            $stmt_insert->execute([$parent['chdate'], $parent['topic_id']]);
        }
    }

    /**
     * move the passed topic to the passed area
     *
     * @param string $topic_id the topic to move
     * @param string $destination the area_id where the topic is moved to
     *
     * @return void
     */
    public static function move($topic_id, $destination)
    {
        // #TODO: Zusammenfassen in eine Transaktion!!!
        $constraints = ForumEntry::getConstraints($topic_id);

        // move the affected entries "outside" the tree
        $stmt = DBManager::get()->prepare("UPDATE forum_entries
            SET lft = lft * -1, rgt = rgt * -1
            WHERE seminar_id = ? AND lft >= ? AND rgt <= ?");
        $stmt->execute([$constraints['seminar_id'], $constraints['lft'], $constraints['rgt']]);

        // update the lft and rgt values of the parent to reflect the "deletion"
        $diff = $constraints['rgt'] - $constraints['lft'] + 1;
        $stmt = DBManager::get()->prepare("UPDATE forum_entries SET lft = lft - ?
            WHERE lft > ? AND seminar_id = ?");
        $stmt->execute([$diff, $constraints['rgt'], $constraints['seminar_id']]);

        $stmt = DBManager::get()->prepare("UPDATE forum_entries SET rgt = rgt - ?
            WHERE rgt > ? AND seminar_id = ?");
        $stmt->execute([$diff, $constraints['rgt'], $constraints['seminar_id']]);

        // make some space by updating the lft and rgt values of the target node
        $constraints_destination = ForumEntry::getConstraints($destination);
        $size = $constraints['rgt'] - $constraints['lft'] + 1;

        $stmt = DBManager::get()->prepare("UPDATE forum_entries SET lft = lft + ?
            WHERE lft > ? AND seminar_id = ?");
        $stmt->execute([$size, $constraints_destination['rgt'], $constraints_destination['seminar_id']]);

        $stmt = DBManager::get()->prepare("UPDATE forum_entries SET rgt = rgt + ?
            WHERE rgt >= ? AND seminar_id = ?");
        $stmt->execute([$size, $constraints_destination['rgt'], $constraints_destination['seminar_id']]);

        //move the entries from "outside" the tree to the target node
        $constraints_destination = ForumEntry::getConstraints($destination);


        // update the depth to reflect the new position in the tree
        // determine if we need to add, subtract or even do nothing to/from the depth
        $depth_mod = $constraints_destination['depth'] - $constraints['depth'] + 1;

        $stmt = DBManager::get()->prepare("UPDATE forum_entries
            SET depth = depth + ?
            WHERE seminar_id = ? AND lft < 0");
        $stmt->execute([$depth_mod, $constraints_destination['seminar_id']]);

        // if the depth is larger than 3, fix it
        $stmt = DBManager::get()->prepare("UPDATE forum_entries
            SET depth = 3
            WHERE seminar_id = ? AND depth > 3 AND lft < 0");
        $stmt->execute([$constraints_destination['seminar_id']]);

        // move the tree to its destination
        $diff = ($constraints_destination['rgt'] - ($constraints['rgt'] - $constraints['lft'])) - 1 - $constraints['lft'];

        $stmt = DBManager::get()->prepare("UPDATE forum_entries
            SET lft = (lft * -1) + ?, rgt = (rgt * -1) + ?
            WHERE seminar_id = ? AND lft < 0");
        $stmt->execute([$diff, $diff, $constraints_destination['seminar_id']]);

        if ($depth_mod != 0) {
            self::fix_ordering($topic_id);
        }
    }

    private static function fix_ordering($parent_id)
    {
        $db = DBManager::get();

        $entry = ForumEntry::getConstraints($parent_id);

        $stmt= $db->prepare('SELECT topic_id FROM forum_entries
                               WHERE lft > ? AND rgt < ? AND depth = 3
                                    AND seminar_id = ?
                               ORDER BY mkdate');

        $stmt->execute([$entry['lft'], $entry['rgt'], $entry['seminar_id']]);

        $lft = $entry['lft'] + 1;
        $rgt = $lft + 1;

        $inner_stmt = $db->prepare("UPDATE forum_entries SET lft=?, rgt=?
            WHERE topic_id = ?");
        while ($topic_id = $stmt->fetchColumn()) {
            $inner_stmt->execute([$lft, $rgt, $topic_id]);

            $lft += 2;
            $rgt += 2;
        }
    }

    /**
     * close the passed topic
     *
     * @param string $topic_id the topic to close
     *
     * @return void
     */
    public static function close($topic_id)
    {
        // close all entries belonging to the topic
        $stmt = DBManager::get()->prepare("UPDATE forum_entries
            SET closed = 1
            WHERE topic_id = ?");
        $stmt->execute([$topic_id]);
    }

    /**
     * open the passed topic
     *
     * @param string $topic_id the topic to open
     *
     * @return void
     */
    public static function open($topic_id)
    {
        // open all entries belonging to the topic
        $stmt = DBManager::get()->prepare("UPDATE forum_entries
            SET closed = 0
            WHERE topic_id = ?");
        $stmt->execute([$topic_id]);
    }

    /**
     * make the passed topic sticky
     *
     * @param string $topic_id the topic to make sticky
     *
     * @return void
     */
    public static function sticky($topic_id)
    {
        // open all entries belonging to the topic
        $stmt = DBManager::get()->prepare("UPDATE forum_entries
            SET sticky = 1
            WHERE topic_id = ?");
        $stmt->execute([$topic_id]);
    }

    /**
     * make the passed topic unsticky
     *
     * @param string $topic_id the topic to make unsticky
     *
     * @return void
     */
    public static function unsticky($topic_id)
    {
        // open all entries belonging to the topic
        $stmt = DBManager::get()->prepare("UPDATE forum_entries
            SET sticky = 0
            WHERE topic_id = ?");
        $stmt->execute([$topic_id]);
    }

    /**
     * check, if the default root-node for this seminar exists and make sure
     * the default category exists as well
     *
     * @param string $seminar_id
     *
     * @return void
     */
    public static function checkRootEntry($seminar_id)
    {
        setTempLanguage();

        // check, if the root entry in the topic tree exists
        $stmt = DBManager::get()->prepare("SELECT COUNT(*) FROM forum_entries
            WHERE topic_id = ? AND seminar_id = ?");
        $stmt->execute([$seminar_id, $seminar_id]);
        if ($stmt->fetchColumn() == 0) {
            $stmt = DBManager::get()->prepare("INSERT INTO forum_entries
                (topic_id, seminar_id, user_id, name, content, author, author_host, mkdate, chdate, lft, rgt, depth)
                VALUES (?, ?, '', 'Übersicht', '', '', '', UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), 0, 1, 0)");
            $stmt->execute([$seminar_id, $seminar_id]);
        }

        // make sure, that the category "Allgemein" exists
        $stmt = DBManager::get()->prepare("INSERT IGNORE INTO forum_categories
            (category_id, seminar_id, entry_name) VALUES (?, ?, ?)");
        $stmt->execute([$seminar_id, $seminar_id, _('Allgemein')]);

        // make sure that the default area "Allgemeine Diskussionen" exists, if there is nothing else present
        $stmt = DBManager::get()->prepare("SELECT COUNT(*) FROM forum_entries
            WHERE seminar_id = ? AND depth = 1");
        $stmt->execute([$seminar_id]);

        // add default area
        if ($stmt->fetchColumn() == 0) {
            $data = [
                'topic_id'    => md5(uniqid()),
                'seminar_id'  => $seminar_id,
                'user_id'     => '',
                'name'        => _('Allgemeine Diskussion'),
                'content'     => _('Hier ist Raum für allgemeine Diskussionen'),
                'author'      => '',
                'author_host' => ''
            ];
            ForumEntry::insert($data, $seminar_id);
        }

        restoreLanguage();
    }

    /**
     * returns the ten most active seminars
     *
     * @return array
     */
    public static function getTopTenSeminars()
    {
        return DBManager::get()->query("SELECT a.seminar_id, b.name AS display,
            count( a.seminar_id ) AS count FROM forum_entries a
            INNER JOIN seminare b USING ( seminar_id )
            WHERE b.visible = 1
            AND a.mkdate > UNIX_TIMESTAMP( NOW( ) - INTERVAL 2 WEEK )
            GROUP BY a.seminar_id
            ORDER BY count DESC
            LIMIT 10")->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * count all entries that exists in the whole installation and return it.
     *
     * @return int
     */
    public static function countAllEntries()
    {
        return count_table_rows('forum_entries');
    }

    /**
     * updates the user-entries and replaces the old user-id by the new one
     *
     * @param string $user_from
     * @param string $user_to
     */
    public static function migrateUser($user_from, $user_to)
    {
        $stmt = DBManager::get()->prepare("UPDATE forum_entries SET user_id = ? WHERE user_id = ?");
        $stmt->execute([$user_to, $user_from]);

        $stmt = DBManager::get()->prepare("UPDATE IGNORE forum_favorites SET user_id = ? WHERE user_id = ?");
        $stmt->execute([$user_to, $user_from]);

        $stmt = DBManager::get()->prepare("UPDATE IGNORE forum_visits SET user_id = ? WHERE user_id = ?");
        $stmt->execute([$user_to, $user_from]);

        $stmt = DBManager::get()->prepare("UPDATE IGNORE forum_likes SET user_id = ? WHERE user_id = ?");
        $stmt->execute([$user_to, $user_from]);

        $stmt = DBManager::get()->prepare("UPDATE IGNORE forum_abo_users SET user_id = ? WHERE user_id = ?");
        $stmt->execute([$user_to, $user_from]);
    }

    /**
     * returns the complete seminar or only the passed sub-tree as a html-string
     *
     * @param string $seminar_id
     *
     * @return string
     */
    public static function getDump($seminar_id, $parent_id = null)
    {
        $seminar_name = get_object_name($seminar_id, 'sem');
        $content = '<h1>'. _('Forum') .': '  . $seminar_name['name'] .'</h1>';
        $data = ForumEntry::getList('dump', $parent_id ?: $seminar_id);

        foreach ($data as $entry) {
            if ($entry['depth'] == 1) {
                $content .= '<h2>'. _('Bereich') .': '. $entry['name'] .'</h2>';
                $content .= $entry['content'] .'<br><br>';
            } else if ($entry['depth'] == 2) {
                $content .= '<h3 style="margin-bottom: 0px;">'. _('Thema') .': '. $entry['name'] .'</h3>';
                $content .= '<i>' . sprintf(_('erstellt von %s am %s'), htmlReady($entry['author']),
                    strftime('%A %d. %B %Y, %H:%M', (int)$entry['mkdate'])) . '</i><br>';
                $content .= $entry['content'] .'<br><br>';
            } else if ($entry['depth'] == 3) {
                $content .= '<b>'.$entry['name'] .'</b><br>';
                $content .= '<i>' . sprintf(_('erstellt von %s am %s'), htmlReady($entry['author']),
                    strftime('%A %d. %B %Y, %H:%M', (int)$entry['mkdate'])) . '</i><br>';
                $content .= $entry['content'] .'<hr><br>';
            }
        }

        return $content;
    }

    public static function isClosed($topic_id)
    {
        foreach(ForumEntry::getPathToPosting($topic_id) as $entry) {
            if ($entry['closed']) {
                return true;
            }
        }

        return false;
    }

    /**
     * Export available data of a given user into a storage object
     * (an instance of the StoredUserData class) for that user.
     *
     * @param StoredUserData $storage object to store data into
     */
    public static function exportUserData(StoredUserData $storage)
    {
        $field_data = DBManager::get()->fetchAll("SELECT * FROM forum_entries WHERE user_id = ?", [$storage->user_id]);
        if ($field_data) {
            $storage->addTabularData(_('Forum Einträge'), 'forum_entries', $field_data);
        }
    }

}