aboutsummaryrefslogtreecommitdiff
path: root/app/controllers/room_management/planning.php
blob: c450c642ee84bd8fa7979801239f9587c2db3a44 (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
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
<?php

/**
 * planning.php - contains RoomManagement_PlanningController
 *
 * 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 2 of
 * the License, or (at your option) any later version.
 *
 * @author      Moritz Strohm <strohm@data-quest.de>
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GPL version 2
 * @copyright   2017
 * @category    Stud.IP
 * @since       4.1
 */


/**
 * RoomManagement_PlanningController contains room planning functionality.
 */
class RoomManagement_PlanningController extends AuthenticatedController
{
    public function index_action($selected_clipboard_id = null)
    {
        PageLayout::setTitle(
            _('Raumgruppen-Belegungsplan')
        );

        if (Navigation::hasItem('/resources/planning/index')) {
            Navigation::activateItem('/resources/planning/index');
        }
        $selected_clipboard_id = Request::get('clipboard_id', $selected_clipboard_id);

        $this->no_clipboard = false;
        $this->no_rooms = false;

        if ($selected_clipboard_id) {
            $_SESSION['selected_clipboard_id'] = $selected_clipboard_id;
        } else {
            $selected_clipboard_id = $_SESSION['selected_clipboard_id'];
        }

        $this->display_all_requests = Request::get('display_all_requests');

        //Build sidebar:
        $sidebar = Sidebar::get();

        $actions = new ActionsWidget();
        $actions->addLink(
            _('Drucken'),
            'javascript:void(window.print());',
            Icon::create('print')
        );
        $sidebar->addWidget($actions);

        $views = new ViewsWidget();
        if ($GLOBALS['user']->id && ($GLOBALS['user']->id !== 'nobody')) {
            $views->addLink(
                _('Standard Zeitfenster'),
                URLHelper::getURL(
                    'dispatch.php/room_management/planning/index',
                    [
                        'defaultDate' => Request::get('defaultDate', date('Y-m-d'))
                    ]
                ),
                null,
                ['class' => 'booking-plan-std_view']
            )->setActive(!Request::get('allday'));

            $views->addLink(
                _('Ganztägiges Zeitfenster'),
                URLHelper::getURL(
                    'dispatch.php/room_management/planning/index',
                    [
                        'allday'      => true,
                        'defaultDate' => Request::get('defaultDate', date('Y-m-d'))
                    ]
                ),
                null,
                ['class' => 'booking-plan-allday_view']
            )->setActive(Request::get('allday'));
        }
        $sidebar->addWidget($views);

        $dpicker = new SidebarWidget();
        $dpicker->setTitle('Datum');
        $picker_html = $this->get_template_factory()->render(
            'resources/room_planning/_sidebar_date_selection.php'
        );
        $dpicker->addElement(new WidgetElement($picker_html));
        $sidebar->addWidget($dpicker);

        $clipboards = Clipboard::getClipboardsForUser($GLOBALS['user']->id);
        if (!empty($clipboards)) {
            $clipboard_widget = new SelectWidget(
                _('Individuelle Raumgruppen'),
                $this->indexURL(),
                'clipboard_id',
                'get'
            );
            foreach ($clipboards as $clipboard) {
                $clipboard_widget->addElement(new SelectElement(
                    $clipboard->id,
                    $clipboard->name,
                    $clipboard->id === $selected_clipboard_id
                ), "clipboard_id-{$clipboard->id}");
            }
            $sidebar->addWidget($clipboard_widget);
        }

        $rooms = [];
        if ($selected_clipboard_id) {
            $clipboard = Clipboard::find($selected_clipboard_id);
            $this->clipboard = $clipboard;
            if ($clipboard) {
                PageLayout::setTitle(
                    $clipboard->name . ': ' . _('Raumgruppen-Belegungsplan')
                );
                $room_ids = $clipboard->getAllRangeIds('Room');
                $rooms = Room::findMany($room_ids);
            } else {
                $this->no_clipboard = true;
                return;
            }
        }

        if (!$rooms) {
            //No rooms could be found.
            $this->no_rooms = true;
            return;
        }

        //Generate the resources array for the fullcalendar scheduler plugin:
        $this->scheduler_resources = [];
        foreach ($room_ids as $room_id) {
            $room = Room::find($room_id);
            $this->scheduler_resources[] = [
                'id'          => $room->id,
                'parent_name' => $room->building->name,
                'title'       => $room->name
            ];
        }

        $current_user = User::findCurrent();

        $room_c = count($rooms);
        $requestable_rooms_c = 0;
        $request_rights_c = 0;
        $booking_rights_c = 0;
        $admin_rights_c = 0;
        $this->booking_types = [
            ResourceBooking::TYPE_NORMAL,
            ResourceBooking::TYPE_RESERVATION,
            ResourceBooking::TYPE_LOCK,
        ];

        foreach ($rooms as $room) {
            if ($room->userHasRequestRights($current_user)) {
                $request_rights_c++;
            }
            if ($room->userHasBookingRights($current_user)) {
                $booking_rights_c++;
            }
            if ($room->userHasPermission($current_user, 'admin')) {
                $admin_rights_c++;
            }
            if ($room->requestable) {
                $requestable_rooms_c++;
            }

            //Check the permissions for the room:
            //The booking plan must be visible for the user.
            $sufficient_permissions =
                $room->bookingPlanVisibleForUser($current_user);
            if (!$sufficient_permissions) {
                throw new AccessDeniedException(
                    sprintf(
                        _('Der Belegungsplan des Raumes %s ist für Sie nicht zugänglich!'),
                        $room->name
                    )
                );
            }
        }

        $this->all_rooms_booking_rights = ($room_c == $booking_rights_c);
        $all_rooms_admin = ($room_c == $admin_rights_c);
        if ($all_rooms_admin) {
            //Display planned bookings, too:
            $this->booking_types[] = ResourceBooking::TYPE_PLANNED;
        }
        if (!$this->all_rooms_booking_rights && $this->display_all_requests) {
            throw new AccessDeniedException(
                _('Sie sind nicht dazu berechtigt, alle Anfragen im Belegungsplan zu sehen!')
            );
        }

        if (Config::get()->RESOURCES_ALLOW_ROOM_REQUESTS && $this->all_rooms_booking_rights) {
            $options = new OptionsWidget();
            $options->addCheckbox(
                _('Alle Anfragen anzeigen'),
                $this->display_all_requests ? 'checked' : '',
                $this->url_for(
                    'room_management/planning/index/' . $_SESSION['selected_clipboard_id'],
                    [
                        'display_all_requests' => '1'
                    ]
                ),
                $this->url_for(
                    'room_management/planning/index/' . $_SESSION['selected_clipboard_id']
                ),
                []
            );
            $sidebar->insertWidget($options, 'roomclipboard');
        }

        $this->fullcalendar_studip_urls = [];
        if ($this->all_rooms_booking_rights) {
            $this->fullcalendar_studip_urls['add'] = URLHelper::getURL(
                'dispatch.php/resources/booking/add'
            );
        }

        $booking_colour = ColourValue::find('Resources.BookingPlan.Booking.Bg');
        $course_booking_colour = ColourValue::find('Resources.BookingPlan.CourseBooking.Bg');
        $lock_colour = ColourValue::find('Resources.BookingPlan.Lock.Bg');
        $preparation_colour = ColourValue::find('Resources.BookingPlan.PreparationTime.Bg');
        $reservation_colour = ColourValue::find('Resources.BookingPlan.Reservation.Bg');
        $request_colour = ColourValue::find('Resources.BookingPlan.Request.Bg');
        $this->table_keys = [
            [
                'colour' => $booking_colour->__toString(),
                'text'   => _('Manuelle Buchung')
            ],
            [
                'colour' => $course_booking_colour->__toString(),
                'text'   => _('Veranstaltungsbezogene Buchung')
            ],
            [
                'colour' => $lock_colour->__toString(),
                'text'   => _('Sperrbuchung')
            ],
            [
                'colour' => $preparation_colour->__toString(),
                'text'   => _('Rüstzeit')
            ],
            [
                'colour' => $reservation_colour->__toString(),
                'text'   => _('Reservierung')
            ],
        ];
        if ($all_rooms_admin) {
            $planned_booking_colour = ColourValue::find('Resources.BookingPlan.PlannedBooking.Bg');
            $this->table_keys[] = [
                'colour' => $planned_booking_colour->__toString(),
                'text'   => _('Geplante Buchung')
            ];
        }
        if ($this->display_all_requests) {
            $this->table_keys[] = [
                'colour' => $request_colour->__toString(),
                'text'   => _('Anfrage')
            ];
        }
    }

    public function semester_plan_action($selected_clipboard_id = null)
    {
        PageLayout::setTitle(
            _('Raumgruppen-Semester-Belegungsplan')
        );

        if (Navigation::hasItem('/resources/planning/semestergroup_plan')) {
            Navigation::activateItem('/resources/planning/semestergroup_plan');
        }

        $selected_clipboard_id = Request::get('clipboard_id', $selected_clipboard_id);

        $this->no_clipboard = false;
        $this->no_rooms = false;

        if ($selected_clipboard_id) {
            $_SESSION['selected_clipboard_id'] = $selected_clipboard_id;
        } else {
            $selected_clipboard_id = $_SESSION['selected_clipboard_id'];
        }

        $this->display_all_requests = Request::get('display_all_requests');

        //Build sidebar:
        $sidebar = Sidebar::get();

        $this->semester = Semester::findCurrent();
        //For the semester selector:
        if (Request::submitted('semester_id')) {
            $this->semester = Semester::find(Request::get('semester_id'));
            if (!$this->semester) {
                PageLayout::postError(
                    _('Das ausgewählte Semester wurde nicht in der Datenbank gefunden!')
                );
                return;
            }
        }

        $actions = new ActionsWidget();
        $actions->addLink(
            _('Drucken'),
            'javascript:void(window.print());',
            Icon::create('print')
        );
        $actions->addLink(
            _('Buchungen kopieren'),
            $this->url_for('room_management/planning/copy_bookings'),
            Icon::create('clipboard'),
            ['data-dialog' => 'size=auto']
        );
        $sidebar->addWidget($actions);


        if ($GLOBALS['user']->id && ($GLOBALS['user']->id != 'nobody')) {
            $views = new ViewsWidget();
            $views->setTitle(_('Zeitfenster'));
            $views->addLink(
                _('Standard Zeitfenster'),
                URLHelper::getURL(
                    'dispatch.php/room_management/planning/semester_plan',
                    [
                        'defaultDate' => Request::get('defaultDate', date('Y-m-d')),
                        'semester_id' => $this->semester->id,
                        'semester_timerange' => Request::get('semester_timerange', 'vorles')
                    ]
                ),
                null,
                ['class' => 'booking-plan-std_view']
            )->setActive(!Request::get('allday'));

            $views->addLink(
                _('Ganztägiges Zeitfenster'),
                URLHelper::getURL(
                    'dispatch.php/room_management/planning/semester_plan',
                    [
                        'allday' => true,
                        'defaultDate' => Request::get('defaultDate', date('Y-m-d')),
                        'semester_id' => $this->semester->id,
                        'semester_timerange' => Request::get('semester_timerange', 'vorles')
                    ]
                ),
                null,
                ['class' => 'booking-plan-allday_view']
            )->setActive(Request::get('allday'));
            $sidebar->addWidget($views);

            $views2 = new ViewsWidget();
            $views2->setTitle(_('Semesterzeitraum'));
            $views2->addLink(
                _('Vorlesungszeit'),
                URLHelper::getURL(
                    'dispatch.php/room_management/planning/semester_plan',
                    [
                        'allday' => Request::get('allday'),
                        'defaultDate' => Request::get('defaultDate', date('Y-m-d')),
                        'semester_id' => $this->semester->id,
                        'semester_timerange' => 'vorles'
                    ]
                ),
                null,
                ['class' => 'booking-plan-vorles_view']
            )->setActive(Request::get('semester_timerange') != 'fullsem');
            $views2->addLink(
                _('gesamtes Semester'),
                URLHelper::getURL(
                    'dispatch.php/room_management/planning/semester_plan',
                    [
                        'allday' => Request::get('allday'),
                        'defaultDate' => Request::get('defaultDate', date('Y-m-d')),
                        'semester_id' => $this->semester->id,
                        'semester_timerange' => 'fullsem'
                    ]
                ),
                null,
                ['class' => 'booking-plan-fullsem_view']
            )->setActive(Request::get('semester_timerange') == 'fullsem');
            $sidebar->addWidget($views2);
        }
        $semester_selector = new SemesterSelectorWidget(
            URLHelper::getURL(
                'dispatch.php/room_management/planning/semester_plan/' . (!empty($this->resource) ? $this->resource->id : ''),
                [
                    'allday' => Request::get('allday', false)
                ]
            )
        );
        $sidebar->addWidget($semester_selector);

        $clipboards = Clipboard::getClipboardsForUser($GLOBALS['user']->id);
        if (!empty($clipboards)) {
            $clipboard_widget = new SelectWidget(
                _('Individuelle Raumgruppen'),
                $this->semester_planURL(),
                'clipboard_id',
                'get'
            );
            foreach ($clipboards as $clipboard) {
                $clipboard_widget->addElement(new SelectElement(
                    $clipboard->id,
                    $clipboard->name,
                    $clipboard->id === $selected_clipboard_id
                ), "clipboard_id-{$clipboard->id}");
            }
            $sidebar->addWidget($clipboard_widget);
        }

        //Check if a clipboard is selected:
        $selected_clipboard_id = $_SESSION['selected_clipboard_id'];
        $rooms = [];
        if ($selected_clipboard_id) {
            $clipboard = Clipboard::find($selected_clipboard_id);
            $this->clipboard = $clipboard;
            if ($clipboard) {
                PageLayout::setTitle(
                    $clipboard->name . ': ' . _('Raumgruppen-Semester-Belegungsplan')
                );
                $room_ids = $clipboard->getAllRangeIds('Room');
                $rooms = Room::findMany($room_ids);
            } else {
                $this->no_clipboard = true;
                return;
            }
        }

        if (!$rooms) {
            //No rooms could be found.
            $this->no_rooms = true;
            return;
        }

        //Generate the resources array for the fullcalendar scheduler plugin:
        $this->scheduler_resources = [];
        foreach ($room_ids as $room_id) {
            $room = Room::find($room_id);
            $this->scheduler_resources[] = [
                'id' => $room->id,
                'parent_name' => $room->building->name,
                'title' => $room->name
            ];
        }

        $current_user = User::findCurrent();

        $room_c = count($rooms);
        $requestable_rooms_c = 0;
        $booking_rights_c = 0;
        $admin_rights_c = 0;
        $this->booking_types = [
            ResourceBooking::TYPE_NORMAL,
            ResourceBooking::TYPE_RESERVATION,
            ResourceBooking::TYPE_LOCK,
        ];

        foreach ($rooms as $room) {
            if ($room->userHasBookingRights($current_user)) {
                $booking_rights_c++;
            }
            if ($room->userHasPermission($current_user, 'admin')) {
                $admin_rights_c++;
            }
            if ($room->requestable) {
                $requestable_rooms_c++;
            }

            //Check the permissions for the room:
            if (!$room->bookingPlanVisibleForUser($current_user)) {
                throw new AccessDeniedException();
            }
        }

        $all_rooms_requestable = ($room_c == $requestable_rooms_c);
        $all_rooms_booking_rights = ($room_c == $booking_rights_c);
        $all_rooms_admin = ($room_c == $admin_rights_c);
        if ($all_rooms_admin) {
            //Display planned bookings, too:
            $this->booking_types[] = ResourceBooking::TYPE_PLANNED;
        }

        if (!$all_rooms_booking_rights && $this->display_all_requests) {
            throw new AccessDeniedException(
                _('Sie sind nicht dazu berechtigt, alle Anfragen im Belegungsplan zu sehen!')
            );
        }

        if ($all_rooms_booking_rights) {
            $options = new OptionsWidget();
            $options->addCheckbox(
                _('Alle Anfragen anzeigen'),
                $this->display_all_requests ? 'checked' : '',
                $this->url_for(
                    'room_management/planning/semester_plan/' . $_SESSION['selected_clipboard_id'],
                    [
                        'display_all_requests' => '1',
                        'semester_id' => Request::option('semester_id')
                    ]
                ),
                $this->url_for(
                    'room_management/planning/semester_plan/' . $_SESSION['selected_clipboard_id'],
                    [
                        'semester_id' => Request::option('semester_id')
                    ]
                ),
                []
            );
            $sidebar->insertWidget($options, 'roomclipboard');
        }

        $booking_colour = ColourValue::find('Resources.BookingPlan.Booking.Bg');
        $simple_booking_exception_colour = ColourValue::find('Resources.BookingPlan.SimpleBookingWithExceptions.Bg');
        $course_booking_colour = ColourValue::find('Resources.BookingPlan.CourseBooking.Bg');
        $course_booking_with_exceptions_colour = ColourValue::find('Resources.BookingPlan.CourseBookingWithExceptions.Bg');
        $lock_colour = ColourValue::find('Resources.BookingPlan.Lock.Bg');
        $preparation_colour = ColourValue::find('Resources.BookingPlan.PreparationTime.Bg');
        $reservation_colour = ColourValue::find('Resources.BookingPlan.Reservation.Bg');
        $request_colour = ColourValue::find('Resources.BookingPlan.Request.Bg');
        $this->table_keys = [
            [
                'colour' => $booking_colour->__toString(),
                'text'   => _('Manuelle Buchung')
            ],
            [
                'colour' => $course_booking_colour->__toString(),
                'text'   => _('Veranstaltungsbezogene Buchung')
            ],
            [
                'colour' => $lock_colour->__toString(),
                'text'   => _('Sperrbuchung')
            ],
            [
                'colour' => $preparation_colour->__toString(),
                'text'   => _('Rüstzeit')
            ],
            [
                'colour' => $reservation_colour->__toString(),
                'text'   => _('Reservierung')
            ],
        ];
        if ($all_rooms_admin) {
            $planned_booking_colour = ColourValue::find('Resources.BookingPlan.PlannedBooking.Bg');
            $this->table_keys[] = [
                'colour' => $planned_booking_colour->__toString(),
                'text'   => _('Geplante Buchung')
            ];
        }
        if ($this->display_all_requests) {
            $this->table_keys[] = [
                'colour' => $request_colour->__toString(),
                'text'   => _('Anfrage')
            ];
        }

    }

    public function copy_bookings_action($clipboard_id = null)
    {
        PageLayout::setTitle(
            _('Buchungen kopieren')
        );

        if (Navigation::hasItem('/resources/planning/copy_bookings')) {
            Navigation::activateItem('/resources/planning/copy_bookings');
        }

        //Check if the clipboard is selected:
        $selected_clipboard_id = $_SESSION['selected_clipboard_id'];

        $user = User::findCurrent();

        $this->clipboard = null;
        if ($selected_clipboard_id) {
            $this->clipboard = Clipboard::find($selected_clipboard_id);
        } else {
            $this->clipboard = Clipboard::find($clipboard_id);
            if (!$clipboard_id) {
                PageLayout::postError(
                    _('Es wurde keine Raumgruppe ausgewählt!')
                );
                return;
            }
        }
        if (!$this->clipboard) {
            PageLayout::postError(
                _('Die gewählte Raumgruppe wurde nicht gefunden!')
            );
            return;
        }
        if ($this->clipboard->user_id != $GLOBALS['user']->id) {
            throw new AccessDeniedException();
        }

        PageLayout::setTitle(
            $this->clipboard->name . ': ' . _('Buchungen kopieren')
        );

        //Step 1: Room selection
        $this->step = 1;

        //Get all Room items from the clipboard where the user has at least
        //user permissions:
        $all_room_ids = $this->clipboard->getAllRangeIds('Room');
        $unfiltered_rooms = Room::findMany($all_room_ids);
        $this->rooms = [];
        $this->available_room_ids = [];
        foreach ($unfiltered_rooms as $room) {
            if ($room->userHasPermission($user, 'autor')) {
                $this->rooms[] = $room;
                $this->available_room_ids[] = $room->id;
            }
        }

        $this->selected_room_ids = [];

        //Get all available semesters:
        $this->available_semesters = Semester::getAll();
        $this->sem_week_selected = false;
        $this->selected_sem_week = 1;

        if (Request::isPost()) {
            CSRFProtection::verifyUnsafeRequest();
            if (Request::submitted('select_rooms') || Request::submitted('step1')) {
                $this->step = 2;
            } elseif (Request::submitted('test_copy') || Request::submitted('step2')
                      || Request::submitted('download_booking_list')) {
                $this->step = 3;
            } elseif (Request::submitted('copy')) {
                $this->step = 4;
            }
        }

        if ($this->step >= 2) {
            //Step 2: Select and verify bookings and semester
            $this->source_semester_id = Request::get('source_semester_id');
            $this->sem_week_selected = Request::get('sem_week_selected');
            $this->selected_sem_week = Request::get('selected_sem_week');
            $this->selected_room_ids = Request::getArray('selected_room_ids');
            if (!$this->source_semester_id) {
                PageLayout::postError(
                    _('Es wurde kein Semester ausgewählt!')
                );
                $this->step = 1;
                return;
            }
            $this->source_semester = Semester::find($this->source_semester_id);
            if (!$this->source_semester) {
                PageLayout::postError(
                    _('Das gewählte Semester wurde nicht gefunden!')
                );
                $this->step = 1;
                return;
            }
            if ($this->sem_week_selected) {
                $last_sem_week_number = $this->source_semester->getSemWeekNumber(
                    $this->source_semester->vorles_ende
                );
                if (($this->selected_sem_week < 1) || ($this->selected_sem_week > $last_sem_week_number)) {
                    PageLayout::postError(
                        _('Die gewählte Semesterwoche liegt außerhalb des gewählten Semesters!')
                    );
                    $this->step = 1;
                    return;
                }
            }
            if (!$this->selected_room_ids) {
                PageLayout::postError(
                    _('Es wurden keine Räume ausgewählt!')
                );
                $this->step = 1;
                return;
            }

            foreach ($this->selected_room_ids as $room_id) {
                if (!in_array($room_id, $all_room_ids)) {
                    PageLayout::postError(
                        _('Es wurde ein Raum ausgewählt, der nicht Teil der Raumgruppe ist!')
                    );
                    $this->step = 1;
                    return;
                }
                if (!in_array($room_id, $this->available_room_ids)) {
                    PageLayout::postError(
                        _('Es wurde ein Raum ausgewählt, an dem die Berechtigungen zum Kopieren von Buchungen nicht ausreichend sind!')
                    );
                    $this->step = 1;
                    return;
                }
            }

            if (Request::submitted('step1')) {
                $this->step = 1;
                return;
            }

            $this->selected_rooms = Room::findMany($this->selected_room_ids);

            $this->available_target_semesters = Semester::findBySql(
                'beginn > :source_semester_end ORDER BY beginn ASC',
                ['source_semester_end' => $this->source_semester->ende]
            );
            if (!$this->available_target_semesters) {
                PageLayout::postError(
                    _('Es sind keine Semester vorhanden, die nach dem ausgewählten Semester starten!')
                );
                $this->step = 1;
                return;
            }

            $unfiltered_bookings = [];
            foreach ($this->selected_rooms as $room) {
                $room_bookings = [];
                if ($this->sem_week_selected) {
                    $selected_week_begin = $this->source_semester->vorles_beginn;
                    if ($this->selected_sem_week > 1) {
                        $selected_week_begin = strtotime(
                            sprintf('+%d weeks', $this->selected_sem_week),
                            $this->source_semester->vorles_beginn
                        );
                    }
                    $room_bookings = ResourceBooking::findByResourceAndTimeRanges(
                        $room,
                        [
                            [
                                'begin' => $selected_week_begin,
                                'end' => $this->source_semester->ende
                            ]
                        ]
                    );
                } else {
                    $room_bookings = ResourceBooking::findByResourceAndTimeRanges(
                        $room,
                        [
                            [
                                'begin' => $this->source_semester->beginn,
                                'end' => $this->source_semester->ende
                            ]
                        ]
                    );
                }
                if ($room_bookings) {
                    $unfiltered_bookings = array_merge(
                        $unfiltered_bookings,
                        $room_bookings
                    );
                }
            }
            $this->bookings = [];
            $this->available_booking_ids = [];
            $this->booking_time_ranges = [];
            foreach ($unfiltered_bookings as $booking) {
                if (!$booking->repetition_interval || !$booking->isSimpleBooking()) {
                    //We only regard simple bookings with repetitions here.
                    continue;
                }
                $this->bookings[] = $booking;
                $this->available_booking_ids[] = $booking->id;
                $this->booking_time_ranges[$booking->id] =
                    $booking->getTimeIntervalStrings();
            }

            if (!$this->available_booking_ids) {
                PageLayout::postError(
                    sprintf(
                        _('Die gewählten Räume haben im Semester %s keine einfachen Buchungen mit Wiederholungen!'),
                        htmlReady($this->source_semester->name)
                    )
                );
                $this->step = 1;
                return;
            }
        }
        if ($this->step >= 3) {
            //Step 3: Test copying into the target semester
            $this->show_copy_button = false;
            $this->target_semester_id = Request::get('target_semester_id');
            $this->selected_booking_ids = Request::getArray('selected_booking_ids');
            if (!$this->target_semester_id) {
                PageLayout::postError(
                    _('Es wurde kein Zielsemester ausgewählt!')
                );
                $this->step = 2;
                return;
            }
            $this->target_semester = Semester::find($this->target_semester_id);
            if (!$this->target_semester) {
                PageLayout::postError(
                    _('Das gewählte Zielsemester wurde nicht gefunden!')
                );
                $this->step = 2;
                return;
            }

            if (!$this->selected_booking_ids) {
                PageLayout::postError(
                    _('Es wurden keine Buchungen ausgewählt!')
                );
                $this->step = 2;
                return;
            }

            foreach ($this->selected_booking_ids as $booking_id) {
                if (!in_array($booking_id, $this->available_booking_ids)) {
                    PageLayout::postError(
                        _('Es wurde eine Buchung ausgewählt, die nicht Teil der Raumgruppe ist!')
                    );
                    $this->step = 2;
                    return;
                }
            }

            if (Request::submitted('step2')) {
                $this->step = 2;
                return;
            }

            //Retrieve booking objects:
            $this->selected_bookings = ResourceBooking::findMany($this->selected_booking_ids);

            if (!$this->selected_bookings) {
                PageLayout::postError(
                    _('Die gewählten Buchungen wurden nicht in der Datenbank gefunden!')
                );
                $this->step = 2;
                return;
            }

            //$booking_copy_data is an associative array where the items have
            //the following strucutre:
            //[
            //    'sem_week' => The week number of the target semester.
            //    'begin' => The timestamp of the begin of the copied booking.
            //    'end' => The timestamp of the end of the copied booking.
            //    'available' => Whether the resource is available
            //        on the specified time range (true) or not (false).
            //]
            $this->booking_copy_data = [];

            //Loop over each booking and do the following:
            //1. Calculate the week number and the week day of the booking
            //   in the semester, unless the week number has been explicitly
            //   specified in step 1.
            //2. Calculate the date for the copy of the booking and store it
            //   in an array.
            //3. Check if the resource of the booking is available on the
            //   calculcated date in the time range of the original booking.
            //4. Add the availability information to the array
            //   with the booking copies.
            //5. Count the number of bookings and how many of them can be
            //   copied in the target semester. If more that 50% of bookings
            //   cannot be copied, do not show the copy action and instead
            //   provide a download button to download the list of bookings.

            $available_booking_c = 0;
            foreach ($this->selected_bookings as $booking) {
                $begin_sem_week_number = 0;
                if ($this->sem_week_selected) {
                    $begin_sem_week_number = $this->selected_sem_week +
                                             $this->source_semester->getSemWeekNumber($booking->begin) - 1;
                } else {
                    $begin_sem_week_number = $this->source_semester->getSemWeekNumber($booking->begin);
                }
                if (!$begin_sem_week_number) {
                    PageLayout::postError(
                        sprintf(
                            _('Eine Buchung (%1$s) liegt außerhalb des Semesters %2$s!'),
                            htmlReady($booking->__toString()),
                            htmlReady($this->source_semester->name)
                        )
                    );
                    $this->step = 2;
                    return;
                }
                $begin_week_day = date('N', $booking->begin);
                $begin_time = explode(':', date('H:i:s', $booking->begin));
                $end_time = explode(':', date('H:i:s', $booking->end));

                //Calculate the duration (begin-end-difference):
                $booking_begin = new DateTime();
                $booking_begin->setTimestamp($booking->begin);
                $booking_end = new DateTime();
                $booking_end->setTimestamp($booking->end);

                $duration = $booking_begin->diff($booking_end);
                $booking_repeat_end = new DateTime();
                $booking_repeat_end->setTimestamp($booking->repeat_end);
                $repeat_duration = $booking_end->diff($booking_repeat_end);

                //Calculate the new begin date:
                $target_sem_week_begin = new DateTime();
                $target_sem_week_begin->setTimestamp($this->target_semester->beginn);
                $target_sem_week_begin = $target_sem_week_begin->add(
                    new DateInterval('P' . ($begin_sem_week_number - 1) . 'W')
                );
                $target_begin = clone $target_sem_week_begin;
                $begin_week_day_diff = $begin_week_day - $target_sem_week_begin->format('N');
                if ($begin_week_day_diff < 0) {
                    $target_begin = $target_begin->sub(
                        new DateInterval('P' . abs($begin_week_day_diff) . 'D')
                    );
                } elseif ($begin_week_day_diff > 0) {
                    $target_begin = $target_begin->add(
                        new DateInterval('P' . $begin_week_day_diff . 'D')
                    );
                }
                $target_begin->setTime(
                    intval($begin_time[0]),
                    intval($begin_time[1]),
                    intval($begin_time[2])
                );

                //Calculcate the new end date using the duration:
                $target_end = clone $target_begin;
                $target_end = $target_end->add($duration);

                //Calculcate the new repeat end using the repeat duration
                //or the end of the semester, if repeat_end of the original
                //booking is the same timestamp as the course end of the
                //source semester.
                $target_repeat_end = clone $target_end;
                if ($booking->repeat_end >= $this->source_semester->vorles_ende) {
                    $target_repeat_end->setTimestamp(
                        $this->target_semester->vorles_ende
                    );
                } else {
                    $target_repeat_end = $target_repeat_end->add(
                        $repeat_duration
                    );
                    if ($target_repeat_end >= $this->target_semester->vorles_ende) {
                        $target_repeat_end->setTimestamp(
                            $this->target_semester->vorles_ende
                        );
                    }
                }

                $copy_data = [
                    'sem_week_number' => $begin_sem_week_number,
                    'copy' => null,
                    'available' => null,
                    'original' => $booking,
                    'time_intervals' => []
                ];

                $copy = new ResourceBooking();
                $copy->resource_id = $booking->resource_id;
                $copy->range_id = $booking->range_id;
                $copy->booking_user_id = $GLOBALS['user']->id;
                $copy->description = $booking->description;
                $copy->begin = $target_begin->getTimestamp() +
                               $booking->preparation_time;
                $copy->end = $target_end->getTimestamp();
                $copy->preparation_time = $booking->preparation_time;
                $copy->booking_type = $booking->booking_type;
                $copy->repeat_end = $target_repeat_end->getTimestamp();
                $copy->repetition_interval = $booking->repetition_interval;
                $copy->internal_comment = $booking->internal_comment;
                if ($this->step == 3) {
                    //We only need to call validate when we are really
                    //trying to check if the booking can be made.
                    //After step 3, we don't need to call validate manually
                    //since it is automatically called before storing.
                    //Furthermore, the availability flag isn't important
                    //anymore after step 3.
                    $time_intervals = $copy->calculateTimeIntervals();
                    if (!$time_intervals) {
                        //The copied booking will have no time intervals.
                        //So we can skip to the next one.
                        continue;
                    }
                    $copy_data['time_intervals'] = $copy->calculateTimeIntervals();
                    try {
                        $copy->validate();
                        $copy_data['available'] = true;
                        $available_booking_c++;
                    } catch (Exception $e) {
                        $copy_data['available'] = false;
                    }
                }
                $copy_data['copy'] = $copy;
                $this->booking_copy_data[$booking->id] = $copy_data;
            }
            if (Request::submitted('download_booking_list')) {
                $csv_data = [
                    [
                        _('Buchungsnummer'),
                        _('Buchungszeitraum'),
                        _('Raum'),
                        _('Verfügbar')
                    ]
                ];
                $booking_c = 1;
                foreach ($this->booking_copy_data as $data) {
                    foreach ($data['time_intervals'] as $interval) {
                        $time_range = sprintf(
                            '%1$s - %2$s',
                            date('d.m.Y H:i', $interval['begin']),
                            date('d.m.Y H:i', $interval['end'])
                        );
                        $csv_data[] = [
                            $booking_c,
                            $time_range,
                            $data['original']->resource->name,
                            $data['available'] ? _('ja') : _('nein')
                        ];
                    }
                    $booking_c++;
                }
                $filename = sprintf(
                    _('Zu kopierende Buchungen am %s') . '.csv',
                    date('d.m.Y')
                );
                $this->render_csv($csv_data, $filename);
                return;
            } elseif ($this->step < 4) {
                $booking_c = count($this->selected_bookings);
                if ($booking_c) {
                    if (($available_booking_c / $booking_c) < 0.5) {
                        PageLayout::postInfo(
                            _('Weniger als die Hälfte der Buchungen können in das Zielsemester kopiert werden!')
                        );
                        return;
                    } else {
                        $this->show_copy_button = true;
                    }
                }
            }
        }
        if ($this->step >= 4) {
            $errors = [];
            $count = 0;
            //Step 4: Copy the bookings
            foreach ($this->booking_copy_data as $copy_data) {
                try {
                    $copy_data['copy']->store();
                } catch (Exception $e) {
                    $errors[] = $e->getMessage();
                }
                $count++;
            }

            if (!$errors) {
                PageLayout::postSuccess(
                    _('Alle Buchungen wurden kopiert!')
                );
            } else {
                if (count($errors) < $count) {
                    PageLayout::postWarning(
                        _('Es konnten nicht alle Buchungen kopiert werden!'),
                        $errors
                    );
                } else {
                    PageLayout::postError(
                        _('Keine der ausgewählten Buchungen konnte kopiert werden!'),
                        $errors
                    );
                }
            }
        }
    }

    public function booking_comments_action($selected_clipboard_id = null)
    {
        PageLayout::setTitle(_('Buchungsübersicht mit Kommentaren'));

        if (Navigation::hasItem('/resources/planning/booking_comments')) {
            Navigation::activateItem('/resources/planning/booking_comments');
        }

        $selected_clipboard_id = Request::get('clipboard_id', $selected_clipboard_id);
        $this->standalone = false;

        if ($selected_clipboard_id) {
            $_SESSION['selected_clipboard_id'] = $selected_clipboard_id;
        } else {
            $selected_clipboard_id = $_SESSION['selected_clipboard_id'];
        }

        //Get the selected date or use the current date, if none specified:
        $this->date = Request::getDateTime('date', 'd.m.Y', null, null, new DateTime());
        if ($this->date === false) {
            //Format parsing error. Try the YYYY-mm-dd format:
            $this->date = Request::getDateTime('date', 'Y-m-d', null, null, new DateTime());
            if ($this->date === false) {
                //Fallback to the current date:
                $this->date = new DateTime();
            }
        }

        //Build sidebar:
        $sidebar = Sidebar::get();

        //Add the date selection widget:
        $date_search = new SearchWidget(
            $this->url_for('room_management/planning/booking_comments')
        );
        $date_search->setTitle(_('Datum'));
        $date_search->setMethod('get');
        $date_search->addNeedle(
            _('Datum'),
            'date',
            'DD.MM.YYYY',
            null,
            null,
            $this->date->format('d.m.Y'),
            ['class' => 'with-datepicker']
        );
        $sidebar->addWidget($date_search);

        //Add clipboard widget:
        $clipboards = Clipboard::getClipboardsForUser($GLOBALS['user']->id);
        if (!empty($clipboards)) {
            if (!$selected_clipboard_id) {
                //Select the first clipboard so that the user doesn't have to select one first:
                $selected_clipboard_id = $clipboards[0]->id;
            }
            $clipboard_widget = new SelectWidget(
                _('Individuelle Raumgruppen'),
                $this->booking_commentsURL(),
                'clipboard_id',
                'get'
            );
            foreach ($clipboards as $clipboard) {
                $clipboard_widget->addElement(new SelectElement(
                    $clipboard->id,
                    $clipboard->name,
                    $clipboard->id === $selected_clipboard_id
                ), "clipboard_id-{$clipboard->id}");
            }
            $sidebar->addWidget($clipboard_widget);
        }

        $this->current_user = User::findCurrent();
        $this->room_ids = [];
        if ($selected_clipboard_id) {
            $clipboard = Clipboard::find($selected_clipboard_id);
            $this->clipboard = $clipboard;
            if ($clipboard) {
                PageLayout::setTitle(
                    $clipboard->name . ': ' . _('Buchungsübersicht mit Kommentaren')
                );
                $room_ids = $clipboard->getAllRangeIds('Room');
                $rooms = Resource::findMany($room_ids);
                foreach ($rooms as $room) {
                    $room = $room->getDerivedClassInstance();
                    if ($room instanceof Room) {
                        if ($room->userHasPermission($this->current_user)) {
                            $this->room_ids[] = $room->id;
                        }
                    }
                }
            }
        }

        //Add the actions widget:

        $actions = new ActionsWidget();
        $actions->addLink(
            _('Export für Word'),
            $this->url_for(
                'room_management/planning/booking_comments',
                [
                    'export' => 'html',
                    'date' => $this->date->format('d.m.Y')
                ]
            ),
            Icon::create('export')
        );
        $actions->addLink(
            _('Export als CSV'),
            $this->url_for(
                'room_management/planning/booking_comments',
                [
                    'export' => 'csv',
                    'date' => $this->date->format('d.m.Y')
                ]
            ),
            Icon::create('export')
        );
        $sidebar->addWidget($actions);

        //Calculate week begin and end:
        $week_end = new DateTime();
        $week_end->setTimestamp(strtotime('next sunday', $this->date->getTimestamp()));
        $week_end->setTime(23,59,59);
        $week_begin = clone $week_end;
        $week_begin = $week_begin->sub(new DateInterval('P1W'))->add(new DateInterval('PT1S'));

        //Get bookings:

        $booking_intervals = ResourceBookingInterval::findBySql(
            "INNER JOIN resource_bookings rb
            ON resource_booking_intervals.booking_id = rb.id
            WHERE rb.resource_id IN ( :room_ids )
            AND resource_booking_intervals.begin < :end AND resource_booking_intervals.end > :begin
            ORDER BY resource_booking_intervals.begin ASC, resource_booking_intervals.end ASC",
            [
                'room_ids' => $this->room_ids,
                'begin' => $week_begin->getTimestamp(),
                'end' => $week_end->getTimestamp()
            ]
        );

        //Array structure:
        //Layer 1: keys: resource-IDs, content: Array
        //Layer 2: keys: 0 = name (resource name), 1-7: weekdays: Array
        //Layer 3 (weekdays): Array
        //Layer 4 (weekdays): 0 = time, 1 = comment
        $this->data = [
        ];

        foreach ($booking_intervals as $interval) {
            $l1_index = $interval->booking->resource_id; //Layer 1 index
            if (!is_array($this->data[$l1_index])) {
                $this->data[$l1_index] = [
                    $interval->booking->resource->name,
                    [],
                    [],
                    [],
                    [],
                    [],
                    [],
                    []
                ];
            }

            $booking_text_items = [];
            if ($interval->booking->description) {
                $booking_text_items[] = $interval->booking->description;
            }
            if ($interval->booking->assigned_user instanceof User) {
                $booking_text_items[] =
                    $interval->booking->assigned_user->getFullName();
            }
            if ($interval->booking->internal_comment) {
                $booking_text_items[] = $interval->booking->internal_comment;
            }
            $booking_text_string = implode('; ', $booking_text_items);

            $interval_begin = new DateTime();
            $interval_begin->setTimestamp($interval->begin);
            $interval_end = new DateTime();
            $interval_end->setTimestamp($interval->end);
            $begin_weekday = date('N', $interval->begin);
            $end_weekday = date('N', $interval->end);

            if ($interval_begin->format('Ymd') != $interval_end->format('Ymd')) {
                //The interval is spread over several days.
                //It must be displayd on each of them.
                $current_day = clone $interval_begin;
                if ($interval_begin < $week_begin) {
                    $current_day->setTime(0,0,0);
                    //The interval starts before the current week.
                    //We have to move the current day to the begin
                    //of the week to calculate the begin time.
                    while ($current_day < $week_begin) {
                        $current_day = $current_day->add(
                            new DateInterval('P1D')
                        );
                    }
                }

                //At this point we have reached the begin of the selected week.
                //Add an entry to the data array:
                $l2_index = intval($current_day->format('N'));
                if (!is_array($this->data[$l1_index][$l2_index])) {
                    $this->data[$l1_index][$l2_index] = [];
                }

                if ($current_day->format('Ymd') == $interval_end->format('Ymd')) {
                    //The interval ends on the first day of the week.
                    $time_string = sprintf(
                        _('%1$s - %2$s Uhr'),
                        $current_day->format('H:i'),
                        $interval_end->format('H:i')
                    );
                    $this->data[$l1_index][$l2_index][] = [
                        $time_string,
                        $booking_text_string
                    ];
                    //There is nothing else to do for this interval.
                } else {
                    //The interval ends on another day of the week.
                    $time_string = sprintf(
                        _('%1$s - %2$s Uhr'),
                        $current_day->format('H:i'),
                        '23:59'
                    );

                    $this->data[$l1_index][$l2_index][] = [
                        $time_string,
                        $booking_text_string
                    ];

                    $current_day = $current_day->add(new DateInterval('P1D'));

                    //Now we loop over each day until we have reached the end day.
                    //We compare date strings, because the time may differ
                    //between $current_day and $interval_end.
                    while ($current_day->format('Ymd') < $interval_end->format('Ymd')) {
                        if ($current_day > $week_end) {
                            //out of range
                            break;
                        }
                        if ($current_day >= $week_begin) {
                            $l2_index = intval($current_day->format('N'));
                            if (!is_array($this->data[$l1_index][$l2_index])) {
                                $this->data[$l1_index][$l2_index] = [];
                            }
                            $time_string = sprintf(
                                _('%1$s - %2$s Uhr'),
                                '0:00',
                                '23:59'
                            );
                            $this->data[$l1_index][$l2_index][] = [
                                $time_string,
                                $booking_text_string
                            ];
                        }
                        $current_day = $current_day->add(
                            new DateInterval('P1D')
                        );
                    }
                    if ($current_day->format('Ymd') <= $week_end->format('Ymd')) {
                        //We have reached the last day of the interval,
                        //which lies inside the week.
                        $time_string = sprintf(
                            _('%1$s - %2$s Uhr'),
                            '0:00',
                            $interval_end->format('H:i')
                        );
                        $l2_index = intval($interval_end->format('N'));
                        if (!is_array($this->data[$l1_index][$l2_index])) {
                            $this->data[$l1_index][$l2_index] = [];
                        }
                        $this->data[$l1_index][$l2_index][] = [
                            $time_string,
                            $booking_text_string
                        ];
                    }
                }
            } else {
                $l2_index = intval($begin_weekday); //Layer 2 index
                if (!is_array($this->data[$l1_index][$l2_index])) {
                    $this->data[$l1_index][$l2_index] = [];
                }
                $time_string = sprintf(
                    _('%1$s - %2$s Uhr'),
                    date('H:i', $interval->booking->begin),
                    date('H:i', $interval->booking->end)
                );
                $this->data[$l1_index][$l2_index][] = [
                    $time_string,
                    $booking_text_string
                ];
            }
        }

        //Sort the data array by the room name:
        usort($this->data, function ($a, $b)
            {
                if ($a[0] == $b[0]) {
                    return 0;
                }
                return ($a[0] < $b[0]) ? -1 : 1;
            }
        );

        $export = Request::get('export');
        if ($export == 'html') {
            //Load the export template:
            $factory = new Flexi_TemplateFactory(
                $GLOBALS['STUDIP_BASE_PATH'] . '/app/views/room_management/planning/'
            );

            $template = $factory->open('booking_comments_html_export_frame.php');

            $template->set_attribute(
                'data',
                $this->data
            );
            $template->set_attribute('date', $this->date);

            $html = $template->render();

            $file_name = sprintf(
                _('Buchungen, KW %d.doc'),
                $this->date->format('W')
            );

            $this->set_content_type('application/msword; charset=utf-8');
            header('Content-Disposition: attachment;filename="' . $file_name . '"');
            $this->render_text($html);
        } elseif ($export == 'csv') {
            $csv_data = [
                [
                    sprintf(
                        _('%d. Kalenderwoche'),
                        $this->date->format('W')
                    ),
                    sprintf(
                        '%1$s' . "\n" . '%2$s',
                        _('Montag'),
                        date(
                            'd.m.Y',
                            strtotime('this week monday', $this->date->getTimestamp())
                        )
                    ),
                    sprintf(
                        '%1$s' . "\n" . '%2$s',
                        _('Dienstag'),
                        date(
                            'd.m.Y',
                            strtotime('this week tuesday', $this->date->getTimestamp())
                        )
                    ),
                    sprintf(
                        '%1$s' . "\n" . '%2$s',
                        _('Mittwoch'),
                        date(
                            'd.m.Y',
                            strtotime('this week wednesday', $this->date->getTimestamp())
                        )
                    ),
                    sprintf(
                        '%1$s' . "\n" . '%2$s',
                        _('Donnerstag'),
                        date(
                            'd.m.Y',
                            strtotime('this week thursday', $this->date->getTimestamp())
                        )
                    ),
                    sprintf(
                        '%1$s' . "\n" . '%2$s',
                        _('Freitag'),
                        date(
                            'd.m.Y',
                            strtotime('this week friday', $this->date->getTimestamp())
                        )
                    ),
                    sprintf(
                        '%1$s' . "\n" . '%2$s',
                        _('Samstag'),
                        date(
                            'd.m.Y',
                            strtotime('this week saturday', $this->date->getTimestamp())
                        )
                    ),
                    sprintf(
                        '%1$s' . "\n" . '%2$s',
                        _('Sonntag'),
                        date(
                            'd.m.Y',
                            strtotime('this week sunday', $this->date->getTimestamp())
                        )
                    )
                ]
            ];

            foreach ($this->data as $row) {
                $csv_row = [];
                foreach ($row as $i => $cell) {
                    if ($i == 0) {
                        $csv_row[0] = $cell;
                    } else {
                        $csv_row[$i] = '';
                        if ($cell) {
                            $items = [];
                            foreach ($cell as $day_item) {
                                $items[] = $day_item[0] . ': ' . $day_item[1];
                            }
                            $csv_row[$i] = implode("\n\n", $items);
                        }
                    }
                }
                $csv_data[] = $csv_row;
            }

            $this->set_content_type('text/csv');
            $this->render_text(array_to_csv($csv_data));
        }
    }
}