summaryrefslogtreecommitdiffstats
path: root/comphelper/source/misc/backupfilehelper.cxx
blob: e9b173a47369707a73e1cd1fe8f27cf218cbcf6b (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
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <sal/config.h>
#include <rtl/ustring.hxx>
#include <rtl/bootstrap.hxx>
#include <sal/log.hxx>
#include <osl/file.hxx>
#include <comphelper/backupfilehelper.hxx>
#include <comphelper/DirectoryHelper.hxx>
#include <rtl/crc.h>
#include <algorithm>
#include <deque>
#include <memory>
#include <string_view>
#include <utility>
#include <vector>
#include <zlib.h>

#include <comphelper/processfactory.hxx>
#include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
#include <com/sun/star/ucb/CommandAbortedException.hpp>
#include <com/sun/star/ucb/CommandFailedException.hpp>
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/deployment/DeploymentException.hpp>
#include <com/sun/star/deployment/ExtensionManager.hpp>
#include <com/sun/star/xml/dom/XDocumentBuilder.hpp>
#include <com/sun/star/xml/dom/DocumentBuilder.hpp>
#include <com/sun/star/xml/dom/XElement.hpp>
#include <com/sun/star/xml/dom/XNodeList.hpp>
#include <com/sun/star/xml/dom/XText.hpp>
#include <com/sun/star/xml/sax/XSAXSerializable.hpp>
#include <com/sun/star/xml/sax/Writer.hpp>
#include <com/sun/star/xml/sax/XWriter.hpp>
#include <com/sun/star/io/XStream.hpp>
#include <com/sun/star/io/TempFile.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <cppuhelper/exc_hlp.hxx>

using namespace comphelper;
using namespace css;
using namespace css::xml::dom;

const sal_uInt32 BACKUP_FILE_HELPER_BLOCK_SIZE = 16384;

namespace
{
    typedef std::shared_ptr< osl::File > FileSharedPtr;

    sal_uInt32 createCrc32(FileSharedPtr const & rCandidate, sal_uInt32 nOffset)
    {
        sal_uInt32 nCrc32(0);

        if (rCandidate && osl::File::E_None == rCandidate->open(osl_File_OpenFlag_Read))
        {
            sal_uInt8 aArray[BACKUP_FILE_HELPER_BLOCK_SIZE];
            sal_uInt64 nBytesTransfer(0);
            sal_uInt64 nSize(0);

            rCandidate->getSize(nSize);

            // set offset in source file - should be zero due to crc32 should
            // only be needed to be created for new entries, gets loaded with old
            // ones
            if (osl::File::E_None == rCandidate->setPos(osl_Pos_Absolut, sal_Int64(nOffset)))
            {
                while (nSize != 0)
                {
                    const sal_uInt64 nToTransfer(std::min(nSize, sal_uInt64(BACKUP_FILE_HELPER_BLOCK_SIZE)));

                    if (osl::File::E_None == rCandidate->read(static_cast<void*>(aArray), nToTransfer, nBytesTransfer) && nBytesTransfer == nToTransfer)
                    {
                        // add to crc and reduce size
                        nCrc32 = rtl_crc32(nCrc32, static_cast<void*>(aArray), static_cast<sal_uInt32>(nBytesTransfer));
                        nSize -= nToTransfer;
                    }
                    else
                    {
                        // error - reset to zero again
                        nSize = nCrc32 = 0;
                    }
                }
            }

            rCandidate->close();
        }

        return nCrc32;
    }

    bool read_sal_uInt32(FileSharedPtr const & rFile, sal_uInt32& rTarget)
    {
        sal_uInt8 aArray[4];
        sal_uInt64 nBaseRead(0);

        // read rTarget
        if (osl::File::E_None == rFile->read(static_cast<void*>(aArray), 4, nBaseRead) && 4 == nBaseRead)
        {
            rTarget = (sal_uInt32(aArray[0]) << 24) + (sal_uInt32(aArray[1]) << 16) + (sal_uInt32(aArray[2]) << 8) + sal_uInt32(aArray[3]);
            return true;
        }

        return false;
    }

    bool write_sal_uInt32(oslFileHandle& rHandle, sal_uInt32 nSource)
    {
        sal_uInt8 aArray[4];
        sal_uInt64 nBaseWritten(0);

        // write nSource
        aArray[0] = sal_uInt8((nSource & 0xff000000) >> 24);
        aArray[1] = sal_uInt8((nSource & 0x00ff0000) >> 16);
        aArray[2] = sal_uInt8((nSource & 0x0000ff00) >> 8);
        aArray[3] = sal_uInt8(nSource & 0x000000ff);

        return osl_File_E_None == osl_writeFile(rHandle, static_cast<const void*>(aArray), 4, &nBaseWritten) && 4 == nBaseWritten;
    }

    bool read_OString(FileSharedPtr const & rFile, OString& rTarget)
    {
        sal_uInt32 nLength(0);

        if (!read_sal_uInt32(rFile, nLength))
        {
            return false;
        }

        sal_uInt64 nPos;
        if (osl::File::E_None != rFile->getPos(nPos))
            return false;

        sal_uInt64 nSize;
        if (osl::File::E_None != rFile->getSize(nSize))
            return false;

        const auto nRemainingSize = nSize - nPos;
        if (nLength > nRemainingSize)
            return false;

        std::vector<char> aTarget(nLength);
        sal_uInt64 nBaseRead(0);

        // read rTarget
        if (osl::File::E_None == rFile->read(static_cast<void*>(aTarget.data()), nLength, nBaseRead) && nLength == nBaseRead)
        {
            rTarget = OString(aTarget.data(), static_cast<sal_Int32>(nBaseRead));
            return true;
        }

        return false;
    }

    bool write_OString(oslFileHandle& rHandle, const OString& rSource)
    {
        const sal_uInt32 nLength(rSource.getLength());

        if (!write_sal_uInt32(rHandle, nLength))
        {
            return false;
        }

        sal_uInt64 nBaseWritten(0);

        return osl_File_E_None == osl_writeFile(rHandle, static_cast<const void*>(rSource.getStr()), nLength, &nBaseWritten) && nLength == nBaseWritten;
    }

    OUString createFileURL(
        std::u16string_view rURL, std::u16string_view rName, std::u16string_view rExt)
    {
        OUString aRetval;

        if (!rURL.empty() && !rName.empty())
        {
            aRetval = OUString::Concat(rURL) + "/" + rName;

            if (!rExt.empty())
            {
                aRetval += OUString::Concat(".") + rExt;
            }
        }

        return aRetval;
    }

    OUString createPackURL(std::u16string_view rURL, std::u16string_view rName)
    {
        OUString aRetval;

        if (!rURL.empty() && !rName.empty())
        {
            aRetval = OUString::Concat(rURL) + "/" + rName + ".pack";
        }

        return aRetval;
    }
}

namespace
{
    enum PackageRepository { USER, SHARED, BUNDLED };

    class ExtensionInfoEntry
    {
    private:
        OString             maName;         // extension name
        PackageRepository   maRepository;   // user|shared|bundled
        bool                mbEnabled;      // state

    public:
        ExtensionInfoEntry()
        :   maRepository(USER),
            mbEnabled(false)
        {
        }

        ExtensionInfoEntry(OString aName, bool bEnabled)
        :   maName(std::move(aName)),
            maRepository(USER),
            mbEnabled(bEnabled)
        {
        }

        ExtensionInfoEntry(const uno::Reference< deployment::XPackage >& rxPackage)
        :   maName(OUStringToOString(rxPackage->getName(), RTL_TEXTENCODING_ASCII_US)),
            maRepository(USER),
            mbEnabled(false)
        {
            // check maRepository
            const OString aRepName(OUStringToOString(rxPackage->getRepositoryName(), RTL_TEXTENCODING_ASCII_US));

            if (aRepName == "shared")
            {
                maRepository = SHARED;
            }
            else if (aRepName == "bundled")
            {
                maRepository = BUNDLED;
            }

            // check mbEnabled
            const beans::Optional< beans::Ambiguous< sal_Bool > > option(
                rxPackage->isRegistered(uno::Reference< task::XAbortChannel >(),
                uno::Reference< ucb::XCommandEnvironment >()));

            if (option.IsPresent)
            {
                ::beans::Ambiguous< sal_Bool > const& reg = option.Value;

                if (!reg.IsAmbiguous)
                {
                    mbEnabled = reg.Value;
                }
            }
        }

        bool isSameExtension(const ExtensionInfoEntry& rComp) const
        {
            return (maRepository == rComp.maRepository && maName == rComp.maName);
        }

        bool operator<(const ExtensionInfoEntry& rComp) const
        {
            if (maRepository == rComp.maRepository)
            {
                if (maName == rComp.maName)
                {
                    return mbEnabled < rComp.mbEnabled;
                }
                else
                {
                    return 0 > maName.compareTo(rComp.maName);
                }
            }
            else
            {
                return maRepository < rComp.maRepository;
            }
        }

        bool read_entry(FileSharedPtr const & rFile)
        {
            // read maName
            if (!read_OString(rFile, maName))
            {
                return false;
            }

            // read maRepository
            sal_uInt32 nState(0);

            if (read_sal_uInt32(rFile, nState))
            {
                maRepository = static_cast< PackageRepository >(nState);
            }
            else
            {
                return false;
            }

            // read mbEnabled
            if (read_sal_uInt32(rFile, nState))
            {
                mbEnabled = static_cast< bool >(nState);
            }
            else
            {
                return false;
            }

            return true;
        }

        bool write_entry(oslFileHandle& rHandle) const
        {
            // write maName;
            if (!write_OString(rHandle, maName))
            {
                return false;
            }

            // write maRepository
            sal_uInt32 nState(maRepository);

            if (!write_sal_uInt32(rHandle, nState))
            {
                return false;
            }

            // write mbEnabled
            nState = static_cast< sal_uInt32 >(mbEnabled);

            return write_sal_uInt32(rHandle, nState);
        }

        const OString& getName() const
        {
            return maName;
        }

        bool isEnabled() const
        {
            return mbEnabled;
        }
    };

    typedef std::vector< ExtensionInfoEntry > ExtensionInfoEntryVector;

    constexpr OUStringLiteral gaRegPath { u"/registry/com.sun.star.comp.deployment.bundle.PackageRegistryBackend/backenddb.xml" };

    class ExtensionInfo
    {
    private:
        ExtensionInfoEntryVector    maEntries;

    public:
        ExtensionInfo()
        {
        }

        const ExtensionInfoEntryVector& getExtensionInfoEntryVector() const
        {
            return maEntries;
        }

        void reset()
        {
            // clear all data
            maEntries.clear();
        }

        void createUsingXExtensionManager()
        {
            // clear all data
            reset();

            // create content from current extension configuration
            uno::Sequence< uno::Sequence< uno::Reference< deployment::XPackage > > > xAllPackages;
            uno::Reference< uno::XComponentContext > xContext = ::comphelper::getProcessComponentContext();
            uno::Reference< deployment::XExtensionManager > m_xExtensionManager = deployment::ExtensionManager::get(xContext);

            try
            {
                xAllPackages = m_xExtensionManager->getAllExtensions(uno::Reference< task::XAbortChannel >(),
                    uno::Reference< ucb::XCommandEnvironment >());
            }
            catch (const deployment::DeploymentException &)
            {
                return;
            }
            catch (const ucb::CommandFailedException &)
            {
                return;
            }
            catch (const ucb::CommandAbortedException &)
            {
                return;
            }
            catch (const lang::IllegalArgumentException & e)
            {
                css::uno::Any anyEx = cppu::getCaughtException();
                throw css::lang::WrappedTargetRuntimeException( e.Message,
                                e.Context, anyEx );
            }

            for (const uno::Sequence< uno::Reference< deployment::XPackage > > & xPackageList : std::as_const(xAllPackages))
            {
                for (const uno::Reference< deployment::XPackage > & xPackage : xPackageList)
                {
                    if (xPackage.is())
                    {
                        maEntries.emplace_back(xPackage);
                    }
                }
            }

            if (!maEntries.empty())
            {
                // sort the list
                std::sort(maEntries.begin(), maEntries.end());
            }
        }

    private:
        void visitNodesXMLRead(const uno::Reference< xml::dom::XElement >& rElement)
        {
            if (!rElement.is())
                return;

            const OUString aTagName(rElement->getTagName());

            if (aTagName == "extension")
            {
                OUString aAttrUrl(rElement->getAttribute("url"));
                const OUString aAttrRevoked(rElement->getAttribute("revoked"));

                if (!aAttrUrl.isEmpty())
                {
                    const sal_Int32 nIndex(aAttrUrl.lastIndexOf('/'));

                    if (nIndex > 0 && aAttrUrl.getLength() > nIndex + 1)
                    {
                        aAttrUrl = aAttrUrl.copy(nIndex + 1);
                    }

                    const bool bEnabled(aAttrRevoked.isEmpty() || !aAttrRevoked.toBoolean());
                    maEntries.emplace_back(
                            OUStringToOString(aAttrUrl, RTL_TEXTENCODING_ASCII_US),
                            bEnabled);
                }
            }
            else
            {
                uno::Reference< xml::dom::XNodeList > aList = rElement->getChildNodes();

                if (aList.is())
                {
                    const sal_Int32 nLength(aList->getLength());

                    for (sal_Int32 a(0); a < nLength; a++)
                    {
                        const uno::Reference< xml::dom::XElement > aChild(aList->item(a), uno::UNO_QUERY);

                        if (aChild.is())
                        {
                            visitNodesXMLRead(aChild);
                        }
                    }
                }
            }
        }

    public:
        void createUserExtensionRegistryEntriesFromXML(std::u16string_view rUserConfigWorkURL)
        {
            const OUString aPath(
                OUString::Concat(rUserConfigWorkURL) + "/uno_packages/cache" + gaRegPath);
            createExtensionRegistryEntriesFromXML(aPath);
        }

        void createSharedExtensionRegistryEntriesFromXML(std::u16string_view rUserConfigWorkURL)
        {
            const OUString aPath(
                OUString::Concat(rUserConfigWorkURL) + "/extensions/shared" + gaRegPath);
            createExtensionRegistryEntriesFromXML(aPath);
        }

        void createBundledExtensionRegistryEntriesFromXML(std::u16string_view rUserConfigWorkURL)
        {
            const OUString aPath(
                OUString::Concat(rUserConfigWorkURL) + "/extensions/bundled" + gaRegPath);
            createExtensionRegistryEntriesFromXML(aPath);
        }


        void createExtensionRegistryEntriesFromXML(const OUString& aPath)
        {
            if (DirectoryHelper::fileExists(aPath))
            {
                uno::Reference< uno::XComponentContext > xContext = ::comphelper::getProcessComponentContext();
                uno::Reference< xml::dom::XDocumentBuilder > xBuilder(xml::dom::DocumentBuilder::create(xContext));
                uno::Reference< xml::dom::XDocument > aDocument = xBuilder->parseURI(aPath);

                if (aDocument.is())
                {
                    visitNodesXMLRead(aDocument->getDocumentElement());
                }
            }

            if (!maEntries.empty())
            {
                // sort the list
                std::sort(maEntries.begin(), maEntries.end());
            }
        }

    private:
        static bool visitNodesXMLChange(
            const OUString& rTagToSearch,
            const uno::Reference< xml::dom::XElement >& rElement,
            const ExtensionInfoEntryVector& rToBeEnabled,
            const ExtensionInfoEntryVector& rToBeDisabled)
        {
            bool bChanged(false);

            if (rElement.is())
            {
                const OUString aTagName(rElement->getTagName());

                if (aTagName == rTagToSearch)
                {
                    const OString aAttrUrl(OUStringToOString(rElement->getAttribute("url"), RTL_TEXTENCODING_ASCII_US));
                    const OUString aAttrRevoked(rElement->getAttribute("revoked"));
                    const bool bEnabled(aAttrRevoked.isEmpty() || !aAttrRevoked.toBoolean());

                    if (!aAttrUrl.isEmpty())
                    {
                        for (const auto& enable : rToBeEnabled)
                        {
                            if (-1 != aAttrUrl.indexOf(enable.getName()))
                            {
                                if (!bEnabled)
                                {
                                    // needs to be enabled
                                    rElement->removeAttribute("revoked");
                                    bChanged = true;
                                }
                            }
                        }

                        for (const auto& disable : rToBeDisabled)
                        {
                            if (-1 != aAttrUrl.indexOf(disable.getName()))
                            {
                                if (bEnabled)
                                {
                                    // needs to be disabled
                                    rElement->setAttribute("revoked", "true");
                                    bChanged = true;
                                }
                            }
                        }
                    }
                }
                else
                {
                    uno::Reference< xml::dom::XNodeList > aList = rElement->getChildNodes();

                    if (aList.is())
                    {
                        const sal_Int32 nLength(aList->getLength());

                        for (sal_Int32 a(0); a < nLength; a++)
                        {
                            const uno::Reference< xml::dom::XElement > aChild(aList->item(a), uno::UNO_QUERY);

                            if (aChild.is())
                            {
                                bChanged |= visitNodesXMLChange(
                                    rTagToSearch,
                                    aChild,
                                    rToBeEnabled,
                                    rToBeDisabled);
                            }
                        }
                    }
                }
            }

            return bChanged;
        }

        static void visitNodesXMLChangeOneCase(
            const OUString& rUnoPackagReg,
            const OUString& rTagToSearch,
            const ExtensionInfoEntryVector& rToBeEnabled,
            const ExtensionInfoEntryVector& rToBeDisabled)
        {
            if (!DirectoryHelper::fileExists(rUnoPackagReg))
                return;

            uno::Reference< uno::XComponentContext > xContext = ::comphelper::getProcessComponentContext();
            uno::Reference< xml::dom::XDocumentBuilder > xBuilder = xml::dom::DocumentBuilder::create(xContext);
            uno::Reference< xml::dom::XDocument > aDocument = xBuilder->parseURI(rUnoPackagReg);

            if (!aDocument.is())
                return;

            if (!visitNodesXMLChange(
                rTagToSearch,
                aDocument->getDocumentElement(),
                rToBeEnabled,
                rToBeDisabled))
                return;

            // did change - write back
            uno::Reference< xml::sax::XSAXSerializable > xSerializer(aDocument, uno::UNO_QUERY);

            if (!xSerializer.is())
                return;

            // create a SAXWriter
            uno::Reference< xml::sax::XWriter > const xSaxWriter = xml::sax::Writer::create(xContext);
            uno::Reference< io::XTempFile > xTempFile = io::TempFile::create(xContext);
            uno::Reference< io::XOutputStream > xOutStrm = xTempFile->getOutputStream();

            // set output stream and do the serialization
            xSaxWriter->setOutputStream(xOutStrm);
            xSerializer->serialize(xSaxWriter, uno::Sequence< beans::StringPair >());

            // get URL from temp file
            OUString aTempURL = xTempFile->getUri();

            // copy back file
            if (aTempURL.isEmpty() || !DirectoryHelper::fileExists(aTempURL))
                return;

            if (DirectoryHelper::fileExists(rUnoPackagReg))
            {
                osl::File::remove(rUnoPackagReg);
            }

#if OSL_DEBUG_LEVEL > 1
            SAL_WARN_IF(osl::FileBase::E_None != osl::File::move(aTempURL, rUnoPackagReg), "comphelper.backupfilehelper", "could not copy back modified Extension configuration file");
#else
            osl::File::move(aTempURL, rUnoPackagReg);
#endif
        }

    public:
        static void changeEnableDisableStateInXML(
            std::u16string_view rUserConfigWorkURL,
            const ExtensionInfoEntryVector& rToBeEnabled,
            const ExtensionInfoEntryVector& rToBeDisabled)
        {
            static const OUStringLiteral aRegPathFront(u"/uno_packages/cache/registry/com.sun.star.comp.deployment.");
            static const OUStringLiteral aRegPathBack(u".PackageRegistryBackend/backenddb.xml");
            // first appearance to check
            {
                const OUString aUnoPackagReg(OUString::Concat(rUserConfigWorkURL) + aRegPathFront + "bundle" + aRegPathBack);

                visitNodesXMLChangeOneCase(
                    aUnoPackagReg,
                    "extension",
                    rToBeEnabled,
                    rToBeDisabled);
            }

            // second appearance to check
            {
                const OUString aUnoPackagReg(OUString::Concat(rUserConfigWorkURL) + aRegPathFront + "configuration" + aRegPathBack);

                visitNodesXMLChangeOneCase(
                    aUnoPackagReg,
                    "configuration",
                    rToBeEnabled,
                    rToBeDisabled);
            }

            // third appearance to check
            {
                const OUString aUnoPackagReg(OUString::Concat(rUserConfigWorkURL) + aRegPathFront + "script" + aRegPathBack);

                visitNodesXMLChangeOneCase(
                    aUnoPackagReg,
                    "script",
                    rToBeEnabled,
                    rToBeDisabled);
            }
        }

        bool read_entries(FileSharedPtr const & rFile)
        {
            // read NumExtensionEntries
            sal_uInt32 nExtEntries(0);

            if (!read_sal_uInt32(rFile, nExtEntries))
            {
                return false;
            }

            // coverity#1373663 Untrusted loop bound, check file size
            // isn't utterly broken
            sal_uInt64 nFileSize(0);
            rFile->getSize(nFileSize);
            if (nFileSize < nExtEntries)
                return false;

            for (sal_uInt32 a(0); a < nExtEntries; a++)
            {
                ExtensionInfoEntry aNewEntry;

                if (aNewEntry.read_entry(rFile))
                {
                    maEntries.push_back(aNewEntry);
                }
                else
                {
                    return false;
                }
            }

            return true;
        }

        bool write_entries(oslFileHandle& rHandle) const
        {
            const sal_uInt32 nExtEntries(maEntries.size());

            if (!write_sal_uInt32(rHandle, nExtEntries))
            {
                return false;
            }

            for (const auto& a : maEntries)
            {
                if (!a.write_entry(rHandle))
                {
                    return false;
                }
            }

            return true;
        }

        bool createTempFile(OUString& rTempFileName)
        {
            oslFileHandle aHandle;
            bool bRetval(false);

            // create current configuration
            if (maEntries.empty())
            {
                createUsingXExtensionManager();
            }

            // open target temp file and write current configuration to it - it exists until deleted
            if (osl::File::E_None == osl::FileBase::createTempFile(nullptr, &aHandle, &rTempFileName))
            {
                bRetval = write_entries(aHandle);

                // close temp file - it exists until deleted
                osl_closeFile(aHandle);
            }

            return bRetval;
        }

        bool areThereEnabledExtensions() const
        {
            for (const auto& a : maEntries)
            {
                if (a.isEnabled())
                {
                    return true;
                }
            }

            return false;
        }
    };
}

namespace
{
    class PackedFileEntry
    {
    private:
        sal_uInt32          mnFullFileSize;     // size in bytes of unpacked original file
        sal_uInt32          mnPackFileSize;     // size in bytes in file backup package (smaller if compressed, same if not)
        sal_uInt32          mnOffset;           // offset in File (zero identifies new file)
        sal_uInt32          mnCrc32;            // checksum
        FileSharedPtr       maFile;             // file where to find the data (at offset)
        bool const          mbDoCompress;       // flag if this file is scheduled to be compressed when written

        bool copy_content_straight(oslFileHandle& rTargetHandle)
        {
            if (!maFile || osl::File::E_None != maFile->open(osl_File_OpenFlag_Read))
                return false;

            sal_uInt8 aArray[BACKUP_FILE_HELPER_BLOCK_SIZE];
            sal_uInt64 nBytesTransfer(0);
            sal_uInt64 nSize(getPackFileSize());

            // set offset in source file - when this is zero, a new file is to be added
            if (osl::File::E_None == maFile->setPos(osl_Pos_Absolut, sal_Int64(getOffset())))
            {
                while (nSize != 0)
                {
                    const sal_uInt64 nToTransfer(std::min(nSize, sal_uInt64(BACKUP_FILE_HELPER_BLOCK_SIZE)));

                    if (osl::File::E_None != maFile->read(static_cast<void*>(aArray), nToTransfer, nBytesTransfer) || nBytesTransfer != nToTransfer)
                    {
                        break;
                    }

                    if (osl_File_E_None != osl_writeFile(rTargetHandle, static_cast<const void*>(aArray), nToTransfer, &nBytesTransfer) || nBytesTransfer != nToTransfer)
                    {
                        break;
                    }

                    nSize -= nToTransfer;
                }
            }

            maFile->close();
            return (0 == nSize);
        }

        bool copy_content_compress(oslFileHandle& rTargetHandle)
        {
            if (!maFile || osl::File::E_None != maFile->open(osl_File_OpenFlag_Read))
                return false;

            sal_uInt8 aArray[BACKUP_FILE_HELPER_BLOCK_SIZE];
            sal_uInt8 aBuffer[BACKUP_FILE_HELPER_BLOCK_SIZE];
            sal_uInt64 nBytesTransfer(0);
            sal_uInt64 nSize(getPackFileSize());
            z_stream zstream;
            memset(&zstream, 0, sizeof(zstream));

            if (Z_OK == deflateInit(&zstream, Z_BEST_COMPRESSION))
            {
                // set offset in source file - when this is zero, a new file is to be added
                if (osl::File::E_None == maFile->setPos(osl_Pos_Absolut, sal_Int64(getOffset())))
                {
                    bool bOkay(true);

                    while (bOkay && nSize != 0)
                    {
                        const sal_uInt64 nToTransfer(std::min(nSize, sal_uInt64(BACKUP_FILE_HELPER_BLOCK_SIZE)));

                        if (osl::File::E_None != maFile->read(static_cast<void*>(aArray), nToTransfer, nBytesTransfer) || nBytesTransfer != nToTransfer)
                        {
                            break;
                        }

                        zstream.avail_in = nToTransfer;
                        zstream.next_in = reinterpret_cast<unsigned char*>(aArray);

                        do {
                            zstream.avail_out = BACKUP_FILE_HELPER_BLOCK_SIZE;
                            zstream.next_out = reinterpret_cast<unsigned char*>(aBuffer);
#if !defined Z_PREFIX
                            const sal_Int64 nRetval(deflate(&zstream, nSize == nToTransfer ? Z_FINISH : Z_NO_FLUSH));
#else
                            const sal_Int64 nRetval(z_deflate(&zstream, nSize == nToTransfer ? Z_FINISH : Z_NO_FLUSH));
#endif
                            if (Z_STREAM_ERROR == nRetval)
                            {
                                bOkay = false;
                            }
                            else
                            {
                                const sal_uInt64 nAvailable(BACKUP_FILE_HELPER_BLOCK_SIZE - zstream.avail_out);

                                if (osl_File_E_None != osl_writeFile(rTargetHandle, static_cast<const void*>(aBuffer), nAvailable, &nBytesTransfer) || nBytesTransfer != nAvailable)
                                {
                                    bOkay = false;
                                }
                            }
                        } while (bOkay && 0 == zstream.avail_out);

                        if (!bOkay)
                        {
                            break;
                        }

                        nSize -= nToTransfer;
                    }

#if !defined Z_PREFIX
                    deflateEnd(&zstream);
#else
                    z_deflateEnd(&zstream);
#endif
                }
            }

            maFile->close();

            // get compressed size and add to entry
            if (mnFullFileSize == mnPackFileSize && mnFullFileSize == zstream.total_in)
            {
                mnPackFileSize = zstream.total_out;
            }

            return (0 == nSize);
        }

        bool copy_content_uncompress(oslFileHandle& rTargetHandle)
        {
            if (!maFile || osl::File::E_None != maFile->open(osl_File_OpenFlag_Read))
                return false;

            sal_uInt8 aArray[BACKUP_FILE_HELPER_BLOCK_SIZE];
            sal_uInt8 aBuffer[BACKUP_FILE_HELPER_BLOCK_SIZE];
            sal_uInt64 nBytesTransfer(0);
            sal_uInt64 nSize(getPackFileSize());
            z_stream zstream;
            memset(&zstream, 0, sizeof(zstream));

            if (Z_OK == inflateInit(&zstream))
            {
                // set offset in source file - when this is zero, a new file is to be added
                if (osl::File::E_None == maFile->setPos(osl_Pos_Absolut, sal_Int64(getOffset())))
                {
                    bool bOkay(true);

                    while (bOkay && nSize != 0)
                    {
                        const sal_uInt64 nToTransfer(std::min(nSize, sal_uInt64(BACKUP_FILE_HELPER_BLOCK_SIZE)));

                        if (osl::File::E_None != maFile->read(static_cast<void*>(aArray), nToTransfer, nBytesTransfer) || nBytesTransfer != nToTransfer)
                        {
                            break;
                        }

                        zstream.avail_in = nToTransfer;
                        zstream.next_in = reinterpret_cast<unsigned char*>(aArray);

                        do {
                            zstream.avail_out = BACKUP_FILE_HELPER_BLOCK_SIZE;
                            zstream.next_out = reinterpret_cast<unsigned char*>(aBuffer);
#if !defined Z_PREFIX
                            const sal_Int64 nRetval(inflate(&zstream, Z_NO_FLUSH));
#else
                            const sal_Int64 nRetval(z_inflate(&zstream, Z_NO_FLUSH));
#endif
                            if (Z_STREAM_ERROR == nRetval)
                            {
                                bOkay = false;
                            }
                            else
                            {
                                const sal_uInt64 nAvailable(BACKUP_FILE_HELPER_BLOCK_SIZE - zstream.avail_out);

                                if (osl_File_E_None != osl_writeFile(rTargetHandle, static_cast<const void*>(aBuffer), nAvailable, &nBytesTransfer) || nBytesTransfer != nAvailable)
                                {
                                    bOkay = false;
                                }
                            }
                        } while (bOkay && 0 == zstream.avail_out);

                        if (!bOkay)
                        {
                            break;
                        }

                        nSize -= nToTransfer;
                    }

#if !defined Z_PREFIX
                    deflateEnd(&zstream);
#else
                    z_deflateEnd(&zstream);
#endif
                }
            }

            maFile->close();
            return (0 == nSize);
        }


    public:
        // create new, uncompressed entry
        PackedFileEntry(
            sal_uInt32 nFullFileSize,
            sal_uInt32 nCrc32,
            FileSharedPtr xFile,
            bool bDoCompress)
        :   mnFullFileSize(nFullFileSize),
            mnPackFileSize(nFullFileSize),
            mnOffset(0),
            mnCrc32(nCrc32),
            maFile(std::move(xFile)),
            mbDoCompress(bDoCompress)
        {
        }

        // create entry to be loaded as header (read_header)
        PackedFileEntry()
        :   mnFullFileSize(0),
            mnPackFileSize(0),
            mnOffset(0),
            mnCrc32(0),
            mbDoCompress(false)
        {
        }

        sal_uInt32 getFullFileSize() const
        {
            return  mnFullFileSize;
        }

        sal_uInt32 getPackFileSize() const
        {
            return  mnPackFileSize;
        }

        sal_uInt32 getOffset() const
        {
            return mnOffset;
        }

        void setOffset(sal_uInt32 nOffset)
        {
            mnOffset = nOffset;
        }

        static sal_uInt32 getEntrySize()
        {
            return 12;
        }

        sal_uInt32 getCrc32() const
        {
            return mnCrc32;
        }

        bool read_header(FileSharedPtr const & rFile)
        {
            if (!rFile)
            {
                return false;
            }

            maFile = rFile;

            // read and compute full file size
            if (!read_sal_uInt32(rFile, mnFullFileSize))
            {
                return false;
            }

            // read and compute entry crc32
            if (!read_sal_uInt32(rFile, mnCrc32))
            {
                return false;
            }

            // read and compute packed size
            if (!read_sal_uInt32(rFile, mnPackFileSize))
            {
                return false;
            }

            return true;
        }

        bool write_header(oslFileHandle& rHandle) const
        {
            // write full file size
            if (!write_sal_uInt32(rHandle, mnFullFileSize))
            {
                return false;
            }

            // write crc32
            if (!write_sal_uInt32(rHandle, mnCrc32))
            {
                return false;
            }

            // write packed file size
            if (!write_sal_uInt32(rHandle, mnPackFileSize))
            {
                return false;
            }

            return true;
        }

        bool copy_content(oslFileHandle& rTargetHandle, bool bUncompress)
        {
            if (bUncompress)
            {
                if (getFullFileSize() == getPackFileSize())
                {
                    // not compressed, just copy
                    return copy_content_straight(rTargetHandle);
                }
                else
                {
                    // compressed, need to uncompress on copy
                    return copy_content_uncompress(rTargetHandle);
                }
            }
            else if (0 == getOffset())
            {
                if (mbDoCompress)
                {
                    // compressed wanted, need to compress on copy
                    return copy_content_compress(rTargetHandle);
                }
                else
                {
                    // not compressed, straight copy
                    return copy_content_straight(rTargetHandle);
                }
            }
            else
            {
                return copy_content_straight(rTargetHandle);
            }
        }
    };
}

namespace
{
    class PackedFile
    {
    private:
        const OUString          maURL;
        std::deque< PackedFileEntry >
                                maPackedFileEntryVector;
        bool                    mbChanged;

    public:
        PackedFile(const OUString& rURL)
        :   maURL(rURL),
            mbChanged(false)
        {
            FileSharedPtr aSourceFile = std::make_shared<osl::File>(rURL);

            if (osl::File::E_None == aSourceFile->open(osl_File_OpenFlag_Read))
            {
                sal_uInt64 nBaseLen(0);
                aSourceFile->getSize(nBaseLen);

                // we need at least File_ID and num entries -> 8byte
                if (8 < nBaseLen)
                {
                    sal_uInt8 aArray[4];
                    sal_uInt64 nBaseRead(0);

                    // read and check File_ID
                    if (osl::File::E_None == aSourceFile->read(static_cast< void* >(aArray), 4, nBaseRead) && 4 == nBaseRead)
                    {
                        if ('P' == aArray[0] && 'A' == aArray[1] && 'C' == aArray[2] && 'K' == aArray[3])
                        {
                            // read and compute num entries in this file
                            if (osl::File::E_None == aSourceFile->read(static_cast<void*>(aArray), 4, nBaseRead) && 4 == nBaseRead)
                            {
                                sal_uInt32 nEntries((sal_uInt32(aArray[0]) << 24) + (sal_uInt32(aArray[1]) << 16) + (sal_uInt32(aArray[2]) << 8) + sal_uInt32(aArray[3]));

                                // if there are entries (and less than max), read them
                                if (nEntries >= 1 && nEntries <= 10)
                                {
                                    for (sal_uInt32 a(0); a < nEntries; a++)
                                    {
                                        // create new entry, read header (size, crc and PackedSize),
                                        // set offset and source file
                                        PackedFileEntry aEntry;

                                        if (aEntry.read_header(aSourceFile))
                                        {
                                            // add to local data
                                            maPackedFileEntryVector.push_back(aEntry);
                                        }
                                        else
                                        {
                                            // error
                                            nEntries = 0;
                                        }
                                    }

                                    if (0 == nEntries)
                                    {
                                        // on read error clear local data
                                        maPackedFileEntryVector.clear();
                                    }
                                    else
                                    {
                                        // calculate and set offsets to file binary content
                                        sal_uInt32 nHeaderSize(8);

                                        nHeaderSize += maPackedFileEntryVector.size() * PackedFileEntry::getEntrySize();

                                        sal_uInt32 nOffset(nHeaderSize);

                                        for (auto& b : maPackedFileEntryVector)
                                        {
                                            b.setOffset(nOffset);
                                            nOffset += b.getPackFileSize();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                aSourceFile->close();
            }

            if (maPackedFileEntryVector.empty())
            {
                // on error or no data get rid of pack file
                osl::File::remove(maURL);
            }
        }

        void flush()
        {
            bool bRetval(true);

            if (maPackedFileEntryVector.empty())
            {
                // get rid of (now?) empty pack file
                osl::File::remove(maURL);
            }
            else if (mbChanged)
            {
                // need to create a new pack file, do this in a temp file to which data
                // will be copied from local file (so keep it here until this is done)
                oslFileHandle aHandle = nullptr;
                OUString aTempURL;

                // open target temp file - it exists until deleted
                if (osl::File::E_None == osl::FileBase::createTempFile(nullptr, &aHandle, &aTempURL))
                {
                    sal_uInt8 aArray[4];
                    sal_uInt64 nBaseWritten(0);

                    aArray[0] = 'P';
                    aArray[1] = 'A';
                    aArray[2] = 'C';
                    aArray[3] = 'K';

                    // write File_ID
                    if (osl_File_E_None == osl_writeFile(aHandle, static_cast<const void*>(aArray), 4, &nBaseWritten) && 4 == nBaseWritten)
                    {
                        const sal_uInt32 nSize(maPackedFileEntryVector.size());

                        // write number of entries
                        if (write_sal_uInt32(aHandle, nSize))
                        {
                            // write placeholder for headers. Due to the fact that
                            // PackFileSize for newly added files gets set during
                            // writing the content entry, write headers after content
                            // is written. To do so, write placeholders here
                            sal_uInt32 nWriteSize(0);

                            nWriteSize += maPackedFileEntryVector.size() * PackedFileEntry::getEntrySize();

                            aArray[0] = aArray[1] = aArray[2] = aArray[3] = 0;

                            for (sal_uInt32 a(0); bRetval && a < nWriteSize; a++)
                            {
                                if (osl_File_E_None != osl_writeFile(aHandle, static_cast<const void*>(aArray), 1, &nBaseWritten) || 1 != nBaseWritten)
                                {
                                    bRetval = false;
                                }
                            }

                            if (bRetval)
                            {
                                // write contents - this may adapt PackFileSize for new
                                // files
                                for (auto& candidate : maPackedFileEntryVector)
                                {
                                    if (!candidate.copy_content(aHandle, false))
                                    {
                                        bRetval = false;
                                        break;
                                    }
                                }
                            }

                            if (bRetval)
                            {
                                // seek back to header start (at position 8)
                                if (osl_File_E_None != osl_setFilePos(aHandle, osl_Pos_Absolut, sal_Int64(8)))
                                {
                                    bRetval = false;
                                }
                            }

                            if (bRetval)
                            {
                                // write headers
                                for (const auto& candidate : maPackedFileEntryVector)
                                {
                                    if (!candidate.write_header(aHandle))
                                    {
                                        // error
                                        bRetval = false;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                // close temp file (in all cases) - it exists until deleted
                osl_closeFile(aHandle);

                if (bRetval)
                {
                    // copy over existing file by first deleting original
                    // and moving the temp file to old original
                    osl::File::remove(maURL);
                    osl::File::move(aTempURL, maURL);
                }

                // delete temp file (in all cases - it may be moved already)
                osl::File::remove(aTempURL);
            }
        }

        bool tryPush(FileSharedPtr const & rFileCandidate, bool bCompress)
        {
            sal_uInt64 nFileSize(0);

            if (rFileCandidate && osl::File::E_None == rFileCandidate->open(osl_File_OpenFlag_Read))
            {
                rFileCandidate->getSize(nFileSize);
                rFileCandidate->close();
            }

            if (0 == nFileSize)
            {
                // empty file offered
                return false;
            }

            bool bNeedToAdd(false);
            sal_uInt32 nCrc32(0);

            if (maPackedFileEntryVector.empty())
            {
                // no backup yet, add as 1st backup
                bNeedToAdd = true;
            }
            else
            {
                // already backups there, check if different from last entry
                const PackedFileEntry& aLastEntry = maPackedFileEntryVector.back();

                // check if file is different
                if (aLastEntry.getFullFileSize() != static_cast<sal_uInt32>(nFileSize))
                {
                    // different size, different file
                    bNeedToAdd = true;
                }
                else
                {
                    // same size, check crc32
                    nCrc32 = createCrc32(rFileCandidate, 0);

                    if (nCrc32 != aLastEntry.getCrc32())
                    {
                        // different crc, different file
                        bNeedToAdd = true;
                    }
                }
            }

            if (bNeedToAdd)
            {
                // create crc32 if not yet done
                if (0 == nCrc32)
                {
                    nCrc32 = createCrc32(rFileCandidate, 0);
                }

                // create a file entry for a new file. Offset is set automatically
                // to 0 to mark the entry as new file entry
                maPackedFileEntryVector.emplace_back(
                        static_cast< sal_uInt32 >(nFileSize),
                        nCrc32,
                        rFileCandidate,
                        bCompress);

                mbChanged = true;
            }

            return bNeedToAdd;
        }

        bool tryPop(oslFileHandle& rHandle)
        {
            if (maPackedFileEntryVector.empty())
                return false;

            // already backups there, check if different from last entry
            PackedFileEntry& aLastEntry = maPackedFileEntryVector.back();

            // here the uncompress flag has to be determined, true
            // means to add the file compressed, false means to add it
            // uncompressed
            bool bRetval = aLastEntry.copy_content(rHandle, true);

            if (bRetval)
            {
                maPackedFileEntryVector.pop_back();
                mbChanged = true;
            }

            return bRetval;
        }

        void tryReduceToNumBackups(sal_uInt16 nNumBackups)
        {
            while (maPackedFileEntryVector.size() > nNumBackups)
            {
                maPackedFileEntryVector.pop_front();
                mbChanged = true;
            }
        }

        bool empty() const
        {
            return maPackedFileEntryVector.empty();
        }
    };
}

namespace comphelper
{
    sal_uInt16 BackupFileHelper::mnMaxAllowedBackups = 10;
    bool BackupFileHelper::mbExitWasCalled = false;
    bool BackupFileHelper::mbSafeModeDirExists = false;
    OUString BackupFileHelper::maInitialBaseURL;
    OUString BackupFileHelper::maUserConfigBaseURL;
    OUString BackupFileHelper::maUserConfigWorkURL;
    OUString BackupFileHelper::maRegModName;
    OUString BackupFileHelper::maExt;

    const OUString& BackupFileHelper::getInitialBaseURL()
    {
        if (maInitialBaseURL.isEmpty())
        {
            // try to access user layer configuration file URL, the one that
            // points to registrymodifications.xcu
            OUString conf("${CONFIGURATION_LAYERS}");
            rtl::Bootstrap::expandMacros(conf);
            static const OUStringLiteral aTokenUser(u"user:");
            sal_Int32 nStart(conf.indexOf(aTokenUser));

            if (-1 != nStart)
            {
                nStart += aTokenUser.getLength();
                sal_Int32 nEnd(conf.indexOf(' ', nStart));

                if (-1 == nEnd)
                {
                    nEnd = conf.getLength();
                }

                maInitialBaseURL = conf.copy(nStart, nEnd - nStart);
                (void)maInitialBaseURL.startsWith("!", &maInitialBaseURL);
            }

            if (!maInitialBaseURL.isEmpty())
            {
                // split URL at extension and at last path separator
                maUserConfigBaseURL = DirectoryHelper::splitAtLastToken(
                    DirectoryHelper::splitAtLastToken(maInitialBaseURL, '.', maExt), '/',
                    maRegModName);
            }

            if (!maUserConfigBaseURL.isEmpty())
            {
                // check if SafeModeDir exists
                mbSafeModeDirExists = DirectoryHelper::dirExists(maUserConfigBaseURL + "/" + getSafeModeName());
            }

            maUserConfigWorkURL = maUserConfigBaseURL;

            if (mbSafeModeDirExists)
            {
                // adapt work URL to do all repair op's in the correct directory
                maUserConfigWorkURL += "/" + getSafeModeName();
            }
        }

        return maInitialBaseURL;
    }

    const OUString& BackupFileHelper::getSafeModeName()
    {
        static const OUString aSafeMode("SafeMode");

        return aSafeMode;
    }

    BackupFileHelper::BackupFileHelper()
    :   mnNumBackups(2),
        mnMode(1),
        mbActive(false),
        mbExtensions(true),
        mbCompress(true)
    {
        OUString sTokenOut;

        // read configuration item 'SecureUserConfig' -> bool on/off
        if (rtl::Bootstrap::get("SecureUserConfig", sTokenOut))
        {
            mbActive = sTokenOut.toBoolean();
        }

        if (mbActive)
        {
            // ensure existence
            getInitialBaseURL();

            // if not found, we are out of business (maExt may be empty)
            mbActive = !maInitialBaseURL.isEmpty() && !maUserConfigBaseURL.isEmpty() && !maRegModName.isEmpty();
        }

        if (mbActive && rtl::Bootstrap::get("SecureUserConfigNumCopies", sTokenOut))
        {
            const sal_uInt16 nConfigNumCopies(static_cast<sal_uInt16>(sTokenOut.toUInt32()));

            // limit to range [1..mnMaxAllowedBackups]
            mnNumBackups = std::clamp(mnNumBackups, nConfigNumCopies, mnMaxAllowedBackups);
        }

        if (mbActive && rtl::Bootstrap::get("SecureUserConfigMode", sTokenOut))
        {
            const sal_uInt16 nMode(static_cast<sal_uInt16>(sTokenOut.toUInt32()));

            // limit to range [0..2]
            mnMode = std::min(nMode, sal_uInt16(2));
        }

        if (mbActive && rtl::Bootstrap::get("SecureUserConfigExtensions", sTokenOut))
        {
            mbExtensions = sTokenOut.toBoolean();
        }

        if (mbActive && rtl::Bootstrap::get("SecureUserConfigCompress", sTokenOut))
        {
            mbCompress = sTokenOut.toBoolean();
        }
    }

    void BackupFileHelper::setExitWasCalled()
    {
        mbExitWasCalled = true;
    }

    bool BackupFileHelper::getExitWasCalled()
    {
        return mbExitWasCalled;
    }

    void BackupFileHelper::reactOnSafeMode(bool bSafeMode)
    {
        // ensure existence of needed paths
        getInitialBaseURL();

        if (maUserConfigBaseURL.isEmpty())
            return;

        if (bSafeMode)
        {
            if (!mbSafeModeDirExists)
            {
                std::set< OUString > aExcludeList;

                // do not move SafeMode directory itself
                aExcludeList.insert(getSafeModeName());

                // init SafeMode by creating the 'SafeMode' directory and moving
                // all stuff there. All repairs will happen there. Both Dirs have to exist.
                // extend maUserConfigWorkURL as needed
                maUserConfigWorkURL = maUserConfigBaseURL + "/" + getSafeModeName();

                osl::Directory::createPath(maUserConfigWorkURL);
                DirectoryHelper::moveDirContent(maUserConfigBaseURL, maUserConfigWorkURL, aExcludeList);

                // switch local flag, maUserConfigWorkURL is already reset
                mbSafeModeDirExists = true;
            }
        }
        else
        {
            if (mbSafeModeDirExists)
            {
                // SafeMode has ended, return to normal mode by moving all content
                // from 'SafeMode' directory back to UserDirectory and deleting it.
                // Both Dirs have to exist
                std::set< OUString > aExcludeList;

                DirectoryHelper::moveDirContent(maUserConfigWorkURL, maUserConfigBaseURL, aExcludeList);
                osl::Directory::remove(maUserConfigWorkURL);

                // switch local flag and reset maUserConfigWorkURL
                mbSafeModeDirExists = false;
                maUserConfigWorkURL = maUserConfigBaseURL;
            }
        }
    }

    void BackupFileHelper::tryPush()
    {
        // no push when SafeModeDir exists, it may be Office's exit after SafeMode
        // where SafeMode flag is already deleted, but SafeModeDir cleanup is not
        // done yet (is done at next startup)
        if (!mbActive || mbSafeModeDirExists)
            return;

        const OUString aPackURL(getPackURL());

        // ensure dir and file vectors
        fillDirFileInfo();

        // process all files in question recursively
        if (!maDirs.empty() || !maFiles.empty())
        {
            tryPush_Files(
                maDirs,
                maFiles,
                maUserConfigWorkURL,
                aPackURL);
        }
    }

    void BackupFileHelper::tryPushExtensionInfo()
    {
        // no push when SafeModeDir exists, it may be Office's exit after SafeMode
        // where SafeMode flag is already deleted, but SafeModeDir cleanup is not
        // done yet (is done at next startup)
        if (mbActive && mbExtensions && !mbSafeModeDirExists)
        {
            const OUString aPackURL(getPackURL());

            tryPush_extensionInfo(aPackURL);
        }
    }

    bool BackupFileHelper::isPopPossible()
    {
        bool bPopPossible(false);

        if (mbActive)
        {
            const OUString aPackURL(getPackURL());

            // ensure dir and file vectors
            fillDirFileInfo();

            // process all files in question recursively
            if (!maDirs.empty() || !maFiles.empty())
            {
                bPopPossible = isPopPossible_files(
                    maDirs,
                    maFiles,
                    maUserConfigWorkURL,
                    aPackURL);
            }
        }

        return bPopPossible;
    }

    void BackupFileHelper::tryPop()
    {
        if (!mbActive)
            return;

        bool bDidPop(false);
        const OUString aPackURL(getPackURL());

        // ensure dir and file vectors
        fillDirFileInfo();

        // process all files in question recursively
        if (!maDirs.empty() || !maFiles.empty())
        {
            bDidPop = tryPop_files(
                maDirs,
                maFiles,
                maUserConfigWorkURL,
                aPackURL);
        }

        if (bDidPop)
        {
            // try removal of evtl. empty directory
            osl::Directory::remove(aPackURL);
        }
    }

    bool BackupFileHelper::isPopPossibleExtensionInfo() const
    {
        bool bPopPossible(false);

        if (mbActive && mbExtensions)
        {
            const OUString aPackURL(getPackURL());

            bPopPossible = isPopPossible_extensionInfo(aPackURL);
        }

        return bPopPossible;
    }

    void BackupFileHelper::tryPopExtensionInfo()
    {
        if (!(mbActive && mbExtensions))
            return;

        bool bDidPop(false);
        const OUString aPackURL(getPackURL());

        bDidPop = tryPop_extensionInfo(aPackURL);

        if (bDidPop)
        {
            // try removal of evtl. empty directory
            osl::Directory::remove(aPackURL);
        }
    }

    bool BackupFileHelper::isTryDisableAllExtensionsPossible()
    {
        // check if there are still enabled extension which can be disabled,
        // but as we are now in SafeMode, use XML infos for this since the
        // extensions are not loaded from XExtensionManager
        class ExtensionInfo aExtensionInfo;

        aExtensionInfo.createUserExtensionRegistryEntriesFromXML(maUserConfigWorkURL);

        return aExtensionInfo.areThereEnabledExtensions();
    }

    void BackupFileHelper::tryDisableAllExtensions()
    {
        // disable all still enabled extensions,
        // but as we are now in SafeMode, use XML infos for this since the
        // extensions are not loaded from XExtensionManager
        ExtensionInfo aCurrentExtensionInfo;
        const ExtensionInfoEntryVector aToBeEnabled{};
        ExtensionInfoEntryVector aToBeDisabled;

        aCurrentExtensionInfo.createUserExtensionRegistryEntriesFromXML(maUserConfigWorkURL);

        const ExtensionInfoEntryVector& rCurrentVector = aCurrentExtensionInfo.getExtensionInfoEntryVector();

        for (const auto& rCurrentInfo : rCurrentVector)
        {
            if (rCurrentInfo.isEnabled())
            {
                aToBeDisabled.push_back(rCurrentInfo);
            }
        }

        ExtensionInfo::changeEnableDisableStateInXML(maUserConfigWorkURL, aToBeEnabled, aToBeDisabled);
    }

    bool BackupFileHelper::isTryDeinstallUserExtensionsPossible()
    {
        // check if there are User Extensions installed.
        class ExtensionInfo aExtensionInfo;

        aExtensionInfo.createUserExtensionRegistryEntriesFromXML(maUserConfigWorkURL);

        return !aExtensionInfo.getExtensionInfoEntryVector().empty();
    }

    void BackupFileHelper::tryDeinstallUserExtensions()
    {
        // delete User Extension installs
        DirectoryHelper::deleteDirRecursively(maUserConfigWorkURL + "/uno_packages");
    }

    bool BackupFileHelper::isTryResetSharedExtensionsPossible()
    {
        // check if there are shared Extensions installed
        class ExtensionInfo aExtensionInfo;

        aExtensionInfo.createSharedExtensionRegistryEntriesFromXML(maUserConfigWorkURL);

        return !aExtensionInfo.getExtensionInfoEntryVector().empty();
    }

    void BackupFileHelper::tryResetSharedExtensions()
    {
        // reset shared extension info
        DirectoryHelper::deleteDirRecursively(maUserConfigWorkURL + "/extensions/shared");
    }

    bool BackupFileHelper::isTryResetBundledExtensionsPossible()
    {
        // check if there are shared Extensions installed
        class ExtensionInfo aExtensionInfo;

        aExtensionInfo.createBundledExtensionRegistryEntriesFromXML(maUserConfigWorkURL);

        return !aExtensionInfo.getExtensionInfoEntryVector().empty();
    }

    void BackupFileHelper::tryResetBundledExtensions()
    {
        // reset shared extension info
        DirectoryHelper::deleteDirRecursively(maUserConfigWorkURL + "/extensions/bundled");
    }

    const std::vector< OUString >& BackupFileHelper::getCustomizationDirNames()
    {
        static std::vector< OUString > aDirNames =
        {
            "config",     // UI config stuff
            "registry",   // most of the registry stuff
            "psprint",    // not really needed, can be abandoned
            "store",      // not really needed, can be abandoned
            "temp",       // not really needed, can be abandoned
            "pack"       // own backup dir
        };

        return aDirNames;
    }

    const std::vector< OUString >& BackupFileHelper::getCustomizationFileNames()
    {
        static std::vector< OUString > aFileNames =
        {
            "registrymodifications.xcu" // personal registry stuff
        };

        return aFileNames;
    }

    namespace {
        uno::Reference<XElement> lcl_getConfigElement(const uno::Reference<XDocument>& xDocument, const OUString& rPath,
                                  const OUString& rKey, const OUString& rValue)
        {
            uno::Reference< XElement > itemElement = xDocument->createElement("item");
            itemElement->setAttribute("oor:path", rPath);

            uno::Reference< XElement > propElement = xDocument->createElement("prop");
            propElement->setAttribute("oor:name", rKey);
            propElement->setAttribute("oor:op", "replace"); // Replace any other options

            uno::Reference< XElement > valueElement = xDocument->createElement("value");
            uno::Reference< XText > textElement = xDocument->createTextNode(rValue);

            valueElement->appendChild(textElement);
            propElement->appendChild(valueElement);
            itemElement->appendChild(propElement);

            return itemElement;
        }
    }

    void BackupFileHelper::tryDisableHWAcceleration()
    {
        const OUString aRegistryModifications(maUserConfigWorkURL + "/registrymodifications.xcu");
        if (!DirectoryHelper::fileExists(aRegistryModifications))
            return;

        uno::Reference< uno::XComponentContext > xContext = ::comphelper::getProcessComponentContext();
        uno::Reference< XDocumentBuilder > xBuilder = DocumentBuilder::create(xContext);
        uno::Reference< XDocument > xDocument = xBuilder->parseURI(aRegistryModifications);
        uno::Reference< XElement > xRootElement = xDocument->getDocumentElement();

        xRootElement->appendChild(lcl_getConfigElement(xDocument, "/org.openoffice.Office.Common/VCL",
                                                       "DisableOpenGL", "true"));
        xRootElement->appendChild(lcl_getConfigElement(xDocument, "/org.openoffice.Office.Common/Misc",
                                                       "UseOpenCL", "false"));
        // Do not disable Skia entirely, just force its CPU-based raster mode.
        xRootElement->appendChild(lcl_getConfigElement(xDocument, "/org.openoffice.Office.Common/VCL",
                                                       "ForceSkia", "false"));
        xRootElement->appendChild(lcl_getConfigElement(xDocument, "/org.openoffice.Office.Common/VCL",
                                                       "ForceSkiaRaster", "true"));

        OUString aTempURL;
        {
            // use the scope to make sure that the temp file gets properly closed before move

            // write back
            uno::Reference< xml::sax::XSAXSerializable > xSerializer(xDocument, uno::UNO_QUERY);

            if (!xSerializer.is())
                return;

            // create a SAXWriter
            uno::Reference< xml::sax::XWriter > const xSaxWriter = xml::sax::Writer::create(xContext);
            uno::Reference< io::XTempFile > xTempFile = io::TempFile::create(xContext);
            xTempFile->setRemoveFile(false); // avoid removal of tempfile when leaving the scope
            uno::Reference< io::XOutputStream > xOutStrm = xTempFile->getOutputStream();

            // set output stream and do the serialization
            xSaxWriter->setOutputStream(xOutStrm);
            xSerializer->serialize(xSaxWriter, uno::Sequence< beans::StringPair >());

            // get URL from temp file
            aTempURL = xTempFile->getUri();
        }

        // copy back file
        if (aTempURL.isEmpty() || !DirectoryHelper::fileExists(aTempURL))
            return;

        if (DirectoryHelper::fileExists(aRegistryModifications))
        {
            osl::File::remove(aRegistryModifications);
        }

        int result = osl::File::move(aTempURL, aRegistryModifications);
        SAL_WARN_IF(result != osl::FileBase::E_None, "comphelper.backupfilehelper", "could not copy back modified Extension configuration file");
    }

    bool BackupFileHelper::isTryResetCustomizationsPossible()
    {
        // return true if not all of the customization selection dirs or files are deleted
        const std::vector< OUString >& rDirs = getCustomizationDirNames();

        for (const auto& a : rDirs)
        {
            if (DirectoryHelper::dirExists(maUserConfigWorkURL + "/" + a))
            {
                return true;
            }
        }

        const std::vector< OUString >& rFiles = getCustomizationFileNames();

        for (const auto& b : rFiles)
        {
            if (DirectoryHelper::fileExists(maUserConfigWorkURL + "/" + b))
            {
                return true;
            }
        }

        return false;
    }

    void BackupFileHelper::tryResetCustomizations()
    {
        // delete all of the customization selection dirs
        const std::vector< OUString >& rDirs = getCustomizationDirNames();

        for (const auto& a : rDirs)
        {
            DirectoryHelper::deleteDirRecursively(maUserConfigWorkURL + "/" + a);
        }

        const std::vector< OUString >& rFiles = getCustomizationFileNames();

        for (const auto& b : rFiles)
        {
            osl::File::remove(maUserConfigWorkURL + "/" + b);
        }
    }

    void BackupFileHelper::tryResetUserProfile()
    {
        // completely delete the current UserProfile
        DirectoryHelper::deleteDirRecursively(maUserConfigWorkURL);
    }

    const OUString& BackupFileHelper::getUserProfileURL()
    {
        return maUserConfigBaseURL;
    }

    const OUString& BackupFileHelper::getUserProfileWorkURL()
    {
        return maUserConfigWorkURL;
    }

    /////////////////// helpers ///////////////////////

    OUString BackupFileHelper::getPackURL()
    {
        return OUString(maUserConfigWorkURL + "/pack");
    }

    /////////////////// file push helpers ///////////////////////

    bool BackupFileHelper::tryPush_Files(
        const std::set< OUString >& rDirs,
        const std::set< std::pair< OUString, OUString > >& rFiles,
        std::u16string_view rSourceURL, // source dir without trailing '/'
        const OUString& rTargetURL // target dir without trailing '/'
        )
    {
        bool bDidPush(false);
        osl::Directory::createPath(rTargetURL);

        // process files
        for (const auto& file : rFiles)
        {
            bDidPush |= tryPush_file(
                rSourceURL,
                rTargetURL,
                file.first,
                file.second);
        }

        // process dirs
        for (const auto& dir : rDirs)
        {
            OUString aNewSourceURL(OUString::Concat(rSourceURL) + "/" + dir);
            OUString aNewTargetURL(rTargetURL + "/" + dir);
            std::set< OUString > aNewDirs;
            std::set< std::pair< OUString, OUString > > aNewFiles;

            DirectoryHelper::scanDirsAndFiles(
                aNewSourceURL,
                aNewDirs,
                aNewFiles);

            if (!aNewDirs.empty() || !aNewFiles.empty())
            {
                bDidPush |= tryPush_Files(
                    aNewDirs,
                    aNewFiles,
                    aNewSourceURL,
                    aNewTargetURL);
            }
        }

        if (!bDidPush)
        {
            // try removal of evtl. empty directory
            osl::Directory::remove(rTargetURL);
        }

        return bDidPush;
    }

    bool BackupFileHelper::tryPush_file(
        std::u16string_view rSourceURL, // source dir without trailing '/'
        std::u16string_view rTargetURL, // target dir without trailing '/'
        std::u16string_view rName,  // filename
        std::u16string_view rExt    // extension (or empty)
        )
    {
        const OUString aFileURL(createFileURL(rSourceURL, rName, rExt));

        if (DirectoryHelper::fileExists(aFileURL))
        {
            const OUString aPackURL(createPackURL(rTargetURL, rName));
            PackedFile aPackedFile(aPackURL);
            FileSharedPtr aBaseFile = std::make_shared<osl::File>(aFileURL);

            if (aPackedFile.tryPush(aBaseFile, mbCompress))
            {
                // reduce to allowed number and flush
                aPackedFile.tryReduceToNumBackups(mnNumBackups);
                aPackedFile.flush();

                return true;
            }
        }

        return false;
    }

    /////////////////// file pop possibilities helper ///////////////////////

    bool BackupFileHelper::isPopPossible_files(
        const std::set< OUString >& rDirs,
        const std::set< std::pair< OUString, OUString > >& rFiles,
        std::u16string_view rSourceURL, // source dir without trailing '/'
        std::u16string_view rTargetURL // target dir without trailing '/'
        )
    {
        bool bPopPossible(false);

        // process files
        for (const auto& file : rFiles)
        {
            bPopPossible |= isPopPossible_file(
                rSourceURL,
                rTargetURL,
                file.first,
                file.second);
        }

        // process dirs
        for (const auto& dir : rDirs)
        {
            OUString aNewSourceURL(OUString::Concat(rSourceURL) + "/" + dir);
            OUString aNewTargetURL(OUString::Concat(rTargetURL) + "/" + dir);
            std::set< OUString > aNewDirs;
            std::set< std::pair< OUString, OUString > > aNewFiles;

            DirectoryHelper::scanDirsAndFiles(
                aNewSourceURL,
                aNewDirs,
                aNewFiles);

            if (!aNewDirs.empty() || !aNewFiles.empty())
            {
                bPopPossible |= isPopPossible_files(
                    aNewDirs,
                    aNewFiles,
                    aNewSourceURL,
                    aNewTargetURL);
            }
        }

        return bPopPossible;
    }

    bool BackupFileHelper::isPopPossible_file(
        std::u16string_view rSourceURL, // source dir without trailing '/'
        std::u16string_view rTargetURL, // target dir without trailing '/'
        std::u16string_view rName,  // filename
        std::u16string_view rExt    // extension (or empty)
        )
    {
        const OUString aFileURL(createFileURL(rSourceURL, rName, rExt));

        if (DirectoryHelper::fileExists(aFileURL))
        {
            const OUString aPackURL(createPackURL(rTargetURL, rName));
            PackedFile aPackedFile(aPackURL);

            return !aPackedFile.empty();
        }

        return false;
    }

    /////////////////// file pop helpers ///////////////////////

    bool BackupFileHelper::tryPop_files(
        const std::set< OUString >& rDirs,
        const std::set< std::pair< OUString, OUString > >& rFiles,
        std::u16string_view rSourceURL, // source dir without trailing '/'
        const OUString& rTargetURL  // target dir without trailing '/'
        )
    {
        bool bDidPop(false);

        // process files
        for (const auto& file : rFiles)
        {
            bDidPop |= tryPop_file(
                rSourceURL,
                rTargetURL,
                file.first,
                file.second);
        }

        // process dirs
        for (const auto& dir : rDirs)
        {
            OUString aNewSourceURL(OUString::Concat(rSourceURL) + "/" + dir);
            OUString aNewTargetURL(rTargetURL + "/" + dir);
            std::set< OUString > aNewDirs;
            std::set< std::pair< OUString, OUString > > aNewFiles;

            DirectoryHelper::scanDirsAndFiles(
                aNewSourceURL,
                aNewDirs,
                aNewFiles);

            if (!aNewDirs.empty() || !aNewFiles.empty())
            {
                bDidPop |= tryPop_files(
                    aNewDirs,
                    aNewFiles,
                    aNewSourceURL,
                    aNewTargetURL);
            }
        }

        if (bDidPop)
        {
            // try removal of evtl. empty directory
            osl::Directory::remove(rTargetURL);
        }

        return bDidPop;
    }

    bool BackupFileHelper::tryPop_file(
        std::u16string_view rSourceURL, // source dir without trailing '/'
        std::u16string_view rTargetURL, // target dir without trailing '/'
        std::u16string_view rName,  // filename
        std::u16string_view rExt    // extension (or empty)
        )
    {
        const OUString aFileURL(createFileURL(rSourceURL, rName, rExt));

        if (!DirectoryHelper::fileExists(aFileURL))
            return false;

        // try Pop for base file
        const OUString aPackURL(createPackURL(rTargetURL, rName));
        PackedFile aPackedFile(aPackURL);

        if (aPackedFile.empty())
            return false;

        oslFileHandle aHandle;
        OUString aTempURL;

        // open target temp file - it exists until deleted
        if (osl::File::E_None != osl::FileBase::createTempFile(nullptr, &aHandle, &aTempURL))
            return false;

        bool bRetval(aPackedFile.tryPop(aHandle));

        // close temp file (in all cases) - it exists until deleted
        osl_closeFile(aHandle);

        if (bRetval)
        {
            // copy over existing file by first deleting original
            // and moving the temp file to old original
            osl::File::remove(aFileURL);
            osl::File::move(aTempURL, aFileURL);

            // reduce to allowed number and flush
            aPackedFile.tryReduceToNumBackups(mnNumBackups);
            aPackedFile.flush();
        }

        // delete temp file (in all cases - it may be moved already)
        osl::File::remove(aTempURL);

        return bRetval;
    }

    /////////////////// ExtensionInfo helpers ///////////////////////

    bool BackupFileHelper::tryPush_extensionInfo(
        std::u16string_view rTargetURL // target dir without trailing '/'
        )
    {
        ExtensionInfo aExtensionInfo;
        OUString aTempURL;
        bool bRetval(false);

        // create current configuration and write to temp file - it exists until deleted
        if (aExtensionInfo.createTempFile(aTempURL))
        {
            const OUString aPackURL(createPackURL(rTargetURL, u"ExtensionInfo"));
            PackedFile aPackedFile(aPackURL);
            FileSharedPtr aBaseFile = std::make_shared<osl::File>(aTempURL);

            if (aPackedFile.tryPush(aBaseFile, mbCompress))
            {
                // reduce to allowed number and flush
                aPackedFile.tryReduceToNumBackups(mnNumBackups);
                aPackedFile.flush();
                bRetval = true;
            }
        }

        // delete temp file (in all cases)
        osl::File::remove(aTempURL);
        return bRetval;
    }

    bool BackupFileHelper::isPopPossible_extensionInfo(
        std::u16string_view rTargetURL // target dir without trailing '/'
        )
    {
        // extensionInfo always exists internally, no test needed
        const OUString aPackURL(createPackURL(rTargetURL, u"ExtensionInfo"));
        PackedFile aPackedFile(aPackURL);

        return !aPackedFile.empty();
    }

    bool BackupFileHelper::tryPop_extensionInfo(
        std::u16string_view rTargetURL // target dir without trailing '/'
        )
    {
        // extensionInfo always exists internally, no test needed
        const OUString aPackURL(createPackURL(rTargetURL, u"ExtensionInfo"));
        PackedFile aPackedFile(aPackURL);

        if (aPackedFile.empty())
            return false;

        oslFileHandle aHandle;
        OUString aTempURL;

        // open target temp file - it exists until deleted
        if (osl::File::E_None != osl::FileBase::createTempFile(nullptr, &aHandle, &aTempURL))
            return false;

        bool bRetval(aPackedFile.tryPop(aHandle));

        // close temp file (in all cases) - it exists until deleted
        osl_closeFile(aHandle);

        if (bRetval)
        {
            // last config is in temp file, load it to ExtensionInfo
            ExtensionInfo aLoadedExtensionInfo;
            FileSharedPtr aBaseFile = std::make_shared<osl::File>(aTempURL);

            if (osl::File::E_None == aBaseFile->open(osl_File_OpenFlag_Read))
            {
                if (aLoadedExtensionInfo.read_entries(aBaseFile))
                {
                    // get current extension info, but from XML config files
                    ExtensionInfo aCurrentExtensionInfo;

                    aCurrentExtensionInfo.createUserExtensionRegistryEntriesFromXML(maUserConfigWorkURL);

                    // now we have loaded last_working (aLoadedExtensionInfo) and
                    // current (aCurrentExtensionInfo) ExtensionInfo and may react on
                    // differences by de/activating these as needed
                    const ExtensionInfoEntryVector& aUserEntries = aCurrentExtensionInfo.getExtensionInfoEntryVector();
                    const ExtensionInfoEntryVector& rLoadedVector = aLoadedExtensionInfo.getExtensionInfoEntryVector();
                    ExtensionInfoEntryVector aToBeDisabled;
                    ExtensionInfoEntryVector aToBeEnabled;

                    for (const auto& rCurrentInfo : aUserEntries)
                    {
                        const ExtensionInfoEntry* pLoadedInfo = nullptr;

                        for (const auto& rLoadedInfo : rLoadedVector)
                        {
                            if (rCurrentInfo.isSameExtension(rLoadedInfo))
                            {
                                pLoadedInfo = &rLoadedInfo;
                                break;
                            }
                        }

                        if (nullptr != pLoadedInfo)
                        {
                            // loaded info contains information about the Extension rCurrentInfo
                            const bool bCurrentEnabled(rCurrentInfo.isEnabled());
                            const bool bLoadedEnabled(pLoadedInfo->isEnabled());

                            if (bCurrentEnabled && !bLoadedEnabled)
                            {
                                aToBeDisabled.push_back(rCurrentInfo);
                            }
                            else if (!bCurrentEnabled && bLoadedEnabled)
                            {
                                aToBeEnabled.push_back(rCurrentInfo);
                            }
                        }
                        else
                        {
                            // There is no loaded info about the Extension rCurrentInfo.
                            // It needs to be disabled
                            if (rCurrentInfo.isEnabled())
                            {
                                aToBeDisabled.push_back(rCurrentInfo);
                            }
                        }
                    }

                    if (!aToBeDisabled.empty() || !aToBeEnabled.empty())
                    {
                        ExtensionInfo::changeEnableDisableStateInXML(maUserConfigWorkURL, aToBeEnabled, aToBeDisabled);
                    }

                    bRetval = true;
                }
            }

            // reduce to allowed number and flush
            aPackedFile.tryReduceToNumBackups(mnNumBackups);
            aPackedFile.flush();
        }

        // delete temp file (in all cases - it may be moved already)
        osl::File::remove(aTempURL);

        return bRetval;
    }

    /////////////////// FileDirInfo helpers ///////////////////////

    void BackupFileHelper::fillDirFileInfo()
    {
        if (!maDirs.empty() || !maFiles.empty())
        {
            // already done
            return;
        }

        // Information about the configuration and the role/purpose of directories in
        // the UserConfiguration is taken from: https://wiki.documentfoundation.org/UserProfile

        // fill dir and file info list to work with dependent on work mode
        switch (mnMode)
        {
        case 0:
        {
            // simple mode: add just registrymodifications
            // (the orig file in maInitialBaseURL)
            maFiles.insert(std::pair< OUString, OUString >(maRegModName, maExt));
            break;
        }
        case 1:
        {
            // defined mode: Add a selection of dirs containing User-Defined and thus
            // valuable configuration information.
            // This is clearly discussable in every single point and may be adapted/corrected
            // over time. Main focus is to secure User-Defined/adapted values

            // add registrymodifications (the orig file in maInitialBaseURL)
            maFiles.insert(std::pair< OUString, OUString >(maRegModName, maExt));

            // User-defined substitution table (Tools/AutoCorrect)
            maDirs.insert("autocorr");

            // User-Defined AutoText (Edit/AutoText)
            maDirs.insert("autotext");

            // User-defined Macros
            maDirs.insert("basic");

            // User-adapted toolbars for modules
            maDirs.insert("config");

            // Initial and User-defined Databases
            maDirs.insert("database");

            // most part of registry files
            maDirs.insert("registry");

            // User-Defined Scripts
            maDirs.insert("Scripts");

            // Template files
            maDirs.insert("template");

            // Custom Dictionaries
            maDirs.insert("wordbook");

            // Questionable - where and how is Extension stuff held and how
            // does this interact with enabled/disabled states which are extra handled?
            // Keep out of business until deeper evaluated
            //
            // maDirs.insert("extensions");
            // maDirs.insert("uno-packages");
            break;
        }
        case 2:
        {
            // whole directory. To do so, scan directory and exclude some dirs
            // from which we know they do not need to be secured explicitly. This
            // should already include registrymodifications, too.
            DirectoryHelper::scanDirsAndFiles(
                maUserConfigWorkURL,
                maDirs,
                maFiles);

            // should not exist, but for the case an error occurred and it got
            // copied somehow, avoid further recursive copying/saving
            maDirs.erase("SafeMode");

            // not really needed, can be abandoned
            maDirs.erase("psprint");

            // not really needed, can be abandoned
            maDirs.erase("store");

            // not really needed, can be abandoned
            maDirs.erase("temp");

            // exclude own backup dir to avoid recursion
            maDirs.erase("pack");

            break;
        }
        }
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */