summaryrefslogtreecommitdiff
path: root/sfx2/source/doc/docfile.cxx
blob: a38704a150395312ace79533dc97f37c98dea2f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
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
/*************************************************************************
 *
 *  $RCSfile: docfile.cxx,v $
 *
 *  $Revision: 1.65 $
 *
 *  last change: $Author: dv $ $Date: 2001-07-03 12:10:35 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "docfile.hxx"

#include <uno/mapping.hxx>
#include <com/sun/star/task/XInteractionHandler.hpp>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/ucb/XContent.hpp>

#ifndef _COM_SUN_STAR_UTIL_XARCHIVER_HPP_
#include <com/sun/star/util/XArchiver.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XACTIVEDATACONTROL_HPP_
#include <com/sun/star/io/XActiveDataControl.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSTREAMLISTENER_HPP_
#include <com/sun/star/io/XStreamListener.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XACTIVEDATASINK_HPP_
#include <com/sun/star/io/XActiveDataSink.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_
#include <com/sun/star/io/XActiveDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_
#include <com/sun/star/io/XSeekable.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef  _COM_SUN_STAR_UCB_INSERTCOMMANDARGUMENT_HPP_
#include <com/sun/star/ucb/InsertCommandArgument.hpp>
#endif
#ifndef  _COM_SUN_STAR_UCB_NAMECLASH_HPP_
#include <com/sun/star/ucb/NameClash.hpp>
#endif
#ifndef  _COM_SUN_STAR_UCB_TRANSFERINFO_HPP_
#include <com/sun/star/ucb/TransferInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _ZCODEC_HXX
#include <tools/zcodec.hxx>
#endif
#ifndef _CACHESTR_HXX //autogen
#include <tools/cachestr.hxx>
#endif
#ifndef _URLOBJ_HXX //autogen
#include <tools/urlobj.hxx>
#endif
#ifndef _UNOTOOLS_TEMPFILE_HXX
#include <unotools/tempfile.hxx>
#endif
#ifndef _UNOTOOLS_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef  _UNOTOOLS_STREAMHELPER_HXX_
#include <unotools/streamhelper.hxx>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SVSTOR_HXX //autogen
#include <so3/svstor.hxx>
#endif
#ifndef _EXTATTR_HXX
#include <svtools/extattr.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#include <svtools/lckbitem.hxx>
#ifndef _SFXECODE_HXX
#include <svtools/sfxecode.hxx>
#endif
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif

#define _SVSTDARR_ULONGS
#define _SVSTDARR_STRINGSDTOR
#include <svtools/svstdarr.hxx>

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::io;

#pragma hdrstop

#include <so3/transbnd.hxx> // SvKeyValueIterator
#include <tools/urlobj.hxx>
#include <unotools/ucblockbytes.hxx>
#include <svtools/pathoptions.hxx>
#include <svtools/asynclink.hxx>
#include <ucbhelper/contentbroker.hxx>
#include <unotools/localfilehelper.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <unotools/ucbhelper.hxx>
#include <ucbhelper/content.hxx>
#include <sot/stg.hxx>

#include "ucbhelp.hxx"
#include "helper.hxx"
#include "request.hxx"      // SFX_ITEMSET_SET
#include "app.hxx"          // GetFilterMatcher
#include "frame.hxx"        // LoadTargetFrame
#include "fltfnc.hxx"       // SfxFilterMatcher
#include "docfilt.hxx"      // SfxFilter
#include "objsh.hxx"        // CheckOpenMode
#include "docfac.hxx"       // GetFilterContainer
#include "doc.hrc"          // MSG_WARNING_BACKUP, MSG_OPEN_READONLY
#include "openflag.hxx"     // SFX_STREAM_READONLY etc.
#include "sfxresid.hxx"

#include "xmlversion.hxx"

#define MAX_REDIRECT 5

class SfxLockBytesHandler_Impl : public ::utl::UcbLockBytesHandler
{
    ULONG           m_nAcquireCount;
    SfxMedium*      m_pMedium;
    ::vos::OMutex   m_aMutex;
public:
                    SfxLockBytesHandler_Impl( SfxMedium* pMedium )
                        : m_pMedium( pMedium )
                        , m_nAcquireCount( 0 )
                    {}

    virtual void    Handle( ::utl::UcbLockBytesHandler::LoadHandlerItem nWhich, ::utl::UcbLockBytesRef xLockBytes );
    ::vos::OMutex&  GetMutex()
                    { return m_aMutex; }
    void            ReleaseMedium()
                    { m_pMedium = NULL; }
};

SV_DECL_IMPL_REF( SfxLockBytesHandler_Impl );

void SfxLockBytesHandler_Impl::Handle( ::utl::UcbLockBytesHandler::LoadHandlerItem nWhich, ::utl::UcbLockBytesRef xLockBytes )
{
    ::vos::OGuard aGuard( m_aMutex );
    if ( IsActive() && xLockBytes.Is()&& m_pMedium )
    {
        switch( nWhich )
        {
            case BEFOREWAIT :
                if ( xLockBytes->IsSynchronMode() )
                {
                    DBG_ASSERT( !m_nAcquireCount, "BeforeWait inside beforewait!" );
                    ::vos::IMutex& rMutex = Application::GetSolarMutex();
                    if ( rMutex.tryToAcquire() )
                        m_nAcquireCount = Application::ReleaseSolarMutex() - 1;
                }

                break;
            case AFTERWAIT :
                if ( xLockBytes->IsSynchronMode() )
                {
                    if ( m_nAcquireCount )
                    {
                        Application::AcquireSolarMutex( m_nAcquireCount );
                        m_nAcquireCount = 0;
                    }
                }

                break;

            case DATA_AVAILABLE :
                m_pMedium->DataAvailable_Impl();
                break;
            case DONE :
                m_pMedium->Done_Impl( xLockBytes->GetError() );
                break;
            case CANCEL :
                m_pMedium->Cancel_Impl();
                break;
            default:
                break;
        }
    }
}

class UcbLockBytesCancellable_Impl : public SfxCancellable
{
    ::utl::UcbLockBytesRef         xLockBytes;

public:
                            UcbLockBytesCancellable_Impl( const ::utl::UcbLockBytesRef& rLockBytes, SfxCancelManager* pManager, const String& rTitle )
                                : SfxCancellable( pManager, rTitle )
                                , xLockBytes( rLockBytes )
                            {}

    virtual void            Cancel();
};

void UcbLockBytesCancellable_Impl::Cancel()
{
    xLockBytes->Cancel();
}

class FileSource_Impl   :   public ::com::sun::star::lang::XTypeProvider    ,
                            public ::com::sun::star::io::XActiveDataSource  ,
                            public ::com::sun::star::io::XActiveDataControl ,
                            public ::com::sun::star::lang::XInitialization  ,
                            public ::cppu::OWeakObject
{
private:
    SvStream*           pStream;
    SfxMedium*          pMedium;
    ::com::sun::star::uno::Reference< ::com::sun::star::io::XStreamListener >   m_xListener;
    ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >     m_xSink;

public:

    SFX_DECL_XINTERFACE_XTYPEPROVIDER

                    FileSource_Impl();
                    FileSource_Impl( SfxMedium* );
    virtual         ~FileSource_Impl();

    void            ResetMedium()
                    { pMedium = NULL; pStream = NULL;}
    DECL_LINK(      DataAvailableHdl, void* );

                    // ::com::sun::star::io::XActiveDataControl
    virtual void SAL_CALL   addListener(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XStreamListener > & aListener) throw( ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL   removeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XStreamListener > & aListener) throw( ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL   start(void) throw( ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL   terminate(void) throw( ::com::sun::star::uno::RuntimeException );

                    // ::com::sun::star::io::XActiveDataSource
    virtual void SAL_CALL   setOutputStream(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > & aStream) throw( ::com::sun::star::uno::RuntimeException );
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > SAL_CALL    getOutputStream(void) throw( ::com::sun::star::uno::RuntimeException );

                    // ::com::sun::star::lang::XInitialization
    virtual void SAL_CALL   initialize(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& Arguments) throw( ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException );

};

class FileSink_Impl :   public ::com::sun::star::lang::XTypeProvider    ,
                        public ::com::sun::star::io::XOutputStream      ,
                        public ::cppu::OWeakObject
{
private:
    SvStream*       pStream;
    SfxMedium*      pMedium;

public:
    SFX_DECL_XINTERFACE_XTYPEPROVIDER

                    FileSink_Impl( SfxMedium* );
    virtual         ~FileSink_Impl();

    void            ResetMedium()
                    { pMedium = NULL; pStream = NULL;}

                    // ::com::sun::star::io::XOutputStream
    virtual void  SAL_CALL  writeBytes(const ::com::sun::star::uno::Sequence< sal_Int8 >& aData) throw( ::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::uno::RuntimeException );
    virtual void  SAL_CALL  flush(void) throw( ::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::uno::RuntimeException );
    virtual void  SAL_CALL  closeOutput(void) throw( ::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::uno::RuntimeException );
};

SFX_IMPL_XINTERFACE_1( FileSink_Impl, OWeakObject, ::com::sun::star::io::XOutputStream )
SFX_IMPL_XTYPEPROVIDER_1( FileSink_Impl, ::com::sun::star::io::XOutputStream )

FileSink_Impl::FileSink_Impl( SfxMedium* pMed )
    : pMedium( pMed )
    , pStream( NULL )
{
}

FileSink_Impl::~FileSink_Impl()
{
    if ( pMedium )
        pMedium->ReleaseRef();
}

void SAL_CALL FileSink_Impl::writeBytes(const ::com::sun::star::uno::Sequence< sal_Int8 >& Buffer) throw( ::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::uno::RuntimeException )
{
    if ( !pStream && pMedium )
        pStream = pMedium->GetOutStream();

    if ( pStream )
        pStream->Write( Buffer.getConstArray(), (sal_uInt32) Buffer.getLength() );
}

void SAL_CALL  FileSink_Impl::flush(void) throw( ::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::uno::RuntimeException )
{
    if ( pMedium )
        pMedium->GetOutStream()->Flush();
}

void SAL_CALL  FileSink_Impl::closeOutput(void) throw( ::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::uno::RuntimeException )
{
    if ( pMedium )
        pMedium->Close();
}

SFX_IMPL_XINTERFACE_3( FileSource_Impl, OWeakObject, ::com::sun::star::io::XActiveDataSource, ::com::sun::star::io::XActiveDataControl, ::com::sun::star::lang::XInitialization )
SFX_IMPL_XTYPEPROVIDER_3( FileSource_Impl, ::com::sun::star::io::XActiveDataSource, ::com::sun::star::io::XActiveDataControl, ::com::sun::star::lang::XInitialization )

FileSource_Impl::FileSource_Impl()
    : pMedium( NULL )
    , pStream( NULL )
{
}

void SAL_CALL  FileSource_Impl::initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& Arguments) throw( ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException )
{
    const ::com::sun::star::uno::Any *pArr = Arguments.getConstArray();
    ::rtl::OUString aName ;
    pArr[0] >>= aName ;
    if ( aName.getLength() )
    {
        pMedium = new SfxMedium( aName, STREAM_STD_READ, sal_True );
        pMedium->SetTransferPriority( SFX_TFPRIO_SYNCHRON );
        pMedium->SetDataAvailableLink( LINK( this, FileSource_Impl, DataAvailableHdl ) );
        pMedium->SetDoneLink( LINK( this, FileSource_Impl, DataAvailableHdl ) );
        pMedium->AddRef();
    }
}

FileSource_Impl::FileSource_Impl( SfxMedium* pMed )
    : pMedium( pMed )
    , pStream( NULL )
{
}

FileSource_Impl::~FileSource_Impl()
{
    if ( pMedium )
        pMedium->ReleaseRef();
}

void SAL_CALL  FileSource_Impl::addListener(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XStreamListener > & aListener) throw( ::com::sun::star::uno::RuntimeException )
{
    if( m_xListener.is() )
    {
        DBG_ERROR( "addSourceControllerListener called when already having a listener!" );
    }
    m_xListener = aListener;
}

void SAL_CALL  FileSource_Impl::removeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XStreamListener > & aListener) throw( ::com::sun::star::uno::RuntimeException )
{
    m_xListener = ::com::sun::star::uno::Reference< ::com::sun::star::io::XStreamListener > ();
}

void SAL_CALL  FileSource_Impl::setOutputStream( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > & Listener )throw( ::com::sun::star::uno::RuntimeException )
{
    m_xSink = Listener;
}

::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >  SAL_CALL  FileSource_Impl::getOutputStream(void) throw( ::com::sun::star::uno::RuntimeException )
{
    return m_xSink;
}

IMPL_LINK( FileSource_Impl, DataAvailableHdl, void*, pVoid )
{
    if ( !pStream )
        pStream = pMedium->GetInStream();

    if ( pStream && m_xSink.is() )
    {
        sal_Int8 buf[ 65536 ];
        sal_uInt32 nBytes = 1;
        while( nBytes && pStream->GetError() != ERRCODE_IO_PENDING )
        {
            nBytes = pStream->Read( buf, (sal_uInt32) sizeof( buf ) );
            if ( nBytes )
                m_xSink->writeBytes( ::com::sun::star::uno::Sequence<sal_Int8>( buf, nBytes ) );
        }

        if ( pStream->GetError() == ERRCODE_IO_PENDING )
            pStream->ResetError();
        else
        {
            ::com::sun::star::uno::Reference< ::com::sun::star::io::XActiveDataSource >  xRef( this );
            m_xSink->closeOutput();
            m_xSink = ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > ();
            if( m_xListener.is() )
                m_xListener->closed();
            m_xListener = ::com::sun::star::uno::Reference< ::com::sun::star::io::XStreamListener > ();
            pMedium->GetItemSet()->ClearItem( SID_LOADENVIRONMENT );
        }
    }

    return 0;
}

void SAL_CALL  FileSource_Impl::start() throw( ::com::sun::star::uno::RuntimeException )
{
    pStream = pMedium->GetInStream();
    if ( pStream && m_xSink.is() )
        DataAvailableHdl( 0 );
}

void SAL_CALL  FileSource_Impl::terminate() throw( ::com::sun::star::uno::RuntimeException )
{
    ::com::sun::star::uno::Reference< ::com::sun::star::io::XActiveDataSource >  xRef( this );
    if ( m_xSink.is() )
        m_xSink->closeOutput();

    m_xSink = ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > ();
    if( m_xListener.is() )
        m_xListener->closed();
    m_xListener = ::com::sun::star::uno::Reference< ::com::sun::star::io::XStreamListener > ();
    pMedium->CancelTransfers();
    pMedium->GetItemSet()->ClearItem( SID_LOADENVIRONMENT );
    pMedium->Close();
}

String ConvertDateTime_Impl(const SfxStamp &rTime);

//----------------------------------------------------------------
SfxPoolCancelManager::SfxPoolCancelManager( SfxCancelManager* pParent, const String& rName )
    : SfxCancelManager( pParent ),
      SfxCancellable( pParent ? pParent : this, rName ),
      wParent( pParent )
{
    if( pParent )
    {
        StartListening( *this );
        SetManager( 0 );
    }
}

//----------------------------------------------------------------
SfxPoolCancelManager::~SfxPoolCancelManager()
{
    for( sal_uInt16 nPos = GetCancellableCount(); nPos--; )
    {
        // nicht an Parent uebernehmen!
        SfxCancellable* pCbl = GetCancellable( nPos );
        if ( pCbl )
            pCbl->SetManager( 0 );
    }
}


//----------------------------------------------------------------
void SfxPoolCancelManager::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
    if( !GetCancellableCount() ) SetManager( 0 );
    else if( !GetManager() )
    {
        if( !wParent.Is() ) wParent = SFX_APP()->GetCancelManager();
        SetManager( wParent );
    }
}

//----------------------------------------------------------------
void SfxPoolCancelManager::Cancel()
{
    SfxPoolCancelManagerRef xThis = this;
    for( sal_uInt16 nPos = GetCancellableCount(); nPos--; )
    {
        SfxCancellable* pCbl = GetCancellable( nPos );
        // Wenn wir nicht im Button stehen
        if( pCbl && pCbl != this )
            pCbl->Cancel();
        if( GetCancellableCount() < nPos )
            nPos = GetCancellableCount();
    }
}

//----------------------------------------------------------------
class SfxMedium_Impl : public SvCompatWeakBase
{
public:
    Reference < XContent > xContent;
    sal_Bool bUpdatePickList : 1;
    sal_Bool bIsTemp        : 1;
    sal_Bool bUsesCache     : 1;
    sal_Bool bForceSynchron : 1;
    sal_Bool bDontCreateCancellable : 1;
    sal_Bool bDownloadDone          : 1;
    sal_Bool bDontCallDoneLinkOnSharingError : 1;
    sal_Bool bStreamReady: 1;
    sal_Bool bIsStorage: 1;

    sal_uInt16       nPrio;

    SfxPoolCancelManagerRef xCancelManager;
    UcbLockBytesCancellable_Impl* pCancellable;
    SfxMedium*       pAntiImpl;
    SvEaMgr*         pEaMgr;

    long             nFileVersion;

    const SfxFilter* pOrigFilter;
    String           aOrigURL;
    String           aPreRedirectionURL;
    String           aReferer;
    DateTime         aExpireTime;
    SfxFrameWeak     wLoadTargetFrame;
    LoadEnvironment_Impl* pLoadEnv;
    SvKeyValueIteratorRef xAttributes;

    svtools::AsynchronLink  aDoneLink;
    svtools::AsynchronLink  aAvailableLink;
    SfxLockBytesHandler_ImplRef  aHandler;

    SfxVersionTableDtor*    pVersions;
    ::utl::TempFile*           pTempDir;
    ::utl::TempFile*           pTempFile;

    Reference < XInputStream > xInputStream;
    WeakReference < XActiveDataSource > wSource;
    WeakReference < XOutputStream > wSink;
    ::utl::UcbLockBytesRef     xLockBytes;

    SfxPoolCancelManager* GetCancelManager();

    SfxMedium_Impl( SfxMedium* pAntiImplP );
    ~SfxMedium_Impl();
};

void SfxMedium::Done_Impl( ErrCode nError )
{
    DELETEZ( pImp->pCancellable );
    pImp->bDownloadDone = sal_True;
    SetError( nError );
    if ( pImp->xLockBytes.Is() )
        pImp->xInputStream = pImp->xLockBytes->getInputStream();

    if ( ( !nError || !pImp->bDontCallDoneLinkOnSharingError ) && ( pImp->bStreamReady || !pInStream ) )
    {
        pImp->aDoneLink.ClearPendingCall();
        pImp->aDoneLink.Call( (void*) nError );
    }
}

void SfxMedium::DataAvailable_Impl()
{
    pImp->aAvailableLink.ClearPendingCall();
    pImp->aAvailableLink.Call( NULL );
}

void SfxMedium::Cancel_Impl()
{
    SetError( ERRCODE_IO_GENERAL );
}

SfxPoolCancelManager* SfxMedium_Impl::GetCancelManager()
{
    if( !xCancelManager.Is() )
    {
        if( !bDontCreateCancellable )
            xCancelManager = new SfxPoolCancelManager(
                wLoadTargetFrame ? wLoadTargetFrame->GetCancelManager() :
                SFX_APP()->GetCancelManager(),
                pAntiImpl->GetURLObject().GetURLNoPass() );
        else
            xCancelManager = new SfxPoolCancelManager(
                0, pAntiImpl->GetURLObject().GetURLNoPass() );
    }
    return xCancelManager;
}

//------------------------------------------------------------------
SfxMedium_Impl::SfxMedium_Impl( SfxMedium* pAntiImplP )
 :
    SvCompatWeakBase( pAntiImplP ),
    bUpdatePickList(sal_True), bIsTemp( sal_False ), pOrigFilter( 0 ),
    bUsesCache(sal_True), pCancellable( 0 ),
    nPrio( 99 ), aExpireTime( Date() + 10, Time() ),
    bForceSynchron( sal_False ), bStreamReady( sal_False ), bIsStorage( sal_False ),
    pLoadEnv( 0 ), pAntiImpl( pAntiImplP ),
    bDontCreateCancellable( sal_False ), pTempDir( NULL ),
    bDownloadDone( sal_True ), bDontCallDoneLinkOnSharingError( sal_False ),nFileVersion( 0 ), pEaMgr( NULL ), pTempFile( NULL )
{
    aHandler = new SfxLockBytesHandler_Impl( pAntiImpl );
    aDoneLink.CreateMutex();
}

//------------------------------------------------------------------
SfxMedium_Impl::~SfxMedium_Impl()
{
    delete pCancellable;

    if ( aHandler.Is() )
        aHandler->Activate( sal_False );

    aDoneLink.ClearPendingCall();
    aAvailableLink.ClearPendingCall();

    delete pEaMgr;
    delete pVersions;

    if ( pTempFile )
        delete pTempFile;

    if ( pTempDir )
        delete pTempDir;
}

//================================================================

#define IMPL_CTOR()                         \
     eError( SVSTREAM_OK ),                 \
                                            \
     bDirect( sal_False ),                  \
     bTriedStorage( sal_False ),            \
     bSetFilter( sal_False ),               \
                                            \
     nStorOpenMode( SFX_STREAM_READWRITE ), \
     pInStream(0),                          \
     pOutStream( 0 )

//------------------------------------------------------------------
const SvGlobalName&  SfxMedium::GetClassFilter()
{
    GetMedium_Impl();
    if( GetError() )
        return aFilterClass;
    if( !bSetFilter && GetStorage() )
        SetClassFilter( GetStorage()->GetClassName() );
    return aFilterClass;
}

//------------------------------------------------------------------
void SfxMedium::ResetError()
{
    eError = SVSTREAM_OK;
    if( aStorage.Is() )
        aStorage->ResetError();
    if( pInStream )
        pInStream->ResetError();
    if( pOutStream )
        pOutStream->ResetError();
}

//------------------------------------------------------------------
sal_uInt32 SfxMedium::GetErrorCode() const
{
    sal_uInt32 lError=eError;
    if(!lError && pInStream)
        lError=pInStream->GetErrorCode();
    if(!lError && pOutStream)
        lError=pOutStream->GetErrorCode();
    if(!lError && aStorage.Is())
        lError=aStorage->GetErrorCode();
    return lError;
}

//------------------------------------------------------------------
long SfxMedium::GetFileVersion() const
{
    if ( !pImp->nFileVersion && pFilter )
        return pFilter->GetVersion();
    else
        return pImp->nFileVersion;
}

//------------------------------------------------------------------
Reference < XContent > SfxMedium::GetContent() const
{
    if ( !pImp->xContent.is() && GetName().Len() )
    {
        String aURL     = GetURLObject().GetMainURL();
        pImp->xContent  = UCB_Helper::CreateContent( aURL );
    }

    if ( pImp->xContent.is() )
        return pImp->xContent;
    else
        return NULL;
}

//------------------------------------------------------------------
SvStream* SfxMedium::GetInStream()
{
    if ( pInStream )
        return pInStream;

    if ( pImp->pTempFile )
    {
        pInStream = new SvFileStream( aName, nStorOpenMode );

        eError = pInStream->GetError();

        if( !eError && (nStorOpenMode & STREAM_WRITE)
                    && ! pInStream->IsWritable() )
        {
            eError = ERRCODE_IO_ACCESSDENIED;
            delete pInStream;
            pInStream = NULL;
        }
        else
            return pInStream;
    }

    GetMedium_Impl();

    if ( !pInStream && eError == ERRCODE_IO_PENDING )
        eError = SVSTREAM_OK;

    return pInStream;
}

//------------------------------------------------------------------
void SfxMedium::CloseInStream()
{
    CloseInStream_Impl();
}

void SfxMedium::CloseInStream_Impl()
{
    // 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 ( pInStream && aStorage.Is() )
    {
        const SvStream *pStorage = aStorage->GetSvStream();
        if ( pStorage == pInStream )
        {
            CloseStorage();
        }
    }

    DELETEZ( pInStream );
    pImp->xInputStream = Reference < XInputStream >();
    pImp->xLockBytes.Clear();
    if ( pSet )
        pSet->ClearItem( SID_INPUTSTREAM );

    DELETEZ( pImp->pCancellable );
}

//------------------------------------------------------------------
SvStream* SfxMedium::GetOutStream()
{
    if ( !pOutStream )
    {
        // Create a temp. file if there is none because we always
        // need one.
        if ( !pImp->pTempFile )
            CreateTempFile();

        if ( pImp->pTempFile )
        {
//            pOutStream = ::utl::UcbStreamHelper::CreateStream( pImp->pTempFile->GetURL(), nStorOpenMode );
            pOutStream = new SvFileStream( aName, STREAM_STD_READWRITE );
            CloseStorage();
        }
    }

    return pOutStream;
}

//------------------------------------------------------------------
sal_Bool SfxMedium::CloseOutStream()
{
    CloseOutStream_Impl();
    return sal_True;
}

sal_Bool SfxMedium::CloseOutStream_Impl()
{
    if ( 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.
        if ( aStorage.Is() )
        {
            const SvStream *pStorage = aStorage->GetSvStream();
            if ( pStorage == pOutStream )
                CloseStorage();
        }

        delete pOutStream;
        pOutStream = NULL;
    }

    return sal_True;
}

//------------------------------------------------------------------
const String& SfxMedium::GetPhysicalName() const
{
    if ( !aName.Len() && aLogicName.Len() )
        (( SfxMedium*)this)->CreateFileStream();

    // return the name then
    return aName;
}

//------------------------------------------------------------------
void SfxMedium::CreateFileStream()
{
    ForceSynchronStream_Impl( TRUE );
    GetInStream();
    if( pInStream )
    {
        if ( !pImp->pTempFile )
            CreateTempFile();
        pImp->bIsTemp = sal_True;
        CloseInStream_Impl();
    }
}

//------------------------------------------------------------------
sal_Bool SfxMedium::Commit()
{
    if( aStorage.Is() )
    {
        // StorageStream immer direkt
        if( !aStorage->Commit() )
            eError = aStorage->GetError();
    }
    else if( pOutStream  )
        pOutStream->Flush();
    else if( pInStream  )
        pInStream->Flush();

    if ( ( GetError() == SVSTREAM_OK ) && pImp->pTempFile )
        Transfer_Impl();

    return GetError() == SVSTREAM_OK;
}

//------------------------------------------------------------------
sal_Bool SfxMedium::IsStorage()
{
    if ( aStorage.Is() )
        return TRUE;

    if ( bTriedStorage )
        return pImp->bIsStorage;

    if ( pImp->pTempFile )
    {
        pImp->bIsStorage = SotStorage::IsStorageFile( pImp->pTempFile->GetFileName() );
        if ( !pImp->bIsStorage )
            bTriedStorage = TRUE;
    }
    else if ( GetName().Len() )
    {
        pImp->bIsStorage = SotStorage::IsStorageFile( GetInStream() );
        if ( pInStream && !pInStream->GetError() && !pImp->bIsStorage )
            bTriedStorage = TRUE;
    }

    return pImp->bIsStorage;
}

//------------------------------------------------------------------
Link SfxMedium::GetDataAvailableLink() const
{
    return pImp->aAvailableLink.GetLink();
}

//------------------------------------------------------------------
Link SfxMedium::GetDoneLink() const
{
    return pImp->aDoneLink.GetLink();
}

//------------------------------------------------------------------
sal_Bool SfxMedium::IsPreview_Impl()
{
    sal_Bool bPreview = sal_False;
    SFX_ITEMSET_ARG( GetItemSet(), pPreview, SfxBoolItem, SID_PREVIEW, sal_False);
    if ( pPreview )
        bPreview = pPreview->GetValue();
    else
    {
        SFX_ITEMSET_ARG( GetItemSet(), pFlags, SfxStringItem, SID_OPTIONS, sal_False);
        if ( pFlags )
        {
            String aFileFlags = pFlags->GetValue();
            aFileFlags.ToUpperAscii();
            if ( STRING_NOTFOUND != aFileFlags.Search( 'B' ) )
                bPreview = sal_True;
        }
    }

    return bPreview;
}

//------------------------------------------------------------------
sal_Bool SfxMedium::TryStorage()
{
    GetStorage();

    if ( aStorage.Is() )
        return sal_True;

    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >  xSMgr( ::comphelper::getProcessServiceFactory() );
    ::com::sun::star::uno::Reference< ::com::sun::star::util::XArchiver >
            xPacker( xSMgr->createInstance( DEFINE_CONST_UNICODE( "com.sun.star.util.Archiver" ) ), ::com::sun::star::uno::UNO_QUERY );

    if( !xPacker.is() )
        return sal_False;

    // extract extra data
    ::rtl::OUString aPath = GetURLObject().PathToFileName();
    ::rtl::OUString aExtraData = xPacker->getExtraData( aPath );
    const ::rtl::OUString aSig1( DEFINE_CONST_UNICODE( "private:" ) );
    String aTmp( '?' );
    aTmp += pFilter->GetFilterContainer()->GetName();
    const ::rtl::OUString aSig2( aTmp );
    sal_Int32 nIndex1 = aExtraData.indexOf( aSig1 );
    sal_Int32 nIndex2 = aExtraData.indexOf( aSig2 );

    if( nIndex1 != 0 || nIndex2 == -1 )
        return sal_False;

    nIndex1 += aSig1.getLength();
    ::rtl::OUString aTempDoku = aExtraData.copy( nIndex1, nIndex2 - nIndex1 );

    // create a temp dir to unpack to
    pImp->pTempDir = new ::utl::TempFile( NULL, sal_True );
    pImp->pTempDir->EnableKillingFile( sal_True );

    // unpack all files to temp dir

    com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > xFactory = ::comphelper::getProcessServiceFactory();
    com::sun::star::uno::Reference< com::sun::star::task::XInteractionHandler > xInteractionHandler(
                xFactory->createInstance( DEFINE_CONST_UNICODE("com.sun.star.task.InteractionHandler") ), UNO_QUERY );

    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aArgs(1);
    aArgs.getArray()[0].Name = DEFINE_CONST_UNICODE( "InteractionHandler" );
    aArgs.getArray()[0].Value <<= xInteractionHandler ;

    ::com::sun::star::uno::Sequence< ::rtl::OUString > files(0);

    if( !xPacker->unpack( pImp->pTempDir->GetURL(), aPath, files, aArgs ) )
        return sal_False;

    String aNewName = pImp->pTempDir->GetURL();
    aNewName += '/';
    aNewName += String( aTempDoku );
    CloseInStream_Impl();
    String aTemp;
    ::utl::LocalFileHelper::ConvertURLToPhysicalName( aNewName, aTemp );
    SetPhysicalName( aTemp );
    GetStorage();

    if ( aStorage.Is() )
    {
        const SfxFilter *pRealFilter = SFX_APP()->GetFilterMatcher().GetFilter4ClipBoardId( aStorage->GetFormat() );
        if ( pRealFilter )
        {
            pImp->nFileVersion = pRealFilter->GetVersion();
            aStorage->SetVersion( pImp->nFileVersion );
        }

        DBG_ASSERT( pRealFilter, "Unknown storage format!" );
    }

    return aStorage.Is();
}

ErrCode SfxMedium::Unpack_Impl( const String& rDest )
{
    ErrCode nRet = ERRCODE_NONE;
    if ( pImp->pTempDir )
    {
/*
        DirEntry aDestEntry( rDest );
        Dir aDir( pImp->pTempDir->GetName(), FSYS_KIND_FILE );
        sal_uInt16 nCount = aDir.Count();
        for ( sal_uInt16 n=0; n<nCount; n++ )
        {
            DirEntry aDest( aDestEntry.GetPath() );
            DirEntry aTmp = aDir[n];
            aDest += aTmp.GetName();
            if ( aDir[n] == DirEntry( GetPhysicalName() ) )
                continue;

            nRet = aTmp.CopyTo( aDest, FSYS_ACTION_COPYFILE );
            if ( nRet != ERRCODE_NONE )
                break;
        }
 */
    }

    return nRet;
}

