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
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
/*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <config_features.h>
#ifdef UNX
#include <sys/stat.h>
#endif
#include <sfx2/docfile.hxx>
#include <sfx2/signaturestate.hxx>
#include <com/sun/star/task/InteractionHandler.hpp>
#include <com/sun/star/task/XStatusIndicator.hpp>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/ucb/XContent.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/container/XChild.hpp>
#include <com/sun/star/document/XDocumentRevisionListPersistence.hpp>
#include <com/sun/star/document/LockedDocumentRequest.hpp>
#include <com/sun/star/document/LockedOnSavingRequest.hpp>
#include <com/sun/star/document/OwnLockOnDocumentRequest.hpp>
#include <com/sun/star/document/LockFileIgnoreRequest.hpp>
#include <com/sun/star/document/LockFileCorruptRequest.hpp>
#include <com/sun/star/document/ChangedByOthersRequest.hpp>
#include <com/sun/star/document/ReloadEditableRequest.hpp>
#include <com/sun/star/embed/XTransactedObject.hpp>
#include <com/sun/star/embed/ElementModes.hpp>
#include <com/sun/star/embed/UseBackupException.hpp>
#include <com/sun/star/embed/XOptimizedStorage.hpp>
#include <com/sun/star/frame/Desktop.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/frame/XTerminateListener.hpp>
#include <com/sun/star/graphic/XGraphic.hpp>
#include <com/sun/star/ucb/ContentCreationException.hpp>
#include <com/sun/star/ucb/InteractiveIOException.hpp>
#include <com/sun/star/ucb/CommandFailedException.hpp>
#include <com/sun/star/ucb/CommandAbortedException.hpp>
#include <com/sun/star/ucb/InteractiveLockingLockedException.hpp>
#include <com/sun/star/ucb/InteractiveNetworkReadException.hpp>
#include <com/sun/star/ucb/InteractiveNetworkWriteException.hpp>
#include <com/sun/star/ucb/Lock.hpp>
#include <com/sun/star/ucb/NameClashException.hpp>
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#include <com/sun/star/ucb/XProgressHandler.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XTruncate.hpp>
#include <com/sun/star/io/XSeekable.hpp>
#include <com/sun/star/io/TempFile.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/ucb/InsertCommandArgument.hpp>
#include <com/sun/star/ucb/NameClash.hpp>
#include <com/sun/star/util/XModifiable.hpp>
#include <com/sun/star/beans/NamedValue.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/security/DocumentDigitalSignatures.hpp>
#include <com/sun/star/security/XCertificate.hpp>
#include <tools/urlobj.hxx>
#include <tools/fileutil.hxx>
#include <unotools/configmgr.hxx>
#include <unotools/tempfile.hxx>
#include <comphelper/fileurl.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/propertyvalue.hxx>
#include <comphelper/interaction.hxx>
#include <comphelper/sequence.hxx>
#include <comphelper/simplefileaccessinteraction.hxx>
#include <comphelper/string.hxx>
#include <framework/interaction.hxx>
#include <utility>
#include <svl/stritem.hxx>
#include <svl/eitem.hxx>
#include <svtools/sfxecode.hxx>
#include <svl/itemset.hxx>
#include <svl/intitem.hxx>
#include <svtools/svparser.hxx>
#include <sal/log.hxx>
#include <unotools/streamwrap.hxx>
#include <osl/file.hxx>
#include <comphelper/storagehelper.hxx>
#include <unotools/mediadescriptor.hxx>
#include <comphelper/docpasswordhelper.hxx>
#include <tools/datetime.hxx>
#include <unotools/pathoptions.hxx>
#include <svtools/asynclink.hxx>
#include <ucbhelper/commandenvironment.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <unotools/ucbhelper.hxx>
#include <unotools/progresshandlerwrap.hxx>
#include <ucbhelper/content.hxx>
#include <ucbhelper/interactionrequest.hxx>
#include <sot/storage.hxx>
#include <svl/documentlockfile.hxx>
#include <svl/msodocumentlockfile.hxx>
#include <com/sun/star/document/DocumentRevisionListPersistence.hpp>
#include <sfx2/app.hxx>
#include <sfx2/frame.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/fcontnr.hxx>
#include <sfx2/docfilt.hxx>
#include <sfx2/sfxsids.hrc>
#include <sfx2/sfxuno.hxx>
#include <openflag.hxx>
#include <officecfg/Office/Common.hxx>
#include <comphelper/propertysequence.hxx>
#include <vcl/weld.hxx>
#include <vcl/svapp.hxx>
#include <comphelper/diagnose_ex.hxx>
#include <unotools/fltrcfg.hxx>
#include <sfx2/digitalsignatures.hxx>
#include <sfx2/viewfrm.hxx>
#include <comphelper/threadpool.hxx>
#include <o3tl/string_view.hxx>
#include <condition_variable>
#include <com/sun/star/io/WrongFormatException.hpp>
#include <memory>
using namespace ::com::sun::star;
using namespace ::com::sun::star::graphic;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::security;
namespace
{
struct ReadOnlyMediumEntry
{
ReadOnlyMediumEntry(std::shared_ptr<std::recursive_mutex> pMutex,
std::shared_ptr<bool> pIsDestructed)
: _pMutex(std::move(pMutex))
, _pIsDestructed(std::move(pIsDestructed))
{
}
std::shared_ptr<std::recursive_mutex> _pMutex;
std::shared_ptr<bool> _pIsDestructed;
};
}
static std::mutex g_chkReadOnlyGlobalMutex;
static bool g_bChkReadOnlyTaskRunning = false;
static std::unordered_map<SfxMedium*, std::shared_ptr<ReadOnlyMediumEntry>> g_newReadOnlyDocs;
static std::unordered_map<SfxMedium*, std::shared_ptr<ReadOnlyMediumEntry>> g_existingReadOnlyDocs;
namespace {
#if HAVE_FEATURE_MULTIUSER_ENVIRONMENT
bool IsSystemFileLockingUsed()
{
#if HAVE_FEATURE_MACOSX_SANDBOX
return true;
#else
return officecfg::Office::Common::Misc::UseDocumentSystemFileLocking::get();
#endif
}
bool IsOOoLockFileUsed()
{
#if HAVE_FEATURE_MACOSX_SANDBOX
return false;
#else
return officecfg::Office::Common::Misc::UseDocumentOOoLockFile::get();
#endif
}
bool IsLockingUsed()
{
return officecfg::Office::Common::Misc::UseLocking::get();
}
#endif
#if HAVE_FEATURE_MULTIUSER_ENVIRONMENT
bool IsWebDAVLockingUsed()
{
return officecfg::Office::Common::Misc::UseWebDAVFileLocking::get();
}
#endif
/// Gets default attributes of a file:// URL.
sal_uInt64 GetDefaultFileAttributes(const OUString& rURL)
{
sal_uInt64 nRet = 0;
if (!comphelper::isFileUrl(rURL))
return nRet;
// Make sure the file exists (and create it if not).
osl::File aFile(rURL);
osl::File::RC nRes = aFile.open(osl_File_OpenFlag_Create);
if (nRes != osl::File::E_None && nRes != osl::File::E_EXIST)
return nRet;
aFile.close();
osl::DirectoryItem aItem;
if (osl::DirectoryItem::get(rURL, aItem) != osl::DirectoryItem::E_None)
return nRet;
osl::FileStatus aStatus(osl_FileStatus_Mask_Attributes);
if (aItem.getFileStatus(aStatus) != osl::DirectoryItem::E_None)
return nRet;
nRet = aStatus.getAttributes();
return nRet;
}
/// Determines if rURL is safe to move or not.
bool IsFileMovable(const INetURLObject& rURL)
{
#ifdef MACOSX
(void)rURL;
// Hide extension macOS-specific file property would be lost.
return false;
#else
if (rURL.GetProtocol() != INetProtocol::File)
// Not a file:// URL.
return false;
#ifdef UNX
OUString sPath = rURL.getFSysPath(FSysStyle::Unix);
if (sPath.isEmpty())
return false;
struct stat buf;
if (lstat(sPath.toUtf8().getStr(), &buf) != 0)
return false;
// Hardlink or symlink: osl::File::move() doesn't play with these nicely.
if (buf.st_nlink > 1 || S_ISLNK(buf.st_mode))
return false;
#elif defined _WIN32
if (tools::IsMappedWebDAVPath(rURL.GetMainURL(INetURLObject::DecodeMechanism::NONE)))
return false;
#endif
return true;
#endif
}
class CheckReadOnlyTaskTerminateListener
: public ::cppu::WeakImplHelper<css::frame::XTerminateListener>
{
public:
// XEventListener
void SAL_CALL disposing(const css::lang::EventObject& Source) override;
// XTerminateListener
void SAL_CALL queryTermination(const css::lang::EventObject& aEvent) override;
void SAL_CALL notifyTermination(const css::lang::EventObject& aEvent) override;
bool bIsTerminated = false;
std::condition_variable mCond;
std::mutex mMutex;
};
class CheckReadOnlyTask : public comphelper::ThreadTask
{
public:
CheckReadOnlyTask(const std::shared_ptr<comphelper::ThreadTaskTag>& pTag);
~CheckReadOnlyTask();
virtual void doWork() override;
private:
rtl::Reference<CheckReadOnlyTaskTerminateListener> m_xListener;
};
} // anonymous namespace
CheckReadOnlyTask::CheckReadOnlyTask(const std::shared_ptr<comphelper::ThreadTaskTag>& pTag)
: ThreadTask(pTag)
, m_xListener(new CheckReadOnlyTaskTerminateListener)
{
Reference<css::frame::XDesktop> xDesktop
= css::frame::Desktop::create(comphelper::getProcessComponentContext());
if (xDesktop.is() && m_xListener != nullptr)
{
xDesktop->addTerminateListener(m_xListener);
}
}
CheckReadOnlyTask::~CheckReadOnlyTask()
{
Reference<css::frame::XDesktop> xDesktop
= css::frame::Desktop::create(comphelper::getProcessComponentContext());
if (xDesktop.is() && m_xListener != nullptr)
{
std::unique_lock<std::mutex> lock(m_xListener->mMutex);
if (!m_xListener->bIsTerminated)
{
lock.unlock();
xDesktop->removeTerminateListener(m_xListener);
}
}
}
namespace
{
void SAL_CALL
CheckReadOnlyTaskTerminateListener::disposing(const css::lang::EventObject& /*Source*/)
{
}
void SAL_CALL
CheckReadOnlyTaskTerminateListener::queryTermination(const css::lang::EventObject& /*aEvent*/)
{
}
void SAL_CALL
CheckReadOnlyTaskTerminateListener::notifyTermination(const css::lang::EventObject& /*aEvent*/)
{
std::unique_lock<std::mutex> lock(mMutex);
bIsTerminated = true;
lock.unlock();
mCond.notify_one();
}
}
class SfxMedium_Impl
{
public:
StreamMode m_nStorOpenMode;
ErrCodeMsg m_eError;
ErrCodeMsg m_eWarningError;
::ucbhelper::Content aContent;
bool bUpdatePickList:1;
bool bIsTemp:1;
bool bDownloadDone:1;
bool bIsStorage:1;
bool bUseInteractionHandler:1;
bool bAllowDefaultIntHdl:1;
bool bDisposeStorage:1;
bool bStorageBasedOnInStream:1;
bool m_bSalvageMode:1;
bool m_bVersionsAlreadyLoaded:1;
bool m_bLocked:1;
bool m_bMSOLockFileCreated : 1;
bool m_bDisableUnlockWebDAV:1;
bool m_bGotDateTime:1;
bool m_bRemoveBackup:1;
bool m_bOriginallyReadOnly:1;
bool m_bOriginallyLoadedReadOnly:1;
bool m_bTriedStorage:1;
bool m_bRemote:1;
bool m_bInputStreamIsReadOnly:1;
bool m_bInCheckIn:1;
bool m_bDisableFileSync = false;
bool m_bNotifyWhenEditable = false;
/// if true, xStorage is an inner package and not directly from xStream
bool m_bODFWholesomeEncryption = false;
OUString m_aName;
OUString m_aLogicName;
OUString m_aLongName;
mutable std::shared_ptr<SfxItemSet> m_pSet;
mutable std::unique_ptr<INetURLObject> m_pURLObj;
std::shared_ptr<const SfxFilter> m_pFilter;
std::shared_ptr<const SfxFilter> m_pCustomFilter;
std::shared_ptr<std::recursive_mutex> m_pCheckEditableWorkerMutex;
std::shared_ptr<bool> m_pIsDestructed;
ImplSVEvent* m_pReloadEvent;
std::unique_ptr<SvStream> m_pInStream;
std::unique_ptr<SvStream> m_pOutStream;
OUString aOrigURL;
DateTime aExpireTime;
SfxFrameWeakRef wLoadTargetFrame;
SvKeyValueIteratorRef xAttributes;
svtools::AsynchronLink aDoneLink;
uno::Sequence < util::RevisionTag > aVersions;
std::unique_ptr<::utl::TempFileNamed> pTempFile;
uno::Reference<embed::XStorage> xStorage;
uno::Reference<embed::XStorage> m_xZipStorage;
uno::Reference<io::XInputStream> m_xInputStreamToLoadFrom;
uno::Reference<io::XInputStream> xInputStream;
uno::Reference<io::XStream> xStream;
uno::Reference<io::XStream> m_xLockingStream;
uno::Reference<task::XInteractionHandler> xInteraction;
uno::Reference<io::XStream> m_xODFDecryptedInnerPackageStream;
uno::Reference<embed::XStorage> m_xODFEncryptedOuterStorage;
uno::Reference<embed::XStorage> m_xODFDecryptedInnerZipStorage;
ErrCodeMsg nLastStorageError;
OUString m_aBackupURL;
// the following member is changed and makes sense only during saving
// TODO/LATER: in future the signature state should be controlled by the medium not by the document
// in this case the member will hold this information
SignatureState m_nSignatureState;
bool m_bHasEmbeddedObjects = false;
util::DateTime m_aDateTime;
uno::Sequence<beans::PropertyValue> m_aArgs;
explicit SfxMedium_Impl();
~SfxMedium_Impl();
SfxMedium_Impl(const SfxMedium_Impl&) = delete;
SfxMedium_Impl& operator=(const SfxMedium_Impl&) = delete;
OUString getFilterMimeType() const
{ return !m_pFilter ? OUString() : m_pFilter->GetMimeType(); }
};
SfxMedium_Impl::SfxMedium_Impl() :
m_nStorOpenMode(SFX_STREAM_READWRITE),
m_eError(ERRCODE_NONE),
m_eWarningError(ERRCODE_NONE),
bUpdatePickList(true),
bIsTemp( false ),
bDownloadDone( true ),
bIsStorage( false ),
bUseInteractionHandler( true ),
bAllowDefaultIntHdl( false ),
bDisposeStorage( false ),
bStorageBasedOnInStream( false ),
m_bSalvageMode( false ),
m_bVersionsAlreadyLoaded( false ),
m_bLocked( false ),
m_bMSOLockFileCreated( false ),
m_bDisableUnlockWebDAV( false ),
m_bGotDateTime( false ),
m_bRemoveBackup( false ),
m_bOriginallyReadOnly(false),
m_bOriginallyLoadedReadOnly(false),
m_bTriedStorage(false),
m_bRemote(false),
m_bInputStreamIsReadOnly(false),
m_bInCheckIn(false),
m_pReloadEvent(nullptr),
aExpireTime( DateTime( DateTime::SYSTEM ) + static_cast<sal_Int32>(10) ),
nLastStorageError( ERRCODE_NONE ),
m_nSignatureState( SignatureState::NOSIGNATURES )
{
}
SfxMedium_Impl::~SfxMedium_Impl()
{
aDoneLink.ClearPendingCall();
pTempFile.reset();
m_pSet.reset();
std::unique_lock<std::recursive_mutex> chkEditLock;
if (m_pCheckEditableWorkerMutex != nullptr)
chkEditLock = std::unique_lock<std::recursive_mutex>(*m_pCheckEditableWorkerMutex);
m_pURLObj.reset();
}
void SfxMedium::ResetError()
{
pImpl->m_eError = ERRCODE_NONE;
if( pImpl->m_pInStream )
pImpl->m_pInStream->ResetError();
if( pImpl->m_pOutStream )
pImpl->m_pOutStream->ResetError();
}
ErrCodeMsg const & SfxMedium::GetWarningError() const
{
return pImpl->m_eWarningError;
}
ErrCodeMsg const & SfxMedium::GetLastStorageCreationState() const
{
return pImpl->nLastStorageError;
}
void SfxMedium::SetError(ErrCodeMsg nError)
{
pImpl->m_eError = nError;
}
void SfxMedium::SetWarningError(const ErrCodeMsg& nWarningError)
{
pImpl->m_eWarningError = nWarningError;
}
ErrCodeMsg SfxMedium::GetErrorCode() const
{
ErrCodeMsg lError = pImpl->m_eError;
if(!lError && pImpl->m_pInStream)
lError = pImpl->m_pInStream->GetErrorCode();
if(!lError && pImpl->m_pOutStream)
lError = pImpl->m_pOutStream->GetErrorCode();
return lError;
}
void SfxMedium::CheckFileDate( const util::DateTime& aInitDate )
{
GetInitFileDate( true );
if ( pImpl->m_aDateTime.Seconds == aInitDate.Seconds
&& pImpl->m_aDateTime.Minutes == aInitDate.Minutes
&& pImpl->m_aDateTime.Hours == aInitDate.Hours
&& pImpl->m_aDateTime.Day == aInitDate.Day
&& pImpl->m_aDateTime.Month == aInitDate.Month
&& pImpl->m_aDateTime.Year == aInitDate.Year )
return;
uno::Reference< task::XInteractionHandler > xHandler = GetInteractionHandler();
if ( !xHandler.is() )
return;
try
{
::rtl::Reference< ::ucbhelper::InteractionRequest > xInteractionRequestImpl = new ::ucbhelper::InteractionRequest( uno::Any(
document::ChangedByOthersRequest() ) );
uno::Sequence< uno::Reference< task::XInteractionContinuation > > aContinuations{
new ::ucbhelper::InteractionAbort( xInteractionRequestImpl.get() ),
new ::ucbhelper::InteractionApprove( xInteractionRequestImpl.get() )
};
xInteractionRequestImpl->setContinuations( aContinuations );
xHandler->handle( xInteractionRequestImpl );
::rtl::Reference< ::ucbhelper::InteractionContinuation > xSelected = xInteractionRequestImpl->getSelection();
if ( uno::Reference< task::XInteractionAbort >( xSelected.get(), uno::UNO_QUERY ).is() )
{
SetError(ERRCODE_ABORT);
}
}
catch ( const uno::Exception& )
{}
}
bool SfxMedium::DocNeedsFileDateCheck() const
{
return ( !IsReadOnly() && ( GetURLObject().GetProtocol() == INetProtocol::File ||
GetURLObject().isAnyKnownWebDAVScheme() ) );
}
util::DateTime const & SfxMedium::GetInitFileDate( bool bIgnoreOldValue )
{
if ( ( bIgnoreOldValue || !pImpl->m_bGotDateTime ) && !pImpl->m_aLogicName.isEmpty() )
{
try
{
// add a default css::ucb::XCommandEnvironment
// in order to have the WebDAV UCP provider manage http/https authentication correctly
::ucbhelper::Content aContent( GetURLObject().GetMainURL( INetURLObject::DecodeMechanism::NONE ),
utl::UCBContentHelper::getDefaultCommandEnvironment(),
comphelper::getProcessComponentContext() );
aContent.getPropertyValue("DateModified") >>= pImpl->m_aDateTime;
pImpl->m_bGotDateTime = true;
}
catch ( const css::uno::Exception& )
{
}
}
return pImpl->m_aDateTime;
}
Reference < XContent > SfxMedium::GetContent() const
{
if ( !pImpl->aContent.get().is() )
{
Reference < css::ucb::XContent > xContent;
// tdf#95144 add a default css::ucb::XCommandEnvironment
// in order to have the WebDAV UCP provider manage https protocol certificates correctly
css:: uno::Reference< task::XInteractionHandler > xIH(
css::task::InteractionHandler::createWithParent( comphelper::getProcessComponentContext(), nullptr ) );
css::uno::Reference< css::ucb::XProgressHandler > xProgress;
rtl::Reference<::ucbhelper::CommandEnvironment> pCommandEnv = new ::ucbhelper::CommandEnvironment( new comphelper::SimpleFileAccessInteraction( xIH ), xProgress );
const SfxUnoAnyItem* pItem = SfxItemSet::GetItem<SfxUnoAnyItem>(pImpl->m_pSet.get(), SID_CONTENT, false);
if ( pItem )
pItem->GetValue() >>= xContent;
if ( xContent.is() )
{
try
{
pImpl->aContent = ::ucbhelper::Content( xContent, pCommandEnv, comphelper::getProcessComponentContext() );
}
catch ( const Exception& )
{
}
}
else
{
// TODO: SAL_WARN( "sfx.doc", "SfxMedium::GetContent()\nCreate Content? This code exists as fallback only. Please clarify, why it's used.");
OUString aURL;
if ( !pImpl->m_aName.isEmpty() )
osl::FileBase::getFileURLFromSystemPath( pImpl->m_aName, aURL );
else if ( !pImpl->m_aLogicName.isEmpty() )
aURL = GetURLObject().GetMainURL( INetURLObject::DecodeMechanism::NONE );
if (!aURL.isEmpty() )
(void)::ucbhelper::Content::create( aURL, pCommandEnv, comphelper::getProcessComponentContext(), pImpl->aContent );
}
}
return pImpl->aContent.get();
}
OUString SfxMedium::GetBaseURL( bool bForSaving )
{
if (bForSaving)
{
bool bIsRemote = IsRemote();
if ((bIsRemote && !officecfg::Office::Common::Save::URL::Internet::get())
|| (!bIsRemote && !officecfg::Office::Common::Save::URL::FileSystem::get()))
return OUString();
}
if (const SfxStringItem* pBaseURLItem = GetItemSet().GetItem<SfxStringItem>(SID_DOC_BASEURL))
return pBaseURLItem->GetValue();
OUString aBaseURL;
if (!utl::ConfigManager::IsFuzzing() && GetContent().is())
{
try
{
Any aAny = pImpl->aContent.getPropertyValue("BaseURI");
aAny >>= aBaseURL;
}
catch ( const css::uno::Exception& )
{
}
if ( aBaseURL.isEmpty() )
aBaseURL = GetURLObject().GetMainURL( INetURLObject::DecodeMechanism::NONE );
}
return aBaseURL;
}
bool SfxMedium::IsSkipImages() const
{
const SfxStringItem* pSkipImagesItem = GetItemSet().GetItem<SfxStringItem>(SID_FILE_FILTEROPTIONS);
return pSkipImagesItem && pSkipImagesItem->GetValue() == "SkipImages";
}
SvStream* SfxMedium::GetInStream()
{
if ( pImpl->m_pInStream )
return pImpl->m_pInStream.get();
if ( pImpl->pTempFile )
{
pImpl->m_pInStream.reset( new SvFileStream(pImpl->m_aName, pImpl->m_nStorOpenMode) );
pImpl->m_eError = pImpl->m_pInStream->GetError();
if (!pImpl->m_eError && (pImpl->m_nStorOpenMode & StreamMode::WRITE)
&& ! pImpl->m_pInStream->IsWritable() )
{
pImpl->m_eError = ERRCODE_IO_ACCESSDENIED;
pImpl->m_pInStream.reset();
}
else
return pImpl->m_pInStream.get();
}
GetMedium_Impl();
if ( GetErrorIgnoreWarning() )
return nullptr;
return pImpl->m_pInStream.get();
}
void SfxMedium::CloseInStream()
{
CloseInStream_Impl();
}
void SfxMedium::CloseInStream_Impl(bool bInDestruction)
{
// if there is a storage based on the InStream, we have to
// close the storage, too, because otherwise the storage
// would use an invalid ( deleted ) stream.
if ( pImpl->m_pInStream && pImpl->xStorage.is() )
{
if ( pImpl->bStorageBasedOnInStream )
CloseStorage();
}
if ( pImpl->m_pInStream && !GetContent().is() && !bInDestruction )
{
CreateTempFile();
return;
}
pImpl->m_pInStream.reset();
if ( pImpl->m_pSet )
pImpl->m_pSet->ClearItem( SID_INPUTSTREAM );
CloseZipStorage_Impl();
pImpl->xInputStream.clear();
if ( !pImpl->m_pOutStream )
{
// output part of the stream is not used so the whole stream can be closed
// TODO/LATER: is it correct?
pImpl->xStream.clear();
if ( pImpl->m_pSet )
pImpl->m_pSet->ClearItem( SID_STREAM );
}
}
SvStream* SfxMedium::GetOutStream()
{
if ( !pImpl->m_pOutStream )
{
// Create a temp. file if there is none because we always
// need one.
CreateTempFile( false );
if ( pImpl->pTempFile )
{
// On windows we try to re-use XOutStream from xStream if that exists;
// because opening new SvFileStream in this situation may fail with ERROR_SHARING_VIOLATION
// TODO: this is a horrible hack that should probably be removed,
// somebody needs to investigate this more thoroughly...
if (getenv("SFX_MEDIUM_REUSE_STREAM") && pImpl->xStream.is())
{
assert(pImpl->xStream->getOutputStream().is()); // need that...
pImpl->m_pOutStream = utl::UcbStreamHelper::CreateStream(
pImpl->xStream, false);
}
else
{
// On Unix don't try to re-use XOutStream from xStream if that exists;
// it causes fdo#59022 (fails opening files via SMB on Linux)
pImpl->m_pOutStream.reset( new SvFileStream(
pImpl->m_aName, StreamMode::STD_READWRITE) );
}
CloseStorage();
}
}
return pImpl->m_pOutStream.get();
}
void SfxMedium::CloseOutStream()
{
CloseOutStream_Impl();
}
void SfxMedium::CloseOutStream_Impl()
{
if ( pImpl->m_pOutStream )
{
// if there is a storage based on the OutStream, we have to
// close the storage, too, because otherwise the storage
// would use an invalid ( deleted ) stream.
//TODO/MBA: how to deal with this?!
//maybe we need a new flag when the storage was created from the outstream
if ( pImpl->xStorage.is() )
{
CloseStorage();
}
pImpl->m_pOutStream.reset();
}
if ( !pImpl->m_pInStream )
{
// input part of the stream is not used so the whole stream can be closed
// TODO/LATER: is it correct?
pImpl->xStream.clear();
if ( pImpl->m_pSet )
pImpl->m_pSet->ClearItem( SID_STREAM );
}
}
const OUString& SfxMedium::GetPhysicalName() const
{
if ( pImpl->m_aName.isEmpty() && !pImpl->m_aLogicName.isEmpty() )
const_cast<SfxMedium*>(this)->CreateFileStream();
// return the name then
return pImpl->m_aName;
}
void SfxMedium::CreateFileStream()
{
// force synchron
if( pImpl->m_pInStream )
{
SvLockBytes* pBytes = pImpl->m_pInStream->GetLockBytes();
if( pBytes )
pBytes->SetSynchronMode();
}
GetInStream();
if( pImpl->m_pInStream )
{
CreateTempFile( false );
pImpl->bIsTemp = true;
CloseInStream_Impl();
}
}
bool SfxMedium::Commit()
{
if( pImpl->xStorage.is() )
StorageCommit_Impl();
else if( pImpl->m_pOutStream )
pImpl->m_pOutStream->FlushBuffer();
else if( pImpl->m_pInStream )
pImpl->m_pInStream->FlushBuffer();
if ( GetErrorIgnoreWarning() == ERRCODE_NONE )
{
// does something only in case there is a temporary file ( means aName points to different location than aLogicName )
Transfer_Impl();
}
bool bResult = ( GetErrorIgnoreWarning() == ERRCODE_NONE );
if ( bResult && DocNeedsFileDateCheck() )
GetInitFileDate( true );
// remove truncation mode from the flags
pImpl->m_nStorOpenMode &= ~StreamMode::TRUNC;
return bResult;
}
bool SfxMedium::IsStorage()
{
if ( pImpl->xStorage.is() )
return true;
if ( pImpl->m_bTriedStorage )
return pImpl->bIsStorage;
if ( pImpl->pTempFile )
{
OUString aURL;
if ( osl::FileBase::getFileURLFromSystemPath( pImpl->m_aName, aURL )
!= osl::FileBase::E_None )
{
SAL_WARN( "sfx.doc", "Physical name '" << pImpl->m_aName << "' not convertible to file URL");
}
pImpl->bIsStorage = SotStorage::IsStorageFile( aURL ) && !SotStorage::IsOLEStorage( aURL);
if ( !pImpl->bIsStorage )
pImpl->m_bTriedStorage = true;
}
else if ( GetInStream() )
{
pImpl->bIsStorage = SotStorage::IsStorageFile( pImpl->m_pInStream.get() ) && !SotStorage::IsOLEStorage( pImpl->m_pInStream.get() );
if ( !pImpl->m_pInStream->GetError() && !pImpl->bIsStorage )
pImpl->m_bTriedStorage = true;
}
return pImpl->bIsStorage;
}
bool SfxMedium::IsPreview_Impl() const
{
bool bPreview = false;
const SfxBoolItem* pPreview = GetItemSet().GetItem(SID_PREVIEW, false);
if ( pPreview )
bPreview = pPreview->GetValue();
else
{
const SfxStringItem* pFlags = GetItemSet().GetItem(SID_OPTIONS, false);
if ( pFlags )
{
OUString aFileFlags = pFlags->GetValue();
aFileFlags = aFileFlags.toAsciiUpperCase();
if ( -1 != aFileFlags.indexOf( 'B' ) )
bPreview = true;
}
}
return bPreview;
}
void SfxMedium::StorageBackup_Impl()
{
::ucbhelper::Content aOriginalContent;
Reference< css::ucb::XCommandEnvironment > xDummyEnv;
bool bBasedOnOriginalFile =
!pImpl->pTempFile
&& ( pImpl->m_aLogicName.isEmpty() || !pImpl->m_bSalvageMode )
&& !GetURLObject().GetMainURL( INetURLObject::DecodeMechanism::NONE ).isEmpty()
&& GetURLObject().GetProtocol() == INetProtocol::File
&& ::utl::UCBContentHelper::IsDocument( GetURLObject().GetMainURL( INetURLObject::DecodeMechanism::NONE ) );
if ( bBasedOnOriginalFile && pImpl->m_aBackupURL.isEmpty()
&& ::ucbhelper::Content::create( GetURLObject().GetMainURL( INetURLObject::DecodeMechanism::NONE ), xDummyEnv, comphelper::getProcessComponentContext(), aOriginalContent ) )
{
DoInternalBackup_Impl( aOriginalContent );
if( pImpl->m_aBackupURL.isEmpty() )
SetError(ERRCODE_SFX_CANTCREATEBACKUP);
}
}
OUString const & SfxMedium::GetBackup_Impl()
{
if ( pImpl->m_aBackupURL.isEmpty() )
StorageBackup_Impl();
return pImpl->m_aBackupURL;
}
uno::Reference < embed::XStorage > SfxMedium::GetOutputStorage()
{
if ( GetErrorIgnoreWarning() )
return uno::Reference< embed::XStorage >();
// if the medium was constructed with a Storage: use this one, not a temp. storage
// if a temporary storage already exists: use it
if (pImpl->xStorage.is()
&& (pImpl->m_bODFWholesomeEncryption || pImpl->m_aLogicName.isEmpty() || pImpl->pTempFile))
{
return pImpl->xStorage;
}
// if necessary close stream that was used for reading
if ( pImpl->m_pInStream && !pImpl->m_pInStream->IsWritable() )
CloseInStream();
DBG_ASSERT( !pImpl->m_pOutStream, "OutStream in a readonly Medium?!" );
// TODO/LATER: The current solution is to store the document temporary and then copy it to the target location;
// in future it should be stored directly and then copied to the temporary location, since in this case no
// file attributes have to be preserved and system copying mechanics could be used instead of streaming.
CreateTempFileNoCopy();
return GetStorage();
}
bool SfxMedium::SetEncryptionDataToStorage_Impl()
{
// in case media-descriptor contains password it should be used on opening
if ( !pImpl->xStorage.is() || !pImpl->m_pSet )
return false;
uno::Sequence< beans::NamedValue > aEncryptionData;
if ( !GetEncryptionData_Impl( pImpl->m_pSet.get(), aEncryptionData ) )
return false;
// replace the password with encryption data
pImpl->m_pSet->ClearItem( SID_PASSWORD );
pImpl->m_pSet->Put( SfxUnoAnyItem( SID_ENCRYPTIONDATA, uno::Any( aEncryptionData ) ) );
try
{
::comphelper::OStorageHelper::SetCommonStorageEncryptionData( pImpl->xStorage, aEncryptionData );
}
catch( const uno::Exception& )
{
SAL_WARN( "sfx.doc", "It must be possible to set a common password for the storage" );
SetError(ERRCODE_IO_GENERAL);
return false;
}
return true;
}
#if HAVE_FEATURE_MULTIUSER_ENVIRONMENT
// FIXME: Hmm actually lock files should be used for sftp: documents
// even if !HAVE_FEATURE_MULTIUSER_ENVIRONMENT. Only the use of lock
// files for *local* documents is unnecessary in that case. But
// actually, the checks for sftp: here are just wishful thinking; I
// don't this there is any support for actually editing documents
// behind sftp: URLs anyway.
// Sure, there could perhaps be a 3rd-party extension that brings UCB
// the potential to handle files behind sftp:. But there could also be
// an extension that handles some arbitrary foobar: scheme *and* it
// could be that lock files would be the correct thing to use for
// foobar: documents, too. But the hardcoded test below won't know
// that. Clearly the knowledge whether lock files should be used or
// not for some URL scheme belongs in UCB, not here.
namespace
{
OUString tryMSOwnerFiles(std::u16string_view sDocURL)
{
svt::MSODocumentLockFile aMSOLockFile(sDocURL);
LockFileEntry aData;
try
{
aData = aMSOLockFile.GetLockData();
}
catch( const uno::Exception& )
{
return OUString();
}
OUString sUserData = aData[LockFileComponent::OOOUSERNAME];
if (!sUserData.isEmpty())
sUserData += " (MS Office)"; // Mention the used office suite
return sUserData;
}
OUString tryForeignLockfiles(std::u16string_view sDocURL)
{
OUString sUserData = tryMSOwnerFiles(sDocURL);
// here we can test for empty result, and add other known applications' lockfile testing
return sUserData.trim();
}
}
SfxMedium::ShowLockResult SfxMedium::ShowLockedDocumentDialog(const LockFileEntry& aData,
bool bIsLoading, bool bOwnLock,
bool bHandleSysLocked)
{
ShowLockResult nResult = ShowLockResult::NoLock;
// tdf#92817: Simple check for empty lock file that needs to be deleted, when system locking is enabled
if( aData[LockFileComponent::OOOUSERNAME].isEmpty() && aData[LockFileComponent::SYSUSERNAME].isEmpty() && !bHandleSysLocked )
bOwnLock=true;
// show the interaction regarding the document opening
uno::Reference< task::XInteractionHandler > xHandler = GetInteractionHandler();
if ( xHandler.is() && ( bIsLoading || !bHandleSysLocked || bOwnLock ) )
{
OUString aDocumentURL
= GetURLObject().GetLastName(INetURLObject::DecodeMechanism::WithCharset);
OUString aInfo;
::rtl::Reference< ::ucbhelper::InteractionRequest > xInteractionRequestImpl;
sal_Int32 nContinuations = 3;
if ( bOwnLock )
{
aInfo = aData[LockFileComponent::EDITTIME];
xInteractionRequestImpl = new ::ucbhelper::InteractionRequest( uno::Any(
document::OwnLockOnDocumentRequest( OUString(), uno::Reference< uno::XInterface >(), aDocumentURL, aInfo, !bIsLoading ) ) );
}
else
{
// Use a fourth continuation in case there's no filesystem lock:
// "Ignore lock file and open/replace the document"
if (!bHandleSysLocked)
nContinuations = 4;
if ( !aData[LockFileComponent::OOOUSERNAME].isEmpty() )
aInfo = aData[LockFileComponent::OOOUSERNAME];
else
aInfo = aData[LockFileComponent::SYSUSERNAME];
if (aInfo.isEmpty() && !GetURLObject().isAnyKnownWebDAVScheme())
// Try to get name of user who has locked the file using other applications
aInfo = tryForeignLockfiles(
GetURLObject().GetMainURL(INetURLObject::DecodeMechanism::NONE));
if ( !aInfo.isEmpty() && !aData[LockFileComponent::EDITTIME].isEmpty() )
aInfo += " ( " + aData[LockFileComponent::EDITTIME] + " )";
if (!bIsLoading) // so, !bHandleSysLocked
{
xInteractionRequestImpl = new ::ucbhelper::InteractionRequest(uno::Any(
document::LockedOnSavingRequest(OUString(), uno::Reference< uno::XInterface >(), aDocumentURL, aInfo)));
// Currently, only the last "Retry" continuation (meaning ignore the lock and try overwriting) can be returned.
}
else /*logically therefore bIsLoading is set */
{
xInteractionRequestImpl = new ::ucbhelper::InteractionRequest( uno::Any(
document::LockedDocumentRequest( OUString(), uno::Reference< uno::XInterface >(), aDocumentURL, aInfo ) ) );
}
}
uno::Sequence< uno::Reference< task::XInteractionContinuation > > aContinuations(nContinuations);
auto pContinuations = aContinuations.getArray();
pContinuations[0] = new ::ucbhelper::InteractionAbort( xInteractionRequestImpl.get() );
pContinuations[1] = new ::ucbhelper::InteractionApprove( xInteractionRequestImpl.get() );
pContinuations[2] = new ::ucbhelper::InteractionDisapprove( xInteractionRequestImpl.get() );
if (nContinuations > 3)
{
// We use InteractionRetry to reflect that user wants to
// ignore the (stale?) alien lock file and open/overwrite the document
pContinuations[3] = new ::ucbhelper::InteractionRetry(xInteractionRequestImpl.get());
}
xInteractionRequestImpl->setContinuations( aContinuations );
xHandler->handle( xInteractionRequestImpl );
bool bOpenReadOnly = false;
::rtl::Reference< ::ucbhelper::InteractionContinuation > xSelected = xInteractionRequestImpl->getSelection();
if ( uno::Reference< task::XInteractionAbort >( xSelected.get(), uno::UNO_QUERY ).is() )
{
SetError(ERRCODE_ABORT);
}
else if ( uno::Reference< task::XInteractionDisapprove >( xSelected.get(), uno::UNO_QUERY ).is() )
{
// own lock on loading, user has selected to ignore the lock
// own lock on saving, user has selected to ignore the lock
// alien lock on loading, user has selected to edit a copy of document
// TODO/LATER: alien lock on saving, user has selected to do SaveAs to different location
if ( !bOwnLock ) // bIsLoading implied from outermost condition
{
// means that a copy of the document should be opened
GetItemSet().Put( SfxBoolItem( SID_TEMPLATE, true ) );
}
else
nResult = ShowLockResult::Succeeded;
}
else if (uno::Reference< task::XInteractionRetry >(xSelected.get(), uno::UNO_QUERY).is())
{
// User decided to ignore the alien (stale?) lock file without filesystem lock
nResult = ShowLockResult::Succeeded;
}
else if (uno::Reference< task::XInteractionApprove >( xSelected.get(), uno::UNO_QUERY ).is())
{
bOpenReadOnly = true;
}
else // user selected "Notify"
{
pImpl->m_bNotifyWhenEditable = true;
AddToCheckEditableWorkerList();
bOpenReadOnly = true;
}
if (bOpenReadOnly)
{
// own lock on loading, user has selected to open readonly
// own lock on saving, user has selected to open readonly
// alien lock on loading, user has selected to retry saving
// TODO/LATER: alien lock on saving, user has selected to retry saving
if (bIsLoading)
GetItemSet().Put(SfxBoolItem(SID_DOC_READONLY, true));
else
nResult = ShowLockResult::Try;
}
}
else
{
if ( bIsLoading )
{
// if no interaction handler is provided the default answer is open readonly
// that usually happens in case the document is loaded per API
// so the document must be opened readonly for backward compatibility
GetItemSet().Put( SfxBoolItem( SID_DOC_READONLY, true ) );
}
else
SetError(ERRCODE_IO_ACCESSDENIED);
}
return nResult;
}
bool SfxMedium::ShowLockFileProblemDialog(MessageDlg nWhichDlg)
{
// system file locking is not active, ask user whether he wants to open the document without any locking
uno::Reference< task::XInteractionHandler > xHandler = GetInteractionHandler();
if (xHandler.is())
{
::rtl::Reference< ::ucbhelper::InteractionRequest > xIgnoreRequestImpl;
switch (nWhichDlg)
{
case MessageDlg::LockFileIgnore:
xIgnoreRequestImpl = new ::ucbhelper::InteractionRequest(uno::Any( document::LockFileIgnoreRequest() ));
break;
case MessageDlg::LockFileCorrupt:
xIgnoreRequestImpl = new ::ucbhelper::InteractionRequest(uno::Any( document::LockFileCorruptRequest() ));
break;
}
uno::Sequence< uno::Reference< task::XInteractionContinuation > > aContinuations{
new ::ucbhelper::InteractionAbort(xIgnoreRequestImpl.get()),
new ::ucbhelper::InteractionApprove(xIgnoreRequestImpl.get())
};
xIgnoreRequestImpl->setContinuations(aContinuations);
xHandler->handle(xIgnoreRequestImpl);
::rtl::Reference< ::ucbhelper::InteractionContinuation > xSelected = xIgnoreRequestImpl->getSelection();
bool bReadOnly = true;
if (uno::Reference<task::XInteractionAbort>(xSelected.get(), uno::UNO_QUERY).is())
{
SetError(ERRCODE_ABORT);
bReadOnly = false;
}
else if (!uno::Reference<task::XInteractionApprove>(xSelected.get(), uno::UNO_QUERY).is())
{
// user selected "Notify"
pImpl->m_bNotifyWhenEditable = true;
AddToCheckEditableWorkerList();
}
if (bReadOnly)
GetItemSet().Put(SfxBoolItem(SID_DOC_READONLY, true));
return bReadOnly;
}
return false;
}
namespace
{
bool isSuitableProtocolForLocking(const OUString & rLogicName)
{
INetURLObject aUrl( rLogicName );
INetProtocol eProt = aUrl.GetProtocol();
#if !HAVE_FEATURE_MACOSX_SANDBOX
if (eProt == INetProtocol::File) {
return true;
}
#endif
return eProt == INetProtocol::Smb || eProt == INetProtocol::Sftp;
}
}
namespace
{
// for LOCK request, suppress dialog on 403, typically indicates read-only
// document and there's a 2nd dialog prompting to open a copy anyway
class LockInteractionHandler : public ::cppu::WeakImplHelper<task::XInteractionHandler>
{
private:
uno::Reference<task::XInteractionHandler> m_xHandler;
public:
explicit LockInteractionHandler(uno::Reference<task::XInteractionHandler> const& xHandler)
: m_xHandler(xHandler)
{
}
virtual void SAL_CALL handle(uno::Reference<task::XInteractionRequest> const& xRequest) override
{
ucb::InteractiveNetworkWriteException readException;
ucb::InteractiveNetworkReadException writeException;
if ((xRequest->getRequest() >>= readException)
|| (xRequest->getRequest() >>= writeException))
{
return; // 403 gets reported as one of these; ignore to avoid dialog
}
m_xHandler->handle(xRequest);
}
};
} // namespace
#endif // HAVE_FEATURE_MULTIUSER_ENVIRONMENT
// sets SID_DOC_READONLY if the document cannot be opened for editing
// if user cancel the loading the ERROR_ABORT is set
SfxMedium::LockFileResult SfxMedium::LockOrigFileOnDemand(bool bLoading, bool bNoUI,
bool bTryIgnoreLockFile,
LockFileEntry* pLockData)
{
#if !HAVE_FEATURE_MULTIUSER_ENVIRONMENT
(void) bLoading;
(void) bNoUI;
(void) bTryIgnoreLockFile;
(void) pLockData;
return LockFileResult::Succeeded;
#else
LockFileResult eResult = LockFileResult::Failed;
// check if path scheme is http:// or https://
// may be this is better if used always, in Android and iOS as well?
// if this code should be always there, remember to move the relevant code in UnlockFile method as well !
if ( GetURLObject().isAnyKnownWebDAVScheme() )
{
// do nothing if WebDAV locking is disabled
if (!IsWebDAVLockingUsed())
return LockFileResult::Succeeded;
{
bool bResult = pImpl->m_bLocked;
bool bIsTemplate = false;
// so, this is webdav stuff...
if ( !bResult )
{
// no read-write access is necessary on loading if the document is explicitly opened as copy
const SfxBoolItem* pTemplateItem = GetItemSet().GetItem(SID_TEMPLATE, false);
bIsTemplate = ( bLoading && pTemplateItem && pTemplateItem->GetValue() );
}
if ( !bIsTemplate && !bResult && !IsReadOnly() )
{
ShowLockResult bUIStatus = ShowLockResult::NoLock;
do
{
if( !bResult )
{
uno::Reference< task::XInteractionHandler > xCHandler = GetInteractionHandler( true );
// Dialog with error is superfluous:
// on loading, will result in read-only with infobar.
// bNoUI case for Reload failing, will open dialog later.
if (bLoading || bNoUI)
{
xCHandler = new LockInteractionHandler(xCHandler);
}
Reference< css::ucb::XCommandEnvironment > xComEnv = new ::ucbhelper::CommandEnvironment(
xCHandler, Reference< css::ucb::XProgressHandler >() );
ucbhelper::Content aContentToLock(
GetURLObject().GetMainURL( INetURLObject::DecodeMechanism::NONE ),
xComEnv, comphelper::getProcessComponentContext() );
try
{
aContentToLock.lock();
bResult = true;
}
catch ( ucb::InteractiveLockingLockedException& )
{
// received when the resource is already locked
if (!bNoUI || pLockData)
{
// get the lock owner, using a special ucb.webdav property
// the owner property retrieved here is what the other principal send the server
// when activating the lock.
// See http://tools.ietf.org/html/rfc4918#section-14.17 for details
LockFileEntry aLockData;
aLockData[LockFileComponent::OOOUSERNAME] = "Unknown user";
// This solution works right when the LO user name and the WebDAV user
// name are the same.
// A better thing to do would be to obtain the 'real' WebDAV user name,
// but that's not possible from a WebDAV UCP provider client.
LockFileEntry aOwnData = svt::LockFileCommon::GenerateOwnEntry();
// use the current LO user name as the system name
aLockData[LockFileComponent::SYSUSERNAME]
= aOwnData[LockFileComponent::SYSUSERNAME];
uno::Sequence<css::ucb::Lock> aLocks;
// getting the property, send a PROPFIND to the server over the net
if ((aContentToLock.getPropertyValue("DAV:lockdiscovery") >>= aLocks) && aLocks.hasElements())
{
// got at least a lock, show the owner of the first lock returned
css::ucb::Lock aLock = aLocks[0];
OUString aOwner;
if (aLock.Owner >>= aOwner)
{
// we need to display the WebDAV user name owning the lock, not the local one
aLockData[LockFileComponent::OOOUSERNAME] = aOwner;
}
}
if (!bNoUI)
{
bUIStatus = ShowLockedDocumentDialog(aLockData, bLoading, false,
true);
}
if (pLockData)
{
std::copy(aLockData.begin(), aLockData.end(), pLockData->begin());
}
}
}
catch( ucb::InteractiveNetworkWriteException& )
{
// This catch it's not really needed, here just for the sake of documentation on the behaviour.
// This is the most likely reason:
// - the remote site is a WebDAV with special configuration: read/only for read operations
// and read/write for write operations, the user is not allowed to lock/write and
// she cancelled the credentials request.
// this is not actually an error, but the exception is sent directly from ucb, avoiding the automatic
// management that takes part in cancelCommandExecution()
// Unfortunately there is no InteractiveNetwork*Exception available to signal this more correctly
// since it mostly happens on read/only part of webdav, this can be the most correct
// exception available
}
catch( uno::Exception& )
{
TOOLS_WARN_EXCEPTION( "sfx.doc", "Locking exception: WebDAV while trying to lock the file" );
}
}
} while( !bResult && bUIStatus == ShowLockResult::Try );
}
pImpl->m_bLocked = bResult;
if ( !bResult && GetErrorIgnoreWarning() == ERRCODE_NONE )
{
// the error should be set in case it is storing process
// or the document has been opened for editing explicitly
const SfxBoolItem* pReadOnlyItem = SfxItemSet::GetItem<SfxBoolItem>(pImpl->m_pSet.get(), SID_DOC_READONLY, false);
if ( !bLoading || (pReadOnlyItem && !pReadOnlyItem->GetValue()) )
SetError(ERRCODE_IO_ACCESSDENIED);
else
GetItemSet().Put( SfxBoolItem( SID_DOC_READONLY, true ) );
}
// when the file is locked, get the current file date
if ( bResult && DocNeedsFileDateCheck() )
GetInitFileDate( true );
if ( bResult )
eResult = LockFileResult::Succeeded;
}
return eResult;
}
if (!IsLockingUsed())
return LockFileResult::Succeeded;
if (GetURLObject().HasError())
return eResult;
try
{
if ( pImpl->m_bLocked && bLoading
&& GetURLObject().GetProtocol() == INetProtocol::File )
{
// if the document is already locked the system locking might be temporarily off after storing
// check whether the system file locking should be taken again
GetLockingStream_Impl();
}
bool bResult = pImpl->m_bLocked;
if ( !bResult )
{
// no read-write access is necessary on loading if the document is explicitly opened as copy
const SfxBoolItem* pTemplateItem = GetItemSet().GetItem(SID_TEMPLATE, false);
bResult = ( bLoading && pTemplateItem && pTemplateItem->GetValue() );
}
if ( !bResult && !IsReadOnly() )
{
bool bContentReadonly = false;
if ( bLoading && GetURLObject().GetProtocol() == INetProtocol::File )
{
// let the original document be opened to check the possibility to open it for editing
// and to let the writable stream stay open to hold the lock on the document
GetLockingStream_Impl();
}
// "IsReadOnly" property does not allow to detect whether the file is readonly always
// so we try always to open the file for editing
// the file is readonly only in case the read-write stream can not be opened
if ( bLoading && !pImpl->m_xLockingStream.is() )
{
try
{
// MediaDescriptor does this check also, the duplication should be avoided in future
Reference< css::ucb::XCommandEnvironment > xDummyEnv;
::ucbhelper::Content aContent( GetURLObject().GetMainURL( INetURLObject::DecodeMechanism::NONE ), xDummyEnv, comphelper::getProcessComponentContext() );
aContent.getPropertyValue("IsReadOnly") >>= bContentReadonly;
}
catch( const uno::Exception& ) {}
}
// do further checks only if the file not readonly in fs
if ( !bContentReadonly )
{
// the special file locking should be used only for suitable URLs
if ( isSuitableProtocolForLocking( pImpl->m_aLogicName ) )
{
// in case of storing the document should request the output before locking
if ( bLoading )
{
// let the stream be opened to check the system file locking
GetMedium_Impl();
if (GetErrorIgnoreWarning() != ERRCODE_NONE) {
return eResult;
}
}
ShowLockResult bUIStatus = ShowLockResult::NoLock;
// check whether system file locking has been used, the default value is false
bool bUseSystemLock = comphelper::isFileUrl( pImpl->m_aLogicName ) && IsSystemFileLockingUsed();
// TODO/LATER: This implementation does not allow to detect the system lock on saving here, actually this is no big problem
// if system lock is used the writeable stream should be available
bool bHandleSysLocked = ( bLoading && bUseSystemLock && !pImpl->xStream.is() && !pImpl->m_pOutStream );
// The file is attempted to get locked for the duration of lockfile creation on save
std::unique_ptr<osl::File> pFileLock;
if (!bLoading && bUseSystemLock && pImpl->pTempFile)
{
INetURLObject aDest(GetURLObject());
OUString aDestURL(aDest.GetMainURL(INetURLObject::DecodeMechanism::NONE));
if (comphelper::isFileUrl(aDestURL) || !aDest.removeSegment())
{
pFileLock = std::make_unique<osl::File>(aDestURL);
auto rc = pFileLock->open(osl_File_OpenFlag_Write);
if (rc == osl::FileBase::E_ACCES)
bHandleSysLocked = true;
}
}
do
{
try
{
::svt::DocumentLockFile aLockFile( pImpl->m_aLogicName );
std::unique_ptr<svt::MSODocumentLockFile> pMSOLockFile;
const SvtFilterOptions& rOpt = SvtFilterOptions::Get();
if (rOpt.IsMSOLockFileCreationIsEnabled() && svt::MSODocumentLockFile::IsMSOSupportedFileFormat(pImpl->m_aLogicName))
{
pMSOLockFile.reset(new svt::MSODocumentLockFile(pImpl->m_aLogicName));
pImpl->m_bMSOLockFileCreated = true;
}
bool bIoErr = false;
if (!bHandleSysLocked)
{
try
{
bResult = aLockFile.CreateOwnLockFile();
if(pMSOLockFile)
bResult &= pMSOLockFile->CreateOwnLockFile();
}
catch (const uno::Exception&)
{
if (tools::IsMappedWebDAVPath(GetURLObject().GetMainURL(
INetURLObject::DecodeMechanism::NONE)))
{
// This is a path that redirects to a WebDAV resource;
// so failure creating lockfile is not an error here.
bResult = true;
}
else if (bLoading && !bNoUI)
{
bIoErr = true;
ShowLockFileProblemDialog(MessageDlg::LockFileIgnore);
bResult = true; // always delete the defect lock-file
}
}
// in case OOo locking is turned off the lock file is still written if possible
// but it is ignored while deciding whether the document should be opened for editing or not
if (!bResult && !IsOOoLockFileUsed() && !bIoErr)
{
bResult = true;
// take the ownership over the lock file
aLockFile.OverwriteOwnLockFile();
if(pMSOLockFile)
pMSOLockFile->OverwriteOwnLockFile();
}
}
if ( !bResult )
{
LockFileEntry aData;
try
{
aData = aLockFile.GetLockData();
}
catch (const io::WrongFormatException&)
{
// we get empty or corrupt data
// info to the user
if (!bIoErr && bLoading && !bNoUI )
bResult = ShowLockFileProblemDialog(MessageDlg::LockFileCorrupt);
// not show the Lock Document Dialog
bIoErr = true;
}
catch( const uno::Exception& )
{
// show the Lock Document Dialog, when locked from other app
bIoErr = !bHandleSysLocked;
}
bool bOwnLock = false;
if (!bHandleSysLocked)
{
LockFileEntry aOwnData = svt::LockFileCommon::GenerateOwnEntry();
bOwnLock = aOwnData[LockFileComponent::SYSUSERNAME] == aData[LockFileComponent::SYSUSERNAME];
if (bOwnLock
&& aOwnData[LockFileComponent::LOCALHOST] == aData[LockFileComponent::LOCALHOST]
&& aOwnData[LockFileComponent::USERURL] == aData[LockFileComponent::USERURL])
{
// this is own lock from the same installation, it could remain because of crash
bResult = true;
}
}
if ( !bResult && !bIoErr)
{
if (!bNoUI)
bUIStatus = ShowLockedDocumentDialog(
aData, bLoading, bOwnLock, bHandleSysLocked);
else if (bLoading && bTryIgnoreLockFile && !bHandleSysLocked)
bUIStatus = ShowLockResult::Succeeded;
if ( bUIStatus == ShowLockResult::Succeeded )
{
// take the ownership over the lock file
bResult = aLockFile.OverwriteOwnLockFile();
if(pMSOLockFile)
pMSOLockFile->OverwriteOwnLockFile();
}
else if (bLoading && !bHandleSysLocked)
eResult = LockFileResult::FailedLockFile;
if (!bResult && pLockData)
{
std::copy(aData.begin(), aData.end(), pLockData->begin());
}
}
}
}
catch( const uno::Exception& )
{
}
} while( !bResult && bUIStatus == ShowLockResult::Try );
pImpl->m_bLocked = bResult;
}
else
{
// this is no file URL, check whether the file is readonly
bResult = !bContentReadonly;
}
}
else // read-only
{
AddToCheckEditableWorkerList();
}
}
if ( !bResult && GetErrorIgnoreWarning() == ERRCODE_NONE )
{
// the error should be set in case it is storing process
// or the document has been opened for editing explicitly
const SfxBoolItem* pReadOnlyItem = SfxItemSet::GetItem<SfxBoolItem>(pImpl->m_pSet.get(), SID_DOC_READONLY, false);
if ( !bLoading || (pReadOnlyItem && !pReadOnlyItem->GetValue()) )
SetError(ERRCODE_IO_ACCESSDENIED);
else
GetItemSet().Put( SfxBoolItem( SID_DOC_READONLY, true ) );
}
// when the file is locked, get the current file date
if ( bResult && DocNeedsFileDateCheck() )
GetInitFileDate( true );
if ( bResult )
eResult = LockFileResult::Succeeded;
}
catch( const uno::Exception& )
{
TOOLS_WARN_EXCEPTION( "sfx.doc", "Locking exception: high probability, that the content has not been created" );
}
return eResult;
#endif
}
// this either returns non-null or throws exception
uno::Reference<embed::XStorage>
SfxMedium::TryEncryptedInnerPackage(uno::Reference<embed::XStorage> const xStorage)
{
uno::Reference<embed::XStorage> xRet;
if (xStorage->hasByName("encrypted-package"))
{
uno::Reference<io::XStream> const
xDecryptedInnerPackage = xStorage->openStreamElement(
"encrypted-package",
embed::ElementModes::READ | embed::ElementModes::NOCREATE);
// either this throws due to wrong password or IO error, or returns stream
assert(xDecryptedInnerPackage.is());
// need a seekable stream => copy
Reference<uno::XComponentContext> const xContext(::comphelper::getProcessComponentContext());
uno::Reference<io::XStream> const xDecryptedInnerPackageStream(
xContext->getServiceManager()->createInstanceWithContext(
"com.sun.star.comp.MemoryStream", xContext),
UNO_QUERY_THROW);
comphelper::OStorageHelper::CopyInputToOutput(xDecryptedInnerPackage->getInputStream(), xDecryptedInnerPackageStream->getOutputStream());
xDecryptedInnerPackageStream->getOutputStream()->closeOutput();
#if 0
// debug: dump to temp file
uno::Reference<io::XTempFile> const xTempFile(io::TempFile::create(xContext), uno::UNO_SET_THROW);
xTempFile->setRemoveFile(false);
comphelper::OStorageHelper::CopyInputToOutput(xDecryptedInnerPackageStream->getInputStream(), xTempFile->getOutputStream());
xTempFile->getOutputStream()->closeOutput();
SAL_DE BUG("AAA tempfile " << xTempFile->getResourceName());
uno::Reference<io::XSeekable>(xDecryptedInnerPackageStream, uno::UNO_QUERY_THROW)->seek(0);
#endif
// create inner storage; opening the stream should have already verified
// the password so any failure here is probably due to a bug
xRet = ::comphelper::OStorageHelper::GetStorageOfFormatFromStream(
PACKAGE_STORAGE_FORMAT_STRING, xDecryptedInnerPackageStream,
embed::ElementModes::READWRITE, xContext, false);
assert(xRet.is());
// consistency check: outer and inner package must have same mimetype
OUString const outerMediaType(uno::Reference<beans::XPropertySet>(pImpl->xStorage,
uno::UNO_QUERY_THROW)->getPropertyValue("MediaType").get<OUString>());
OUString const innerMediaType(uno::Reference<beans::XPropertySet>(xRet,
uno::UNO_QUERY_THROW)->getPropertyValue("MediaType").get<OUString>());
if (outerMediaType.isEmpty() || outerMediaType != innerMediaType)
{
throw io::WrongFormatException("MediaType inconsistent in encrypted ODF package");
}
// success:
pImpl->m_bODFWholesomeEncryption = true;
pImpl->m_xODFDecryptedInnerPackageStream = xDecryptedInnerPackageStream;
pImpl->m_xODFEncryptedOuterStorage = xStorage;
pImpl->xStorage = xRet;
}
return xRet;
}
uno::Reference < embed::XStorage > SfxMedium::GetStorage( bool bCreateTempFile )
{
if ( pImpl->xStorage.is() || pImpl->m_bTriedStorage )
return pImpl->xStorage;
uno::Sequence< uno::Any > aArgs( 2 );
auto pArgs = aArgs.getArray();
// the medium should be retrieved before temporary file creation
// to let the MediaDescriptor be filled with the streams
GetMedium_Impl();
if ( bCreateTempFile )
CreateTempFile( false );
GetMedium_Impl();
if ( GetErrorIgnoreWarning() )
return pImpl->xStorage;
const SfxBoolItem* pRepairItem = GetItemSet().GetItem(SID_REPAIRPACKAGE, false);
if ( pRepairItem && pRepairItem->GetValue() )
{
// the storage should be created for repairing mode
CreateTempFile( false );
GetMedium_Impl();
Reference< css::ucb::XProgressHandler > xProgressHandler;
Reference< css::task::XStatusIndicator > xStatusIndicator;
const SfxUnoAnyItem* pxProgressItem = GetItemSet().GetItem(SID_PROGRESS_STATUSBAR_CONTROL, false);
if( pxProgressItem && ( pxProgressItem->GetValue() >>= xStatusIndicator ) )
xProgressHandler.set( new utl::ProgressHandlerWrap( xStatusIndicator ) );
uno::Sequence< beans::PropertyValue > aAddProps{
comphelper::makePropertyValue("RepairPackage", true),
comphelper::makePropertyValue("StatusIndicator", xProgressHandler)
};
// the first arguments will be filled later
aArgs.realloc( 3 );
pArgs = aArgs.getArray();
pArgs[2] <<= aAddProps;
}
if ( pImpl->xStream.is() )
{
// since the storage is based on temporary stream we open it always read-write
pArgs[0] <<= pImpl->xStream;
pArgs[1] <<= embed::ElementModes::READWRITE;
pImpl->bStorageBasedOnInStream = true;
if (pImpl->m_bDisableFileSync)
{
// Forward NoFileSync to the storage factory.
aArgs.realloc(3); // ??? this may re-write the data added above for pRepairItem
pArgs = aArgs.getArray();
uno::Sequence<beans::PropertyValue> aProperties(
comphelper::InitPropertySequence({ { "NoFileSync", uno::Any(true) } }));
pArgs[2] <<= aProperties;
}
}
else if ( pImpl->xInputStream.is() )
{
// since the storage is based on temporary stream we open it always read-write
pArgs[0] <<= pImpl->xInputStream;
pArgs[1] <<= embed::ElementModes::READ;
pImpl->bStorageBasedOnInStream = true;
}
else
{
CloseStreams_Impl();
pArgs[0] <<= pImpl->m_aName;
pArgs[1] <<= embed::ElementModes::READ;
pImpl->bStorageBasedOnInStream = false;
}
try
{
pImpl->xStorage.set( ::comphelper::OStorageHelper::GetStorageFactory()->createInstanceWithArguments( aArgs ),
uno::UNO_QUERY );
}
catch( const uno::Exception& )
{
// impossibility to create the storage is no error
}
pImpl->nLastStorageError = GetErrorIgnoreWarning();
if( pImpl->nLastStorageError != ERRCODE_NONE )
{
pImpl->xStorage = nullptr;
if ( pImpl->m_pInStream )
pImpl->m_pInStream->Seek(0);
return uno::Reference< embed::XStorage >();
}
pImpl->m_bTriedStorage = true;
if (pImpl->xStorage.is())
{
pImpl->m_bODFWholesomeEncryption = false;
if (SetEncryptionDataToStorage_Impl())
{
try
{
TryEncryptedInnerPackage(pImpl->xStorage);
}
catch (Exception const&)
{
TOOLS_WARN_EXCEPTION("sfx.doc", "exception from TryEncryptedInnerPackage: ");
SetError(ERRCODE_IO_GENERAL);
}
}
}
if (GetErrorCode()) // decryption failed?
{
pImpl->xStorage.clear();
}
// TODO/LATER: Get versionlist on demand
if ( pImpl->xStorage.is() )
{
GetVersionList();
}
const SfxInt16Item* pVersion = SfxItemSet::GetItem<SfxInt16Item>(pImpl->m_pSet.get(), SID_VERSION, false);
bool bResetStorage = false;
if ( pVersion && pVersion->GetValue() )
{
// Read all available versions
if ( pImpl->aVersions.hasElements() )
{
// Search for the version fits the comment
// The versions are numbered starting with 1, versions with
// negative versions numbers are counted backwards from the
// current version
short nVersion = pVersion->GetValue();
if ( nVersion<0 )
nVersion = static_cast<short>(pImpl->aVersions.getLength()) + nVersion;
else // nVersion > 0; pVersion->GetValue() != 0 was the condition to this block
nVersion--;
const util::RevisionTag& rTag = pImpl->aVersions[nVersion];
{
// Open SubStorage for all versions
uno::Reference < embed::XStorage > xSub = pImpl->xStorage->openStorageElement( "Versions",
embed::ElementModes::READ );
DBG_ASSERT( xSub.is(), "Version list, but no Versions!" );
// There the version is stored as packed Stream
uno::Reference < io::XStream > xStr = xSub->openStreamElement( rTag.Identifier, embed::ElementModes::READ );
std::unique_ptr<SvStream> pStream(utl::UcbStreamHelper::CreateStream( xStr ));
if ( pStream && pStream->GetError() == ERRCODE_NONE )
{
// Unpack Stream in TempDir
const OUString aTmpName = ::utl::CreateTempURL();
SvFileStream aTmpStream( aTmpName, SFX_STREAM_READWRITE );
pStream->ReadStream( aTmpStream );
pStream.reset();
aTmpStream.Close();
// Open data as Storage
pImpl->m_nStorOpenMode = SFX_STREAM_READONLY;
pImpl->xStorage = comphelper::OStorageHelper::GetStorageFromURL( aTmpName, embed::ElementModes::READ );
pImpl->bStorageBasedOnInStream = false;
OUString aTemp;
osl::FileBase::getSystemPathFromFileURL( aTmpName, aTemp );
SetPhysicalName_Impl( aTemp );
pImpl->bIsTemp = true;
GetItemSet().Put( SfxBoolItem( SID_DOC_READONLY, true ) );
// TODO/MBA
pImpl->aVersions.realloc(0);
}
else
bResetStorage = true;
}
}
else
bResetStorage = true;
}
if ( bResetStorage )
{
pImpl->xStorage.clear();
pImpl->m_xODFDecryptedInnerPackageStream.clear();
pImpl->m_xODFEncryptedOuterStorage.clear();
if ( pImpl->m_pInStream )
pImpl->m_pInStream->Seek( 0 );
}
pImpl->bIsStorage = pImpl->xStorage.is();
return pImpl->xStorage;
}
uno::Reference<embed::XStorage> SfxMedium::GetScriptingStorageToSign_Impl()
{
// this was set when it was initially loaded
if (pImpl->m_bODFWholesomeEncryption)
{
// (partial) scripting signature can only be in inner storage!
// Note: a "PackageFormat" storage like pImpl->xStorage doesn't work
// (even if it's not encrypted) because it hides the "META-INF" dir.
// This "ZipFormat" storage is used only read-only; a writable one is
// created manually in SignContents_Impl().
if (!pImpl->m_xODFDecryptedInnerZipStorage.is())
{
GetStorage(false);
// don't care about xStorage here because Zip is readonly
SAL_WARN_IF(!pImpl->m_xODFDecryptedInnerPackageStream.is(), "sfx.doc", "no inner package stream?");
if (pImpl->m_xODFDecryptedInnerPackageStream.is())
{
const SfxBoolItem* pRepairItem = GetItemSet().GetItem(SID_REPAIRPACKAGE, false);
const bool bRepairPackage = pRepairItem && pRepairItem->GetValue();
pImpl->m_xODFDecryptedInnerZipStorage =
::comphelper::OStorageHelper::GetStorageOfFormatFromInputStream(
ZIP_STORAGE_FORMAT_STRING,
pImpl->m_xODFDecryptedInnerPackageStream->getInputStream(), {},
bRepairPackage);
}
}
return pImpl->m_xODFDecryptedInnerZipStorage;
}
else
{
return GetZipStorageToSign_Impl(true);
}
}
// note: currently nobody who calls this with "false" writes into an ODF
// storage that is returned here, that is only for OOXML
uno::Reference< embed::XStorage > const & SfxMedium::GetZipStorageToSign_Impl( bool bReadOnly )
{
if ( !GetErrorIgnoreWarning() && !pImpl->m_xZipStorage.is() )
{
GetMedium_Impl();
try
{
const SfxBoolItem* pRepairItem = GetItemSet().GetItem(SID_REPAIRPACKAGE, false);
const bool bRepairPackage = pRepairItem && pRepairItem->GetValue();
// we can not sign document if there is no stream
// should it be possible at all?
if ( !bReadOnly && pImpl->xStream.is() )
{
pImpl->m_xZipStorage = ::comphelper::OStorageHelper::GetStorageOfFormatFromStream(
ZIP_STORAGE_FORMAT_STRING, pImpl->xStream, css::embed::ElementModes::READWRITE,
{}, bRepairPackage);
}
else if ( pImpl->xInputStream.is() )
{
pImpl->m_xZipStorage
= ::comphelper::OStorageHelper::GetStorageOfFormatFromInputStream(
ZIP_STORAGE_FORMAT_STRING, pImpl->xInputStream, {}, bRepairPackage);
}
}
catch( const uno::Exception& )
{
SAL_WARN( "sfx.doc", "No possibility to get readonly version of storage from medium!" );
}
if ( GetErrorIgnoreWarning() ) // do not remove warnings
ResetError();
}
return pImpl->m_xZipStorage;
}
void SfxMedium::CloseZipStorage_Impl()
{
if ( pImpl->m_xZipStorage.is() )
{
try {
pImpl->m_xZipStorage->dispose();
} catch( const uno::Exception& )
{}
pImpl->m_xZipStorage.clear();
}
pImpl->m_xODFDecryptedInnerZipStorage.clear();
}
void SfxMedium::CloseStorage()
{
if ( pImpl->xStorage.is() )
{
uno::Reference < lang::XComponent > xComp = pImpl->xStorage;
// in the salvage mode the medium does not own the storage
if ( pImpl->bDisposeStorage && !pImpl->m_bSalvageMode )
{
try {
xComp->dispose();
} catch( const uno::Exception& )
{
SAL_WARN( "sfx.doc", "Medium's storage is already disposed!" );
}
}
pImpl->xStorage.clear();
pImpl->m_xODFDecryptedInnerPackageStream.clear();
// pImpl->m_xODFDecryptedInnerZipStorage.clear();
pImpl->m_xODFEncryptedOuterStorage.clear();
pImpl->bStorageBasedOnInStream = false;
}
pImpl->m_bTriedStorage = false;
pImpl->bIsStorage = false;
}
void SfxMedium::CanDisposeStorage_Impl( bool bDisposeStorage )
{
pImpl->bDisposeStorage = bDisposeStorage;
}
bool SfxMedium::WillDisposeStorageOnClose_Impl()
{
return pImpl->bDisposeStorage;
}
StreamMode SfxMedium::GetOpenMode() const
{
return pImpl->m_nStorOpenMode;
}
void SfxMedium::SetOpenMode( StreamMode nStorOpen,
bool bDontClose )
{
if ( pImpl->m_nStorOpenMode != nStorOpen )
{
pImpl->m_nStorOpenMode = nStorOpen;
if( !bDontClose )
{
if ( pImpl->xStorage.is() )
CloseStorage();
CloseStreams_Impl();
}
}
}
bool SfxMedium::UseBackupToRestore_Impl( ::ucbhelper::Content& aOriginalContent,
const Reference< css::ucb::XCommandEnvironment >& xComEnv )
{
try
{
::ucbhelper::Content aTransactCont( pImpl->m_aBackupURL, xComEnv, comphelper::getProcessComponentContext() );
Reference< XInputStream > aOrigInput = aTransactCont.openStream();
aOriginalContent.writeStream( aOrigInput, true );
return true;
}
catch( const Exception& )
{
// in case of failure here the backup file should not be removed
// TODO/LATER: a message should be used to let user know about the backup
pImpl->m_bRemoveBackup = false;
// TODO/LATER: needs a specific error code
pImpl->m_eError = ERRCODE_IO_GENERAL;
}
return false;
}
bool SfxMedium::StorageCommit_Impl()
{
bool bResult = false;
Reference< css::ucb::XCommandEnvironment > xDummyEnv;
::ucbhelper::Content aOriginalContent;
if ( pImpl->xStorage.is() )
{
if ( !GetErrorIgnoreWarning() )
{
uno::Reference < embed::XTransactedObject > xTrans( pImpl->xStorage, uno::UNO_QUERY );
if ( xTrans.is() )
{
try
{
xTrans->commit();
CloseZipStorage_Impl();
bResult = true;
}
catch ( const embed::UseBackupException& aBackupExc )
{
// since the temporary file is created always now, the scenario is close to be impossible
if ( !pImpl->pTempFile )
{
OSL_ENSURE( !pImpl->m_aBackupURL.isEmpty(), "No backup on storage commit!" );
if ( !pImpl->m_aBackupURL.isEmpty()
&& ::ucbhelper::Content::create( GetURLObject().GetMainURL( INetURLObject::DecodeMechanism::NONE ),
xDummyEnv, comphelper::getProcessComponentContext(),
aOriginalContent ) )
{
// use backup to restore the file
// the storage has already disconnected from original location
CloseAndReleaseStreams_Impl();
if ( !UseBackupToRestore_Impl( aOriginalContent, xDummyEnv ) )
{
// connect the medium to the temporary file of the storage
pImpl->aContent = ::ucbhelper::Content();
pImpl->m_aName = aBackupExc.TemporaryFileURL;
OSL_ENSURE( !pImpl->m_aName.isEmpty(), "The exception _must_ contain the temporary URL!" );
}
}
}
if (!GetErrorIgnoreWarning())
SetError(ERRCODE_IO_GENERAL);
}
catch ( const uno::Exception& )
{
//TODO/LATER: improve error handling
SetError(ERRCODE_IO_GENERAL);
}
}
}
}
return bResult;
}
void SfxMedium::TransactedTransferForFS_Impl( const INetURLObject& aSource,
const INetURLObject& aDest,
const Reference< css::ucb::XCommandEnvironment >& xComEnv )
{
Reference< css::ucb::XCommandEnvironment > xDummyEnv;
::ucbhelper::Content aOriginalContent;
try
{
aOriginalContent = ::ucbhelper::Content( aDest.GetMainURL( INetURLObject::DecodeMechanism::NONE ), xComEnv, comphelper::getProcessComponentContext() );
}
catch ( const css::ucb::CommandAbortedException& )
{
pImpl->m_eError = ERRCODE_ABORT;
}
catch ( const css::ucb::CommandFailedException& )
{
pImpl->m_eError = ERRCODE_ABORT;
}
catch (const css::ucb::ContentCreationException& ex)
{
pImpl->m_eError = ERRCODE_IO_GENERAL;
if (
(ex.eError == css::ucb::ContentCreationError_NO_CONTENT_PROVIDER ) ||
(ex.eError == css::ucb::ContentCreationError_CONTENT_CREATION_FAILED)
)
{
pImpl->m_eError = ERRCODE_IO_NOTEXISTSPATH;
}
}
catch (const css::uno::Exception&)
{
pImpl->m_eError = ERRCODE_IO_GENERAL;
}
if( pImpl->m_eError && !pImpl->m_eError.IsWarning() )
return;
if ( pImpl->xStorage.is() )
CloseStorage();
CloseStreams_Impl();
::ucbhelper::Content aTempCont;
if( ::ucbhelper::Content::create( aSource.GetMainURL( INetURLObject::DecodeMechanism::NONE ), xDummyEnv, comphelper::getProcessComponentContext(), aTempCont ) )
{
bool bTransactStarted = false;
const SfxBoolItem* pOverWrite = GetItemSet().GetItem<SfxBoolItem>(SID_OVERWRITE, false);
bool bOverWrite = !pOverWrite || pOverWrite->GetValue();
bool bResult = false;
try
{
// tdf#60237 - if the OverWrite property of the MediaDescriptor is set to false,
// try to write the file before trying to rename or copy it
if (!(bOverWrite
&& ::utl::UCBContentHelper::IsDocument(
aDest.GetMainURL(INetURLObject::DecodeMechanism::NONE))))
{
Reference< XInputStream > aTempInput = aTempCont.openStream();
aOriginalContent.writeStream( aTempInput, bOverWrite );
bResult = true;
} else {
OUString aSourceMainURL = aSource.GetMainURL(INetURLObject::DecodeMechanism::NONE);
OUString aDestMainURL = aDest.GetMainURL(INetURLObject::DecodeMechanism::NONE);
sal_uInt64 nAttributes = GetDefaultFileAttributes(aDestMainURL);
if (IsFileMovable(aDest)
&& osl::File::replace(aSourceMainURL, aDestMainURL) == osl::FileBase::E_None)
{
if (nAttributes)
// Adjust attributes, source might be created with
// the osl_File_OpenFlag_Private flag.
osl::File::setAttributes(aDestMainURL, nAttributes);
bResult = true;
}
else
{
if( pImpl->m_aBackupURL.isEmpty() )
DoInternalBackup_Impl( aOriginalContent );
if( !pImpl->m_aBackupURL.isEmpty() )
{
Reference< XInputStream > aTempInput = aTempCont.openStream();
bTransactStarted = true;
aOriginalContent.setPropertyValue( "Size", uno::Any( sal_Int64(0) ) );
aOriginalContent.writeStream( aTempInput, bOverWrite );
bResult = true;
}
else
{
pImpl->m_eError = ERRCODE_SFX_CANTCREATEBACKUP;
}
}
}
}
catch ( const css::ucb::CommandAbortedException& )
{
pImpl->m_eError = ERRCODE_ABORT;
}
catch ( const css::ucb::CommandFailedException& )
{
pImpl->m_eError = ERRCODE_ABORT;
}
catch ( const css::ucb::InteractiveIOException& r )
{
if ( r.Code == IOErrorCode_ACCESS_DENIED )
pImpl->m_eError = ERRCODE_IO_ACCESSDENIED;
else if ( r.Code == IOErrorCode_NOT_EXISTING )
pImpl->m_eError = ERRCODE_IO_NOTEXISTS;
else if ( r.Code == IOErrorCode_CANT_READ )
pImpl->m_eError = ERRCODE_IO_CANTREAD;
else
pImpl->m_eError = ERRCODE_IO_GENERAL;
}
// tdf#60237 - if the file is already present, raise the appropriate error
catch (const css::ucb::NameClashException& )
{
pImpl->m_eError = ERRCODE_IO_ALREADYEXISTS;
}
catch ( const css::uno::Exception& )
{
pImpl->m_eError = ERRCODE_IO_GENERAL;
}
if ( bResult )
{
if ( pImpl->pTempFile )
{
pImpl->pTempFile->EnableKillingFile();
pImpl->pTempFile.reset();
}
}
else if ( bTransactStarted && pImpl->m_eError != ERRCODE_ABORT )
{
UseBackupToRestore_Impl( aOriginalContent, xDummyEnv );
}
}
else
pImpl->m_eError = ERRCODE_IO_CANTREAD;
}
bool SfxMedium::TryDirectTransfer( const OUString& aURL, SfxItemSet const & aTargetSet )
{
if ( GetErrorIgnoreWarning() )
return false;
// if the document had no password it should be stored without password
// if the document had password it should be stored with the same password
// otherwise the stream copying can not be done
const SfxStringItem* pNewPassItem = aTargetSet.GetItem(SID_PASSWORD, false);
const SfxStringItem* pOldPassItem = GetItemSet().GetItem(SID_PASSWORD, false);
if ( ( !pNewPassItem && !pOldPassItem )
|| ( pNewPassItem && pOldPassItem && pNewPassItem->GetValue() == pOldPassItem->GetValue() ) )
{
// the filter must be the same
const SfxStringItem* pNewFilterItem = aTargetSet.GetItem(SID_FILTER_NAME, false);
const SfxStringItem* pOldFilterItem = GetItemSet().GetItem(SID_FILTER_NAME, false);
if ( pNewFilterItem && pOldFilterItem && pNewFilterItem->GetValue() == pOldFilterItem->GetValue() )
{
// get the input stream and copy it
// in case of success return true
uno::Reference< io::XInputStream > xInStream = GetInputStream();
ResetError();
if ( xInStream.is() )
{
try
{
uno::Reference< io::XSeekable > xSeek( xInStream, uno::UNO_QUERY );
sal_Int64 nPos = 0;
if ( xSeek.is() )
{
nPos = xSeek->getPosition();
xSeek->seek( 0 );
}
uno::Reference < css::ucb::XCommandEnvironment > xEnv;
::ucbhelper::Content aTargetContent( aURL, xEnv, comphelper::getProcessComponentContext() );
InsertCommandArgument aInsertArg;
aInsertArg.Data = xInStream;
const SfxBoolItem* pOverWrite = aTargetSet.GetItem<SfxBoolItem>(SID_OVERWRITE, false);
if ( pOverWrite && !pOverWrite->GetValue() ) // argument says: never overwrite
aInsertArg.ReplaceExisting = false;
else
aInsertArg.ReplaceExisting = true; // default is overwrite existing files
Any aCmdArg;
aCmdArg <<= aInsertArg;
aTargetContent.executeCommand( "insert",
aCmdArg );
if ( xSeek.is() )
xSeek->seek( nPos );
return true;
}
catch( const uno::Exception& )
{}
}
}
}
return false;
}
void SfxMedium::Transfer_Impl()
{
// The transfer is required only in two cases: either if there is a temporary file or if there is a salvage item
OUString aNameURL;
if ( pImpl->pTempFile )
aNameURL = pImpl->pTempFile->GetURL();
else if ( !pImpl->m_aLogicName.isEmpty() && pImpl->m_bSalvageMode )
{
// makes sense only in case logic name is set
if ( osl::FileBase::getFileURLFromSystemPath( pImpl->m_aName, aNameURL )
!= osl::FileBase::E_None )
SAL_WARN( "sfx.doc", "The medium name is not convertible!" );
}
if ( aNameURL.isEmpty() || ( pImpl->m_eError && !pImpl->m_eError.IsWarning() ) )
return;
SAL_INFO( "sfx.doc", "SfxMedium::Transfer_Impl, copying to target" );
Reference < css::ucb::XCommandEnvironment > xEnv;
Reference< XOutputStream > rOutStream;
// in case an output stream is provided from outside and the URL is correct
// commit to the stream
if (pImpl->m_aLogicName.startsWith("private:stream"))
{
// TODO/LATER: support storing to SID_STREAM
const SfxUnoAnyItem* pOutStreamItem = SfxItemSet::GetItem<SfxUnoAnyItem>(pImpl->m_pSet.get(), SID_OUTPUTSTREAM, false);
if( pOutStreamItem && ( pOutStreamItem->GetValue() >>= rOutStream ) )
{
if ( pImpl->xStorage.is() )
CloseStorage();
CloseStreams_Impl();
INetURLObject aSource( aNameURL );
::ucbhelper::Content aTempCont;
if( ::ucbhelper::Content::create( aSource.GetMainURL( INetURLObject::DecodeMechanism::NONE ), xEnv, comphelper::getProcessComponentContext(), aTempCont ) )
{
try
{
sal_Int32 nRead;
sal_Int32 nBufferSize = 32767;
Sequence < sal_Int8 > aSequence ( nBufferSize );
Reference< XInputStream > aTempInput = aTempCont.openStream();
do
{
nRead = aTempInput->readBytes ( aSequence, nBufferSize );
if ( nRead < nBufferSize )
{
Sequence < sal_Int8 > aTempBuf ( aSequence.getConstArray(), nRead );
rOutStream->writeBytes ( aTempBuf );
}
else
rOutStream->writeBytes ( aSequence );
}
while ( nRead == nBufferSize );
// remove temporary file
if ( pImpl->pTempFile )
{
pImpl->pTempFile->EnableKillingFile();
pImpl->pTempFile.reset();
}
}
catch( const Exception& )
{}
}
}
else
{
SAL_WARN( "sfx.doc", "Illegal Output stream parameter!" );
SetError(ERRCODE_IO_GENERAL);
}
// free the reference
if ( pImpl->m_pSet )
pImpl->m_pSet->ClearItem( SID_OUTPUTSTREAM );
return;
}
GetContent();
if ( !pImpl->aContent.get().is() )
{
pImpl->m_eError = ERRCODE_IO_NOTEXISTS;
return;
}
INetURLObject aDest( GetURLObject() );
// source is the temp file written so far
INetURLObject aSource( aNameURL );
// a special case, an interaction handler should be used for
// authentication in case it is available
Reference< css::ucb::XCommandEnvironment > xComEnv;
bool bForceInteractionHandler = GetURLObject().isAnyKnownWebDAVScheme();
Reference< css::task::XInteractionHandler > xInteractionHandler = GetInteractionHandler(bForceInteractionHandler);
if (xInteractionHandler.is())
xComEnv = new ::ucbhelper::CommandEnvironment( xInteractionHandler,
Reference< css::ucb::XProgressHandler >() );
OUString aDestURL( aDest.GetMainURL( INetURLObject::DecodeMechanism::NONE ) );
if ( comphelper::isFileUrl( aDestURL ) || !aDest.removeSegment() )
{
TransactedTransferForFS_Impl( aSource, aDest, xComEnv );
if (!pImpl->m_bDisableFileSync)
{
// Hideous - no clean way to do this, so we re-open the file just to fsync it
osl::File aFile( aDestURL );
if ( aFile.open( osl_File_OpenFlag_Write ) == osl::FileBase::E_None )
{
aFile.sync();
SAL_INFO( "sfx.doc", "fsync'd saved file '" << aDestURL << "'" );
aFile.close();
}
}
}
else
{
// create content for the parent folder and call transfer on that content with the source content
// and the destination file name as parameters
::ucbhelper::Content aSourceContent;
::ucbhelper::Content aTransferContent;
::ucbhelper::Content aDestContent;
(void)::ucbhelper::Content::create( aDestURL, xComEnv, comphelper::getProcessComponentContext(), aDestContent );
// For checkin, we need the object URL, not the parent folder:
if ( !IsInCheckIn( ) )
{
// Get the parent URL from the XChild if possible: why would the URL necessarily have
// a hierarchical path? It's not always the case for CMIS.
Reference< css::container::XChild> xChild( aDestContent.get(), uno::UNO_QUERY );
OUString sParentUrl;
if ( xChild.is( ) )
{
Reference< css::ucb::XContent > xParent( xChild->getParent( ), uno::UNO_QUERY );
if ( xParent.is( ) )
{
sParentUrl = xParent->getIdentifier( )->getContentIdentifier();
}
}
if ( sParentUrl.isEmpty() )
aDestURL = aDest.GetMainURL( INetURLObject::DecodeMechanism::NONE );
// adjust to above aDest.removeSegment()
else
aDestURL = sParentUrl;
}
// LongName wasn't defined anywhere, only used here... get the Title instead
// as it's less probably empty
OUString aFileName;
OUString sObjectId;
try
{
Any aAny = aDestContent.getPropertyValue("Title");
aAny >>= aFileName;
aAny = aDestContent.getPropertyValue("ObjectId");
aAny >>= sObjectId;
}
catch (uno::Exception const&)
{
SAL_INFO("sfx.doc", "exception while getting Title or ObjectId");
}
if ( aFileName.isEmpty() )
aFileName = GetURLObject().getName( INetURLObject::LAST_SEGMENT, true, INetURLObject::DecodeMechanism::WithCharset );
try
{
aTransferContent = ::ucbhelper::Content( aDestURL, xComEnv, comphelper::getProcessComponentContext() );
}
catch (const css::ucb::ContentCreationException& ex)
{
pImpl->m_eError = ERRCODE_IO_GENERAL;
if (
(ex.eError == css::ucb::ContentCreationError_NO_CONTENT_PROVIDER ) ||
(ex.eError == css::ucb::ContentCreationError_CONTENT_CREATION_FAILED)
)
{
pImpl->m_eError = ERRCODE_IO_NOTEXISTSPATH;
}
}
catch (const css::uno::Exception&)
{
pImpl->m_eError = ERRCODE_IO_GENERAL;
}
if ( !pImpl->m_eError || pImpl->m_eError.IsWarning() )
{
// free resources, otherwise the transfer may fail
if ( pImpl->xStorage.is() )
CloseStorage();
CloseStreams_Impl();
(void)::ucbhelper::Content::create( aSource.GetMainURL( INetURLObject::DecodeMechanism::NONE ), xEnv, comphelper::getProcessComponentContext(), aSourceContent );
// check for external parameters that may customize the handling of NameClash situations
const SfxBoolItem* pOverWrite = GetItemSet().GetItem<SfxBoolItem>(SID_OVERWRITE, false);
sal_Int32 nNameClash;
if ( pOverWrite && !pOverWrite->GetValue() )
// argument says: never overwrite
nNameClash = NameClash::ERROR;
else
// default is overwrite existing files
nNameClash = NameClash::OVERWRITE;
try
{
OUString aMimeType = pImpl->getFilterMimeType();
::ucbhelper::InsertOperation eOperation = ::ucbhelper::InsertOperation::Copy;
bool bMajor = false;
OUString sComment;
if ( IsInCheckIn( ) )
{
eOperation = ::ucbhelper::InsertOperation::Checkin;
const SfxBoolItem* pMajor = GetItemSet().GetItem<SfxBoolItem>(SID_DOCINFO_MAJOR, false);
bMajor = pMajor && pMajor->GetValue( );
const SfxStringItem* pComments = GetItemSet().GetItem(SID_DOCINFO_COMMENTS, false);
if ( pComments )
sComment = pComments->GetValue( );
}
OUString sResultURL;
aTransferContent.transferContent(
aSourceContent, eOperation,
aFileName, nNameClash, aMimeType, bMajor, sComment,
&sResultURL, sObjectId );
if ( !sResultURL.isEmpty( ) ) // Likely to happen only for checkin
SwitchDocumentToFile( sResultURL );
try
{
if ( GetURLObject().isAnyKnownWebDAVScheme() &&
eOperation == ::ucbhelper::InsertOperation::Copy )
{
// tdf#95272 try to re-issue a lock command when a new file is created.
// This may be needed because some WebDAV servers fail to implement the
// 'LOCK on unallocated reference', see issue comment:
// <https://bugs.documentfoundation.org/show_bug.cgi?id=95792#c8>
// and specification at:
// <http://tools.ietf.org/html/rfc4918#section-7.3>
// If the WebDAV resource is already locked by this LO instance, nothing will
// happen, e.g. the LOCK method will not be sent to the server.
::ucbhelper::Content aLockContent( GetURLObject().GetMainURL( INetURLObject::DecodeMechanism::NONE ), xComEnv, comphelper::getProcessComponentContext() );
aLockContent.lock();
}
}
catch ( css::uno::Exception & )
{
TOOLS_WARN_EXCEPTION( "sfx.doc", "LOCK not working while re-issuing it" );
}
}
catch ( const css::ucb::CommandAbortedException& )
{
pImpl->m_eError = ERRCODE_ABORT;
}
catch ( const css::ucb::CommandFailedException& )
{
pImpl->m_eError = ERRCODE_ABORT;
}
catch ( const css::ucb::InteractiveIOException& r )
{
if ( r.Code == IOErrorCode_ACCESS_DENIED )
pImpl->m_eError = ERRCODE_IO_ACCESSDENIED;
else if ( r.Code == IOErrorCode_NOT_EXISTING )
pImpl->m_eError = ERRCODE_IO_NOTEXISTS;
else if ( r.Code == IOErrorCode_CANT_READ )
pImpl->m_eError = ERRCODE_IO_CANTREAD;
else
pImpl->m_eError = ERRCODE_IO_GENERAL;
}
catch ( const css::uno::Exception& )
{
pImpl->m_eError = ERRCODE_IO_GENERAL;
}
// do not switch from temporary file in case of nonfile protocol
}
}
if ( ( !pImpl->m_eError || pImpl->m_eError.IsWarning() ) && !pImpl->pTempFile )
{
// without a TempFile the physical and logical name should be the same after successful transfer
if (osl::FileBase::getSystemPathFromFileURL(
GetURLObject().GetMainURL( INetURLObject::DecodeMechanism::NONE ), pImpl->m_aName )
!= osl::FileBase::E_None)
{
pImpl->m_aName.clear();
}
pImpl->m_bSalvageMode = false;
}
}
void SfxMedium::DoInternalBackup_Impl( const ::ucbhelper::Content& aOriginalContent,
std::u16string_view aPrefix,
std::u16string_view aExtension,
const OUString& aDestDir )
{
if ( !pImpl->m_aBackupURL.isEmpty() )
return; // the backup was done already
::utl::TempFileNamed aTransactTemp( aPrefix, true, aExtension, &aDestDir );
INetURLObject aBackObj( aTransactTemp.GetURL() );
OUString aBackupName = aBackObj.getName( INetURLObject::LAST_SEGMENT, true, INetURLObject::DecodeMechanism::WithCharset );
Reference < css::ucb::XCommandEnvironment > xDummyEnv;
::ucbhelper::Content aBackupCont;
if( ::ucbhelper::Content::create( aDestDir, xDummyEnv, comphelper::getProcessComponentContext(), aBackupCont ) )
{
try
{
OUString sMimeType = pImpl->getFilterMimeType();
aBackupCont.transferContent( aOriginalContent,
::ucbhelper::InsertOperation::Copy,
aBackupName,
NameClash::OVERWRITE,
sMimeType );
pImpl->m_aBackupURL = aBackObj.GetMainURL( INetURLObject::DecodeMechanism::NONE );
pImpl->m_bRemoveBackup = true;
}
catch( const Exception& )
{}
}
if ( pImpl->m_aBackupURL.isEmpty() )
aTransactTemp.EnableKillingFile();
}
void SfxMedium::DoInternalBackup_Impl( const ::ucbhelper::Content& aOriginalContent )
{
if ( !pImpl->m_aBackupURL.isEmpty() )
return; // the backup was done already
OUString aFileName = GetURLObject().getName( INetURLObject::LAST_SEGMENT,
true,
INetURLObject::DecodeMechanism::NONE );
sal_Int32 nPrefixLen = aFileName.lastIndexOf( '.' );
OUString aPrefix = ( nPrefixLen == -1 ) ? aFileName : aFileName.copy( 0, nPrefixLen );
OUString aExtension = ( nPrefixLen == -1 ) ? OUString() : aFileName.copy( nPrefixLen );
OUString aBakDir = SvtPathOptions().GetBackupPath();
// create content for the parent folder ( = backup folder )
::ucbhelper::Content aContent;
Reference < css::ucb::XCommandEnvironment > xEnv;
if( ::utl::UCBContentHelper::ensureFolder(comphelper::getProcessComponentContext(), xEnv, aBakDir, aContent) )
DoInternalBackup_Impl( aOriginalContent, aPrefix, aExtension, aBakDir );
if ( !pImpl->m_aBackupURL.isEmpty() )
return;
// the copying to the backup catalog failed ( for example because
// of using an encrypted partition as target catalog )
// since the user did not specify to make backup explicitly
// office should try to make backup in another place,
// target catalog does not look bad for this case ( and looks
// to be the only way for encrypted partitions )
INetURLObject aDest = GetURLObject();
if ( aDest.removeSegment() )
DoInternalBackup_Impl( aOriginalContent, aPrefix, aExtension, aDest.GetMainURL( INetURLObject::DecodeMechanism::NONE ) );
}
void SfxMedium::DoBackup_Impl(bool bForceUsingBackupPath)
{
// source file name is the logical name of this medium
INetURLObject aSource( GetURLObject() );
// there is nothing to backup in case source file does not exist
if ( !::utl::UCBContentHelper::IsDocument( aSource.GetMainURL( INetURLObject::DecodeMechanism::NONE ) ) )
return;
bool bSuccess = false;
bool bOnErrorRetryUsingBackupPath = false;
// get path for backups
OUString aBakDir;
if (!bForceUsingBackupPath
&& officecfg::Office::Common::Save::Document::BackupIntoDocumentFolder::get())
{
aBakDir = aSource.GetPartBeforeLastName();
bOnErrorRetryUsingBackupPath = true;
}
else
aBakDir = SvtPathOptions().GetBackupPath();
if( !aBakDir.isEmpty() )
{
// create content for the parent folder ( = backup folder )
::ucbhelper::Content aContent;
Reference < css::ucb::XCommandEnvironment > xEnv;
if( ::utl::UCBContentHelper::ensureFolder(comphelper::getProcessComponentContext(), xEnv, aBakDir, aContent) )
{
// save as ".bak" file
INetURLObject aDest( aBakDir );
aDest.insertName( aSource.getName() );
const OUString sExt
= aSource.hasExtension() ? aSource.getExtension() + ".bak" : OUString("bak");
aDest.setExtension(sExt);
OUString aFileName = aDest.getName( INetURLObject::LAST_SEGMENT, true, INetURLObject::DecodeMechanism::WithCharset );
// create a content for the source file
::ucbhelper::Content aSourceContent;
if ( ::ucbhelper::Content::create( aSource.GetMainURL( INetURLObject::DecodeMechanism::NONE ), xEnv, comphelper::getProcessComponentContext(), aSourceContent ) )
{
try
{
// do the transfer ( copy source file to backup dir )
OUString sMimeType = pImpl->getFilterMimeType();
aContent.transferContent( aSourceContent,
::ucbhelper::InsertOperation::Copy,
aFileName,
NameClash::OVERWRITE,
sMimeType );
pImpl->m_aBackupURL = aDest.GetMainURL( INetURLObject::DecodeMechanism::NONE );
pImpl->m_bRemoveBackup = false;
bSuccess = true;
}
catch ( const css::uno::Exception& )
{
}
}
}
}
if ( !bSuccess )
{
// in case a webdav server prevents file creation, or a partition is full, or whatever...
if (bOnErrorRetryUsingBackupPath)
return DoBackup_Impl(/*bForceUsingBackupPath=*/true);
pImpl->m_eError = ERRCODE_SFX_CANTCREATEBACKUP;
}
}
void SfxMedium::ClearBackup_Impl()
{
if( pImpl->m_bRemoveBackup )
{
// currently a document is always stored in a new medium,
// thus if a backup can not be removed the backup URL should not be cleaned
if ( !pImpl->m_aBackupURL.isEmpty() )
{
if ( ::utl::UCBContentHelper::Kill( pImpl->m_aBackupURL ) )
{
pImpl->m_bRemoveBackup = false;
pImpl->m_aBackupURL.clear();
}
else
{
SAL_WARN( "sfx.doc", "Couldn't remove backup file!");
}
}
}
else
pImpl->m_aBackupURL.clear();
}
void SfxMedium::GetLockingStream_Impl()
{
if ( GetURLObject().GetProtocol() != INetProtocol::File
|| pImpl->m_xLockingStream.is() )
return;
const SfxUnoAnyItem* pWriteStreamItem = SfxItemSet::GetItem<SfxUnoAnyItem>(pImpl->m_pSet.get(), SID_STREAM, false);
if ( pWriteStreamItem )
pWriteStreamItem->GetValue() >>= pImpl->m_xLockingStream;
if ( pImpl->m_xLockingStream.is() )
return;
// open the original document
uno::Sequence< beans::PropertyValue > xProps;
TransformItems( SID_OPENDOC, GetItemSet(), xProps );
utl::MediaDescriptor aMedium( xProps );
aMedium.addInputStreamOwnLock();
uno::Reference< io::XInputStream > xInputStream;
aMedium[utl::MediaDescriptor::PROP_STREAM] >>= pImpl->m_xLockingStream;
aMedium[utl::MediaDescriptor::PROP_INPUTSTREAM] >>= xInputStream;
if ( !pImpl->pTempFile && pImpl->m_aName.isEmpty() )
{
// the medium is still based on the original file, it makes sense to initialize the streams
if ( pImpl->m_xLockingStream.is() )
pImpl->xStream = pImpl->m_xLockingStream;
if ( xInputStream.is() )
pImpl->xInputStream = xInputStream;
if ( !pImpl->xInputStream.is() && pImpl->xStream.is() )
pImpl->xInputStream = pImpl->xStream->getInputStream();
}
}
void SfxMedium::GetMedium_Impl()
{
if ( pImpl->m_pInStream
&& (!pImpl->bIsTemp || pImpl->xInputStream.is() || pImpl->m_xInputStreamToLoadFrom.is() || pImpl->xStream.is() || pImpl->m_xLockingStream.is() ) )
return;
pImpl->bDownloadDone = false;
Reference< css::task::XInteractionHandler > xInteractionHandler = GetInteractionHandler();
//TODO/MBA: need support for SID_STREAM
const SfxUnoAnyItem* pWriteStreamItem = SfxItemSet::GetItem<SfxUnoAnyItem>(pImpl->m_pSet.get(), SID_STREAM, false);
const SfxUnoAnyItem* pInStreamItem = SfxItemSet::GetItem<SfxUnoAnyItem>(pImpl->m_pSet.get(), SID_INPUTSTREAM, false);
if ( pWriteStreamItem )
{
pWriteStreamItem->GetValue() >>= pImpl->xStream;
if ( pInStreamItem )
pInStreamItem->GetValue() >>= pImpl->xInputStream;
if ( !pImpl->xInputStream.is() && pImpl->xStream.is() )
pImpl->xInputStream = pImpl->xStream->getInputStream();
}
else if ( pInStreamItem )
{
pInStreamItem->GetValue() >>= pImpl->xInputStream;
}
else
{
uno::Sequence < beans::PropertyValue > xProps;
OUString aFileName;
if (!pImpl->m_aName.isEmpty())
{
if ( osl::FileBase::getFileURLFromSystemPath( pImpl->m_aName, aFileName )
!= osl::FileBase::E_None )
{
SAL_WARN( "sfx.doc", "Physical name not convertible!");
}
}
else
aFileName = GetName();
// in case the temporary file exists the streams should be initialized from it,
// but the original MediaDescriptor should not be changed
bool bFromTempFile = ( pImpl->pTempFile != nullptr );
if ( !bFromTempFile )
{
GetItemSet().Put( SfxStringItem( SID_FILE_NAME, aFileName ) );
if( !(pImpl->m_nStorOpenMode & StreamMode::WRITE) )
GetItemSet().Put( SfxBoolItem( SID_DOC_READONLY, true ) );
if (xInteractionHandler.is())
GetItemSet().Put( SfxUnoAnyItem( SID_INTERACTIONHANDLER, Any(xInteractionHandler) ) );
}
if ( pImpl->m_xInputStreamToLoadFrom.is() )
{
pImpl->xInputStream = pImpl->m_xInputStreamToLoadFrom;
if (pImpl->m_bInputStreamIsReadOnly)
GetItemSet().Put( SfxBoolItem( SID_DOC_READONLY, true ) );
}
else
{
TransformItems( SID_OPENDOC, GetItemSet(), xProps );
utl::MediaDescriptor aMedium( xProps );
if ( pImpl->m_xLockingStream.is() && !bFromTempFile )
{
// the medium is not based on the temporary file, so the original stream can be used
pImpl->xStream = pImpl->m_xLockingStream;
}
else
{
if ( bFromTempFile )
{
aMedium[utl::MediaDescriptor::PROP_URL] <<= aFileName;
aMedium.erase( utl::MediaDescriptor::PROP_READONLY );
aMedium.addInputStream();
}
else if ( GetURLObject().GetProtocol() == INetProtocol::File )
{
// use the special locking approach only for file URLs
aMedium.addInputStreamOwnLock();
}
else
{
// add a check for protocol, if it's http or https or provide webdav then add
// the interaction handler to be used by the authentication dialog
if ( GetURLObject().isAnyKnownWebDAVScheme() )
{
aMedium[utl::MediaDescriptor::PROP_AUTHENTICATIONHANDLER] <<= GetInteractionHandler( true );
}
aMedium.addInputStream();
}
// the ReadOnly property set in aMedium is ignored
// the check is done in LockOrigFileOnDemand() for file and non-file URLs
//TODO/MBA: what happens if property is not there?!
aMedium[utl::MediaDescriptor::PROP_STREAM] >>= pImpl->xStream;
aMedium[utl::MediaDescriptor::PROP_INPUTSTREAM] >>= pImpl->xInputStream;
}
GetContent();
if ( !pImpl->xInputStream.is() && pImpl->xStream.is() )
pImpl->xInputStream = pImpl->xStream->getInputStream();
}
if ( !bFromTempFile )
{
//TODO/MBA: need support for SID_STREAM
if ( pImpl->xStream.is() )
GetItemSet().Put( SfxUnoAnyItem( SID_STREAM, Any( pImpl->xStream ) ) );
GetItemSet().Put( SfxUnoAnyItem( SID_INPUTSTREAM, Any( pImpl->xInputStream ) ) );
}
}
//TODO/MBA: ErrorHandling - how to transport error from MediaDescriptor
if ( !GetErrorIgnoreWarning() && !pImpl->xStream.is() && !pImpl->xInputStream.is() )
SetError(ERRCODE_IO_ACCESSDENIED);
if ( !GetErrorIgnoreWarning() && !pImpl->m_pInStream )
{
if ( pImpl->xStream.is() )
pImpl->m_pInStream = utl::UcbStreamHelper::CreateStream( pImpl->xStream );
else if ( pImpl->xInputStream.is() )
pImpl->m_pInStream = utl::UcbStreamHelper::CreateStream( pImpl->xInputStream );
}
pImpl->bDownloadDone = true;
pImpl->aDoneLink.ClearPendingCall();
ErrCodeMsg nError = GetErrorIgnoreWarning();
pImpl->aDoneLink.Call( reinterpret_cast<void*>(sal_uInt32(nError.GetCode())) );
}
bool SfxMedium::IsRemote() const
{
return pImpl->m_bRemote;
}
void SfxMedium::SetUpdatePickList(bool bVal)
{
pImpl->bUpdatePickList = bVal;
}
bool SfxMedium::IsUpdatePickList() const
{
return pImpl->bUpdatePickList;
}
void SfxMedium::SetLongName(const OUString &rName)
{
pImpl->m_aLongName = rName;
}
const OUString& SfxMedium::GetLongName() const
{
return pImpl->m_aLongName;
}
void SfxMedium::SetDoneLink( const Link<void*,void>& rLink )
{
pImpl->aDoneLink = rLink;
}
void SfxMedium::Download( const Link<void*,void>& aLink )
{
SetDoneLink( aLink );
GetInStream();
if ( pImpl->m_pInStream && !aLink.IsSet() )
{
while( !pImpl->bDownloadDone && !Application::IsQuit())
Application::Yield();
}
}
/**
Sets m_aLogicName to a valid URL and if available sets
the physical name m_aName to the file name.
*/
void SfxMedium::Init_Impl()
{
Reference< XOutputStream > rOutStream;
// TODO/LATER: handle lifetime of storages
pImpl->bDisposeStorage = false;
const SfxStringItem* pSalvageItem = SfxItemSet::GetItem<SfxStringItem>(pImpl->m_pSet.get(), SID_DOC_SALVAGE, false);
if ( pSalvageItem && pSalvageItem->GetValue().isEmpty() )
{
pSalvageItem = nullptr;
pImpl->m_pSet->ClearItem( SID_DOC_SALVAGE );
}
if (!pImpl->m_aLogicName.isEmpty())
{
INetURLObject aUrl( pImpl->m_aLogicName );
INetProtocol eProt = aUrl.GetProtocol();
if ( eProt == INetProtocol::NotValid )
{
SAL_WARN( "sfx.doc", "URL <" << pImpl->m_aLogicName << "> with unknown protocol" );
}
else
{
if ( aUrl.HasMark() )
{
std::unique_lock<std::recursive_mutex> chkEditLock;
if (pImpl->m_pCheckEditableWorkerMutex != nullptr)
chkEditLock = std::unique_lock<std::recursive_mutex>(
*(pImpl->m_pCheckEditableWorkerMutex));
pImpl->m_aLogicName = aUrl.GetURLNoMark( INetURLObject::DecodeMechanism::NONE );
if (chkEditLock.owns_lock())
chkEditLock.unlock();
GetItemSet().Put( SfxStringItem( SID_JUMPMARK, aUrl.GetMark() ) );
}
// try to convert the URL into a physical name - but never change a physical name
// physical name may be set if the logical name is changed after construction
if ( pImpl->m_aName.isEmpty() )
osl::FileBase::getSystemPathFromFileURL( GetURLObject().GetMainURL( INetURLObject::DecodeMechanism::NONE ), pImpl->m_aName );
else
{
DBG_ASSERT( pSalvageItem, "Suspicious change of logical name!" );
}
}
}
if ( pSalvageItem )
{
std::unique_lock<std::recursive_mutex> chkEditLock;
if (pImpl->m_pCheckEditableWorkerMutex != nullptr)
chkEditLock
= std::unique_lock<std::recursive_mutex>(*(pImpl->m_pCheckEditableWorkerMutex));
pImpl->m_aLogicName = pSalvageItem->GetValue();
pImpl->m_pURLObj.reset();
if (chkEditLock.owns_lock())
chkEditLock.unlock();
pImpl->m_bSalvageMode = true;
}
// in case output stream is by mistake here
// clear the reference
const SfxUnoAnyItem* pOutStreamItem = SfxItemSet::GetItem<SfxUnoAnyItem>(pImpl->m_pSet.get(), SID_OUTPUTSTREAM, false);
if( pOutStreamItem
&& ( !( pOutStreamItem->GetValue() >>= rOutStream )
|| !pImpl->m_aLogicName.startsWith("private:stream")) )
{
pImpl->m_pSet->ClearItem( SID_OUTPUTSTREAM );
SAL_WARN( "sfx.doc", "Unexpected Output stream parameter!" );
}
if (!pImpl->m_aLogicName.isEmpty())
{
// if the logic name is set it should be set in MediaDescriptor as well
const SfxStringItem* pFileNameItem = SfxItemSet::GetItem<SfxStringItem>(pImpl->m_pSet.get(), SID_FILE_NAME, false);
if ( !pFileNameItem )
{
// let the ItemSet be created if necessary
GetItemSet().Put(
SfxStringItem(
SID_FILE_NAME, INetURLObject( pImpl->m_aLogicName ).GetMainURL( INetURLObject::DecodeMechanism::NONE ) ) );
}
}
SetIsRemote_Impl();
osl::DirectoryItem item;
if (osl::DirectoryItem::get(GetName(), item) == osl::FileBase::E_None) {
osl::FileStatus stat(osl_FileStatus_Mask_Attributes);
if (item.getFileStatus(stat) == osl::FileBase::E_None
&& stat.isValid(osl_FileStatus_Mask_Attributes))
{
if ((stat.getAttributes() & osl_File_Attribute_ReadOnly) != 0)
{
pImpl->m_bOriginallyReadOnly = true;
}
}
}
}
SfxMedium::SfxMedium() : pImpl(new SfxMedium_Impl)
{
Init_Impl();
}
void SfxMedium::UseInteractionHandler( bool bUse )
{
pImpl->bAllowDefaultIntHdl = bUse;
}
css::uno::Reference< css::task::XInteractionHandler >
SfxMedium::GetInteractionHandler( bool bGetAlways )
{
// if interaction isn't allowed explicitly ... return empty reference!
if ( !bGetAlways && !pImpl->bUseInteractionHandler )
return css::uno::Reference< css::task::XInteractionHandler >();
// search a possible existing handler inside cached item set
if ( pImpl->m_pSet )
{
css::uno::Reference< css::task::XInteractionHandler > xHandler;
const SfxUnoAnyItem* pHandler = SfxItemSet::GetItem<SfxUnoAnyItem>(pImpl->m_pSet.get(), SID_INTERACTIONHANDLER, false);
if ( pHandler && (pHandler->GetValue() >>= xHandler) && xHandler.is() )
return xHandler;
}
// if default interaction isn't allowed explicitly ... return empty reference!
if ( !bGetAlways && !pImpl->bAllowDefaultIntHdl )
return css::uno::Reference< css::task::XInteractionHandler >();
// otherwise return cached default handler ... if it exist.
if ( pImpl->xInteraction.is() )
return pImpl->xInteraction;
// create default handler and cache it!
Reference< uno::XComponentContext > xContext = ::comphelper::getProcessComponentContext();
pImpl->xInteraction.set(
task::InteractionHandler::createWithParent(xContext, nullptr), UNO_QUERY_THROW );
return pImpl->xInteraction;
}
void SfxMedium::SetFilter( const std::shared_ptr<const SfxFilter>& pFilter )
{
pImpl->m_pFilter = pFilter;
}
const std::shared_ptr<const SfxFilter>& SfxMedium::GetFilter() const
{
return pImpl->m_pFilter;
}
sal_uInt32 SfxMedium::CreatePasswordToModifyHash( std::u16string_view aPasswd, bool bWriter )
{
sal_uInt32 nHash = 0;
if ( !aPasswd.empty() )
{
if ( bWriter )
{
nHash = ::comphelper::DocPasswordHelper::GetWordHashAsUINT32( aPasswd );
}
else
{
rtl_TextEncoding nEncoding = osl_getThreadTextEncoding();
nHash = ::comphelper::DocPasswordHelper::GetXLHashAsUINT16( aPasswd, nEncoding );
}
}
return nHash;
}
void SfxMedium::Close(bool bInDestruction)
{
if ( pImpl->xStorage.is() )
{
CloseStorage();
}
CloseStreams_Impl(bInDestruction);
UnlockFile( false );
}
void SfxMedium::CloseAndRelease()
{
if ( pImpl->xStorage.is() )
{
CloseStorage();
}
CloseAndReleaseStreams_Impl();
UnlockFile( true );
}
void SfxMedium::DisableUnlockWebDAV( bool bDisableUnlockWebDAV )
{
pImpl->m_bDisableUnlockWebDAV = bDisableUnlockWebDAV;
}
void SfxMedium::DisableFileSync(bool bDisableFileSync)
{
pImpl->m_bDisableFileSync = bDisableFileSync;
}
void SfxMedium::UnlockFile( bool bReleaseLockStream )
{
#if !HAVE_FEATURE_MULTIUSER_ENVIRONMENT
(void) bReleaseLockStream;
#else
// check if webdav
if ( GetURLObject().isAnyKnownWebDAVScheme() )
{
// do nothing if WebDAV locking if disabled
// (shouldn't happen because we already skipped locking,
// see LockOrigFileOnDemand, but just in case ...)
if (!IsWebDAVLockingUsed())
return;
if ( pImpl->m_bLocked )
{
// an interaction handler should be used for authentication, if needed
try {
uno::Reference< css::task::XInteractionHandler > xHandler = GetInteractionHandler( true );
uno::Reference< css::ucb::XCommandEnvironment > xComEnv = new ::ucbhelper::CommandEnvironment( xHandler,
Reference< css::ucb::XProgressHandler >() );
ucbhelper::Content aContentToUnlock( GetURLObject().GetMainURL( INetURLObject::DecodeMechanism::NONE ), xComEnv, comphelper::getProcessComponentContext());
pImpl->m_bLocked = false;
//check if WebDAV unlock was explicitly disabled
if ( !pImpl->m_bDisableUnlockWebDAV )
aContentToUnlock.unlock();
}
catch ( uno::Exception& )
{
TOOLS_WARN_EXCEPTION( "sfx.doc", "Locking exception: WebDAV while trying to lock the file" );
}
}
return;
}
if ( pImpl->m_xLockingStream.is() )
{
if ( bReleaseLockStream )
{
try
{
uno::Reference< io::XInputStream > xInStream = pImpl->m_xLockingStream->getInputStream();
uno::Reference< io::XOutputStream > xOutStream = pImpl->m_xLockingStream->getOutputStream();
if ( xInStream.is() )
xInStream->closeInput();
if ( xOutStream.is() )
xOutStream->closeOutput();
}
catch( const uno::Exception& )
{}
}
pImpl->m_xLockingStream.clear();
}
if ( !pImpl->m_bLocked )
return;
try
{
::svt::DocumentLockFile aLockFile(pImpl->m_aLogicName);
try
{
pImpl->m_bLocked = false;
// TODO/LATER: A warning could be shown in case the file is not the own one
aLockFile.RemoveFile();
}
catch (const io::WrongFormatException&)
{
// erase the empty or corrupt file
aLockFile.RemoveFileDirectly();
}
}
catch( const uno::Exception& )
{}
if(!pImpl->m_bMSOLockFileCreated)
return;
try
{
::svt::MSODocumentLockFile aMSOLockFile(pImpl->m_aLogicName);
try
{
pImpl->m_bLocked = false;
// TODO/LATER: A warning could be shown in case the file is not the own one
aMSOLockFile.RemoveFile();
}
catch (const io::WrongFormatException&)
{
// erase the empty or corrupt file
aMSOLockFile.RemoveFileDirectly();
}
}
catch( const uno::Exception& )
{}
pImpl->m_bMSOLockFileCreated = false;
#endif
}
void SfxMedium::CloseAndReleaseStreams_Impl()
{
CloseZipStorage_Impl();
uno::Reference< io::XInputStream > xInToClose = pImpl->xInputStream;
uno::Reference< io::XOutputStream > xOutToClose;
if ( pImpl->xStream.is() )
{
xOutToClose = pImpl->xStream->getOutputStream();
// if the locking stream is closed here the related member should be cleaned
if ( pImpl->xStream == pImpl->m_xLockingStream )
pImpl->m_xLockingStream.clear();
}
// The probably existing SvStream wrappers should be closed first
CloseStreams_Impl();
// in case of salvage mode the storage is based on the streams
if ( pImpl->m_bSalvageMode )
return;
try
{
if ( xInToClose.is() )
xInToClose->closeInput();
if ( xOutToClose.is() )
xOutToClose->closeOutput();
}
catch ( const uno::Exception& )
{
}
}
void SfxMedium::CloseStreams_Impl(bool bInDestruction)
{
CloseInStream_Impl(bInDestruction);
CloseOutStream_Impl();
if ( pImpl->m_pSet )
pImpl->m_pSet->ClearItem( SID_CONTENT );
pImpl->aContent = ::ucbhelper::Content();
}
void SfxMedium::SetIsRemote_Impl()
{
INetURLObject aObj( GetName() );
switch( aObj.GetProtocol() )
{
case INetProtocol::Ftp:
case INetProtocol::Http:
case INetProtocol::Https:
pImpl->m_bRemote = true;
break;
default:
pImpl->m_bRemote = GetName().startsWith("private:msgid");
break;
}
// As files that are written to the remote transmission must also be able
// to be read.
if (pImpl->m_bRemote)
pImpl->m_nStorOpenMode |= StreamMode::READ;
}
void SfxMedium::SetName( const OUString& aNameP, bool bSetOrigURL )
{
if (pImpl->aOrigURL.isEmpty())
pImpl->aOrigURL = pImpl->m_aLogicName;
if( bSetOrigURL )
pImpl->aOrigURL = aNameP;
std::unique_lock<std::recursive_mutex> chkEditLock;
if (pImpl->m_pCheckEditableWorkerMutex != nullptr)
chkEditLock = std::unique_lock<std::recursive_mutex>(*(pImpl->m_pCheckEditableWorkerMutex));
pImpl->m_aLogicName = aNameP;
pImpl->m_pURLObj.reset();
if (chkEditLock.owns_lock())
chkEditLock.unlock();
pImpl->aContent = ::ucbhelper::Content();
Init_Impl();
}
const OUString& SfxMedium::GetOrigURL() const
{
return pImpl->aOrigURL.isEmpty() ? pImpl->m_aLogicName : pImpl->aOrigURL;
}
void SfxMedium::SetPhysicalName_Impl( const OUString& rNameP )
{
if ( rNameP != pImpl->m_aName )
{
pImpl->pTempFile.reset();
if ( !pImpl->m_aName.isEmpty() || !rNameP.isEmpty() )
pImpl->aContent = ::ucbhelper::Content();
pImpl->m_aName = rNameP;
pImpl->m_bTriedStorage = false;
pImpl->bIsStorage = false;
}
}
void SfxMedium::ReOpen()
{
bool bUseInteractionHandler = pImpl->bUseInteractionHandler;
pImpl->bUseInteractionHandler = false;
GetMedium_Impl();
pImpl->bUseInteractionHandler = bUseInteractionHandler;
}
void SfxMedium::CompleteReOpen()
{
// do not use temporary file for reopen and in case of success throw the temporary file away
bool bUseInteractionHandler = pImpl->bUseInteractionHandler;
pImpl->bUseInteractionHandler = false;
std::unique_ptr<::utl::TempFileNamed> pTmpFile;
if ( pImpl->pTempFile )
{
pTmpFile = std::move(pImpl->pTempFile);
pImpl->m_aName.clear();
}
GetMedium_Impl();
if ( GetErrorIgnoreWarning() )
{
if ( pImpl->pTempFile )
{
pImpl->pTempFile->EnableKillingFile();
pImpl->pTempFile.reset();
}
pImpl->pTempFile = std::move( pTmpFile );
if ( pImpl->pTempFile )
pImpl->m_aName = pImpl->pTempFile->GetFileName();
}
else if (pTmpFile)
{
pTmpFile->EnableKillingFile();
pTmpFile.reset();
}
pImpl->bUseInteractionHandler = bUseInteractionHandler;
}
SfxMedium::SfxMedium(const OUString &rName, StreamMode nOpenMode, std::shared_ptr<const SfxFilter> pFilter, const std::shared_ptr<SfxItemSet>& pInSet) :
pImpl(new SfxMedium_Impl)
{
pImpl->m_pSet = pInSet;
pImpl->m_pFilter = std::move(pFilter);
pImpl->m_aLogicName = rName;
pImpl->m_nStorOpenMode = nOpenMode;
Init_Impl();
}
SfxMedium::SfxMedium(const OUString &rName, const OUString &rReferer, StreamMode nOpenMode, std::shared_ptr<const SfxFilter> pFilter, const std::shared_ptr<SfxItemSet>& pInSet) :
pImpl(new SfxMedium_Impl)
{
pImpl->m_pSet = pInSet;
SfxItemSet& s = GetItemSet();
if (s.GetItem(SID_REFERER) == nullptr) {
s.Put(SfxStringItem(SID_REFERER, rReferer));
}
pImpl->m_pFilter = std::move(pFilter);
pImpl->m_aLogicName = rName;
pImpl->m_nStorOpenMode = nOpenMode;
Init_Impl();
}
SfxMedium::SfxMedium( const uno::Sequence<beans::PropertyValue>& aArgs ) :
pImpl(new SfxMedium_Impl)
{
SfxAllItemSet *pParams = new SfxAllItemSet( SfxGetpApp()->GetPool() );
pImpl->m_pSet.reset( pParams );
TransformParameters( SID_OPENDOC, aArgs, *pParams );
SetArgs(aArgs);
OUString aFilterProvider, aFilterName;
{
const SfxStringItem* pItem = nullptr;
if ((pItem = pImpl->m_pSet->GetItemIfSet(SID_FILTER_PROVIDER)))
aFilterProvider = pItem->GetValue();
if ((pItem = pImpl->m_pSet->GetItemIfSet(SID_FILTER_NAME)))
aFilterName = pItem->GetValue();
}
if (aFilterProvider.isEmpty())
{
// This is a conventional filter type.
pImpl->m_pFilter = SfxGetpApp()->GetFilterMatcher().GetFilter4FilterName( aFilterName );
}
else
{
// This filter is from an external provider such as orcus.
pImpl->m_pCustomFilter = std::make_shared<SfxFilter>(aFilterProvider, aFilterName);
pImpl->m_pFilter = pImpl->m_pCustomFilter;
}
const SfxStringItem* pSalvageItem = SfxItemSet::GetItem<SfxStringItem>(pImpl->m_pSet.get(), SID_DOC_SALVAGE, false);
if( pSalvageItem )
{
// QUESTION: there is some treatment of Salvage in Init_Impl; align!
if ( !pSalvageItem->GetValue().isEmpty() )
{
// if a URL is provided in SalvageItem that means that the FileName refers to a temporary file
// that must be copied here
const SfxStringItem* pFileNameItem = SfxItemSet::GetItem<SfxStringItem>(pImpl->m_pSet.get(), SID_FILE_NAME, false);
if (!pFileNameItem) throw uno::RuntimeException();
OUString aNewTempFileURL = SfxMedium::CreateTempCopyWithExt( pFileNameItem->GetValue() );
if ( !aNewTempFileURL.isEmpty() )
{
pImpl->m_pSet->Put( SfxStringItem( SID_FILE_NAME, aNewTempFileURL ) );
pImpl->m_pSet->ClearItem( SID_INPUTSTREAM );
pImpl->m_pSet->ClearItem( SID_STREAM );
pImpl->m_pSet->ClearItem( SID_CONTENT );
}
else
{
SAL_WARN( "sfx.doc", "Can not create a new temporary file for crash recovery!" );
}
}
}
const SfxBoolItem* pReadOnlyItem = SfxItemSet::GetItem<SfxBoolItem>(pImpl->m_pSet.get(), SID_DOC_READONLY, false);
if ( pReadOnlyItem && pReadOnlyItem->GetValue() )
pImpl->m_bOriginallyLoadedReadOnly = true;
const SfxStringItem* pFileNameItem = SfxItemSet::GetItem<SfxStringItem>(pImpl->m_pSet.get(), SID_FILE_NAME, false);
if (!pFileNameItem) throw uno::RuntimeException();
pImpl->m_aLogicName = pFileNameItem->GetValue();
pImpl->m_nStorOpenMode = pImpl->m_bOriginallyLoadedReadOnly
? SFX_STREAM_READONLY : SFX_STREAM_READWRITE;
Init_Impl();
}
void SfxMedium::SetArgs(const uno::Sequence<beans::PropertyValue>& rArgs)
{
static constexpr OUStringLiteral sStream(u"Stream");
static constexpr OUStringLiteral sInputStream(u"InputStream");
comphelper::SequenceAsHashMap aArgsMap(rArgs);
aArgsMap.erase(sStream);
aArgsMap.erase(sInputStream);
pImpl->m_aArgs = aArgsMap.getAsConstPropertyValueList();
}
const uno::Sequence<beans::PropertyValue> & SfxMedium::GetArgs() const { return pImpl->m_aArgs; }
SfxMedium::SfxMedium( const uno::Reference < embed::XStorage >& rStor, const OUString& rBaseURL, const std::shared_ptr<SfxItemSet>& p ) :
pImpl(new SfxMedium_Impl)
{
OUString aType = SfxFilter::GetTypeFromStorage(rStor);
pImpl->m_pFilter = SfxGetpApp()->GetFilterMatcher().GetFilter4EA( aType );
DBG_ASSERT( pImpl->m_pFilter, "No Filter for storage found!" );
Init_Impl();
pImpl->xStorage = rStor;
pImpl->bDisposeStorage = false;
// always take BaseURL first, could be overwritten by ItemSet
GetItemSet().Put( SfxStringItem( SID_DOC_BASEURL, rBaseURL ) );
if ( p )
GetItemSet().Put( *p );
}
SfxMedium::SfxMedium( const uno::Reference < embed::XStorage >& rStor, const OUString& rBaseURL, const OUString &rTypeName, const std::shared_ptr<SfxItemSet>& p ) :
pImpl(new SfxMedium_Impl)
{
pImpl->m_pFilter = SfxGetpApp()->GetFilterMatcher().GetFilter4EA( rTypeName );
DBG_ASSERT( pImpl->m_pFilter, "No Filter for storage found!" );
Init_Impl();
pImpl->xStorage = rStor;
pImpl->bDisposeStorage = false;
// always take BaseURL first, could be overwritten by ItemSet
GetItemSet().Put( SfxStringItem( SID_DOC_BASEURL, rBaseURL ) );
if ( p )
GetItemSet().Put( *p );
}
// NOTE: should only be called on main thread
SfxMedium::~SfxMedium()
{
CancelCheckEditableEntry();
// if there is a requirement to clean the backup this is the last possibility to do it
ClearBackup_Impl();
Close(/*bInDestruction*/true);
if( !pImpl->bIsTemp || pImpl->m_aName.isEmpty() )
return;
OUString aTemp;
if ( osl::FileBase::getFileURLFromSystemPath( pImpl->m_aName, aTemp )
!= osl::FileBase::E_None )
{
SAL_WARN( "sfx.doc", "Physical name not convertible!");
}
if ( !::utl::UCBContentHelper::Kill( aTemp ) )
{
SAL_WARN( "sfx.doc", "Couldn't remove temporary file!");
}
}
const OUString& SfxMedium::GetName() const
{
return pImpl->m_aLogicName;
}
const INetURLObject& SfxMedium::GetURLObject() const
{
std::unique_lock<std::recursive_mutex> chkEditLock;
if (pImpl->m_pCheckEditableWorkerMutex != nullptr)
chkEditLock = std::unique_lock<std::recursive_mutex>(*(pImpl->m_pCheckEditableWorkerMutex));
if (!pImpl->m_pURLObj)
{
pImpl->m_pURLObj.reset( new INetURLObject( pImpl->m_aLogicName ) );
pImpl->m_pURLObj->SetMark(u"");
}
return *pImpl->m_pURLObj;
}
void SfxMedium::SetExpired_Impl( const DateTime& rDateTime )
{
pImpl->aExpireTime = rDateTime;
}
bool SfxMedium::IsExpired() const
{
return pImpl->aExpireTime.IsValidAndGregorian() && pImpl->aExpireTime < DateTime( DateTime::SYSTEM );
}
SfxFrame* SfxMedium::GetLoadTargetFrame() const
{
return pImpl->wLoadTargetFrame;
}
void SfxMedium::setStreamToLoadFrom(const css::uno::Reference<css::io::XInputStream>& xInputStream, bool bIsReadOnly )
{
pImpl->m_xInputStreamToLoadFrom = xInputStream;
pImpl->m_bInputStreamIsReadOnly = bIsReadOnly;
}
void SfxMedium::SetLoadTargetFrame(SfxFrame* pFrame )
{
pImpl->wLoadTargetFrame = pFrame;
}
void SfxMedium::SetStorage_Impl(const uno::Reference<embed::XStorage>& xStorage)
{
pImpl->xStorage = xStorage;
pImpl->m_bODFWholesomeEncryption = false;
}
void SfxMedium::SetInnerStorage_Impl(const uno::Reference<embed::XStorage>& xStorage)
{
pImpl->xStorage = xStorage;
pImpl->m_bODFWholesomeEncryption = true;
}
SfxItemSet& SfxMedium::GetItemSet() const
{
if (!pImpl->m_pSet)
pImpl->m_pSet = std::make_shared<SfxAllItemSet>( SfxGetpApp()->GetPool() );
return *pImpl->m_pSet;
}
SvKeyValueIterator* SfxMedium::GetHeaderAttributes_Impl()
{
if( !pImpl->xAttributes.is() )
{
pImpl->xAttributes = SvKeyValueIteratorRef( new SvKeyValueIterator );
if ( GetContent().is() )
{
try
{
Any aAny = pImpl->aContent.getPropertyValue("MediaType");
OUString aContentType;
aAny >>= aContentType;
pImpl->xAttributes->Append( SvKeyValue( "content-type", aContentType ) );
}
catch ( const css::uno::Exception& )
{
}
}
}
return pImpl->xAttributes.get();
}
css::uno::Reference< css::io::XInputStream > const & SfxMedium::GetInputStream()
{
if ( !pImpl->xInputStream.is() )
GetMedium_Impl();
return pImpl->xInputStream;
}
const uno::Sequence < util::RevisionTag >& SfxMedium::GetVersionList( bool _bNoReload )
{
// if the medium has no name, then this medium should represent a new document and can have no version info
if ( ( !_bNoReload || !pImpl->m_bVersionsAlreadyLoaded ) && !pImpl->aVersions.hasElements() &&
( !pImpl->m_aName.isEmpty() || !pImpl->m_aLogicName.isEmpty() ) && GetStorage().is() )
{
uno::Reference < document::XDocumentRevisionListPersistence > xReader =
document::DocumentRevisionListPersistence::create( comphelper::getProcessComponentContext() );
try
{
pImpl->aVersions = xReader->load( GetStorage() );
}
catch ( const uno::Exception& )
{
}
}
if ( !pImpl->m_bVersionsAlreadyLoaded )
pImpl->m_bVersionsAlreadyLoaded = true;
return pImpl->aVersions;
}
uno::Sequence < util::RevisionTag > SfxMedium::GetVersionList( const uno::Reference < embed::XStorage >& xStorage )
{
uno::Reference < document::XDocumentRevisionListPersistence > xReader =
document::DocumentRevisionListPersistence::create( comphelper::getProcessComponentContext() );
try
{
return xReader->load( xStorage );
}
catch ( const uno::Exception& )
{
}
return uno::Sequence < util::RevisionTag >();
}
void SfxMedium::AddVersion_Impl( util::RevisionTag& rRevision )
{
if ( !GetStorage().is() )
return;
// To determine a unique name for the stream
std::vector<sal_uInt32> aLongs;
sal_Int32 nLength = pImpl->aVersions.getLength();
for ( const auto& rVersion : std::as_const(pImpl->aVersions) )
{
sal_uInt32 nVer = static_cast<sal_uInt32>( o3tl::toInt32(rVersion.Identifier.subView(7)));
size_t n;
for ( n=0; n<aLongs.size(); ++n )
if ( nVer<aLongs[n] )
break;
aLongs.insert( aLongs.begin()+n, nVer );
}
std::vector<sal_uInt32>::size_type nKey;
for ( nKey=0; nKey<aLongs.size(); ++nKey )
if ( aLongs[nKey] > nKey+1 )
break;
OUString aRevName = "Version" + OUString::number( nKey + 1 );
pImpl->aVersions.realloc( nLength+1 );
rRevision.Identifier = aRevName;
pImpl->aVersions.getArray()[nLength] = rRevision;
}
void SfxMedium::RemoveVersion_Impl( const OUString& rName )
{
if ( !pImpl->aVersions.hasElements() )
return;
auto pVersion = std::find_if(std::cbegin(pImpl->aVersions), std::cend(pImpl->aVersions),
[&rName](const auto& rVersion) { return rVersion.Identifier == rName; });
if (pVersion != std::cend(pImpl->aVersions))
{
auto nIndex = static_cast<sal_Int32>(std::distance(std::cbegin(pImpl->aVersions), pVersion));
comphelper::removeElementAt(pImpl->aVersions, nIndex);
}
}
bool SfxMedium::TransferVersionList_Impl( SfxMedium const & rMedium )
{
if ( rMedium.pImpl->aVersions.hasElements() )
{
pImpl->aVersions = rMedium.pImpl->aVersions;
return true;
}
return false;
}
void SfxMedium::SaveVersionList_Impl()
{
if ( !GetStorage().is() )
return;
if ( !pImpl->aVersions.hasElements() )
return;
uno::Reference < document::XDocumentRevisionListPersistence > xWriter =
document::DocumentRevisionListPersistence::create( comphelper::getProcessComponentContext() );
try
{
xWriter->store( GetStorage(), pImpl->aVersions );
}
catch ( const uno::Exception& )
{
}
}
bool SfxMedium::IsReadOnly() const
{
// a) ReadOnly filter can't produce read/write contents!
bool bReadOnly = pImpl->m_pFilter && (pImpl->m_pFilter->GetFilterFlags() & SfxFilterFlags::OPENREADONLY);
// b) if filter allow read/write contents .. check open mode of the storage
if (!bReadOnly)
bReadOnly = !( GetOpenMode() & StreamMode::WRITE );
// c) the API can force the readonly state!
if (!bReadOnly)
{
const SfxBoolItem* pItem = GetItemSet().GetItem(SID_DOC_READONLY, false);
if (pItem)
bReadOnly = pItem->GetValue();
}
return bReadOnly;
}
bool SfxMedium::IsOriginallyReadOnly() const
{
return pImpl->m_bOriginallyReadOnly;
}
void SfxMedium::SetOriginallyReadOnly(bool val)
{
pImpl->m_bOriginallyReadOnly = val;
}
bool SfxMedium::IsOriginallyLoadedReadOnly() const
{
return pImpl->m_bOriginallyLoadedReadOnly;
}
bool SfxMedium::SetWritableForUserOnly( const OUString& aURL )
{
// UCB does not allow to allow write access only for the user,
// use osl API
bool bResult = false;
::osl::DirectoryItem aDirItem;
if ( ::osl::DirectoryItem::get( aURL, aDirItem ) == ::osl::FileBase::E_None )
{
::osl::FileStatus aFileStatus( osl_FileStatus_Mask_Attributes );
if ( aDirItem.getFileStatus( aFileStatus ) == osl::FileBase::E_None
&& aFileStatus.isValid( osl_FileStatus_Mask_Attributes ) )
{
sal_uInt64 nAttributes = aFileStatus.getAttributes();
nAttributes &= ~(osl_File_Attribute_OwnWrite |
osl_File_Attribute_GrpWrite |
osl_File_Attribute_OthWrite |
osl_File_Attribute_ReadOnly);
nAttributes |= (osl_File_Attribute_OwnWrite |
osl_File_Attribute_OwnRead);
bResult = ( osl::File::setAttributes( aURL, nAttributes ) == ::osl::FileBase::E_None );
}
}
return bResult;
}
namespace
{
/// Get the parent directory of a temporary file for output purposes.
OUString GetLogicBase(const INetURLObject& rURL, std::unique_ptr<SfxMedium_Impl> const & pImpl)
{
OUString aLogicBase;
#if HAVE_FEATURE_MACOSX_SANDBOX
// In a sandboxed environment we don't want to attempt to create temporary files in the same
// directory where the user has selected an output file to be stored. The sandboxed process has
// permission only to create the specifically named output file in that directory.
(void) rURL;
(void) pImpl;
#else
if (!pImpl->m_bHasEmbeddedObjects // Embedded objects would mean a special base, ignore that.
&& rURL.GetProtocol() == INetProtocol::File && !pImpl->m_pInStream)
{
// Try to create the temp file in the same directory when storing.
INetURLObject aURL(rURL);
aURL.removeSegment();
aLogicBase = aURL.GetMainURL(INetURLObject::DecodeMechanism::WithCharset);
}
#endif // !HAVE_FEATURE_MACOSX_SANDBOX
return aLogicBase;
}
}
void SfxMedium::CreateTempFile( bool bReplace )
{
if ( pImpl->pTempFile )
{
if ( !bReplace )
return;
pImpl->pTempFile.reset();
pImpl->m_aName.clear();
}
OUString aLogicBase = GetLogicBase(GetURLObject(), pImpl);
pImpl->pTempFile.reset(new ::utl::TempFileNamed(&aLogicBase));
pImpl->pTempFile->EnableKillingFile();
pImpl->m_aName = pImpl->pTempFile->GetFileName();
OUString aTmpURL = pImpl->pTempFile->GetURL();
if ( pImpl->m_aName.isEmpty() || aTmpURL.isEmpty() )
{
SetError(ERRCODE_IO_CANTWRITE);
return;
}
if ( !(pImpl->m_nStorOpenMode & StreamMode::TRUNC) )
{
bool bTransferSuccess = false;
if ( GetContent().is()
&& GetURLObject().GetProtocol() == INetProtocol::File
&& ::utl::UCBContentHelper::IsDocument( GetURLObject().GetMainURL( INetURLObject::DecodeMechanism::NONE ) ) )
{
// if there is already such a document, we should copy it
// if it is a file system use OS copy process
try
{
uno::Reference< css::ucb::XCommandEnvironment > xComEnv;
INetURLObject aTmpURLObj( aTmpURL );
OUString aFileName = aTmpURLObj.getName( INetURLObject::LAST_SEGMENT,
true,
INetURLObject::DecodeMechanism::WithCharset );
if ( !aFileName.isEmpty() && aTmpURLObj.removeSegment() )
{
::ucbhelper::Content aTargetContent( aTmpURLObj.GetMainURL( INetURLObject::DecodeMechanism::NONE ), xComEnv, comphelper::getProcessComponentContext() );
OUString sMimeType = pImpl->getFilterMimeType();
aTargetContent.transferContent( pImpl->aContent, ::ucbhelper::InsertOperation::Copy, aFileName, NameClash::OVERWRITE, sMimeType );
SetWritableForUserOnly( aTmpURL );
bTransferSuccess = true;
}
}
catch( const uno::Exception& )
{}
if ( bTransferSuccess )
{
CloseOutStream();
CloseInStream();
}
}
if ( !bTransferSuccess && pImpl->m_pInStream )
{
// the case when there is no URL-access available or this is a remote protocol
// but there is an input stream
GetOutStream();
if ( pImpl->m_pOutStream )
{
std::unique_ptr<char[]> pBuf(new char [8192]);
ErrCode nErr = ERRCODE_NONE;
pImpl->m_pInStream->Seek(0);
pImpl->m_pOutStream->Seek(0);
while( !pImpl->m_pInStream->eof() && nErr == ERRCODE_NONE )
{
sal_uInt32 nRead = pImpl->m_pInStream->ReadBytes(pBuf.get(), 8192);
nErr = pImpl->m_pInStream->GetError();
pImpl->m_pOutStream->WriteBytes( pBuf.get(), nRead );
}
bTransferSuccess = true;
CloseInStream();
}
CloseOutStream_Impl();
}
else
{
// Quite strange design, but currently it is expected that in this case no transfer happens
// TODO/LATER: get rid of this inconsistent part of the call design
bTransferSuccess = true;
CloseInStream();
}
if ( !bTransferSuccess )
{
SetError(ERRCODE_IO_CANTWRITE);
return;
}
}
CloseStorage();
}
void SfxMedium::CreateTempFileNoCopy()
{
// this call always replaces the existing temporary file
pImpl->pTempFile.reset();
OUString aLogicBase = GetLogicBase(GetURLObject(), pImpl);
pImpl->pTempFile.reset(new ::utl::TempFileNamed(&aLogicBase));
pImpl->pTempFile->EnableKillingFile();
pImpl->m_aName = pImpl->pTempFile->GetFileName();
if ( pImpl->m_aName.isEmpty() )
{
SetError(ERRCODE_IO_CANTWRITE);
return;
}
CloseOutStream_Impl();
CloseStorage();
}
bool SfxMedium::SignDocumentContentUsingCertificate(
const css::uno::Reference<css::frame::XModel>& xModel, bool bHasValidDocumentSignature,
const Reference<XCertificate>& xCertificate)
{
bool bChanges = false;
if (IsOpen() || GetErrorIgnoreWarning())
{
SAL_WARN("sfx.doc", "The medium must be closed by the signer!");
return bChanges;
}
// The component should know if there was a valid document signature, since
// it should show a warning in this case
OUString aODFVersion(comphelper::OStorageHelper::GetODFVersionFromStorage(GetStorage()));
uno::Reference< security::XDocumentDigitalSignatures > xSigner(
security::DocumentDigitalSignatures::createWithVersionAndValidSignature(
comphelper::getProcessComponentContext(), aODFVersion, bHasValidDocumentSignature ) );
auto xModelSigner = dynamic_cast<sfx2::DigitalSignatures*>(xSigner.get());
if (!xModelSigner)
{
return bChanges;
}
uno::Reference< embed::XStorage > xWriteableZipStor;
// we can reuse the temporary file if there is one already
CreateTempFile( false );
GetMedium_Impl();
try
{
if ( !pImpl->xStream.is() )
throw uno::RuntimeException();
bool bODF = GetFilter()->IsOwnFormat();
try
{
xWriteableZipStor = ::comphelper::OStorageHelper::GetStorageOfFormatFromStream( ZIP_STORAGE_FORMAT_STRING, pImpl->xStream );
}
catch (const io::IOException&)
{
if (bODF)
{
TOOLS_WARN_EXCEPTION("sfx.doc", "ODF stream is not a zip storage");
}
}
if ( !xWriteableZipStor.is() && bODF )
throw uno::RuntimeException();
uno::Reference< embed::XStorage > xMetaInf;
if (xWriteableZipStor.is() && xWriteableZipStor->hasByName("META-INF"))
{
xMetaInf = xWriteableZipStor->openStorageElement(
"META-INF",
embed::ElementModes::READWRITE );
if ( !xMetaInf.is() )
throw uno::RuntimeException();
}
{
if (xMetaInf.is())
{
// ODF.
uno::Reference< io::XStream > xStream;
if (GetFilter() && GetFilter()->IsOwnFormat())
xStream.set(xMetaInf->openStreamElement(xSigner->getDocumentContentSignatureDefaultStreamName(), embed::ElementModes::READWRITE), uno::UNO_SET_THROW);
bool bSuccess = xModelSigner->SignModelWithCertificate(
xModel, xCertificate, GetZipStorageToSign_Impl(), xStream);
if (bSuccess)
{
uno::Reference< embed::XTransactedObject > xTransact( xMetaInf, uno::UNO_QUERY_THROW );
xTransact->commit();
xTransact.set( xWriteableZipStor, uno::UNO_QUERY_THROW );
xTransact->commit();
// the temporary file has been written, commit it to the original file
Commit();
bChanges = true;
}
}
else if (xWriteableZipStor.is())
{
// OOXML.
uno::Reference<io::XStream> xStream;
// We need read-write to be able to add the signature relation.
bool bSuccess = xModelSigner->SignModelWithCertificate(
xModel, xCertificate, GetZipStorageToSign_Impl(/*bReadOnly=*/false), xStream);
if (bSuccess)
{
uno::Reference<embed::XTransactedObject> xTransact(xWriteableZipStor, uno::UNO_QUERY_THROW);
xTransact->commit();
// the temporary file has been written, commit it to the original file
Commit();
bChanges = true;
}
}
else
{
// Something not ZIP based: e.g. PDF.
std::unique_ptr<SvStream> pStream(utl::UcbStreamHelper::CreateStream(GetName(), StreamMode::READ | StreamMode::WRITE));
uno::Reference<io::XStream> xStream(new utl::OStreamWrapper(*pStream));
if (xModelSigner->SignModelWithCertificate(
xModel, xCertificate, uno::Reference<embed::XStorage>(), xStream))
bChanges = true;
}
}
}
catch ( const uno::Exception& )
{
TOOLS_WARN_EXCEPTION("sfx.doc", "Couldn't use signing functionality!");
}
CloseAndRelease();
ResetError();
return bChanges;
}
// note: this is the only function creating scripting signature
bool SfxMedium::SignContents_Impl(weld::Window* pDialogParent,
bool bSignScriptingContent,
bool bHasValidDocumentSignature,
const OUString& aSignatureLineId,
const Reference<XCertificate>& xCert,
const Reference<XGraphic>& xValidGraphic,
const Reference<XGraphic>& xInvalidGraphic,
const OUString& aComment)
{
bool bChanges = false;
if (IsOpen() || GetErrorIgnoreWarning())
{
SAL_WARN("sfx.doc", "The medium must be closed by the signer!");
return bChanges;
}
// The component should know if there was a valid document signature, since
// it should show a warning in this case
OUString aODFVersion(comphelper::OStorageHelper::GetODFVersionFromStorage(GetStorage()));
uno::Reference< security::XDocumentDigitalSignatures > xSigner(
security::DocumentDigitalSignatures::createWithVersionAndValidSignature(
comphelper::getProcessComponentContext(), aODFVersion, bHasValidDocumentSignature ) );
if (pDialogParent)
xSigner->setParentWindow(pDialogParent->GetXWindow());
uno::Reference< embed::XStorage > xWriteableZipStor;
// we can reuse the temporary file if there is one already
CreateTempFile( false );
GetMedium_Impl();
try
{
if ( !pImpl->xStream.is() )
throw uno::RuntimeException();
bool bODF = GetFilter()->IsOwnFormat();
try
{
if (pImpl->m_bODFWholesomeEncryption && bSignScriptingContent)
{
assert(pImpl->xStorage); // GetStorage was called above
assert(pImpl->m_xODFDecryptedInnerPackageStream);
xWriteableZipStor = ::comphelper::OStorageHelper::GetStorageOfFormatFromStream(
ZIP_STORAGE_FORMAT_STRING, pImpl->m_xODFDecryptedInnerPackageStream);
}
else
{
xWriteableZipStor = ::comphelper::OStorageHelper::GetStorageOfFormatFromStream(
ZIP_STORAGE_FORMAT_STRING, pImpl->xStream );
}
}
catch (const io::IOException&)
{
if (bODF)
{
TOOLS_WARN_EXCEPTION("sfx.doc", "ODF stream is not a zip storage");
}
}
if ( !xWriteableZipStor.is() && bODF )
throw uno::RuntimeException();
uno::Reference< embed::XStorage > xMetaInf;
if (xWriteableZipStor.is() && xWriteableZipStor->hasByName("META-INF"))
{
xMetaInf = xWriteableZipStor->openStorageElement(
"META-INF",
embed::ElementModes::READWRITE );
if ( !xMetaInf.is() )
throw uno::RuntimeException();
}
if ( bSignScriptingContent )
{
// If the signature has already the document signature it will be removed
// after the scripting signature is inserted.
uno::Reference< io::XStream > xStream(
xMetaInf->openStreamElement( xSigner->getScriptingContentSignatureDefaultStreamName(),
embed::ElementModes::READWRITE ),
uno::UNO_SET_THROW );
// note: the storage passed here must be independent from the
// xWriteableZipStor because a writable storage can't have 2
// instances of sub-storage for the same directory open, but with
// independent storages it somehow works
if (xSigner->signScriptingContent(GetScriptingStorageToSign_Impl(), xStream))
{
// remove the document signature if any
OUString aDocSigName = xSigner->getDocumentContentSignatureDefaultStreamName();
if ( !aDocSigName.isEmpty() && xMetaInf->hasByName( aDocSigName ) )
xMetaInf->removeElement( aDocSigName );
uno::Reference< embed::XTransactedObject > xTransact( xMetaInf, uno::UNO_QUERY_THROW );
xTransact->commit();
xTransact.set( xWriteableZipStor, uno::UNO_QUERY_THROW );
xTransact->commit();
if (pImpl->m_bODFWholesomeEncryption)
{ // manually copy the inner package to the outer one
uno::Reference<io::XSeekable>(pImpl->m_xODFDecryptedInnerPackageStream, uno::UNO_QUERY_THROW)->seek(0);
uno::Reference<io::XStream> const xEncryptedPackage =
pImpl->m_xODFEncryptedOuterStorage->openStreamElement(
"encrypted-package",
embed::ElementModes::WRITE|embed::ElementModes::TRUNCATE);
comphelper::OStorageHelper::CopyInputToOutput(pImpl->m_xODFDecryptedInnerPackageStream->getInputStream(), xEncryptedPackage->getOutputStream());
xTransact.set(pImpl->m_xODFEncryptedOuterStorage, uno::UNO_QUERY_THROW);
xTransact->commit(); // Commit() below won't do this
}
assert(!pImpl->xStorage.is() // ensure this doesn't overwrite
|| !uno::Reference<util::XModifiable>(pImpl->xStorage, uno::UNO_QUERY_THROW)->isModified());
// the temporary file has been written, commit it to the original file
Commit();
bChanges = true;
}
}
else
{
if (xMetaInf.is())
{
// ODF.
uno::Reference< io::XStream > xStream;
if (GetFilter() && GetFilter()->IsOwnFormat())
xStream.set(xMetaInf->openStreamElement(xSigner->getDocumentContentSignatureDefaultStreamName(), embed::ElementModes::READWRITE), uno::UNO_SET_THROW);
bool bSuccess = false;
if (xCert.is())
bSuccess = xSigner->signSignatureLine(
GetZipStorageToSign_Impl(), xStream, aSignatureLineId, xCert,
xValidGraphic, xInvalidGraphic, aComment);
else
bSuccess = xSigner->signDocumentContent(GetZipStorageToSign_Impl(),
xStream);
if (bSuccess)
{
uno::Reference< embed::XTransactedObject > xTransact( xMetaInf, uno::UNO_QUERY_THROW );
xTransact->commit();
xTransact.set( xWriteableZipStor, uno::UNO_QUERY_THROW );
xTransact->commit();
// the temporary file has been written, commit it to the original file
Commit();
bChanges = true;
}
}
else if (xWriteableZipStor.is())
{
// OOXML.
uno::Reference<io::XStream> xStream;
bool bSuccess = false;
if (xCert.is())
{
bSuccess = xSigner->signSignatureLine(
GetZipStorageToSign_Impl(/*bReadOnly=*/false), xStream, aSignatureLineId,
xCert, xValidGraphic, xInvalidGraphic, aComment);
}
else
{
// We need read-write to be able to add the signature relation.
bSuccess =xSigner->signDocumentContent(
GetZipStorageToSign_Impl(/*bReadOnly=*/false), xStream);
}
if (bSuccess)
{
uno::Reference<embed::XTransactedObject> xTransact(xWriteableZipStor, uno::UNO_QUERY_THROW);
xTransact->commit();
// the temporary file has been written, commit it to the original file
Commit();
bChanges = true;
}
}
else
{
// Something not ZIP based: e.g. PDF.
std::unique_ptr<SvStream> pStream(utl::UcbStreamHelper::CreateStream(GetName(), StreamMode::READ | StreamMode::WRITE));
uno::Reference<io::XStream> xStream(new utl::OStreamWrapper(*pStream));
if (xSigner->signDocumentContent(uno::Reference<embed::XStorage>(), xStream))
bChanges = true;
}
}
}
catch ( const uno::Exception& )
{
TOOLS_WARN_EXCEPTION("sfx.doc", "Couldn't use signing functionality!");
}
CloseAndRelease();
ResetError();
return bChanges;
}
SignatureState SfxMedium::GetCachedSignatureState_Impl() const
{
return pImpl->m_nSignatureState;
}
void SfxMedium::SetCachedSignatureState_Impl( SignatureState nState )
{
pImpl->m_nSignatureState = nState;
}
void SfxMedium::SetHasEmbeddedObjects(bool bHasEmbeddedObjects)
{
pImpl->m_bHasEmbeddedObjects = bHasEmbeddedObjects;
}
bool SfxMedium::HasStorage_Impl() const
{
return pImpl->xStorage.is();
}
bool SfxMedium::IsOpen() const
{
return pImpl->m_pInStream || pImpl->m_pOutStream || pImpl->xStorage.is();
}
OUString SfxMedium::CreateTempCopyWithExt( std::u16string_view aURL )
{
OUString aResult;
if ( !aURL.empty() )
{
size_t nPrefixLen = aURL.rfind( '.' );
std::u16string_view aExt = ( nPrefixLen == std::u16string_view::npos ) ? std::u16string_view() : aURL.substr( nPrefixLen );
OUString aNewTempFileURL = ::utl::CreateTempURL( u"", true, aExt );
if ( !aNewTempFileURL.isEmpty() )
{
INetURLObject aSource( aURL );
INetURLObject aDest( aNewTempFileURL );
OUString aFileName = aDest.getName( INetURLObject::LAST_SEGMENT,
true,
INetURLObject::DecodeMechanism::WithCharset );
if ( !aFileName.isEmpty() && aDest.removeSegment() )
{
try
{
uno::Reference< css::ucb::XCommandEnvironment > xComEnv;
::ucbhelper::Content aTargetContent( aDest.GetMainURL( INetURLObject::DecodeMechanism::NONE ), xComEnv, comphelper::getProcessComponentContext() );
::ucbhelper::Content aSourceContent( aSource.GetMainURL( INetURLObject::DecodeMechanism::NONE ), xComEnv, comphelper::getProcessComponentContext() );
aTargetContent.transferContent( aSourceContent,
::ucbhelper::InsertOperation::Copy,
aFileName,
NameClash::OVERWRITE );
aResult = aNewTempFileURL;
}
catch( const uno::Exception& )
{}
}
}
}
return aResult;
}
bool SfxMedium::CallApproveHandler(const uno::Reference< task::XInteractionHandler >& xHandler, const uno::Any& rRequest, bool bAllowAbort)
{
bool bResult = false;
if ( xHandler.is() )
{
try
{
uno::Sequence< uno::Reference< task::XInteractionContinuation > > aContinuations( bAllowAbort ? 2 : 1 );
auto pContinuations = aContinuations.getArray();
::rtl::Reference< ::comphelper::OInteractionApprove > pApprove( new ::comphelper::OInteractionApprove );
pContinuations[ 0 ] = pApprove.get();
if ( bAllowAbort )
{
::rtl::Reference< ::comphelper::OInteractionAbort > pAbort( new ::comphelper::OInteractionAbort );
pContinuations[ 1 ] = pAbort.get();
}
xHandler->handle(::framework::InteractionRequest::CreateRequest(rRequest, aContinuations));
bResult = pApprove->wasSelected();
}
catch( const Exception& )
{
}
}
return bResult;
}
OUString SfxMedium::SwitchDocumentToTempFile()
{
// the method returns empty string in case of failure
OUString aResult;
OUString aOrigURL = pImpl->m_aLogicName;
if ( !aOrigURL.isEmpty() )
{
sal_Int32 nPrefixLen = aOrigURL.lastIndexOf( '.' );
std::u16string_view aExt = (nPrefixLen == -1)
? std::u16string_view()
: aOrigURL.subView(nPrefixLen);
OUString aNewURL = ::utl::CreateTempURL( u"", true, aExt );
// TODO/LATER: In future the aLogicName should be set to shared folder URL
// and a temporary file should be created. Transport_Impl should be impossible then.
if ( !aNewURL.isEmpty() )
{
uno::Reference< embed::XStorage > xStorage = GetStorage();
uno::Reference< embed::XOptimizedStorage > xOptStorage( xStorage, uno::UNO_QUERY );
if ( xOptStorage.is() )
{
// TODO/LATER: reuse the pImpl->pTempFile if it already exists
CanDisposeStorage_Impl( false );
Close();
SetPhysicalName_Impl( OUString() );
SetName( aNewURL );
// remove the readonly state
bool bWasReadonly = false;
pImpl->m_nStorOpenMode = SFX_STREAM_READWRITE;
const SfxBoolItem* pReadOnlyItem = SfxItemSet::GetItem<SfxBoolItem>(pImpl->m_pSet.get(), SID_DOC_READONLY, false);
if ( pReadOnlyItem && pReadOnlyItem->GetValue() )
bWasReadonly = true;
GetItemSet().ClearItem( SID_DOC_READONLY );
GetMedium_Impl();
LockOrigFileOnDemand( false, false );
CreateTempFile();
GetMedium_Impl();
if ( pImpl->xStream.is() )
{
try
{
xOptStorage->writeAndAttachToStream( pImpl->xStream );
pImpl->xStorage = xStorage;
aResult = aNewURL;
}
catch( const uno::Exception& )
{}
}
if (bWasReadonly)
{
// set the readonly state back
pImpl->m_nStorOpenMode = SFX_STREAM_READONLY;
GetItemSet().Put(SfxBoolItem(SID_DOC_READONLY, true));
}
if ( aResult.isEmpty() )
{
Close();
SetPhysicalName_Impl( OUString() );
SetName( aOrigURL );
GetMedium_Impl();
pImpl->xStorage = xStorage;
}
}
}
}
return aResult;
}
bool SfxMedium::SwitchDocumentToFile( const OUString& aURL )
{
// the method is only for storage based documents
bool bResult = false;
OUString aOrigURL = pImpl->m_aLogicName;
if ( !aURL.isEmpty() && !aOrigURL.isEmpty() )
{
uno::Reference< embed::XStorage > xStorage = GetStorage();
uno::Reference< embed::XOptimizedStorage > xOptStorage( xStorage, uno::UNO_QUERY );
// TODO/LATER: reuse the pImpl->pTempFile if it already exists
CanDisposeStorage_Impl( false );
Close();
SetPhysicalName_Impl( OUString() );
SetName( aURL );
// open the temporary file based document
GetMedium_Impl();
LockOrigFileOnDemand( false, false );
CreateTempFile();
GetMedium_Impl();
if ( pImpl->xStream.is() )
{
try
{
uno::Reference< io::XTruncate > xTruncate( pImpl->xStream, uno::UNO_QUERY_THROW );
xTruncate->truncate();
if ( xOptStorage.is() )
xOptStorage->writeAndAttachToStream( pImpl->xStream );
pImpl->xStorage = xStorage;
bResult = true;
}
catch( const uno::Exception& )
{}
}
if ( !bResult )
{
Close();
SetPhysicalName_Impl( OUString() );
SetName( aOrigURL );
GetMedium_Impl();
pImpl->xStorage = xStorage;
}
}
return bResult;
}
void SfxMedium::SetInCheckIn( bool bInCheckIn )
{
pImpl->m_bInCheckIn = bInCheckIn;
}
bool SfxMedium::IsInCheckIn( ) const
{
return pImpl->m_bInCheckIn;
}
// should only be called on main thread
const std::shared_ptr<std::recursive_mutex>& SfxMedium::GetCheckEditableMutex() const
{
return pImpl->m_pCheckEditableWorkerMutex;
}
// should only be called while holding pImpl->m_pCheckEditableWorkerMutex
void SfxMedium::SetWorkerReloadEvent(ImplSVEvent* pEvent)
{
pImpl->m_pReloadEvent = pEvent;
}
// should only be called while holding pImpl->m_pCheckEditableWorkerMutex
ImplSVEvent* SfxMedium::GetWorkerReloadEvent() const
{
return pImpl->m_pReloadEvent;
}
// should only be called on main thread
void SfxMedium::AddToCheckEditableWorkerList()
{
if (!pImpl->m_bNotifyWhenEditable)
return;
CancelCheckEditableEntry();
if (pImpl->m_pCheckEditableWorkerMutex == nullptr)
{
pImpl->m_pCheckEditableWorkerMutex = std::make_shared<std::recursive_mutex>();
if (pImpl->m_pCheckEditableWorkerMutex == nullptr)
return;
}
pImpl->m_pIsDestructed = std::make_shared<bool>(false);
if (pImpl->m_pIsDestructed == nullptr)
return;
std::unique_lock<std::mutex> globalLock(g_chkReadOnlyGlobalMutex);
if (g_newReadOnlyDocs.find(this) == g_newReadOnlyDocs.end())
{
bool bAddNewEntry = false;
if (!g_bChkReadOnlyTaskRunning)
{
std::shared_ptr<comphelper::ThreadTaskTag> pTag
= comphelper::ThreadPool::createThreadTaskTag();
if (pTag != nullptr)
{
g_bChkReadOnlyTaskRunning = true;
bAddNewEntry = true;
comphelper::ThreadPool::getSharedOptimalPool().pushTask(
std::make_unique<CheckReadOnlyTask>(pTag));
}
}
else
bAddNewEntry = true;
if (bAddNewEntry)
{
std::shared_ptr<ReadOnlyMediumEntry> newEntry = std::make_shared<ReadOnlyMediumEntry>(
pImpl->m_pCheckEditableWorkerMutex, pImpl->m_pIsDestructed);
if (newEntry != nullptr)
{
g_newReadOnlyDocs[this] = newEntry;
}
}
}
}
// should only be called on main thread
void SfxMedium::CancelCheckEditableEntry(bool bRemoveEvent)
{
if (pImpl->m_pCheckEditableWorkerMutex != nullptr)
{
std::unique_lock<std::recursive_mutex> lock(*(pImpl->m_pCheckEditableWorkerMutex));
if (pImpl->m_pReloadEvent != nullptr)
{
if (bRemoveEvent)
Application::RemoveUserEvent(pImpl->m_pReloadEvent);
// make sure destructor doesn't use a freed reference
// and reset the event so we can check again
pImpl->m_pReloadEvent = nullptr;
}
if (pImpl->m_pIsDestructed != nullptr)
{
*(pImpl->m_pIsDestructed) = true;
pImpl->m_pIsDestructed = nullptr;
}
}
}
/** callback function, which is triggered by worker thread after successfully checking if the file
is editable. Sent from <Application::PostUserEvent(..)>
Note: This method has to be run in the main thread.
*/
IMPL_STATIC_LINK(SfxMedium, ShowReloadEditableDialog, void*, p, void)
{
SfxMedium* pMed = static_cast<SfxMedium*>(p);
if (pMed == nullptr)
return;
pMed->CancelCheckEditableEntry(false);
uno::Reference<task::XInteractionHandler> xHandler = pMed->GetInteractionHandler();
if (xHandler.is())
{
OUString aDocumentURL
= pMed->GetURLObject().GetLastName(INetURLObject::DecodeMechanism::WithCharset);
::rtl::Reference<::ucbhelper::InteractionRequest> xInteractionRequestImpl
= new ::ucbhelper::InteractionRequest(uno::Any(document::ReloadEditableRequest(
OUString(), uno::Reference<uno::XInterface>(), aDocumentURL)));
if (xInteractionRequestImpl != nullptr)
{
uno::Sequence<uno::Reference<task::XInteractionContinuation>> aContinuations{
new ::ucbhelper::InteractionAbort(xInteractionRequestImpl.get()),
new ::ucbhelper::InteractionApprove(xInteractionRequestImpl.get())
};
xInteractionRequestImpl->setContinuations(aContinuations);
xHandler->handle(xInteractionRequestImpl);
::rtl::Reference<::ucbhelper::InteractionContinuation> xSelected
= xInteractionRequestImpl->getSelection();
if (uno::Reference<task::XInteractionApprove>(xSelected.get(), uno::UNO_QUERY).is())
{
for (SfxViewFrame* pFrame = SfxViewFrame::GetFirst(); pFrame;
pFrame = SfxViewFrame::GetNext(*pFrame))
{
if (pFrame->GetObjectShell()->GetMedium() == pMed)
{
// special case to ensure view isn't set to read-only in
// SfxViewFrame::ExecReload_Impl after reloading
pMed->SetOriginallyReadOnly(false);
pFrame->GetDispatcher()->Execute(SID_RELOAD);
break;
}
}
}
}
}
}
bool SfxMedium::CheckCanGetLockfile() const
{
#if !HAVE_FEATURE_MULTIUSER_ENVIRONMENT
bool bCanReload = true;
#else
bool bCanReload = false;
::svt::DocumentLockFile aLockFile(GetName());
LockFileEntry aData;
osl::DirectoryItem rItem;
auto nError1 = osl::DirectoryItem::get(aLockFile.GetURL(), rItem);
if (nError1 == osl::FileBase::E_None)
{
try
{
aData = aLockFile.GetLockData();
}
catch (const io::WrongFormatException&)
{
// we get empty or corrupt data
return false;
}
catch (const uno::Exception&)
{
// locked from other app
return false;
}
LockFileEntry aOwnData = svt::LockFileCommon::GenerateOwnEntry();
bool bOwnLock
= aOwnData[LockFileComponent::SYSUSERNAME] == aData[LockFileComponent::SYSUSERNAME];
if (bOwnLock
&& aOwnData[LockFileComponent::LOCALHOST] == aData[LockFileComponent::LOCALHOST]
&& aOwnData[LockFileComponent::USERURL] == aData[LockFileComponent::USERURL])
{
// this is own lock from the same installation, it could remain because of crash
bCanReload = true;
}
}
else if (nError1 == osl::FileBase::E_NOENT) // file doesn't exist
{
try
{
aLockFile.CreateOwnLockFile();
try
{
// TODO/LATER: A warning could be shown in case the file is not the own one
aLockFile.RemoveFile();
}
catch (const io::WrongFormatException&)
{
try
{
// erase the empty or corrupt file
aLockFile.RemoveFileDirectly();
}
catch (const uno::Exception&)
{
}
}
bCanReload = true;
}
catch (const uno::Exception&)
{
}
}
#endif
return bCanReload;
}
// worker thread method, should only be one thread globally
void CheckReadOnlyTask::doWork()
{
if (m_xListener == nullptr)
return;
while (true)
{
std::unique_lock<std::mutex> termLock(m_xListener->mMutex);
if (m_xListener->mCond.wait_for(termLock, std::chrono::seconds(60),
[this] { return m_xListener->bIsTerminated; }))
// signalled, spurious wakeups should not be possible
return;
// must have timed-out
termLock.unlock();
std::unique_lock<std::mutex> globalLock(g_chkReadOnlyGlobalMutex);
for (auto it = g_newReadOnlyDocs.begin(); it != g_newReadOnlyDocs.end(); )
{
auto [pMed, roEntry] = *it;
g_existingReadOnlyDocs[pMed] = roEntry;
it = g_newReadOnlyDocs.erase(it);
}
if (g_existingReadOnlyDocs.size() == 0)
{
g_bChkReadOnlyTaskRunning = false;
return;
}
globalLock.unlock();
auto checkForErase = [](SfxMedium* pMed, const std::shared_ptr<ReadOnlyMediumEntry>& roEntry) -> bool
{
if (pMed == nullptr || roEntry == nullptr || roEntry->_pMutex == nullptr
|| roEntry->_pIsDestructed == nullptr)
return true;
std::unique_lock<std::recursive_mutex> medLock(*(roEntry->_pMutex));
if (*(roEntry->_pIsDestructed) || pMed->GetWorkerReloadEvent() != nullptr)
return true;
osl::File aFile(
pMed->GetURLObject().GetMainURL(INetURLObject::DecodeMechanism::WithCharset));
if (aFile.open(osl_File_OpenFlag_Write) != osl::FileBase::E_None)
return false;
if (!pMed->CheckCanGetLockfile())
return false;
if (aFile.close() != osl::FileBase::E_None)
return true;
// we can load, ask user
ImplSVEvent* pEvent = Application::PostUserEvent(
LINK(nullptr, SfxMedium, ShowReloadEditableDialog), pMed);
pMed->SetWorkerReloadEvent(pEvent);
return true;
};
for (auto it = g_existingReadOnlyDocs.begin(); it != g_existingReadOnlyDocs.end(); )
{
if (checkForErase(it->first, it->second))
it = g_existingReadOnlyDocs.erase(it);
else
++it;
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|