aboutsummaryrefslogtreecommitdiff
path: root/lib/models/resources/ResourceRequest.class.php
blob: 9cad900a4c95fa1e622f2258db08b84fbfb800b3 (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
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
<?php

/**
 * ResourceRequest.class.php - Contains a model class for resource requests.
 *
 * 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>
 * @copyright   2017-2019
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GPL version 2
 * @category    Stud.IP
 * @package     resources
 * @since       4.5
 *
 * The attributes begin and end are only used in simple resource requests.
 * The "traditional" resource requests use either course_id, metadate_id
 * or termin_id to store the time ranges connected to the request.
 *
 * @property string $id database column
 * @property string $course_id database column
 * @property string $termin_id database column
 * @property string $metadate_id database column
 * @property string $user_id database column
 * @property string $last_modified_by database column
 * @property string $resource_id database column
 * @property string|null $category_id database column
 * @property string|null $comment database column
 * @property string|null $reply_comment database column
 * @property string $reply_recipients database column
 * @property int $closed database column
 * @property int|null $mkdate database column
 * @property int|null $chdate database column
 * @property int $begin database column
 * @property int $end database column
 * @property int $preparation_time database column
 * @property int $marked database column
 * @property SimpleORMapCollection|ResourceRequestProperty[] $properties has_many ResourceRequestProperty
 * @property SimpleORMapCollection|ResourceRequestAppointment[] $appointments has_many ResourceRequestAppointment
 * @property Resource $resource belongs_to Resource
 * @property ResourceCategory|null $category belongs_to ResourceCategory
 * @property User $user belongs_to User
 * @property User $last_modifier belongs_to User
 * @property Course $course belongs_to Course
 * @property SeminarCycleDate $cycle belongs_to SeminarCycleDate
 * @property CourseDate $date belongs_to CourseDate
 */
class ResourceRequest extends SimpleORMap implements PrivacyObject, Studip\Calendar\EventSource
{
    const MARK_NONE = 0;
    const MARK_RED = 1;
    const MARK_YELLOW = 2;
    const MARK_GREEN = 3;

    const REPLY_REQUESTER = 'requester';
    const REPLY_LECTURER = 'lecturer';

    const STATE_OPEN = 0; // room-request is open
    const STATE_PENDING = 1; // room-request has been processed, but no confirmation has been sent
    const STATE_CLOSED = 2; // room-request has been processed and a confirmation has been sent
    const STATE_DECLINED = 3; // room-request has been declined

    /**
     * The amount of defined marking states.
     */
    const MARKING_STATES = 4;

    protected static function configure($config = [])
    {
        $config['db_table'] = 'resource_requests';

        $config['belongs_to']['resource'] = [
            'class_name'  => Resource::class,
            'foreign_key' => 'resource_id',
            'assoc_func'  => 'find'
        ];

        $config['belongs_to']['category'] = [
            'class_name'  => ResourceCategory::class,
            'foreign_key' => 'category_id',
            'assoc_func'  => 'find'
        ];

        $config['belongs_to']['user'] = [
            'class_name'  => User::class,
            'foreign_key' => 'user_id',
            'assoc_func'  => 'find'
        ];

        $config['belongs_to']['last_modifier'] = [
            'class_name'  => User::class,
            'foreign_key' => 'last_modified_by',
            'assoc_func'  => 'find'
        ];

        $config['belongs_to']['course'] = [
            'class_name'  => Course::class,
            'foreign_key' => 'course_id',
            'assoc_func'  => 'find'
        ];

        $config['belongs_to']['cycle'] = [
            'class_name'  => SeminarCycleDate::class,
            'foreign_key' => 'metadate_id'
        ];

        $config['belongs_to']['date'] = [
            'class_name'  => CourseDate::class,
            'foreign_key' => 'termin_id'
        ];

        $config['has_many']['properties'] = [
            'class_name'        => ResourceRequestProperty::class,
            'foreign_key'       => 'id',
            'assoc_foreign_key' => 'request_id',
            'on_store'          => 'store',
            'on_delete'         => 'delete'
        ];

        $config['has_many']['appointments'] = [
            'class_name'        => ResourceRequestAppointment::class,
            'foreign_key'       => 'id',
            'assoc_foreign_key' => 'request_id',
            'on_store'          => 'store',
            'on_delete'         => 'delete'
        ];

        //In regard to TIC 6460:
        //As long as TIC 6460 is not implemented, we must add the validate
        //method as a callback before storing the object.
        if (!method_exists('SimpleORMap', 'validate')) {
            $config['registered_callbacks']['before_store'][] = 'validate';
        }
        $config['registered_callbacks']['after_create'][] = 'cbLogNewRequest';
        $config['registered_callbacks']['after_store'][] = 'cbAfterStore';
        $config['registered_callbacks']['after_delete'][] = 'cbAfterDelete';


        parent::configure($config);
    }

    /**
     * @inheritDoc
     */
    public static function exportUserdata(StoredUserData $storage)
    {
        $user = User::find($storage->user_id);

        $requests = self::findBySql(
            'user_id = :user_id ORDER BY mkdate',
            [
                'user_id' => $storage->user_id
            ]
        );

        $request_rows = [];
        foreach ($requests as $request) {
            $request_rows[] = $request->toRawArray();
        }
        $storage->addTabularData(
            _('Ressourcenanfragen'),
            'resource_requests',
            $request_rows,
            $user
        );
    }

    /**
     * Retrieves all resource requests from the database.
     *
     * @return ResourceRequest[] An array of ResourceRequests objects
     *     or an empty array, if no resource requests are stored
     *     in the database.
     */
    public static function findAll()
    {
        return self::findBySql('TRUE ORDER BY mkdate ASC');
    }

    /**
     * Retrieves all open resource requests from the database.
     *
     * @return ResourceRequest[] An array of ResourceRequests objects
     *     or an empty array, if no open resource requests are stored
     *     in the database.
     */
    public static function findOpen()
    {
        return self::findBySql(
            'closed = ? ORDER BY mkdate ASC',
            [self::STATE_OPEN]
        );
    }

    /**
     * Internal method that generated the SQL query used in
     * findByResourceAndTimeRanges and countByResourceAndTimeRanges.
     *
     * @see findByResourceAndTimeRanges
     * @inheritDoc
     */
    protected static function buildResourceAndTimeRangesSqlQuery(
        Resource $resource,
        $time_ranges = [],
        $closed_status = null,
        $excluded_request_ids = [],
        $additional_conditions = '',
        $additional_parameters = []
    )
    {
        if (!is_array($time_ranges)) {
            throw new InvalidArgumentException(
                _('Es wurde keine Liste mit Zeiträumen angegeben!')
            );
        }

        //Check the array:
        foreach ($time_ranges as $time_range) {
            if ($time_range['begin'] > $time_range['end']) {
                throw new InvalidArgumentException(
                    _('Der Startzeitpunkt darf nicht hinter dem Endzeitpunkt liegen!')
                );
            }

            if ($time_range['begin'] == $time_range['end']) {
                throw new InvalidArgumentException(
                    _('Startzeitpunkt und Endzeitpunkt dürfen nicht identisch sein!')
                );
            }
        }

        $sql_params = [
            'resource_id' => $resource->id
        ];

        //First we build the SQL snippet for the case that the $closed_status
        //variable is set to something different than null.
        $closed_status_sql = '';
        if ($closed_status !== null) {
            $closed_status_sql    = ' AND (resource_requests.closed = :status) ';
            $sql_params['status'] = strval($closed_status);
        }

        //Then we build the snipped for excluded request IDs, if specified.
        $excluded_request_ids_sql = '';
        if (is_array($excluded_request_ids) && count($excluded_request_ids)) {
            $excluded_request_ids_sql   = ' AND resource_requests.id NOT IN ( :excluded_ids ) ';
            $sql_params['excluded_ids'] = $excluded_request_ids;
        }

        //Now we build the SQL snippet for the time intervals.
        //These are repeated four times in the query below.
        //BEGIN and END are replaced below since the columns for
        //BEGIN and END are different in the four cases where we
        //repeat the SQL snippet for the time intervals.

        $time_sql = '';
        if ($time_ranges) {
            $time_sql = 'AND (';

            $i = 1;
            foreach ($time_ranges as $time_range) {
                if ($i > 1) {
                    $time_sql .= ' OR ';
                }
                $time_sql .= sprintf('BEGIN < :end%d AND END > :begin%d ', $i, $i);

                $sql_params[('begin' . $i)] = $time_range['begin'];
                $sql_params[('end' . $i)]   = $time_range['end'];

                $i++;
            }

            $time_sql .= ') ';
        }

        //Check if the request has a start and end timestamp set or if it belongs
        //to a date, a metadate or a course.
        //This is done in the rest of the SQL query:

        // FIXME this subselect looks unnecessarily complex
        $whole_sql = '
                SELECT id FROM resource_requests
                WHERE
                resource_id = :resource_id
        '
            . str_replace(
                ['BEGIN', 'END'],
                ['(CAST(begin AS SIGNED) - preparation_time)', 'end'],
                $time_sql
            )
            . $closed_status_sql
            . '
                UNION
                SELECT id FROM resource_requests
                INNER JOIN termine USING (termin_id)
                WHERE
                resource_id = :resource_id
                   '
            . str_replace(
                ['BEGIN', 'END'],
                [
                    '(CAST(termine.date AS SIGNED) - resource_requests.preparation_time)',
                    'termine.end_time'
                ],
                $time_sql
            )
            . $closed_status_sql
            . '
                UNION
                SELECT id FROM resource_requests
                INNER JOIN termine USING (metadate_id)
                WHERE
                resource_id = :resource_id
                   '
            . str_replace(
                ['BEGIN', 'END'],
                [
                    '(CAST(termine.date AS SIGNED) - resource_requests.preparation_time)',
                    'termine.end_time'
                ],
                $time_sql
            )
            . $closed_status_sql
            . '
            UNION
            SELECT id FROM resource_requests
            INNER JOIN termine
            ON resource_requests.course_id = termine.range_id
            WHERE
            resource_id = :resource_id
                   '
            . str_replace(
                ['BEGIN', 'END'],
                [
                    '(CAST(termine.date AS SIGNED) - resource_requests.preparation_time)',
                    'termine.end_time'
                ],
                $time_sql
            )
            . $closed_status_sql
            . '
            GROUP BY id
         '
            . $excluded_request_ids_sql;
        $request_ids = DBManager::get()->fetchFirst($whole_sql, $sql_params);
        $whole_sql = "resource_requests.id IN(:request_ids)";
        $sql_params = ['request_ids' => $request_ids];
        if ($additional_conditions) {
            $whole_sql .= ' AND ' . $additional_conditions;
            if ($additional_parameters) {
                $sql_params = array_merge($sql_params, $additional_parameters);
            }
        }
        $whole_sql .= ' ORDER BY mkdate ASC';

        return [
            'sql'    => $whole_sql,
            'params' => $sql_params
        ];
    }

    /**
     * Retrieves all resource requests for the given resource and
     * time range. By default, all requests are returned.
     * To get only open or closed requests set the $closed_status parameter.
     *
     * @param Resource $resource The resource whose requests shall be retrieved.
     * @param array $time_ranges An array with time ranges as DateTime objects.
     *     The array has the following structure:
     *     [
     *         [
     *             'begin' => begin timestamp,
     *             'end' => end timestamp
     *         ],
     *         ...
     *     ]
     * @param mixed $closed_status An optional status for the closed column in the
     *     database. By default this is set to null which means that
     *     resource requests are not filtered by the status column field.
     *     A value of 0 means only open requests are retrived.
     *     A value of 1 means only closed requests are retrieved.
     *
     * @param array $excluded_request_ids An array of strings representing
     *     resource request IDs. IDs specified in this array are excluded from
     *     the search.
     * @return ResourceRequest[] An array of ResourceRequest objects.
     *     If no requests can be found, the array is empty.
     *
     * @throws InvalidArgumentException, if the time ranges are either not in an
     *     array matching the format description from above or if one of the
     *     following conditions is met in one of the time ranges:
     *     - begin > end
     *     - begin == end
     */
    public static function findByResourceAndTimeRanges(
        Resource $resource,
        $time_ranges = [],
        $closed_status = null,
        $excluded_request_ids = [],
        $additional_conditions = '',
        $additional_parameters = []
    )
    {
        //Build the SQL query and the parameter array.

        $sql_data = self::buildResourceAndTimeRangesSqlQuery(
            $resource,
            $time_ranges,
            $closed_status,
            $excluded_request_ids,
            $additional_conditions,
            $additional_parameters
        );

        //Call findBySql:
        return self::findBySql($sql_data['sql'], $sql_data['params']);
    }

    public static function countByResourceAndTimeRanges(
        Resource $resource,
        $time_ranges = [],
        $closed_status = null,
        $excluded_request_ids = [],
        $additional_conditions = '',
        $additional_parameters = []
    )
    {
        $sql_data = self::buildResourceAndTimeRangesSqlQuery(
            $resource,
            $time_ranges,
            $closed_status,
            $excluded_request_ids,
            $additional_conditions,
            $additional_parameters
        );

        return self::countBySql($sql_data['sql'], $sql_data['params']);
    }

    public static function findByCourse($course_id)
    {
        return self::findOneBySql(
            "termin_id = '' AND metadate_id = '' AND course_id = :course_id",
            [
                'course_id' => $course_id
            ]
        );
    }

    public static function findByDate($date_id)
    {
        return self::findOneBySql(
            'termin_id = :date_id',
            [
                'date_id' => $date_id
            ]
        );
    }

    public static function findByMetadate($metadate_id)
    {
        return self::findOneBySql(
            'metadate_id = :metadate_id',
            [
                'metadate_id' => $metadate_id
            ]
        );
    }

    public static function existsByCourse($course_id, $request_is_open = false)
    {
        $parameters = [':course_id' => $course_id];

        $sql = '';
        if ($request_is_open) {
            $sql .= "closed = :closed_state AND ";
            $parameters[':closed_state'] = self::STATE_OPEN;
        }

        $request = self::findOneBySql(
            $sql . "termin_id = '' AND metadate_id = '' AND course_id = :course_id",
            $parameters
        );

        if ($request) {
            return $request->id;
        } else {
            return false;
        }
    }

    public static function existsByDate($date_id, $request_is_open = false)
    {
        $parameters = [':date_id' => $date_id];

        $sql = '';
        if ($request_is_open) {
            $sql .= "closed = :closed_state AND ";
            $parameters[':closed_state'] = self::STATE_OPEN;
        }

        $request = self::findOneBySql(
            $sql . "termin_id = :date_id",
            $parameters
        );

        if ($request) {
            return $request->id;
        } else {
            return false;
        }
    }

    public static function existsByMetadate($metadate_id, $request_is_open = false)
    {
        $parameters = [':metadate_id' => $metadate_id];

        $sql = '';
        if ($request_is_open) {
            $sql .= "closed = :closed_state AND ";
            $parameters[':closed_state'] = self::STATE_OPEN;
        }

        $request = self::findOneBySql(
            $sql . "metadate_id = :metadate_id",
            $parameters
        );

        if ($request) {
            return $request->id;
        } else {
            return false;
        }
    }

    /**
     * A callback method that creates a Stud.IP log entry
     * when a new request has been made.
     */
    public function cbLogNewRequest()
    {
        $this->sendNewRequestMail();
        StudipLog::log('RES_REQUEST_NEW', $this->course_id, $this->resource_id, $this->getLoggingInfoText());
    }

    /**
     * A callback method that send a mail
     * when a new request has been udpated.
     */
    public function cbAfterStore()
    {
        if ($this->isFieldDirty('closed')) {
            if ($this->closed == self::STATE_DECLINED) {
                $this->sendRequestDeniedMail();
                StudipLog::log('RES_REQUEST_DENY', $this->course_id, $this->resource_id, $this->getLoggingInfoText());
            } elseif ($this->closed == self::STATE_PENDING || $this->closed == self::STATE_CLOSED) {
                StudipLog::log('RES_REQUEST_RESOLVE', $this->course_id, $this->resource_id, $this->getLoggingInfoText());
            }
        } else {
            StudipLog::log('RES_REQUEST_UPDATE', $this->course_id, $this->resource_id, $this->getLoggingInfoText());
        }
    }

    public function cbAfterDelete()
    {
        StudipLog::log('RES_REQUEST_DEL', $this->course_id, $this->resource_id, $this->getLoggingInfoText());
    }

    /**
     * This validation method is called before storing an object.
     */
    public function validate()
    {
        if (!$this->resource_id && !$this->category_id) {
            throw new Exception(
                _('Eine Anfrage muss einer konkreten Ressource oder deren Kategorie zugewiesen sein!')
            );
        }
    }

    public function getDerivedClassInstance()
    {
        if (!$this->resource) {
            //We cannot determine a derived class.
            return $this;
        }
        $class_name = $this->resource->class_name;

        if ($class_name === 'Resource') {
            //This is already the correct class.
            return $this;
        }

        if (is_subclass_of($class_name, 'Resource')) {
            //Now we append 'Request' to the class name:
            $class_name         = $class_name . 'Request';
            return $class_name::buildExisting(
                $this->toRawArray()
            );
        } else {
            //$class_name does not contain the name of a subclass
            //of Resource. That's an error!
            throw new NoResourceClassException(
                sprintf(
                    _('Die Klasse %1$s ist keine Spezialisierung der Ressourcen-Kernklasse!'),
                    $class_name
                )
            );
        }
    }

    /**
     * Sets the range fields (termin_id, metadate_id, course_id)
     * or the ResourceRequestAppointment objects related to this request
     * according to the range type and its range-IDs specified as parameters
     * for this method. The ResourceRequest object is not stored after
     * setting the fields / related objects.
     *
     * @param string $range_type The range type for this request. One of
     *     the following: 'date', 'cycle', 'course' or 'date-multiple'.
     *
     * @param array $range_ids An array of range-IDs to be set for the
     *     specified range type. This is mostly an array of size one
     *     since the fields termin_id, metadate_id and course_id only
     *     accept one ID. The range type 'date-multiple' accepts multiple
     *     IDs.
     *
     * @return void No return value.
     */
    public function setRangeFields($range_type = '', $range_ids = [])
    {
        if ($range_type === 'date') {
            $this->termin_id   = $range_ids[0];
            $this->metadate_id = '';
        } elseif ($range_type === 'cycle') {
            $this->termin_id   = '';
            $this->metadate_id = $range_ids[0];
        } elseif ($range_type === 'date-multiple') {
            $this->termin_id   = '';
            $this->metadate_id = '';
            $appointments      = [];
            foreach ($range_ids as $range_id) {
                $app                 = new ResourceRequestAppointment();
                $app->appointment_id = $range_id;
                $appointments[]      = $app;
            }
            $this->appointments = $appointments;
        } elseif ($range_type === 'course') {
            $this->termin_id   = '';
            $this->metadate_id = '';
            $this->course_id   = $range_ids[0];
        }
    }

    /**
     * Closes the requests and sends out notification mails.
     * If the request is closed and a resource has been booked,
     * it can be passed as parameter to be included in the notification mails.
     *
     * @param bool $notify_lecturers Whether to notify lecturers of a course
     *     (true) or not (false). Defaults to false. Note that this parameter
     *     is only useful in case the request is bound to a course, either
     *     directly or via a course date or a course cycle date.
     *
     * @param ResourceBooking $bookings The resource bookings that have been
     *     created from this request.
     * @return bool @TODO
     */
    public function closeRequest($notify_lecturers = false, $bookings = [])
    {
        if (
            $this->closed == self::STATE_CLOSED
            || $this->closed == self::STATE_DECLINED
        ) {
            //The request has already been closed.
            return true;
        }

        $this->closed = self::STATE_PENDING;
        if ($this->isDirty()) {
            $this->store();
        }

        //Now we send the confirmation mail to the requester:
        $this->sendCloseRequestMailToRequester($bookings);

        if ($notify_lecturers) {
            $this->sendCloseRequestMailToLecturers($bookings);
        }

        //Sending successful: The request is closed.
        $this->closed = self::STATE_CLOSED;
        if ($this->isDirty()) {
            return $this->store();
        }
        return true;
    }

    /**
     * Returns the resource requests whose time ranges overlap
     * with those of this resource request.
     *
     * @return ResourceRequest[] An array of ResourceRequest objects.
     */
    public function getOverlappingRequests()
    {
        if ($this->resource) {
            return self::findByResourceAndTimeRanges(
                $this->resource,
                $this->getTimeIntervals(true),
                self::STATE_OPEN,
                [$this->id]
            );
        }
        return [];
    }

    /**
     * Counts the resource requests whose time ranges overlap
     * with those of this resource request.
     *
     * @return int The amount of overlapping resource requests.
     */
    public function countOverlappingRequests()
    {
        if ($this->resource) {
            return self::countByResourceAndTimeRanges(
                $this->resource,
                $this->getTimeIntervals(true),
                self::STATE_OPEN,
                [$this->id]
            );
        }
        return 0;
    }

    /**
     * Returns the resource bookings whose time ranges overlap
     * with those of this resource request.
     *
     * @return ResourceBooking[] An array of ResourceBooking objects.
     */
    public function getOverlappingBookings()
    {
        if ($this->resource) {
            return ResourceBooking::findByResourceAndTimeRanges(
                $this->resource,
                $this->getTimeIntervals(true),
                [ResourceBooking::TYPE_NORMAL, ResourceBooking::TYPE_LOCK]
            );
        }
        return [];
    }

    /**
     * Counts the resource bookings whose time ranges overlap
     * with those of this resource request.
     *
     * @return int The amount of overlapping resource bookings.
     */
    public function countOverlappingBookings()
    {
        if ($this->resource) {
            return ResourceBooking::countByResourceAndTimeRanges(
                $this->resource,
                $this->getTimeIntervals(true),
                [ResourceBooking::TYPE_NORMAL, ResourceBooking::TYPE_LOCK]
            );
        }
        return 0;
    }

    /**
     * Returns the repetion interval if regular appointments are used
     * for this request.
     *
     * @return DateInterval|null In case regular appointments are used
     *     for this request a DateInterval is returned.
     *     Otherwise null is returned.
     */
    public function getRepetitionInterval()
    {
        if ($this->metadate_id) {
            //It is a set of regular appointments.
            //We just have to compute the time difference between the first
            //two appointments to get the interval.

            $first_date  = $this->cycle->dates[0];
            $second_date = $this->cycle->dates[1];

            if (!$first_date || !$second_date) {
                //Either only one date is in the set of regular appointments
                //or there is a database error. We cannot continue.
                return null;
            }

            $first_datetime = new DateTime();
            $first_datetime->setTimestamp($first_date->date);
            $second_datetime = new DateTime();
            $second_datetime->setTimestamp($second_date->date);

            return $first_datetime->diff($second_datetime);
        }

        return null;
    }

    public function getStartDate()
    {
        $start_date = new DateTime();
        if (count($this->appointments) > 0) {
            $start_date->setTimestamp($this->appointments->first()->appointment->date);
            return $start_date;
        }

        if ($this->termin_id) {
            $start_date->setTimestamp($this->date->date);
            return $start_date;
        }

        if (isset($this->cycle) && count($this->cycle->dates) > 0) {
            $first_date = $this->cycle->dates->first();
            if ($this->metadate_id && isset($first_date->date)) {
                $start_date->setTimestamp($first_date->date);
                return $start_date;
            }

            if ($this->course_id && isset($first_date->date)) {
                $start_date->setTimestamp($first_date->date);
                return $start_date;
            }
        }

        if ($this->begin) {
            $start_date->setTimestamp($this->begin);
            return $start_date;
        }

        return null;
    }

    public function getEndDate()
    {
        $end_date = new DateTime();
        if (count($this->appointments) > 0) {
            $end_date->setTimestamp($this->appointments->last()->appointment->end_time);
            return $end_date;
        }

        if ($this->termin_id) {
            $end_date->setTimestamp($this->date->end_time);
            return $end_date;
        }

        if ($this->metadate_id) {
            $date = $this->cycle->dates->last();
            if (!isset($date)) {
                return null;
            }

            $end_date->setTimestamp($this->cycle->dates->last()->end_time);
            return $end_date;
        }

        if ($this->course_id) {
            $date = $this->course->dates->last();
            if (!isset($date)) {
                return null;
            }

            $end_date->setTimestamp($this->course->dates->last()->end_time);
            return $end_date;
        }

        if ($this->end) {
            $end_date->setTimestamp($this->end);
            return $end_date;
        }

        return null;
    }

    public function getStartSemester()
    {
        $start_date = $this->getStartDate();
        if ($start_date instanceof DateTime) {
            return Semester::findByTimestamp($start_date->getTimestamp());
        }
        return null;
    }

    public function getEndSemester()
    {
        $end_date = $this->getEndDate();
        if ($end_date instanceof DateTime) {
            return Semester::findByTimestamp($end_date->getTimestamp());
        }
        return null;
    }

    public function getRepetitionEndDate()
    {
        $repetition_interval = $this->getRepetitionInterval();

        if (!$repetition_interval) {
            //There is no repetition.
            return null;
        }

        return $this->getEndDate();
    }

    /**
     * Retrieves the time intervals by looking at metadate objects
     * and other time interval sources and returns them grouped by metadate.
     * @param bool $with_preparation_time @TODO
     * @return mixed[][][] A three-dimensional array with
     *     the following structure:
     *     - The first dimension has the metadate-id as index. For single dates
     *       an empty string is used as index.
     *     - The second dimension contains two elements:
     *       - 'metadate' => The metadate object. This is only set, if the
     *                       request is for a metadate.
     *       - 'intervals' => The time intervals.
     *     - The third dimension contains a time interval
     *       in the following format:
     *       [
     *           'begin' => The begin timestamp
     *           'end' => The end timestamp
     *           'range' => The name of the range class that provides the range_id.
     *               This is usually the name of the SORM class.
     *           'range_id' => The ID of the single date or ResourceRequestAppointment.
     *       ]
     */
    public function getGroupedTimeIntervals($with_preparation_time = false, $with_past_intervals = true)
    {
        $now = time();
        if (count($this->appointments)) {
            $time_intervals = [
                '' => [
                    'metadate'  => null,
                    'intervals' => []
                ]
            ];
            foreach ($this->appointments as $appointment) {
                if (!$with_past_intervals && $appointment->appointment->end_time < $now) {
                    continue;
                }
                if ($with_preparation_time) {
                    $interval = [
                        'begin' => $appointment->appointment->date - $this->preparation_time,
                        'end'   => $appointment->appointment->end_time
                    ];
                } else {
                    $interval = [
                        'begin' => $appointment->appointment->date,
                        'end'   => $appointment->appointment->end_time
                    ];
                }

                $date = CourseDate::find($appointment->appointment_id);
                $interval['range']                 = 'CourseDate';
                $interval['range_id']              = $appointment->appointment_id;
                $interval['booked_room']           = $date->room_booking->resource_id;
                $interval['booking_id']            = $date->room_booking->id;
                $time_intervals['']['intervals'][] = $interval;
            }

            if (empty($time_intervals['']['intervals'])) {
                return [];
            } else {
                return $time_intervals;
            }
        } elseif ($this->termin_id) {
            if (!$with_past_intervals && $this->date->end_time < $now) {
                return [];
            }
            if ($with_preparation_time) {
                $interval = [
                    'begin' => $this->date->date - $this->preparation_time,
                    'end'   => $this->date->end_time
                ];
            } else {
                $interval = [
                    'begin' => $this->date->date,
                    'end'   => $this->date->end_time
                ];
            }

            $date = CourseDate::find($this->termin_id);
            $interval['range']       = 'CourseDate';
            $interval['range_id']    = $this->termin_id;
            $interval['booked_room'] = $date->room_booking->resource_id;
            $interval['booking_id']  = $date->room_booking->id;

            if (!empty($interval)) {
                return [
                    '' => [
                        'metadate'  => null,
                        'intervals' => [$interval]
                    ]
                ];
            } else {
                return [];
            }
        } elseif ($this->metadate_id) {
            $time_intervals = [
                $this->metadate_id => [
                    'metadate'  => $this->cycle,
                    'intervals' => []
                ]
            ];
            foreach ($this->cycle->dates as $date) {
                if (!$with_past_intervals && $date->end_time < $now) {
                    continue;
                }
                if ($with_preparation_time) {
                    $interval = [
                        'begin' => $date->date - $this->preparation_time,
                        'end'   => $date->end_time
                    ];
                } else {
                    $interval = [
                        'begin' => $date->date,
                        'end'   => $date->end_time
                    ];
                }
                $interval['range']                                 = 'CourseDate';
                $interval['range_id']                              = $date->id;
                $interval['booked_room']                           = $date->room_booking->resource_id;
                $interval['booking_id']                            = $date->room_booking->id;
                $time_intervals[$this->metadate_id]['intervals'][] = $interval;
            }
            return $time_intervals;
        } elseif ($this->course_id) {
            $time_intervals = [];
            if ($this->course->cycles) {
                foreach ($this->course->cycles as $cycle) {
                    $time_intervals[$cycle->id] = [
                        'metadate'  => $cycle,
                        'intervals' => []
                    ];
                    if ($cycle->dates) {
                        foreach ($cycle->dates as $date) {
                            if (!$with_past_intervals && $date->end_time < $now) {
                                continue;
                            }
                            if ($with_preparation_time) {
                                $interval = [
                                    'begin' => $date->date - $this->preparation_time,
                                    'end'   => $date->end_time
                                ];
                            } else {
                                $interval = [
                                    'begin' => $date->date,
                                    'end'   => $date->end_time
                                ];
                            }
                            $interval['range']                         = 'CourseDate';
                            $interval['range_id']                      = $date->id;
                            $interval['booked_room']                   = $date->room_booking->resource_id;
                            $interval['booking_id']                    = $date->room_booking->id;
                            $time_intervals[$cycle->id]['intervals'][] = $interval;
                        }
                    }
                }
            }
            if ($this->course->dates) {
                $time_intervals[''] = [
                    'metadate'  => null,
                    'intervals' => []
                ];
                foreach ($this->course->dates as $date) {
                    if (!$with_past_intervals && $date->end_time < $now) {
                        continue;
                    }
                    if ($date->cycle instanceof SeminarCycleDate) {
                        //Metadates are already handled above.
                        continue;
                    }
                    if ($with_preparation_time) {
                        $interval = [
                            'begin' => $date->date - $this->preparation_time,
                            'end'   => $date->end_time
                        ];
                    } else {
                        $interval = [
                            'begin' => $date->date,
                            'end'   => $date->end_time
                        ];
                    }
                    $interval['range']                 = 'CourseDate';
                    $interval['range_id']              = $date->id;
                    $interval['booked_room']           = $date->room_booking->resource_id;
                    $interval['booking_id']            = $date->room_booking->id;
                    $time_intervals['']['intervals'][] = $interval;
                }

                if (empty($time_intervals['']['intervals'])) {
                    unset($time_intervals['']);
                }
            }
            return $time_intervals;
        } elseif ($this->begin && $this->end) {
            if (!$with_past_intervals && $this->end < $now) {
                return [];
            }
            if ($with_preparation_time) {
                $interval = [
                    'begin' => $this->begin - $this->preparation_time,
                    'end'   => $this->end
                ];
            } else {
                $interval = [
                    'begin' => $this->begin,
                    'end'   => $this->end
                ];
            }
            $interval['range']    = 'User';
            $interval['range_id'] = $this->user_id;

            return [
                '' => [
                    'metadate'  => null,
                    'intervals' => [$interval]
                ]
            ];
        } else {
            return [];
        }
    }

    /**
     * Retrieves the time intervals for this request.
     *
     * @param bool $with_preparation_time Whether the preparation time
     *     of the request shall be prepended to the begin timestamp (true)
     *     or whether it should not be included at all (false).
     *     Defaults to false.
     *
     * @param bool $with_range Whether to include data of the Stud.IP range
     *     and its corresponding ID to the request (true) or not (false).
     *     Defaults to false.
     *
     * @param bool $with_past_intervals Whether to include past intervals (true)
     *     or only include intervals from the current time and the future (false).
     *     Defaults to true.
     *
     * @return string[][] A two-dimensional array of unix timestamps.
     *     The first dimension contains one entry for each date,
     *     the second dimension contains the start and end timestamp
     *     for the date.
     *     The second dimension uses the array keys 'begin' and 'end'
     *     for start and end date.
     *     If the @with_range parameter is set to true, the second array
     *     dimension also contains the key 'range' for specifying the
     *     range type and 'range_id' for specifying the ID of the
     *     range object.
     *     The range can be "CourseDate", "ResourceRequestAppointment"
     *     or "User". The last two can only be present for simple requests
     *     that are not bound to a course. The range "CourseDate"
     *     can only occur on course-bound requests.
     */
    public function getTimeIntervals($with_preparation_time = false, $with_range = false, $with_past_intervals = true)
    {
        $now = time();
        if (count($this->appointments)) {
            $time_intervals = [];
            foreach ($this->appointments as $appointment) {
                if (!$with_past_intervals && $appointment->appointment->end_time < $now) {
                    continue;
                }
                if ($with_preparation_time) {
                    $interval = [
                        'begin' => $appointment->appointment->date - $this->preparation_time,
                        'end'   => $appointment->appointment->end_time
                    ];
                } else {
                    $interval = [
                        'begin' => $appointment->appointment->date,
                        'end'   => $appointment->appointment->end_time
                    ];
                }
                if ($with_range) {
                    $date = CourseDate::find($appointment->appointment_id);

                    $interval['range']       = ResourceRequestAppointment::class;
                    $interval['range_id']    = $appointment->appointment_id;
                    $interval['booked_room'] = $date->room_booking->resource_id ?? null;
                    $interval['booking_id']  = $date->room_booking->id ?? null;

                }
                $time_intervals[] = $interval;
            }
            return $time_intervals;
        } elseif ($this->termin_id) {
            if (!$with_past_intervals && $this->date->end_time < $now) {
                return [];
            }
            if ($with_preparation_time) {
                $interval = [
                    'begin' => $this->date->date - $this->preparation_time,
                    'end'   => $this->date->end_time
                ];
            } else {
                $interval = [
                    'begin' => $this->date->date,
                    'end'   => $this->date->end_time
                ];
            }
            if ($with_range) {
                $interval['range']       = CourseDate::class;
                $interval['range_id']    = $this->termin_id;
                $interval['booked_room'] = $this->date->room_booking->resource_id ?? null;
                $interval['booking_id']  = $this->date->room_booking->id ?? null;
            }
            return [$interval];
        } elseif ($this->metadate_id) {
            $time_intervals = [];
            foreach ($this->cycle->dates as $date) {
                if (!$with_past_intervals && $date->end_time < $now) {
                    continue;
                }
                if ($with_preparation_time) {
                    $interval = [
                        'begin' => $date->date - $this->preparation_time,
                        'end'   => $date->end_time
                    ];
                } else {
                    $interval = [
                        'begin' => $date->date,
                        'end'   => $date->end_time
                    ];
                }
                if ($with_range) {
                    $interval['range']       = CourseDate::class;
                    $interval['range_id']    = $date->id;
                    $interval['booked_room'] = $date->room_booking->resource_id ?? null;
                    $interval['booking_id']  = $date->room_booking->id ?? null;
                }
                $time_intervals[] = $interval;
            }
            return $time_intervals;
        } elseif ($this->course_id) {
            $time_intervals = [];
            if ($this->course->dates) {
                foreach ($this->course->dates as $date) {
                    if (!$with_past_intervals && $date->end_time < $now) {
                        continue;
                    }
                    if ($with_preparation_time) {
                        $interval = [
                            'begin' => $date->date - $this->preparation_time,
                            'end'   => $date->end_time
                        ];
                    } else {
                        $interval = [
                            'begin' => $date->date,
                            'end'   => $date->end_time
                        ];
                    }
                    if ($with_range) {
                        $interval['range']       = CourseDate::class;
                        $interval['range_id']    = $date->id;
                        $interval['booked_room'] = $date->room_booking->resource_id ?? null;
                        $interval['booking_id']  = $date->room_booking->id ?? null;
                    }
                    $time_intervals[] = $interval;
                }
            }
            return $time_intervals;
        } elseif ($this->begin && $this->end) {
            if (!$with_past_intervals && $this->end < $now) {
                return [];
            }
            if ($with_preparation_time) {
                $interval = [
                    'begin' => $this->begin - $this->preparation_time,
                    'end'   => $this->end
                ];
            } else {
                $interval = [
                    'begin' => $this->begin,
                    'end'   => $this->end
                ];
            }
            if ($with_range) {
                $interval['range']    = 'User';
                $interval['range_id'] = $this->user_id;
            }
            return [$interval];
        } else {
            return [];
        }
    }


    /**
     * Returns a string representation of the time intervals for this request.
     */
    public function getTimeIntervalStrings()
    {
        $strings   = [];
        $intervals = $this->getTimeIntervals(false, true);
        foreach ($intervals as $interval) {
            $room = '';

            if ($interval['range'] === 'CourseDate') {
                $date = call_user_func([$interval['range'], 'find'], $interval['range_id']);
                if ($date->room_booking) {
                    $room_obj = Room::find($date->room_booking->resource_id);
                    if ($room_obj) {
                        $room = $room_obj->name;
                    }
                }
            }

            $same_day = date('Ymd', $interval['begin']) === date('Ymd', $interval['end']);
            if ($same_day) {
                $strings[] = strftime('%a. %x %R', $interval['begin'])
                    . ' - ' . strftime('%R', $interval['end'])
                    . ($room ? ', '. $room : '');
            } else {
                $strings[] = strftime('%a. %x %R', $interval['begin'])
                    . ' - ' . strftime('%a %x %R', $interval['end'])
                    . ($room ? ', '. $room : '');
            }

        }
        return $strings;
    }


    /**
     * Filters the time intervals for this request
     * by a specified time range.
     *
     * @see ResourceRequest::getTimeIntervals for the return format.
     */
    public function getTimeIntervalsInTimeRange(DateTime $begin, DateTime $end)
    {
        $all_time_intervals = $this->getTimeIntervals();

        $included_intervals = [];
        foreach ($all_time_intervals as $interval) {
            $interval_in_range = (
                (
                    $interval['begin'] >= $begin->getTimestamp()
                    &&
                    $interval['begin'] <= $end->getTimestamp()
                )
                ||
                (
                    $interval['end'] >= $begin->getTimestamp()
                    &&
                    $interval['end'] <= $end->getTimestamp()
                )
            );
            if ($interval_in_range) {
                $included_intervals[] = $interval;
            }
        }

        return $included_intervals;
    }


    /**
     * Returns a string representation of the ResourceRequest's type.
     */
    public function getType()
    {
        if (count($this->appointments)) {
            return 'appointments';
        } elseif ($this->termin_id) {
            return 'date';
        } elseif ($this->metadate_id) {
            return 'cycle';
        } elseif ($this->course_id) {
            return 'course';
        }
        return null;
    }

    /**
     * Returns a string representation of the status of the ResourceRequest.
     */
    public function getStatus()
    {
        switch ($this->closed) {
            case self::STATE_OPEN:
                return 'open';
            case self::STATE_PENDING:
                return 'pending';
            case self::STATE_CLOSED:
                return 'closed';
            case self::STATE_DECLINED:
                return 'declined';
            default:
                return '';
        }
    }


    /**
     * Returns a textual representation of the status of the ResourceRequest.
     */
    public function getStatusText()
    {
        if ($this->isNew()) {
            return _('Diese Anfrage wurde noch nicht gespeichert.');
        }
        if ($this->closed == self::STATE_OPEN) {
            return _('Die Anfrage wurde noch nicht bearbeitet.');
        } else if ($this->closed == self::STATE_DECLINED) {
            return _('Die Anfrage wurde bearbeitet und abgelehnt.');
        } else {
            return _('Die Anfrage wurde bearbeitet.');
        }
    }


    /**
     * Returns a textual representation of the dates for which the request
     * has been created.
     *
     * @param bool $as_array True, if an array with a string for each date
     *     (single or cycle date) shall be returned, false otherwise.
     *
     * @returns string|array Depending on the parameter $as_array, the text
     *     is returned as one string or as an array of strings for each date
     *     (single or cycle date).
     */
    public function getDateString($as_array = false, $with_past_intervals = true)
    {
        $now = time();
        $strings = [];
        $resource_name = '';
        if (count($this->appointments)) {
            $parts  = [];
            foreach ($this->appointments as $rra) {
                if (!$with_past_intervals && $rra->appointment->end_time < $now) {
                    continue;
                }
                if ($rra->appointment) {
                    $parts[] = $rra->appointment->getFullName('include-room');
                }
            }
            $strings[] = implode('; ', $parts);
        } elseif ($this->termin_id) {
            if ($this->date) {
                if ($with_past_intervals || $this->date->end_time >= $now) {
                    $strings[] = $this->date->getFullName('include-room');
                }
            }
        } elseif ($this->metadate_id) {
            if ($this->cycle) {
                $this->cycle->dates->filter(function($date) use($with_past_intervals, $now) {
                    return $with_past_intervals || $date->end_time >= $now;
                })->map(function($date) use(&$strings) {
                    $strings[] = $date->getFullName('include-room');
                });
            }
        } elseif ($this->course_id) {
            $course = new Seminar($this->course_id);
            $strings[] = $course->getDatesTemplate('dates/seminar_html_roomplanning',
                [
                    'shrink'    => false,
                    'show_room' => true,
                    'with_past_intervals' => $with_past_intervals
                ]
            );
        } elseif ($this->begin && $this->end) {
            $begin_date = date('Ymd', $this->begin);
            $end_date   = date('Ymd', $this->end);
            if($this->resource) {
                $resource_name = htmlReady($this->resource->getFullName());
            }
            if ($begin_date == $end_date) {
                $strings[] = strftime('%a., %x, %R', $this->begin) . ' - '
                           . strftime('%R', $this->end) . ' ' . $resource_name;
            } else {
                //Begin and end are on differnt dates
                $strings[] = strftime('%a., %x, %R', $this->begin) . ' - '
                    . strftime('%a., %x, %R', $this->end) . ' ' . $resource_name;
            }
        }

        if ($as_array) {
            return $strings;
        } else {
            return implode(';', $strings);
        }
    }


    /**
     * Returns a human-readable string describing the type of the request.
     *
     * @param bool $short If this parameter is set to true, only the
     *     type of the request is returned without any information about the
     *     appointments. Otherwise, appointment information like the
     *     date or the repetition are appended. Defaults to false.
     * @return string
     */
    public function getTypeString($short = false)
    {
        if (count($this->appointments) > 1) {
            if ($short) {
                return _('Einzeltermine');
            } else {
                return sprintf(_('Einzeltermine (%sx)'), count($this->appointments));
            }
        } elseif (count($this->appointments) === 1) {
            $date = $this->appointments[0]->appointment;
            if ($short || !$date) {
                return _('Einzeltermin');
            } else {
                return sprintf(_('Einzeltermin (%s)'), $date->getFullName());
            }
        } elseif ($this->date) {
            if ($short) {
                return _('Einzeltermin');
            } else {
                return sprintf(_('Einzeltermin (%s)'), $this->date->getFullName());
            }
        } elseif ($this->cycle) {
            if ($short) {
                return _('Regelmäßige Termine');
            } else {
                return sprintf(
                    _('Regelmäßige Termine (%s)'),
                    $this->cycle->toString('full')
                );
            }
        } elseif ($this->course) {
            if ($short) {
                return _('Alle Termine der Veranstaltung');
            } else {
                return sprintf(
                    _('Alle Termine der Veranstaltung (%sx)'),
                    count($this->course->dates)
                );
            }
        } else {
            return _('Einfache Anfrage');
        }
    }


    /**
     * Returns an array of date objects which are affected
     * by this ResourceRequest.
     */
    public function getAffectedDates()
    {
        $dates = [];
        switch ($this->getType()) {
            case 'date':
                $dates[] = $this->date;
                break;
            case 'cycle':
                $dates = $this->cycle->dates->getArrayCopy();
                break;
            case 'course':
                $dates = $this->course->dates->getArrayCopy();
                break;
        }
        return $dates;
    }


    /**
     * @param array $excluded_property_names
     * Returns all resource property definitions for all properties
     * which can be applied for this ResourceRequest by looking at the
     * Resource category. If no resource category ID is set for the request
     * an empty array is returned.
     */
    public function getAvailableProperties($excluded_property_names = [])
    {
        if (!$this->category_id) {
            //Without a category-ID we cannot find any property!
            return [];
        }
        if (count($excluded_property_names)) {
            return ResourcePropertyDefinition::findBySql(
                "INNER JOIN resource_category_properties
                USING (property_id)
                WHERE requestable = '1' AND category_id = :category_id
                AND name NOT IN ( :excluded_property_names )",
                [
                    'category_id'             => $this->category_id,
                    'excluded_property_names' => $excluded_property_names
                ]
            );
        } else {
            return ResourcePropertyDefinition::findBySql(
                "INNER JOIN resource_category_properties
                USING (property_id)
                WHERE requestable = '1' AND category_id = :category_id",
                [
                    'category_id' => $this->category_id
                ]
            );
        }
    }


    /**
     * Returns a "compressed" array of resource request properties.
     * @param array $excluded_property_names
     * @return array An associative array where the keys represent the
     *     property names and the values represent the property states.
     *     Note that the value can be an array in case of range properties.
     */
    public function getPropertyData($excluded_property_names = [])
    {
        $data = [];
        foreach ($this->properties as $property) {
            if ($property->definition->range_search) {
                //Assume that a minimum value is requested:
                $data[$property->name] = [$property->state];
            } else {
                $data[$property->name] = $property->state;
            }
        }
        return $data;
    }

    /**
     * @param $name
     * @return bool
     */
    public function propertyExists($name)
    {
        $db = DBManager::get();

        $exists_stmt = $db->prepare(
            "SELECT TRUE FROM resource_request_properties
            INNER JOIN resource_property_definitions rpd
                ON resource_request_properties.property_id = rpd.property_id
            WHERE resource_request_properties.request_id = :request_id
                AND rpd.name = :name");

        $exists_stmt->execute(
            [
                'request_id' => $this->id,
                'name'       => $name
            ]
        );

        $exists = $exists_stmt->fetchColumn(0);

        return (bool)$exists;
    }


    /**
     * @param $name
     * Returns the state of the property specified by $name.
     */
    public function getProperty($name)
    {
        if (!$this->propertyExists($name)) {
            //A property with the name $name does not exist for this
            //resource request object.
            //In that case we can only return null, since resource requests
            //store only those properties which are requested:

            return null;
        }

        $db = DBManager::get();

        $value_stmt = $db->prepare(
            "SELECT resource_request_properties.state FROM resource_request_properties
            INNER JOIN resource_property_definitions rpd
                ON resource_request_properties.property_id = rpd.property_id
            WHERE resource_request_properties.request_id = :request_id
                AND rpd.name = :name");

        $value_stmt->execute(
            [
                'request_id' => $this->id,
                'name'       => $name
            ]
        );

        $value = $value_stmt->fetchColumn(0);

        if (!$value) {
            return null;
        }

        return $value;
    }


    /**
     * @param $name
     * @return ResourceRequestProperty
     * @throws InvalidResourceCategoryException If this resource category
     *     doesn't match the category of the resource request object.
     * @throws ResourcePropertyException If the name of the
     *     resource request property is not defined for this resource category.
     */
    public function getPropertyObject($name)
    {
        if (!$this->propertyExists($name)) {
            //A property with the name $name does not exist for this
            //resource object. If it is a mandatory property
            //we can still try to create it:

            $property = $this->category->createDefinedResourceRequestProperty(
                $this,
                $name
            );

            $property->store();
            return $property;
        }

        return ResourceRequestProperty::findOneBySql(
            "INNER JOIN resource_property_definitions rpd
                ON resource_request_properties.property_id = rpd.property_id
            WHERE resource_request_properties.request_id = :request_id
                AND rpd.name = :name",
            [
                'request_id' => $this->id,
                'name'       => $name
            ]
        );
    }


    /**
     * @param string $name
     * @param string $state
     * @return bool True, if the property state could be set, false otherwise.
     */
    public function setProperty($name, $state = '')
    {
        if (!$this->propertyExists($name)) {
            //A property with the name $name does not exist for this
            //resource object. If it is a mandatory property
            //we can still try to create it:

            if ($this->category) {
                $property = $this->category->createDefinedResourceRequestProperty(
                    $this,
                    $name,
                    $state
                );
                return $property->store();
            }
            return false;
        }

        $property = $this->getPropertyObject($name);

        if ($property) {
            $property->state = $state;
            if ($property->isDirty()) {
                return $property->store();
            }
            return true;
        }
    }


    /**
     * Sets or unsets the properties for this resource request.
     *
     * @param array $property_list The properties which shall be set
     *     or unset. The array has the following structure:
     *     [
     *         property_name => property_value
     *     ]
     *
     * @param bool $accept_null_values True, if a value of null
     *     shall be used when setting the property.
     *     If $accept_null_values is set to false all properties
     *     with a value equal to null will be deleted.
     *
     * @return null
     */
    public function updateProperties($property_list = [], $accept_null_values = false)
    {
        //Delete all properties first then re-create them
        //from the $property_list array:
        $this->properties->delete();
        if (is_array($property_list)) {
            foreach ($property_list as $name => $state) {
                if ($state or $accept_null_values) {
                    //State is set or null values are allowed:
                    //create/update the property
                    $this->setProperty($name, $state);
                }
            }
        }
        $this->resetRelation('properties');
    }


    public function deletePropertyIfExists($name = '')
    {
        if (!$this->propertyExists($name)) {
            return true;
        } else {
            $property = $this->getPropertyObject($name);
            return $property->delete();
        }
    }


    public function getRangeName()
    {
        if ($this->getRangeType() === 'course') {
            $name = $this->getRangeObject()->getFullName();
            $name .= ' (' . implode(',', $this->getRangeObject()->getMembersWithStatus('dozent', true)->limit(3)->getValue('nachname')) . ')';
        } else {
            $range_object = $this->getRangeObject();
            if ($range_object instanceof User) {
                if (get_visibility_by_id($range_object->id)) {
                    $name = $range_object->getFullName();
                } else if ($this->user_id === $GLOBALS['user']->id) {
                    $name = $range_object->getFullName();
                } else {
                    $current_user = User::findCurrent();
                    if ($current_user instanceof User) {
                        //If the current user has at least autor permissions
                        //(which are required to see all requests), they can
                        //see the name of the requester.
                        if ($this->resource_id && ($this->resource instanceof Resource)
                            && $this->resource->userHasPermission($current_user, 'autor')) {
                            $name = $range_object->getFullName();
                        } else if (ResourceManager::userHasGlobalPermission($current_user, 'autor')) {
                            $name = $range_object->getFullName();
                        } else {
                            return '';
                        }
                    } else {
                        return '';
                    }
                }
            } else {
                $name = $range_object->getFullName();
            }
            if ($this->comment) {
                $name .= " \n" . $this->comment;
            }
        }
        return $name;
    }


    public function isSimpleRequest()
    {
        return !$this->course_id && !$this->metadate_id && !$this->termin_id;
    }


    public function getRangeId()
    {
        //Check if the request belongs to a course:
        if ($this->termin_id) {
            return $this->date->range_id;
        } elseif ($this->metadate_id) {
            return $this->cycle->seminar_id;
        } elseif ($this->course_id) {
            return $this->course_id;
        }

        //The request does not belong to a course and therefore
        //belongs to a user:
        return $this->user_id;
    }


    public function getRangeType()
    {
        if ($this->course_id || $this->termin_id || $this->metadate_id) {
            return 'course';
        }
        return 'user';
    }


    public function getRangeObject()
    {
        if ($this->course_id) {
            return $this->course;
        }
        if ($this->termin_id) {
            return $this->date->course;
        }
        if ($this->metadate_id) {
            return $this->cycle->course;
        }
        return $this->user;
    }


    /**
     * This method sends a notification mail to all room administrators
     * that informs them of this new request.
     */
    public function sendNewRequestMail()
    {
        //First we must get all users who have admin permissions in the
        //resource management system. Depending wheter a resource_id is set
        //for this resource request either all admins of a resource or
        //all admins of the resource management system must be informed.

        $now         = time();
        if ($this->resource_id) {
            //The resource-ID is set for this request:
            //Get all admins of the resource and the resource management system.
            $admin_users = User::findBySql(
                "user_id IN (
                    SELECT user_id FROM resource_permissions
                    WHERE (
                        resource_id = :resource_id
                        OR resource_id = 'global'
                    )
                    AND perms = 'admin'
                    UNION
                    SELECT user_id FROM resource_temporary_permissions
                    WHERE resource_id = :resource_id
                    AND perms = 'admin'
                    AND begin <= :now AND end >= :now
                )",
                [
                    'resource_id' => $this->resource_id,
                    'now'         => $now
                ]
            );
        } else {
            //Get all admins of the resource management system.
            $admin_users = User::findBySql(
                "user_id IN (
                    SELECT user_id FROM resource_permissions
                    WHERE resource_id = 'global'
                    AND perms = 'admin'
                    UNION
                    SELECT user_id FROM resource_temporary_permissions
                    WHERE resource_id = 'global'
                    AND perms = 'admin'
                    AND begin <= :now AND end >= :now
                    GROUP BY user_id
                )",
                [
                    'now' => $now
                ]
            );
        }

        if (!$admin_users) {
            return;
        }

        $factory = new Flexi\Factory(
            $GLOBALS['STUDIP_BASE_PATH'] . '/locale/'
        );

        foreach ($admin_users as $user) {
            $user_lang_path = getUserLanguagePath($user->id);

            $template = $factory->open(
                $user_lang_path . '/LC_MAILS/new_resource_request.php'
            );
            $template->set_attribute('request', $this);

            if ($this->resource instanceof Resource) {
                $resource = $this->resource->getDerivedClassInstance();
                if ($resource instanceof Room) {
                    $template->set_attribute('requested_room', $resource->name);
                } else {
                    $template->set_attribute('requested_resource', $resource->name);
                }
            }

            $mail_text = $template->render();

            setLocaleEnv($user->preferred_language);

            if ($this->resource) {
                $resource = $this->resource->getDerivedClassInstance();
                $template->set_attribute('derived_resource', $resource);
                $mail_title = sprintf(
                    _('%1$s: Neue Anfrage in der Raumverwaltung'),
                    $resource->getFullName()
                );
            } else {
                $mail_title = sprintf(
                    _('Neue Anfrage in der Raumverwaltung')
                );
            }

            Message::send(
                User::findCurrent()->id,
                $user->username,
                $mail_title,
                $mail_text
            );

            restoreLanguage();
        }
    }


    /**
     * @param array $bookings
     * This method sends a mail to inform the requester that
     * the request has been closed.
     */
    public function sendCloseRequestMailToRequester($bookings = [])
    {
        $factory = new Flexi\Factory(
            $GLOBALS['STUDIP_BASE_PATH'] . '/locale/'
        );

        $requester_lang      = $this->user->preferred_language;
        $requester_lang_path = getUserLanguagePath($this->user->id);
        setLocaleEnv($requester_lang);

        $template = $factory->open(
            $requester_lang_path . '/LC_MAILS/close_resource_request.php'
        );
        $template->set_attribute('request', $this);
        if ($this->course) {
            $lecturers      = CourseMember::findByCourseAndStatus(
                $this->course->id,
                'dozent'
            );
            $lecturer_names = [];
            foreach ($lecturers as $lecturer) {
                if ($lecturer->user instanceof User) {
                    $lecturer_names[] = $lecturer->user->getFullName();
                }
            }

            $lecturer_names = implode(', ', $lecturer_names);
            $template->set_attribute('lecturer_names', $lecturer_names);
        }
        if (is_array($bookings)) {
            $booked_rooms          = [];
            $booked_time_intervals = [];
            $metadates             = [];
            $single_dates          = [];
            foreach ($bookings as $booking) {
                if (!($booking instanceof ResourceBooking)) {
                    continue;
                }
                $booked_rooms[] = $booking->resource->name;
                if ($booking->assigned_course_date instanceof CourseDate) {
                    $single_date = $booking->assigned_course_date;
                    $metadate    = $single_date->cycle;
                    if ($metadate instanceof SeminarCycleDate) {
                        $metadates[$metadate->id] = $metadate;
                    } else {
                        $single_dates[$single_date->id] = $single_date;
                    }
                } else {
                    $time_intervals = $booking->getTimeIntervals();
                    foreach ($time_intervals as $time_interval) {
                        $booked_time_intervals[] = $time_interval->__toString();
                    }
                }
            }
            $booked_rooms = array_unique($booked_rooms);
            sort($booked_rooms);
            $template->set_attribute('booked_rooms', implode(', ', $booked_rooms));
            $template->set_attribute('metadates', $metadates);
            $template->set_attribute('single_dates', $single_dates);
            $template->set_attribute('booked_time_intervals', $booked_time_intervals);
        }

        $mail_title = _('Ihre Anfrage wurde bearbeitet!');
        $mail_text  = $template->render();

        Message::send(
            User::findCurrent()->id,
            $this->user->username,
            $mail_title,
            $mail_text
        );

        restoreLanguage();
    }


    /**
     * @param array $bookings
     * This method sends mails to the lecurers of the course (if any)
     * where this request has been assigned to. The sent mail informs them
     * about the closing of the request.
     */
    public function sendCloseRequestMailToLecturers($bookings = [])
    {
        //Notify each lecturer of the course:
        if ($this->course) {
            $lecturers = CourseMember::findByCourseAndStatus(
                $this->course->id,
                'dozent'
            );

            if ($lecturers) {
                $factory = new Flexi\Factory(
                    $GLOBALS['STUDIP_BASE_PATH'] . '/locale/'
                );

                $lecturer_names = [];
                foreach ($lecturers as $lecturer) {
                    if ($lecturer->user instanceof User) {
                        $lecturer_names[] = $lecturer->user->getFullName();
                    }
                }
                $lecturer_names = implode(', ', $lecturer_names);

                $booked_rooms          = [];
                $booked_time_intervals = [];
                $metadates             = [];
                $single_dates          = [];
                if (is_array($bookings)) {
                    foreach ($bookings as $booking) {
                        if (!($booking instanceof ResourceBooking)) {
                            continue;
                        }
                        $booked_rooms[] = $booking->resource->name;
                        if ($booking->assigned_course_date instanceof CourseDate) {
                            $single_date = $booking->assigned_course_date;
                            $metadate    = $single_date->cycle;
                            if ($metadate instanceof SeminarCycleDate) {
                                $metadates[$metadate->id] = $metadate;
                            } else {
                                $single_dates[$single_date->id] = $single_date;
                            }
                        } else {
                            $time_intervals = $booking->getTimeIntervals();
                            foreach ($time_intervals as $time_interval) {
                                $booked_time_intervals[] = $time_interval->__toString();
                            }
                        }
                    }
                }
                $booked_rooms = array_unique($booked_rooms);
                sort($booked_rooms);
                $booked_rooms = implode(', ', $booked_rooms);

                foreach ($lecturers as $lecturer) {
                    $lec_lang      = $lecturer->user->preferred_language;
                    $lec_lang_path = getUserLanguagePath($lecturer->user->id);

                    setLocaleEnv($lec_lang);

                    $template = $factory->open(
                        $lec_lang_path . '/LC_MAILS/close_resource_request.php'
                    );
                    $template->set_attribute('request', $this);
                    $template->set_attribute('lecturer_names', $lecturer_names);
                    $template->set_attribute('booked_rooms', $booked_rooms);
                    $template->set_attribute('metadates', $metadates);
                    $template->set_attribute('single_dates', $single_dates);
                    $template->set_attribute('booked_time_intervals', $booked_time_intervals);

                    $mail_title = _('Bearbeitung einer Anfrage!');
                    $mail_text  = $template->render();

                    Message::send(
                        User::findCurrent()->id,
                        $lecturer->user->username,
                        $mail_title,
                        $mail_text
                    );

                    restoreLanguage();
                }
            }
        }
    }


    /**
     * This method sends a mail to inform the requester
     * about the denial of the request.
     */
    public function sendRequestDeniedMail()
    {
        //Get the user who made the request:
        $user = $this->user;
        if (!($user instanceof User)) {
            //No mail to send.
            return;
        }

        //Load the mail template:
        $factory = new Flexi\Factory(
            $GLOBALS['STUDIP_BASE_PATH'] . '/locale/'
        );
        $user_lang_path = getUserLanguagePath($user->id);
        $template       = $factory->open(
            $user_lang_path . '/LC_MAILS/request_denied_mail.inc.php'
        );

        $range_object = $this->getRangeObject();
        $mail_title = _('Raumanfrage wurde abgelehnt');
        if($range_object instanceof Course) {
            $mail_title .= ': ' . $range_object->getFullName();
        }
        $mail_text  = $template->render(
            [
                'request' => $this,
                'range_object' => $range_object
            ]
        );

        //Send the mail:
        Message::send(
            User::findCurrent()->id,
            $user->username,
            $mail_title,
            $mail_text
        );
    }


    public function isReadOnlyForUser(User $user)
    {
        $resource = $this->resource;
        if (!$resource) {
            //We cannot continue with the permission check.
            return false;
        }
        $resource = $resource->getDerivedClassInstance();

        return !$resource->userHasPermission($user, 'autor')
            && ($this->user_id != $user->id);
    }

    protected function convertToEventData(array $time_intervals, User $user)
    {
        $booking_plan_request_bg     =
            ColourValue::find('Resources.BookingPlan.Request.Bg');
        $booking_plan_request_fg     =
            ColourValue::find('Resources.BookingPlan.Request.Fg');
        $booking_plan_preparation_bg =
            ColourValue::find('Resources.BookingPlan.PreparationTime.Bg');
        $booking_plan_preparation_fg =
            ColourValue::find('Resources.BookingPlan.PreparationTime.Fg');

        $user_is_resource_autor = false;
        if ($this->resource_id && ($this->resource instanceof Resource)) {
            $user_is_resource_autor = $this->resource->userHasPermission(
                $user,
                'autor'
            );
        }
        $request_is_editable =
            $user_is_resource_autor || ($user->id == $this->user_id);

        $request_api_urls  = [];
        $request_view_urls = [];

        if ($request_is_editable) {
            $request_api_urls = [
                'resize' => URLHelper::getURL(
                    'api.php/resources/request/'
                    . $this->id . '/move',
                    [
                        'quiet' => '1'
                    ]
                ),
                'move'   => URLHelper::getURL(
                    'api.php/resources/request/'
                    . $this->id . '/move',
                    [
                        'quiet' => '1'
                    ]
                )
            ];

            $request_view_urls = [
                'edit' => URLHelper::getURL(
                    'dispatch.php/resources/room_request/edit/'
                    . $this->id
                )
            ];
            if ($this->resource_id && ($this->resource instanceof Resource)) {
                if ($this->resource->userHasBookingRights($user)) {
                    $request_view_urls['edit'] = URLHelper::getURL(
                        'dispatch.php/resources/room_request/resolve/'
                        . $this->id
                    );
                }
            }
        }

        $events = [];

        foreach ($time_intervals as $interval) {
            $real_begin = $interval['begin'];
            if ($this->preparation_time) {
                $real_begin += (int)$this->preparation_time;
                $begin      = new DateTime();
                $begin->setTimestamp($interval['begin']);
                $end = new DateTime();
                $end->setTimestamp($real_begin);
                $events[] = new Studip\Calendar\EventData(
                    $begin,
                    $end,
                    _('Rüstzeit'),
                    ['preparation-time'],
                    $booking_plan_preparation_fg->__toString(),
                    $booking_plan_preparation_bg->__toString(),
                    $request_is_editable,
                    '',
                    '',
                    'ResourceRequest',
                    $this->id,
                    'Resource',
                    $this->resource_id,
                    $request_view_urls,
                    $request_api_urls
                );
            }

            $begin = new DateTime();
            $begin->setTimestamp($real_begin);
            $end = new DateTime();
            $end->setTimestamp($interval['end']);

            $events[] = new Studip\Calendar\EventData(
                $begin,
                $end,
                $this->getRangeName(),
                ['resource-request'],
                $booking_plan_request_fg->__toString(),
                $booking_plan_request_bg->__toString(),
                $request_is_editable,
                'ResourceRequest',
                $this->id,
                'Resource',
                $this->resource_id,
                'Resource',
                $this->resource_id,
                $request_view_urls,
                $request_api_urls
            );
        }

        return $events;
    }


    public function getAllEventData()
    {
        return $this->convertToEventData(
            $this->getTimeIntervals(true),
            User::findCurrent()
        );
    }


    public function getEventDataForTimeRange(DateTime $begin, DateTime $end)
    {
        $intervals      = $this->getTimeIntervals(true);
        $time_intervals = [];

        $begin_timestamp = $begin->getTimestamp();
        $end_timestamp   = $end->getTimestamp();

        foreach ($intervals as $interval) {
            if ((($interval['begin'] >= $begin_timestamp)
                    && ($interval['begin'] <= $end_timestamp)) ||
                (($interval['end'] >= $begin_timestamp)
                    && ($interval['end'] <= $end_timestamp)) ||
                (($interval['begin'] < $begin_timestamp)
                    && ($interval['end'] > $end_timestamp))
            ) {
                $time_intervals[] = $interval;
            }
        }

        return $this->convertToEventData($time_intervals, User::findCurrent());
    }


    public function getFilteredEventData(
        $user_id = null,
        $range_id = null,
        $range_type = null,
        $begin = null,
        $end = null
    )
    {
        $intervals      = $this->getTimeIntervals(true);
        $time_intervals = [];

        if ($begin && $end) {
            $begin_timestamp = $begin;
            $end_timestamp   = $end;
            if ($begin instanceof DateTime) {
                $begin_timestamp = $begin->getTimestamp();
            }
            if ($end instanceof DateTime) {
                $end_timestamp = $end->getTimestamp();
            }

            foreach ($intervals as $interval) {
                if ((($interval['begin'] >= $begin_timestamp)
                        && ($interval['begin'] <= $end_timestamp)) ||
                    (($interval['end'] >= $begin_timestamp)
                        && ($interval['end'] <= $end_timestamp)) ||
                    (($interval['begin'] < $begin_timestamp)
                        && ($interval['end'] > $end_timestamp))
                ) {
                    $time_intervals[] = $interval;
                }
            }
        } else {
            $time_intervals = $intervals;
        }

        if ($user_id) {
            $user = User::find($user_id);
        } else {
            $user = User::findCurrent();
        }

        return $this->convertToEventData($time_intervals, $user);
    }

    public function getPriority()
    {

        $result = $this->getTimeIntervals();
        if (count($result) === 0) {
            return null;
        }
        $first = $result[0];
        return round(($first['begin'] - time()) / 86400);
    }

    public function getLoggingInfoText()
    {
        $props = '';
        foreach ($this->getPropertyData() as $name => $state) {
            $props .= $name . '=' . $state . ' ';
        }
        $info['Anfrage'] = $this->getType();
        $info['Status'] = $this->getStatus();
        if ($this->category) {
            $info['Raumtyp'] = $this->category->name;
        }
        if ($this->termin_id) {
            $info['Termin'] = $this->termin_id;
        }
        if ($this->metadate_id) {
            $info['Metadate'] = $this->metadate_id;
        }
        if ($props) {
            $info['Eigenschaften'] = $props;
        }
        if ($this->comment) {
            $info['Kommentar'] = $this->comment;
        }
        $txt = '';
        foreach ($info as $n => $m) {
            $txt .= $n . ': ' . $m . ', ';
        }
        return trim($txt, ' ,');
    }
}