//------------------------------------------------------------------
SvStorage* SfxMedium::GetOutputStorage( BOOL bUCBStorage )
{
    // if the medium was constructed with a SvStorage: use this one, not a temp. storage
    if ( aStorage.Is() && !aLogicName.Len() )
        return aStorage;

    if ( !pImp->pTempFile )
        CreateTempFile();
    return GetStorage_Impl( bUCBStorage );
}

SvStorage* SfxMedium::GetStorage()
{
    return GetStorage_Impl( pFilter && SOFFICE_FILEFORMAT_60 <= pFilter->GetVersion() );
}

SvStorage* SfxMedium::GetStorage_Impl( BOOL bUCBStorage )
{
    if ( aStorage.Is() || bTriedStorage )
        return aStorage;

    BOOL bResetSorage = FALSE;
    SvStream *pStream;

    String aStorageName;
    if ( pImp->pTempFile )
    {
        aStorageName = pImp->pTempFile->GetURL();
        pStream = GetOutStream();
    }
    else
    {
        aStorageName = GetURLObject().GetMainURL();
        pStream = GetInStream();
        if ( pStream )
        {
            pStream->GetLockBytes()->SetSynchronMode( sal_True );
            if ( !pImp->aDoneLink.IsSet() )
                DownLoad();
        }
    }

    if( !pStream || ( GetError() != SVSTREAM_OK ) )
        return aStorage;

    bTriedStorage = sal_True;

    if ( pImp->pTempFile && pOutStream )
    {
        DELETEZ( pOutStream );
        aStorage = new SvStorage( bUCBStorage, aStorageName, nStorOpenMode, bDirect ? 0 : STORAGE_TRANSACTED );
    }
    else
    {
        aStorage = new SvStorage( pStream, FALSE );
        if ( !aStorage->GetName().Len() )
            aStorage->SetName( aStorageName );
    }

    if ( aStorage->GetError() == SVSTREAM_OK )
        GetVersionList();

    // ???? wird das noch gebraucht?
//  GetMedium_Impl();
//  if ( !aStorage.Is() )
//      CreateFileStream();

    SFX_ITEMSET_ARG( pSet, pVersion, SfxInt16Item, SID_VERSION, sal_False);

    if ( pVersion )
    {
        // Alle verf"ugbaren Versionen einlesen
        if ( pImp->pVersions )
        {
            // Die zum Kommentar passende Version suchen
            // Die Versionen sind von 1 an durchnumeriert, mit negativen
            // Versionsnummern werden die Versionen von der aktuellen aus
            // r"uckw"arts gez"ahlt
            short nVersion = pVersion ? pVersion->GetValue() : 0;
            if ( nVersion<0 )
                nVersion = ( (short) pImp->pVersions->Count() ) + nVersion;
            else if ( nVersion )
                nVersion--;

            SfxVersionInfo* pInfo = nVersion>=0 ? pImp->pVersions->GetObject( nVersion ) : NULL;
            if ( pInfo )
            {
                String aVersionStream = pInfo->aName;

                // SubStorage f"ur alle Versionen "offnen
                SvStorageRef aSub =
                    aStorage->OpenStorage( DEFINE_CONST_UNICODE( "Versions" ), SFX_STREAM_READONLY | STREAM_NOCREATE );

                DBG_ASSERT( aSub.Is() && !aSub->GetError(), "Versionsliste, aber keine Versionen!" );

                // Dort ist die Version als gepackter Stream gespeichert
                SvStorageStreamRef aStream =
                    aSub->OpenStream( aVersionStream, SFX_STREAM_READONLY );

                if ( aStream.Is() && aStream->GetError() == SVSTREAM_OK )
                {
                    // Stream ins TempDir auspacken
                    ::utl::TempFile aTempFile;
                    String          aTmpName = aTempFile.GetURL();
                    SvFileStream    aTmpStream( aTmpName, SFX_STREAM_READWRITE );

                    // The new file format uses UCB storages instead of OLE storages.
                    // These storages aren't compressed.
                    if ( !aSub->IsOLEStorage() )
                    {
                        *aStream >> aTmpStream;
                    }
                    else
                    {
                        ZCodec aCodec;
                        aCodec.BeginCompression();
                        aCodec.Decompress( *aStream, aTmpStream );
                        aCodec.EndCompression();
                    }
                    aTmpStream.Close();

                    // Datei als Storage "offnen
                    nStorOpenMode = SFX_STREAM_READONLY;
                    aStorage = new SvStorage( aTmpName, nStorOpenMode );

                    String aTemp;
                    ::utl::LocalFileHelper::ConvertURLToPhysicalName( aTmpName, aTemp );
                    SetPhysicalName( aTemp );

                    pImp->bIsTemp = sal_True;
                    GetItemSet()->Put( SfxBoolItem( SID_DOC_READONLY, sal_True ) );
                    DELETEZ( pImp->pVersions );
                }
                else
                    bResetSorage = TRUE;
            }
            else
                bResetSorage = TRUE;
        }
        else
            bResetSorage = TRUE;
    }

    if ( aStorage.Is() )
    {
        if( aStorage->GetError() != SVSTREAM_OK )
            bResetSorage = TRUE;
        else if ( GetFilter() )
            aStorage->SetVersion( GetFilter()->GetVersion() );
    }

    if ( bResetSorage )
    {
        aStorage.Clear();
        pStream->Seek( 0L );
    }

    pImp->bIsStorage = aStorage.Is();
    return aStorage;
}

//------------------------------------------------------------------
void SfxMedium::CloseStorage()
{
    aStorage.Clear();
    bTriedStorage = sal_False;
    pImp->bIsStorage = sal_False;
}

//------------------------------------------------------------------
void SfxMedium::SetOpenMode( StreamMode nStorOpen,
                             sal_Bool bDirectP,
                             sal_Bool bDontClose )
{
    if ( nStorOpenMode != nStorOpen )
    {
        nStorOpenMode = nStorOpen;

        if( !bDontClose )
            Close();
    }

    bDirect     = bDirectP;
    bSetFilter  = sal_False;
}

//------------------------------------------------------------------
void SfxMedium::Transfer_Impl()
{
    if( pImp->pTempFile && ( !eError || eError & ERRCODE_WARNING_MASK ) )
    {
        Reference < XContent > xContent = GetContent();
        if ( !xContent.is() )
        {
            eError = ERRCODE_IO_NOTEXISTS;
            return;
        }

        SFX_ITEMSET_ARG( GetItemSet(), pSegmentSize, SfxInt32Item, SID_SEGMENTSIZE, sal_False);
        if ( pSegmentSize )
        {
            // this file must be stored into a disk spanned package
            SotStorageRef xStor = new SotStorage( TRUE, GetName(), STREAM_STD_READWRITE | STREAM_TRUNC, STORAGE_TRANSACTED );
            if ( xStor->GetError() == ERRCODE_NONE )
            {
                // set segment size property; package will automatically be divided in pieces fitting
                // into this size
                ::com::sun::star::uno::Any aAny;
                aAny <<= pSegmentSize->GetValue();
                xStor->SetProperty( String::CreateFromAscii("SegmentSize"), aAny );

                // copy the temporary storage into the disk spanned package
                GetStorage()->CopyTo( xStor );
                xStor->Commit();
            }

            if ( !GetError() )
                SetError( xStor->GetError() );
            return;
        }

        if ( pFilter && SOFFICE_FILEFORMAT_60 <= pFilter->GetVersion() )
        {
            SFX_ITEMSET_ARG( GetItemSet(), pItem, SfxBoolItem, SID_PACK, sal_False);
            if ( pItem && !pItem->GetValue() )
            {
                // this file must be stored without packing into a JAR file
                // check for an existing unpacked storage
                SvStream* pStream = ::utl::UcbStreamHelper::CreateStream( GetName(), STREAM_STD_READ );
                if ( !pStream->GetError() )
                {
                    String aURL = UCBStorage::GetLinkedFile( *pStream );
                    if ( aURL.Len() )
                        // remove a possibly existing old folder
                        SfxContentHelper::Kill( aURL );
                }

                DELETEZ( pStream );

                // create a link file for unpacked storages
                String aURL = UCBStorage::CreateLinkFile( GetName() );

                // create a new folder based storage
                SvStorageRef xStor = new SvStorage( TRUE, GetName() );

                // copy package into unpacked storage
                if ( GetStorage()->CopyTo( xStor ) )
                {
                    // commit changes, writing will happen now
                    xStor->Commit();

                    // take new unpacked storage as own storage
                    Close();
                    DELETEZ( pImp->pTempFile );
                    SetStorage_Impl( xStor );
                }
                else if ( !GetError() )
                    SetError( GetStorage()->GetError() );
                return;
            }
        }

        sal_Bool bSuccess = sal_False;

        // check wether the the temp file has the same protocol
        // scheme as the destination, wether the destination supports
        // the transfer command and wether or not the command
        // executed successfully

        BOOL            bTryTransfer = FALSE;
        String          aName;
        INetURLObject   aDest = GetURLObject();
        INetURLObject   aSource( pImp->pTempFile->GetURL() );

        aName = GetLongName();
        if ( !aName.Len() )
            aName = aDest.getName( INetURLObject::LAST_SEGMENT, true,
                                   INetURLObject::DECODE_WITH_CHARSET );

        if ( aDest.GetProtocol() == aSource.GetProtocol() )
        {
            bTryTransfer = UCB_Helper::HasCommand( xContent,
                                                   WID_TRANSFER );
        }

        // free resources, otherwise the transfer may fail
        Close();
        if ( bTryTransfer && aDest.removeSegment() )
        {
            // content says: direct transfer is possible
            TransferInfo    aInfo;
            String          aParentURL = aDest.GetMainURL();
            Any             aAny;

            aInfo.MoveData = sal_True;
            aInfo.SourceURL = aSource.GetMainURL();
            aInfo.NewTitle = aName;

            SFX_ITEMSET_ARG( GetItemSet(), pRename, SfxBoolItem, SID_RENAME, sal_False );
            SFX_ITEMSET_ARG( GetItemSet(), pOverWrite, SfxBoolItem, SID_OVERWRITE, sal_False );

            if ( pOverWrite && !pOverWrite->GetValue() )
            {
                aInfo.NameClash = NameClash::ERROR;
            }
            else if ( pRename && pRename->GetValue() )
            {
                aInfo.NameClash = NameClash::RENAME;
            }
            else
            {
                aInfo.NameClash = NameClash::OVERWRITE;
            }

            aAny <<= aInfo;
            UCB_Helper::ExecuteCommand( aParentURL, WID_TRANSFER, aAny, &bSuccess );
            if ( bSuccess )
            {
                // when the transfer command executed successful, there will be no tempfile
                // anymore ( because the file has been moved! ), so we have to get rid of it
                pImp->pTempFile->EnableKillingFile( sal_False );
                delete pImp->pTempFile;
                pImp->pTempFile = NULL;
                return;
            }
        }

        if ( !bSuccess )
        {
            // direct transfer impossible or failed: transfer data as stream
            SvStream *pStream = new SvFileStream( pImp->pTempFile->GetFileName(), STREAM_STD_READ );
            SvLockBytesRef xLockBytes = new SvLockBytes( pStream );
            Reference < ::com::sun::star::io::XInputStream > xStream = new ::utl::OInputStreamHelper( xLockBytes, 8192 );

            Any aAny;
            InsertCommandArgument aArg;
            aArg.Data = xStream;
            aArg.ReplaceExisting = sal_True;
            aAny <<= aArg;

            UCB_Helper::ExecuteCommand( xContent, WID_INSERT, aAny, &bSuccess );
            delete pStream;
        }

        if ( !bSuccess )
            eError = ERRCODE_IO_GENERAL;
    }
}

//------------------------------------------------------------------
void SfxMedium::DoBackup_Impl()
{
    INetURLObject   aDest;
    INetURLObject   aSource = GetURLObject();
    String          aParentURL;
    String          aName;
    String          aBakDir = SvtPathOptions().GetBackupPath();
    BOOL            bTryTransfer = FALSE;
    sal_Bool        bSuccess = sal_False;
    Reference < XContent > xContent;

    // Backup Path gesetzt ? Dann diesen benutzen.
    if( aBakDir.Len() )
    {
        aDest.SetURL( aBakDir );
        aDest.insertName( aSource.getName() );
    }
    else
    {
        aDest = GetURLObject();
    }

    aDest.setExtension( DEFINE_CONST_UNICODE( "bak" ) );
    aName = aDest.getName( INetURLObject::LAST_SEGMENT, true,
                           INetURLObject::DECODE_WITH_CHARSET );

    // check wether the the temp file has the same protocol
    // scheme as the destination, wether the destination supports
    // the transfer command and wether or not the command
    // executed successfully

    if ( aDest.GetProtocol() == aSource.GetProtocol() )
    {
        INetURLObject aDestDir = aDest;
        if ( aDestDir.removeSegment() )
        {
            aParentURL = aDestDir.GetMainURL();
            xContent = UCB_Helper::CreateContent( aParentURL );
            if ( xContent.is() )
            {
                bTryTransfer = UCB_Helper::HasCommand( xContent,
                                               WID_TRANSFER );
            }
        }
    }

    if ( bTryTransfer )
    {
        TransferInfo    aInfo;
        Any             aAny;

        aInfo.MoveData = sal_True;
        aInfo.SourceURL = aSource.GetMainURL();
        aInfo.NewTitle = aName;
        aInfo.NameClash = NameClash::OVERWRITE;

        aAny <<= aInfo;
        Close();
        UCB_Helper::ExecuteCommand( xContent, WID_TRANSFER,
                                    aAny, &bSuccess );
    }

    if ( !bSuccess )
    {
        xContent = UCB_Helper::CreateContent( aDest.GetMainURL() );
        if ( xContent.is() )
        {
            SvStream *pStream = GetInStream();
            SvLockBytesRef xLockBytes = new SvLockBytes( pStream );
            Reference < ::com::sun::star::io::XInputStream > xStream
                    = new ::utl::OInputStreamHelper( xLockBytes, 8192 );

            Any aAny;
            InsertCommandArgument aArg;

            aArg.Data = xStream;
            aArg.ReplaceExisting = sal_True;
            aAny <<= aArg;

            UCB_Helper::ExecuteCommand( xContent, WID_INSERT, aAny, &bSuccess );
        }
    }

    if ( ! bSuccess )
        WarningBox( NULL, SfxResId( MSG_WARNING_BACKUP ) ).Execute();
}

//----------------------------------------------------------------
void SfxMedium::GetMedium_Impl()
{
    if ( !pInStream )
    {
        pImp->bDownloadDone = sal_False;
        pImp->bStreamReady = sal_False;

//        ::utl::UcbLockBytesRef xLockBytes;
        ::utl::UcbLockBytesHandler* pHandler = pImp->aHandler;
        INetProtocol eProt = GetURLObject().GetProtocol();
        if ( eProt != INET_PROT_HTTP && eProt != INET_PROT_FTP )
            pHandler = NULL;
        BOOL bSynchron = pImp->bForceSynchron || ! pImp->aDoneLink.IsSet();
        SFX_ITEMSET_ARG( pSet, pStreamItem, SfxUnoAnyItem, SID_INPUTSTREAM, sal_False);
        if ( pStreamItem )
        {
            if ( GetContent().is() && !IsReadOnly() )
            {
                Any aAny( UCB_Helper::GetProperty( GetContent(), WID_FLAG_READONLY ) );
                BOOL bReadonly;
                if ( !( aAny >>= bReadonly ) || bReadonly )
                {
                    GetItemSet()->Put( SfxBoolItem(SID_DOC_READONLY, sal_True));
                    SetOpenMode(SFX_STREAM_READONLY, sal_False);
                }
            }

            Reference < ::com::sun::star::io::XInputStream > xStream;
            if ( ( pStreamItem->GetValue() >>= xStream ) && xStream.is() )
                pImp->xLockBytes = utl::UcbLockBytes::CreateInputLockBytes( xStream );
            Done_Impl( pImp->xLockBytes.Is() ? pImp->xLockBytes->GetError() : ERRCODE_IO_NOTSUPPORTED );
        }
        else
        {
            if ( !SfxContentHelper::Exists( GetName() ) )
            {
                Done_Impl( ERRCODE_IO_NOTEXISTS );
                return;
            }

            SFX_ITEMSET_ARG( GetItemSet(), pItem, SfxBoolItem, SID_DOC_READONLY, sal_False);
            BOOL bAllowReadOnlyMode = pItem ? pItem->GetValue() : TRUE;
            BOOL bIsWritable = ( nStorOpenMode & STREAM_WRITE );

            SFX_ITEMSET_ARG( GetItemSet(), pPostDataItem, SfxUnoAnyItem, SID_POSTDATA, sal_False);
            SFX_ITEMSET_ARG( GetItemSet(), pContentTypeItem, SfxStringItem, SID_CONTENT_TYPE, sal_False);
            SFX_ITEMSET_ARG( GetItemSet(), pRefererItem, SfxStringItem, SID_REFERER, sal_False);

            Sequence < PropertyValue > aProps(1);
            ::rtl::OUString aReferer;
            if ( pRefererItem )
                aReferer = pRefererItem->GetValue();

            aProps[0].Name = ::rtl::OUString::createFromAscii("Referer");
            aProps[0].Value <<= aReferer;

            if ( pPostDataItem )
            {
                DBG_ASSERT( !bIsWritable && bAllowReadOnlyMode, "Strange open mode!" );
                bIsWritable = FALSE;

                ::rtl::OUString aMimeType;
                if ( pContentTypeItem )
                    aMimeType = pContentTypeItem->GetValue();
                else
                    aMimeType = ::rtl::OUString::createFromAscii( "application/x-www-form-urlencoded" );

                aProps.realloc(2);
                aProps[1].Name = ::rtl::OUString::createFromAscii("ContentType");
                aProps[1].Value <<= aMimeType;

                Reference < XInputStream > xPostData;
                if ( pPostDataItem )
                {
                    Any aAny = pPostDataItem->GetValue();
                    aAny >>= xPostData;
                }

                pImp->xLockBytes = ::utl::UcbLockBytes::CreateLockBytes( GetContent(), aProps, xPostData, pHandler );
            }
            else
            {
                // no callbacks for opening read/write because we might try readonly later
                pImp->bDontCallDoneLinkOnSharingError = ( bIsWritable && bAllowReadOnlyMode );
                pImp->xLockBytes = ::utl::UcbLockBytes::CreateLockBytes( GetContent(), aProps, nStorOpenMode, bIsWritable ? NULL : pHandler );
            }

            if ( !pImp->xLockBytes.Is() )
            {
                pImp->bDontCallDoneLinkOnSharingError = sal_False;
                Done_Impl( ERRCODE_IO_NOTEXISTS );
            }
            else if ( pImp->xLockBytes->GetError() == ERRCODE_IO_NOTEXISTS && bIsWritable && bAllowReadOnlyMode )
            {
                GetItemSet()->Put( SfxBoolItem(SID_DOC_READONLY, sal_True));
                SetOpenMode(SFX_STREAM_READONLY, sal_False);
                ResetError();
                pImp->bDownloadDone = sal_False;
                pImp->bDontCallDoneLinkOnSharingError = sal_False;
                pImp->xLockBytes = ::utl::UcbLockBytes::CreateLockBytes( GetContent(), aProps, nStorOpenMode, pHandler );
                if ( !pHandler && !pImp->bDownloadDone )
                    Done_Impl( pImp->xLockBytes->GetError() );
            }
            else if ( !pHandler && !pImp->bDownloadDone )
                // opening readwrite is always done synchronously
                Done_Impl( pImp->xLockBytes->GetError() );
        }

        if ( pImp->xLockBytes.Is() )
        {
            if ( bSynchron )
                pImp->xLockBytes->SetSynchronMode( sal_True );
            if ( !pImp->bDownloadDone )
                pImp->pCancellable = new UcbLockBytesCancellable_Impl( pImp->xLockBytes, pImp->GetCancelManager(), aLogicName );
            pInStream = new SvStream( pImp->xLockBytes );
            pInStream->SetBufferSize( 4096 );
            pImp->bStreamReady = sal_True;
        }
    }

    // Download completion happened while pInStream was constructed
    if ( pImp->bDownloadDone )
        Done_Impl( GetError() );

}

//------------------------------------------------------------------
SfxPoolCancelManager* SfxMedium::GetCancelManager_Impl() const
{
    return pImp->GetCancelManager();
}

//------------------------------------------------------------------
void SfxMedium::SetCancelManager_Impl( SfxPoolCancelManager* pMgr )
{
    pImp->xCancelManager = pMgr;
}

//----------------------------------------------------------------
void SfxMedium::CancelTransfers()
{
    if( pImp->xCancelManager.Is() )
        pImp->xCancelManager->Cancel();
}

//----------------------------------------------------------------
/*
String SfxMedium::GetStatusString( const SvProgressArg* pArg )
{
    String aString;
    StringList_Impl aSL( SfxResId( RID_DLSTATUS2 ), (USHORT)pArg->eStatus );
    USHORT nTotal = 0;

    if ( pArg->eStatus == SVBINDSTATUS_ENDDOWNLOADDATA && nTotal <= 1 )
        return aString;

    if( aSL )
    {
        INetURLObject aObj( pArg->rStatus );
        aString = aSL.GetString();
        aString.SearchAndReplaceAscii( "$(HOST)", aObj.GetHost() );
        String aTarget = aObj.GetFull();
        if( aTarget.Len() <= 1 && pArg->eStatus != SVBINDSTATUS_CONNECTING )
            aTarget = aObj.GetHost();
        if( pArg->nMax )
        {
            aTarget += DEFINE_CONST_UNICODE( " (" );
            AddNumber_Impl( aTarget, pArg->nMax );
            aTarget += ')';
        }

        aString.SearchAndReplaceAscii( "$(TARGET)",aTarget );
        String aNumber;
        AddNumber_Impl( aNumber, pArg->nProgress );
        if( pArg->nRate )
        {
            aNumber+= DEFINE_CONST_UNICODE( " (" );
            AddNumber_Impl( aNumber, (ULONG)pArg->nRate );
            aNumber+= DEFINE_CONST_UNICODE( "/s)" );
        }
        if( pArg->nMax && pArg->nProgress && pArg->nMax != pArg->nProgress )
        {
            aNumber += DEFINE_CONST_UNICODE( " [" );
            float aPerc = pArg->nProgress / (float)pArg->nMax;
            aNumber += String::CreateFromInt32( (USHORT)(aPerc * 100) );
            aNumber += DEFINE_CONST_UNICODE( "%]" );
        }
        aString.SearchAndReplaceAscii( "$(BYTE)", aNumber );
    }
    return aString;
}
*/

sal_Bool SfxMedium::IsRemote()
{
    return bRemote;
}

//------------------------------------------------------------------

void SfxMedium::SetUpdatePickList(sal_Bool bVal)
{
    if(!pImp)
        pImp = new SfxMedium_Impl( this );
    pImp->bUpdatePickList = bVal;
}
//------------------------------------------------------------------

sal_Bool SfxMedium::IsUpdatePickList() const
{
    return pImp? pImp->bUpdatePickList: sal_True;
}
//----------------------------------------------------------------

void SfxMedium::SetDoneLink( const Link& rLink )
{
    pImp->aDoneLink = rLink;
}

//----------------------------------------------------------------

void SfxMedium::SetDataAvailableLink( const Link& rLink )
{
    pImp->aAvailableLink = rLink;
}

//----------------------------------------------------------------
void SfxMedium::StartDownload()
{
    GetMedium_Impl();
    GetInStream();
}

void SfxMedium::DownLoad( const Link& aLink )
{
    SetDoneLink( aLink );
    GetInStream();
    if ( pInStream && !aLink.IsSet() )
    {
        while( !pImp->bDownloadDone )
            Application::Yield();
    }
}

//------------------------------------------------------------------
void SfxMedium::Init_Impl()
/*  [Beschreibung]
    Setzt in den Logischen Namen eine gueltige ::com::sun::star::util::URL (Falls zuvor ein Filename
    drin war) und setzt den physikalschen Namen auf den Filenamen, falls
    vorhanden.
 */

{
    pImp->pVersions = NULL;

    if( aLogicName.Len() )
    {
        INetURLObject aUrl( aLogicName );
        INetProtocol eProt = aUrl.GetProtocol();
        if ( eProt == INET_PROT_NOT_VALID )
        {
            DBG_ERROR ( "Unknown protocol!" );
        }
        else
        {
            // try to convert the URL into a physical name
            ::utl::LocalFileHelper::ConvertURLToPhysicalName( aLogicName, aName );
        }
    }

    SetIsRemote_Impl();

    // Recover-Files sind immer temp
    SFX_ITEMSET_ARG( pSet, pSalvageItem, SfxStringItem, SID_DOC_SALVAGE, sal_False);
    if ( pSalvageItem )
        pImp->bIsTemp = sal_True;
}

//------------------------------------------------------------------

SfxMedium::SfxMedium()
:   IMPL_CTOR(),
    bRoot( sal_False ),
    pURLObj(0),

    pSet(0),
    pImp(new SfxMedium_Impl( this )),
    pFilter(0)
{
    Init_Impl();
}
//------------------------------------------------------------------

SfxMedium::SfxMedium( const SfxMedium& rMedium, sal_Bool bTemporary )
:   IMPL_CTOR(),
    bRoot(sal_True),
    pURLObj( rMedium.pURLObj ? new INetURLObject(*rMedium.pURLObj) : 0 ),
    pImp(new SfxMedium_Impl( this ))
{
    bDirect       = rMedium.IsDirect();
    nStorOpenMode = rMedium.GetOpenMode();
    if ( !bTemporary )
        aName = rMedium.GetName();

    pImp->bIsTemp = bTemporary;
    DBG_ASSERT( ! rMedium.pImp->bIsTemp, "Temporaeres Medium darf nicht kopiert werden" );
    aLogicName = rMedium.aLogicName;
    pSet =  rMedium.GetItemSet() ? new SfxItemSet(*rMedium.GetItemSet()) : 0;
    pFilter = rMedium.pFilter;
    Init_Impl();
    if( bTemporary )
        CreateTempFile();

    if ( rMedium.pImp->pEaMgr )
        GetEaMgr();
}
//------------------------------------------------------------------

void SfxMedium::SetFilter( const SfxObjectFactory& rFact, const String & rFilter )
{
    SetFilter(  rFact.GetFilterContainer()->GetFilter(rFilter) );
}
//----------------------------------------------------------------

void SfxMedium::SetFilter( const SfxFilter* pFilterP, sal_Bool bResetOrig )
{
    pFilter = pFilterP;
    pImp->nFileVersion = 0;
}
//----------------------------------------------------------------

const SfxFilter* SfxMedium::GetOrigFilter( sal_Bool bNotCurrent ) const
{
    return ( pImp->pOrigFilter || bNotCurrent ) ? pImp->pOrigFilter : pFilter;
}
//----------------------------------------------------------------

void SfxMedium::SetOrigFilter_Impl( const SfxFilter* pFilter )
{
    pImp->pOrigFilter = pFilter;
}
//------------------------------------------------------------------

void SfxMedium::Close()
{
    if ( aStorage.Is() )
    {
        // don't close the streams if they belong to the
        // storage

        const SvStream *pStream = aStorage->GetSvStream();
        if ( pStream && pStream == pInStream )
        {
            pInStream = NULL;
            pImp->xInputStream = Reference < XInputStream >();
            pImp->xLockBytes.Clear();
            if ( pSet )
                pSet->ClearItem( SID_INPUTSTREAM );
            aStorage->SetDeleteStream( TRUE );
        }
        else if ( pStream && pStream == pOutStream )
        {
            pOutStream = NULL;
            aStorage->SetDeleteStream( TRUE );
        }

        CloseStorage();
    }

    if ( pInStream )
        CloseInStream_Impl();

    if ( pOutStream )
        CloseOutStream_Impl();

    pImp->xContent = Reference < XContent >();
}

//------------------------------------------------------------------

void SfxMedium::RefreshName_Impl()
{
#if 0   //(dv)
    if ( pImp->xContent.is() )
    {
        String aNameP = pImp->xAnchor->GetViewURL();
        pImp->aOrigURL = aNameP;
        aLogicName = aNameP;
        DELETEZ( pURLObj );
        if (aLogicName.Len())
            aLogicName = GetURLObject().GetMainURL();
        SetIsRemote_Impl();
    }
#endif  //(dv)
}

void SfxMedium::SetIsRemote_Impl()
{
    INetURLObject aObj( GetName() );
    switch( aObj.GetProtocol() )
    {
        case INET_PROT_FTP:
        case INET_PROT_HTTP:
        case INET_PROT_HTTPS:
        case INET_PROT_POP3:
        case INET_PROT_NEWS:
        case INET_PROT_IMAP:
//        case INET_PROT_OUT:
        case INET_PROT_VIM:
            bRemote = TRUE; break;
        default:
            bRemote = ( GetName().CompareToAscii( "private:msgid", 13 ) == COMPARE_EQUAL );
            break;
    }

    // Da Dateien, die Remote geschrieben werden zur Uebertragung auch
    // gelesen werden koennen muessen
    if( bRemote )
        nStorOpenMode |= STREAM_READ;
}



void SfxMedium::SetName( const String& aNameP, sal_Bool bSetOrigURL )
{
    if( !pImp->aOrigURL.Len() )
        pImp->aOrigURL = aLogicName;
    if( bSetOrigURL )
        pImp->aOrigURL = aNameP;
    aLogicName = aNameP;
    DELETEZ( pURLObj );
    pImp->xContent = ::com::sun::star::uno::Reference < ::com::sun::star::ucb::XContent > ();
    Init_Impl();
}

//----------------------------------------------------------------
const String& SfxMedium::GetOrigURL() const
{
    return !pImp->aOrigURL.Len() ? (String &)aLogicName : pImp->aOrigURL;
}

//----------------------------------------------------------------

void SfxMedium::SetPhysicalName( const String& rNameP )
{
    if( pImp->pTempFile )
    {
        delete pImp->pTempFile;
        pImp->pTempFile = NULL;
    }

    aName = rNameP;
    bTriedStorage = sal_False;
    pImp->bIsStorage = sal_False;
    if ( aName.Len() )
        pImp->xContent = Reference < XContent >();
}

//------------------------------------------------------------------
void SfxMedium::SetTemporary( sal_Bool bTemp )
{
    pImp->bIsTemp = bTemp;
}

//------------------------------------------------------------------
sal_Bool SfxMedium::IsTemporary() const
{
    return pImp->bIsTemp;
}

//------------------------------------------------------------------

sal_Bool SfxMedium::Exists( sal_Bool bForceSession )
{
    DBG_ERROR( "Not implemented!" );
    return sal_True;
}

//------------------------------------------------------------------

void SfxMedium::ReOpen()
{
    DBG_ASSERT( pFilter, "Kein Filter, aber ReOpen!" );
    if( pFilter )
    {
        if( pFilter->UsesStorage() )
            GetStorage();
        else
            GetInStream();
    }
}
//------------------------------------------------------------------
SfxMedium::SfxMedium
(
    const String &rName, StreamMode nOpenMode,  sal_Bool bDirectP,
    const SfxFilter *pFlt, SfxItemSet *pInSet
)
:   IMPL_CTOR(),
    bRoot( sal_False ),
    pFilter(pFlt),
    pURLObj(0),
    pImp(new SfxMedium_Impl( this )),
    pSet( pInSet )
{
    aName = aLogicName = rName;
    nStorOpenMode = nOpenMode;
    bDirect = bDirectP;
    Init_Impl();
}
//------------------------------------------------------------------

SfxMedium::SfxMedium( SvStorage *pStorage, sal_Bool bRootP )
:   IMPL_CTOR(),
    bRoot( bRootP ),
    aStorage(pStorage),
    pURLObj(0),
    pImp( new SfxMedium_Impl( this )),
    pSet(0)
{
    SfxApplication* pApp = SFX_APP();
    sal_uInt32 nFormat = pStorage->GetFormat();
    if( !nFormat )
    {
#ifdef DBG_UTIL
        if( aLogicName.Len() )
            DBG_ERROR( "Unbekanntes StorageFormat, versuche eigenes Format" );
#endif
        pFilter = SfxObjectFactory::GetDefaultFactory().GetFilterContainer()->
            GetFilter( 0 );
    }
    else
        pFilter = pApp->GetFilterMatcher().GetFilter4ClipBoardId( nFormat, 0, 0 );
    if( !pFilter && nFormat )
    {
        DBG_ERROR( "No Filter for storage found!" );
        pFilter = SfxObjectFactory::GetDefaultFactory().GetFilterContainer()->GetFilter( 0 );
    }

    Init_Impl();
}

//------------------------------------------------------------------

SfxMedium::~SfxMedium()
{
//  CancelTransfers();
    ::vos::OClearableGuard aGuard( pImp->aHandler->GetMutex() );
    pImp->aHandler->ReleaseMedium();
    aGuard.clear();

    Close();

    delete pSet;

    if( pImp->bIsTemp && GetPhysicalName().Len() )
    {
        String aTemp;
        ::utl::LocalFileHelper::ConvertPhysicalNameToURL( aName, aTemp );
        SfxContentHelper::Kill( aTemp );
    }

    pFilter = 0;

    delete pURLObj;
    delete pImp;
}
//------------------------------------------------------------------

void SfxMedium::SetItemSet(SfxItemSet *pNewSet)
{
    delete pSet;
    pSet = pNewSet;
}
//------------------------------------------------------------------

void SfxMedium::SetClassFilter( const SvGlobalName & rFilterClass )
{
    bSetFilter = sal_True;
    aFilterClass = rFilterClass;
}
//----------------------------------------------------------------

const INetURLObject& SfxMedium::GetURLObject() const
{
    if( !pURLObj )
    {
        SfxMedium* pThis = const_cast < SfxMedium* > (this);
        pThis->pURLObj = new INetURLObject( aLogicName );
    }

    return *pURLObj;
}

//----------------------------------------------------------------

const String& SfxMedium::GetPreRedirectedURL() const
{
    return pImp->aPreRedirectionURL;
}
//----------------------------------------------------------------

sal_uInt32 SfxMedium::GetMIMEAndRedirect( String &rName )
{
/* dv !!!! not needed any longer ?
    INetProtocol eProt = GetURLObject().GetProtocol();
    if( eProt == INET_PROT_FTP && SvBinding::ShouldUseFtpProxy( GetURLObject().GetMainURL() ) )
    {
        Any aAny( UCB_Helper::GetProperty( GetContent(), WID_FLAG_IS_FOLDER ) );
        sal_Bool bIsFolder = FALSE;
        if ( ( aAny >>= bIsFolder ) && bIsFolder )
            return ERRCODE_NONE;
    }

    GetMedium_Impl();
    if( !eError && pImp->xBinding.Is() )
    {
        eError = pImp->xBinding->GetMimeType( rName );

        // Wir koennen keine Parameter wie CharSets usw.
        rName = rName.GetToken( 0, ';' );
        if( !eError )
        {
            if( !pImp->aPreRedirectionURL.Len() )
                pImp->aPreRedirectionURL = aLogicName;
            SetName( pImp->xBinding->GetRedirectedURL() );
        }
        pImp->aExpireTime = pImp->xBinding->GetExpireDateTime();
    }
    return eError;
*/
    return 0;
}

//----------------------------------------------------------------

void SfxMedium::SetUsesCache( sal_Bool bUse )
{
    pImp->bUsesCache = bUse;
}
//----------------------------------------------------------------

sal_Bool SfxMedium::UsesCache() const
{
    return pImp->bUsesCache;
}
//----------------------------------------------------------------

//----------------------------------------------------------------

void SfxMedium::SetReferer( const String& rRefer )
{
    pImp->aReferer = rRefer;
}
//----------------------------------------------------------------

const String& SfxMedium::GetReferer( ) const
{
    return pImp->aReferer;
}
//----------------------------------------------------------------

void SfxMedium::SetTransferPriority( sal_uInt16 nPrio )
{
    pImp->nPrio = nPrio;
}
//----------------------------------------------------------------

sal_uInt16 SfxMedium::GetTransferPriority( ) const
{
    return pImp->nPrio;
}
//----------------------------------------------------------------

void SfxMedium::SetExpired_Impl( const DateTime& rDateTime )
{
    pImp->aExpireTime = rDateTime;
}
//----------------------------------------------------------------

sal_Bool SfxMedium::IsExpired() const
{
    return pImp->aExpireTime.IsValid() && pImp->aExpireTime < DateTime();
}
//----------------------------------------------------------------

void SfxMedium::ForceSynchronStream_Impl( sal_Bool bForce )
{
    if( pInStream )
    {
        SvLockBytes* pBytes = pInStream->GetLockBytes();
        if( pBytes )
            pBytes->SetSynchronMode( bForce );
    }
    pImp->bForceSynchron = bForce;
}
//----------------------------------------------------------------
/* Kann der URL ein MIME Type zugeordnent werden? */
sal_Bool SfxMedium::SupportsMIME_Impl() const
{
    INetProtocol eProt = GetURLObject().GetProtocol();
    if( eProt == INET_PROT_HTTPS || eProt == INET_PROT_HTTP  )
        return sal_True;

    if( eProt == INET_PROT_NOT_VALID )
        return sal_False;

    if( eProt == INET_PROT_FTP )
    {
        Any aAny( UCB_Helper::GetProperty( GetContent(), WID_FLAG_IS_FOLDER ) );
        sal_Bool bIsFolder = FALSE;
        if ( ( aAny >>= bIsFolder ) && bIsFolder )
            return SvBinding::ShouldUseFtpProxy( GetURLObject().GetMainURL() );
        else
            return sal_False;
    }

    return sal_False;
}

//----------------------------------------------------------------
SfxFrame* SfxMedium::GetLoadTargetFrame() const
{
    return pImp->wLoadTargetFrame;
}
//----------------------------------------------------------------

void SfxMedium::SetLoadTargetFrame(SfxFrame* pFrame )
{
    pImp->wLoadTargetFrame = pFrame;
}
//----------------------------------------------------------------

void SfxMedium::SetStorage_Impl( SvStorage* pStor )
{
    aStorage = pStor;
}
//----------------------------------------------------------------

SfxItemSet* SfxMedium::GetItemSet() const
{
    if( !pSet ) ((SfxMedium*)this)->pSet =
                    new SfxAllItemSet( SFX_APP()->GetPool() );
    return pSet;
}
//----------------------------------------------------------------

void SfxMedium::SetLoadEnvironment_Impl( LoadEnvironment_Impl* pEnv )
{
    pImp->pLoadEnv = pEnv;
}
//----------------------------------------------------------------

LoadEnvironment_Impl* SfxMedium::GetLoadEnvironment_Impl() const
{
    return pImp->pLoadEnv;
}
//----------------------------------------------------------------

SvKeyValueIterator* SfxMedium::GetHeaderAttributes_Impl()
{
    if( !pImp->xAttributes.Is() )
/*!!!!      if ( pImp->xBinding.Is() )
            pImp->xAttributes = pImp->xBinding->GetHeaders();
        else
*/          pImp->xAttributes = SvKeyValueIteratorRef( new SvKeyValueIterator );

    return pImp->xAttributes;
}
//----------------------------------------------------------------

SvCompatWeakHdl* SfxMedium::GetHdl()
{
    return pImp->GetHdl();
}

sal_Bool SfxMedium::IsDownloadDone_Impl()
{
    return pImp->bDownloadDone;
}

SvEaMgr* SfxMedium::GetEaMgr()
{
    if ( !pImp->pEaMgr && pFilter )
    {
        /* the stream in the storage is probably not a filestream ( the stream is
            closed anyway! ). Therefor we will always use GetPhysicalName to
            create the SvEaMgr. */
        //  SvStream *pStream = aStorage.Is() ? aStorage->GetTargetSvStream() : NULL;
        //  if ( pStream && pStream->IsA() == ID_FILESTREAM )
        //      pImp->pEaMgr = new SvEaMgr(*(SvFileStream *)pStream);
        //  else
        pImp->pEaMgr = new SvEaMgr( GetPhysicalName() );
    }

    return pImp->pEaMgr;
}

//----------------------------------------------------------------

void SfxMedium::SetDontCreateCancellable( )
{
    pImp->bDontCreateCancellable = sal_True;
}

::com::sun::star::uno::Reference< ::com::sun::star::io::XActiveDataSource >  SfxMedium::GetDataSource()
{
    Reference < XActiveDataSource > xRet( pImp->wSource.get(), UNO_QUERY );
    if ( !xRet.is() )
    {
        SfxLoadEnvironment *pEnv = NULL;
        if ( pImp->pLoadEnv )
        {
            pEnv = new SfxLoadEnvironment( pImp->pLoadEnv );
            SfxRefItem aItem( SID_LOADENVIRONMENT, pEnv );
            GetItemSet()->Put( aItem );
        }

        FileSource_Impl* pSource = new FileSource_Impl( this );
        xRet = pSource;
        pImp->wSource = xRet;
        if ( pEnv )
            pEnv->SetDataAvailableLink( LINK( pSource, FileSource_Impl, DataAvailableHdl ) );
    }

    return xRet;
}

::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >  SfxMedium::GetDataSink()
{
    Reference < XOutputStream > xRet( pImp->wSink.get(), UNO_QUERY );
    if ( !xRet.is() )
    {
        xRet = new FileSink_Impl( this );
        pImp->wSink = xRet;
    }

    return xRet;
}

::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >  SfxMedium::GetInputStream()
{
    return pImp->xInputStream;
}

const SfxVersionTableDtor* SfxMedium::GetVersionList()
{
    if ( !pImp->pVersions && GetStorage() )
    {
        SvStorageStreamRef aStream =
            GetStorage()->OpenStream( DEFINE_CONST_UNICODE( "VersionList" ), SFX_STREAM_READONLY | STREAM_NOCREATE );
        if ( aStream.Is() && aStream->GetError() == SVSTREAM_OK )
        {
            pImp->pVersions = new SfxVersionTableDtor;
            pImp->pVersions->Read( *aStream );
        }
        else
        {
            SfxVersionTableDtor *pList = new SfxVersionTableDtor;
            if ( SfxXMLVersList_Impl::ReadInfo( GetStorage(), pList ) )
                pImp->pVersions = pList;
            else
                delete pList;
        }
    }

    return pImp->pVersions;
}

sal_uInt16 SfxMedium::AddVersion_Impl( SfxVersionInfo& rInfo )
{
    if ( GetStorage() )
    {
        if ( !pImp->pVersions )
            pImp->pVersions = new SfxVersionTableDtor;

        // Einen eindeutigen Namen f"ur den Stream ermitteln
        SvULongs aLongs;
        SfxVersionInfo* pInfo = pImp->pVersions->First();
        while ( pInfo )
        {
            sal_uInt32 nVer = (sal_uInt32) pInfo->aName.Copy(7).ToInt32();
            sal_uInt16 n;
            for ( n=0; n<aLongs.Count(); n++ )
                if ( nVer<aLongs[n] )
                    break;

            aLongs.Insert( nVer, n );
            pInfo = pImp->pVersions->Next();
        }

        sal_uInt16 nKey;
        for ( nKey=0; nKey<aLongs.Count(); nKey++ )
            if ( aLongs[nKey] > ( ULONG ) nKey+1 )
                break;

        rInfo.aName = DEFINE_CONST_UNICODE( "Version" );
        rInfo.aName += String::CreateFromInt32( nKey + 1 );
        pInfo = new SfxVersionInfo( rInfo );
        pImp->pVersions->Insert( pInfo, LIST_APPEND );
        return nKey;
    }

    return 0;
}

sal_Bool SfxMedium::RemoveVersion_Impl( const SfxVersionInfo& rInfo )
{
    if ( !pImp->pVersions )
        return sal_False;

    SfxVersionInfo* pInfo = pImp->pVersions->First();
    while( pInfo )
    {
        if ( pInfo->aName == rInfo.aName )
        {
            pImp->pVersions->Remove( pInfo );
            delete pInfo;
            return sal_True;
        }

        pInfo = pImp->pVersions->Next();
    }

    return sal_False;
}

sal_Bool SfxMedium::TransferVersionList_Impl( SfxMedium& rMedium )
{
    if ( rMedium.pImp->pVersions )
    {
        delete pImp->pVersions;
        pImp->pVersions = new SfxVersionTableDtor( *rMedium.pImp->pVersions );
        return sal_True;
    }

    return sal_False;
}

sal_Bool SfxMedium::SaveVersionList_Impl( sal_Bool bUseXML )
{
    if ( GetStorage() )
    {
        if ( !pImp->pVersions )
            return sal_True;

        if ( bUseXML )
        {
            SfxXMLVersList_Impl::WriteInfo( aStorage, pImp->pVersions );
            return sal_True;
        }
        else
        {
            SvStorageStreamRef aStream =
                GetStorage()->OpenStream( DEFINE_CONST_UNICODE( "VersionList" ), SFX_STREAM_READWRITE );
            if ( aStream.Is() && aStream->GetError() == SVSTREAM_OK )
            {
                pImp->pVersions->Write( *aStream );
                return sal_True;
            }
        }
    }

    return sal_False;
}

//----------------------------------------------------------------
sal_Bool SfxMedium::IsReadOnly()
{
    sal_Bool bReadOnly = !( GetOpenMode() & STREAM_WRITE );
/*(dv)  if ( bReadOnly && pURLObj && CntAnchor::IsViewURL( pURLObj->GetMainURL() ) )
        // Chaos-Storages sind niemals als readonly anzusehen!
        return sal_False;
*/
    if ( !bReadOnly )
    {
        // logisch readonly ge"offnet
        SFX_ITEMSET_ARG( GetItemSet(), pItem, SfxBoolItem, SID_DOC_READONLY, sal_False);
        if ( pItem )
            bReadOnly = pItem->GetValue();
    }

    return bReadOnly;
}

//----------------------------------------------------------------
void SfxMedium::CreateTempFile()
{
    if ( pImp->pTempFile )
        DELETEZ( pImp->pTempFile );

    StreamMode nOpenMode = nStorOpenMode;
    GetInStream();
    BOOL bCopy = ( nStorOpenMode == nOpenMode && ! ( nOpenMode & STREAM_TRUNC ) );
    nStorOpenMode = nOpenMode;
    ResetError();

    SFX_ITEMSET_ARG( GetItemSet(), pSegmentSize, SfxInt32Item, SID_SEGMENTSIZE, sal_False);
    SFX_ITEMSET_ARG( GetItemSet(), pItem, SfxBoolItem, SID_PACK, sal_False);
    if ( pSegmentSize || pItem && !pItem->GetValue() )
    {
        pImp->pTempFile = new ::utl::TempFile();
    }
    else
    {
        String          aParentName;
        INetURLObject   aParent = GetURLObject();
        if ( aParent.removeSegment() )
            aParentName = aParent.GetMainURL();
        pImp->pTempFile = new ::utl::TempFile( &aParentName );
    }

    pImp->pTempFile->EnableKillingFile( sal_True );
    aName = pImp->pTempFile->GetFileName();

    if ( bCopy )
    {
        GetOutStream();
        if ( pInStream && pOutStream )
        {
            char        *pBuf = new char [8192];
            sal_uInt32   nErr = ERRCODE_NONE;

            pInStream->Seek(0);
            pOutStream->Seek(0);

            while( !pInStream->IsEof() && nErr == ERRCODE_NONE )
            {
                sal_uInt32 nRead = pInStream->Read( pBuf, 8192 );
                nErr = pInStream->GetError();
                pOutStream->Write( pBuf, nRead );
            }

            delete pBuf;
            CloseInStream();
        }
        CloseOutStream_Impl();
    }
    else
        CloseInStream();

    CloseStorage();
}

//----------------------------------------------------------------
void SfxMedium::CreateTempFileNoCopy()
{
    if ( pImp->pTempFile )
        delete pImp->pTempFile;

    SFX_ITEMSET_ARG( GetItemSet(), pSegmentSize, SfxInt32Item, SID_SEGMENTSIZE, sal_False);
    SFX_ITEMSET_ARG( GetItemSet(), pItem, SfxBoolItem, SID_PACK, sal_False);
    if ( pSegmentSize || pItem && !pItem->GetValue() )
    {
        pImp->pTempFile = new ::utl::TempFile();
    }
    else
    {
        String          aParentName;
        INetURLObject   aParent = GetURLObject();
        if ( aParent.removeSegment() )
            aParentName = aParent.GetMainURL();
        pImp->pTempFile = new ::utl::TempFile( &aParentName );
    }

    pImp->pTempFile->EnableKillingFile( sal_True );
    aName = pImp->pTempFile->GetFileName();

    CloseOutStream_Impl();
    CloseStorage();
}

//----------------------------------------------------------------
#define nActVersion 1

SvStream& SfxVersionTableDtor::Read( SvStream& rStrm )
{
    sal_uInt16 nCount = 0, nVersion = 0;

    rStrm >> nVersion;
    rStrm >> nCount;

    for( sal_uInt16 i=0; i<nCount; ++i )
    {
        SfxVersionInfo *pNew = new SfxVersionInfo;
        rStrm.ReadByteString( pNew->aComment, RTL_TEXTENCODING_UTF8 );
        rStrm.ReadByteString( pNew->aName, RTL_TEXTENCODING_UTF8 );
        pNew->aCreateStamp.Load( rStrm );
        Insert( pNew, LIST_APPEND );
    }

    return rStrm;
}

SvStream& SfxVersionTableDtor::Write( SvStream& rStream ) const
{
    rStream << (sal_uInt16) nActVersion;
    rStream << (sal_uInt16) Count();

    SfxVersionInfo* pInfo = ((SfxVersionTableDtor*)this)->First();
    while( pInfo && rStream.GetError() == SVSTREAM_OK )
    {
        rStream.WriteByteString( pInfo->aComment, RTL_TEXTENCODING_UTF8 );
        rStream.WriteByteString( pInfo->aName, RTL_TEXTENCODING_UTF8 );
        pInfo->aCreateStamp.Save( rStream );
        pInfo = ((SfxVersionTableDtor*)this)->Next();
    }

    return rStream;
}

void SfxVersionTableDtor::DelDtor()
{
    SfxVersionInfo* pTmp = First();
    while( pTmp )
    {
        delete pTmp;
        pTmp = Next();
    }
    Clear();
}

SfxVersionTableDtor& SfxVersionTableDtor::operator=( const SfxVersionTableDtor& rTbl )
{
    DelDtor();
    SfxVersionInfo* pTmp = ((SfxVersionTableDtor&)rTbl).First();
    while( pTmp )
    {
        SfxVersionInfo *pNew = new SfxVersionInfo( *pTmp );
        Insert( pNew, LIST_APPEND );
        pTmp = ((SfxVersionTableDtor&)rTbl).Next();
    }
    return *this;
}

//----------------------------------------------------------------
//----------------------------------------------------------------
//----------------------------------------------------------------
SfxVersionInfo::SfxVersionInfo()
{
}

SvStringsDtor* SfxVersionTableDtor::GetVersions() const
{
    SvStringsDtor *pList = new SvStringsDtor;
    SfxVersionInfo* pInfo = ((SfxVersionTableDtor*) this)->First();
    while ( pInfo )
    {
        String *pString = new String( pInfo->aComment );
        (*pString) += DEFINE_CONST_UNICODE( "; " );
        (*pString) += ConvertDateTime_Impl( pInfo->aCreateStamp );
        pList->Insert( pString, pList->Count() );
        pInfo = ((SfxVersionTableDtor*) this)->Next();
    }

    return pList;
}