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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/


#include "sal/config.h"
#include "cppuhelper/factory.hxx"
#include "cppuhelper/implementationentry.hxx"
#include "cppuhelper/compbase6.hxx"
#include "com/sun/star/lang/XServiceInfo.hpp"
#include "com/sun/star/document/XDocumentProperties.hpp"
#include "com/sun/star/lang/XInitialization.hpp"
#include "com/sun/star/util/XCloneable.hpp"
#include "com/sun/star/util/XModifiable.hpp"
#include "com/sun/star/xml/sax/XSAXSerializable.hpp"

#include "com/sun/star/lang/WrappedTargetRuntimeException.hpp"
#include "com/sun/star/lang/EventObject.hpp"
#include "com/sun/star/beans/XPropertySet.hpp"
#include "com/sun/star/beans/XPropertySetInfo.hpp"
#include "com/sun/star/beans/PropertyAttribute.hpp"
#include "com/sun/star/task/ErrorCodeIOException.hpp"
#include "com/sun/star/embed/XStorage.hpp"
#include "com/sun/star/embed/XTransactedObject.hpp"
#include "com/sun/star/embed/ElementModes.hpp"
#include "com/sun/star/io/XActiveDataControl.hpp"
#include "com/sun/star/io/XActiveDataSource.hpp"
#include "com/sun/star/io/XStream.hpp"
#include "com/sun/star/document/XImporter.hpp"
#include "com/sun/star/document/XExporter.hpp"
#include "com/sun/star/document/XFilter.hpp"
#include "com/sun/star/xml/sax/XParser.hpp"
#include "com/sun/star/xml/dom/XDocument.hpp"
#include "com/sun/star/xml/dom/XElement.hpp"
#include "com/sun/star/xml/dom/XDocumentBuilder.hpp"
#include "com/sun/star/xml/dom/XSAXDocumentBuilder.hpp"
#include "com/sun/star/xml/dom/NodeType.hpp"
#include "com/sun/star/xml/xpath/XXPathAPI.hpp"
#include "com/sun/star/util/Date.hpp"
#include "com/sun/star/util/Time.hpp"
#include "com/sun/star/util/Duration.hpp"

#include "SfxDocumentMetaData.hxx"
#include "rtl/ustrbuf.hxx"
#include "tools/debug.hxx"
#include "tools/datetime.hxx"
#include "osl/mutex.hxx"
#include "cppuhelper/basemutex.hxx"
#include "cppuhelper/interfacecontainer.hxx"
#include "comphelper/storagehelper.hxx"
#include "comphelper/mediadescriptor.hxx"
#include "comphelper/sequenceasvector.hxx"
#include "comphelper/stlunosequence.hxx"
#include "sot/storage.hxx"
#include "sfx2/docfile.hxx"
#include "sax/tools/converter.hxx"

#include <utility>
#include <vector>
#include <map>
#include <cstring>
#include <limits>


#include <cppuhelper/implbase1.hxx>
#include <com/sun/star/document/XCompatWriterDocProperties.hpp>

/**
 * This file contains the implementation of the service
 * com.sun.star.document.DocumentProperties.
 * This service enables access to the meta-data stored in documents.
 * Currently, this service only handles documents in ODF format.
 *
 * The implementation uses an XML DOM to store the properties.
 * This approach was taken because it allows for preserving arbitrary XML data
 * in loaded documents, which will be stored unmodified when saving the
 * document again.
 *
 * Upon access, some properties are directly read from and updated in the DOM.
 * Exception: it seems impossible to get notified upon addition of a property
 * to a com.sun.star.beans.PropertyBag, which is used for storing user-defined
 * properties; because of this, user-defined properties are updated in the
 * XML DOM only when storing the document.
 * Exception 2: when setting certain properties which correspond to attributes
 * in the XML DOM, we want to remove the corresponding XML element. Detecting
 * this condition can get messy, so we store all such properties as members,
 * and update the DOM tree only when storing the document (in
 * <method>updateUserDefinedAndAttributes</method>).
 *
 * @author mst
 */

/// anonymous implementation namespace
namespace {

namespace css = ::com::sun::star;


/// a list of attribute-lists, where attribute means name and content
typedef std::vector<std::vector<std::pair<const char*, ::rtl::OUString> > >
        AttrVector;

typedef ::cppu::WeakComponentImplHelper6<
            css::lang::XServiceInfo,
            css::document::XDocumentProperties,
            css::lang::XInitialization,
            css::util::XCloneable,
            css::util::XModifiable,
            css::xml::sax::XSAXSerializable>
    SfxDocumentMetaData_Base;

class SfxDocumentMetaData:
    private ::cppu::BaseMutex,
    public SfxDocumentMetaData_Base
{
public:
    explicit SfxDocumentMetaData(
        css::uno::Reference< css::uno::XComponentContext > const & context);

    // ::com::sun::star::lang::XServiceInfo:
    virtual ::rtl::OUString SAL_CALL getImplementationName()
        throw (css::uno::RuntimeException);
    virtual ::sal_Bool SAL_CALL supportsService(
        const ::rtl::OUString & ServiceName) throw (css::uno::RuntimeException);
    virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL
        getSupportedServiceNames() throw (css::uno::RuntimeException);

    // ::com::sun::star::lang::XComponent:
    virtual void SAL_CALL dispose() throw (css::uno::RuntimeException);

    // ::com::sun::star::document::XDocumentProperties:
    virtual ::rtl::OUString SAL_CALL getAuthor()
        throw (css::uno::RuntimeException);
    virtual void SAL_CALL setAuthor(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getGenerator()
        throw (css::uno::RuntimeException);
    virtual void SAL_CALL setGenerator(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException);
    virtual css::util::DateTime SAL_CALL getCreationDate()
        throw (css::uno::RuntimeException);
    virtual void SAL_CALL setCreationDate(const css::util::DateTime & the_value)
        throw (css::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getTitle()
        throw (css::uno::RuntimeException);
    virtual void SAL_CALL setTitle(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getSubject()
        throw (css::uno::RuntimeException);
    virtual void SAL_CALL setSubject(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getDescription()
        throw (css::uno::RuntimeException);
    virtual void SAL_CALL setDescription(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException);
    virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getKeywords()
        throw (css::uno::RuntimeException);
    virtual void SAL_CALL setKeywords(
        const css::uno::Sequence< ::rtl::OUString > & the_value)
        throw (css::uno::RuntimeException);
    virtual css::lang::Locale SAL_CALL getLanguage()
        throw (css::uno::RuntimeException);
    virtual void SAL_CALL setLanguage(const css::lang::Locale & the_value)
        throw (css::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getModifiedBy()
        throw (css::uno::RuntimeException);
    virtual void SAL_CALL setModifiedBy(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException);
    virtual css::util::DateTime SAL_CALL getModificationDate()
        throw (css::uno::RuntimeException);
    virtual void SAL_CALL setModificationDate(
            const css::util::DateTime & the_value)
        throw (css::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getPrintedBy()
        throw (css::uno::RuntimeException);
    virtual void SAL_CALL setPrintedBy(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException);
    virtual css::util::DateTime SAL_CALL getPrintDate()
        throw (css::uno::RuntimeException);
    virtual void SAL_CALL setPrintDate(const css::util::DateTime & the_value)
        throw (css::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getTemplateName()
        throw (css::uno::RuntimeException);
    virtual void SAL_CALL setTemplateName(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getTemplateURL()
        throw (css::uno::RuntimeException);
    virtual void SAL_CALL setTemplateURL(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException);
    virtual css::util::DateTime SAL_CALL getTemplateDate()
        throw (css::uno::RuntimeException);
    virtual void SAL_CALL setTemplateDate(const css::util::DateTime & the_value)
        throw (css::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getAutoloadURL()
        throw (css::uno::RuntimeException);
    virtual void SAL_CALL setAutoloadURL(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException);
    virtual ::sal_Int32 SAL_CALL getAutoloadSecs()
        throw (css::uno::RuntimeException);
    virtual void SAL_CALL setAutoloadSecs(::sal_Int32 the_value)
        throw (css::uno::RuntimeException, css::lang::IllegalArgumentException);
    virtual ::rtl::OUString SAL_CALL getDefaultTarget()
        throw (css::uno::RuntimeException);
    virtual void SAL_CALL setDefaultTarget(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException);
    virtual css::uno::Sequence< css::beans::NamedValue > SAL_CALL
        getDocumentStatistics() throw (css::uno::RuntimeException);
    virtual void SAL_CALL setDocumentStatistics(
        const css::uno::Sequence< css::beans::NamedValue > & the_value)
        throw (css::uno::RuntimeException);
    virtual ::sal_Int16 SAL_CALL getEditingCycles()
        throw (css::uno::RuntimeException);
    virtual void SAL_CALL setEditingCycles(::sal_Int16 the_value)
        throw (css::uno::RuntimeException, css::lang::IllegalArgumentException);
    virtual ::sal_Int32 SAL_CALL getEditingDuration()
        throw (css::uno::RuntimeException);
    virtual void SAL_CALL setEditingDuration(::sal_Int32 the_value)
        throw (css::uno::RuntimeException, css::lang::IllegalArgumentException);
    virtual void SAL_CALL resetUserData(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException);
    virtual css::uno::Reference< css::beans::XPropertyContainer > SAL_CALL
        getUserDefinedProperties() throw (css::uno::RuntimeException);
    virtual void SAL_CALL loadFromStorage(
        const css::uno::Reference< css::embed::XStorage > & Storage,
        const css::uno::Sequence< css::beans::PropertyValue > & Medium)
        throw (css::uno::RuntimeException, css::lang::IllegalArgumentException,
               css::io::WrongFormatException,
               css::lang::WrappedTargetException, css::io::IOException);
    virtual void SAL_CALL loadFromMedium(const ::rtl::OUString & URL,
        const css::uno::Sequence< css::beans::PropertyValue > & Medium)
        throw (css::uno::RuntimeException,
               css::io::WrongFormatException,
               css::lang::WrappedTargetException, css::io::IOException);
    virtual void SAL_CALL storeToStorage(
        const css::uno::Reference< css::embed::XStorage > & Storage,
        const css::uno::Sequence< css::beans::PropertyValue > & Medium)
        throw (css::uno::RuntimeException, css::lang::IllegalArgumentException,
               css::lang::WrappedTargetException, css::io::IOException);
    virtual void SAL_CALL storeToMedium(const ::rtl::OUString & URL,
        const css::uno::Sequence< css::beans::PropertyValue > & Medium)
        throw (css::uno::RuntimeException,
               css::lang::WrappedTargetException, css::io::IOException);

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

    // ::com::sun::star::util::XCloneable:
    virtual css::uno::Reference<css::util::XCloneable> SAL_CALL createClone()
        throw (css::uno::RuntimeException);

    // ::com::sun::star::util::XModifiable:
    virtual ::sal_Bool SAL_CALL isModified(  )
        throw (css::uno::RuntimeException);
    virtual void SAL_CALL setModified( ::sal_Bool bModified )
        throw (css::beans::PropertyVetoException, css::uno::RuntimeException);

    // ::com::sun::star::util::XModifyBroadcaster:
    virtual void SAL_CALL addModifyListener(
        const css::uno::Reference< css::util::XModifyListener > & xListener)
        throw (css::uno::RuntimeException);
    virtual void SAL_CALL removeModifyListener(
        const css::uno::Reference< css::util::XModifyListener > & xListener)
        throw (css::uno::RuntimeException);

    // ::com::sun::star::xml::sax::XSAXSerializable
    virtual void SAL_CALL serialize(
        const css::uno::Reference<css::xml::sax::XDocumentHandler>& i_xHandler,
        const css::uno::Sequence< css::beans::StringPair >& i_rNamespaces)
        throw (css::uno::RuntimeException, css::xml::sax::SAXException);

protected:
    SfxDocumentMetaData(SfxDocumentMetaData &); // not defined
    SfxDocumentMetaData& operator =(SfxDocumentMetaData &); // not defined

    virtual ~SfxDocumentMetaData() {}
    virtual SfxDocumentMetaData* createMe( css::uno::Reference< css::uno::XComponentContext > const & context ) { return new SfxDocumentMetaData( context ); };
    const css::uno::Reference< css::uno::XComponentContext > m_xContext;

    /// for notification
    ::cppu::OInterfaceContainerHelper m_NotifyListeners;
    /// flag: false means not initialized yet, or disposed
    bool m_isInitialized;
    /// flag
    bool m_isModified;
    /// meta-data DOM tree
    css::uno::Reference< css::xml::dom::XDocument > m_xDoc;
    /// meta-data super node in the meta-data DOM tree
    css::uno::Reference< css::xml::dom::XNode> m_xParent;
    /// standard meta data (single occurrence)
    std::map< ::rtl::OUString, css::uno::Reference<css::xml::dom::XNode> >
        m_meta;
    /// standard meta data (multiple occurrences)
    std::map< ::rtl::OUString,
        std::vector<css::uno::Reference<css::xml::dom::XNode> > > m_metaList;
    /// user-defined meta data (meta:user-defined) @ATTENTION may be null!
    css::uno::Reference<css::beans::XPropertyContainer> m_xUserDefined;
    // now for some meta-data attributes; these are not updated directly in the
    // DOM because updates (detecting "empty" elements) would be quite messy
    ::rtl::OUString m_TemplateName;
    ::rtl::OUString m_TemplateURL;
    css::util::DateTime m_TemplateDate;
    ::rtl::OUString m_AutoloadURL;
    sal_Int32 m_AutoloadSecs;
    ::rtl::OUString m_DefaultTarget;

    /// check if we are initialized properly
    void SAL_CALL checkInit() const;
    /// initialize state from given DOM tree
    void SAL_CALL init(css::uno::Reference<css::xml::dom::XDocument> i_xDom);
    /// update element in DOM tree
    void SAL_CALL updateElement(const char *i_name,
        std::vector<std::pair<const char *, ::rtl::OUString> >* i_pAttrs = 0);
    /// update user-defined meta data and attributes in DOM tree
    void SAL_CALL updateUserDefinedAndAttributes();
    /// create empty DOM tree (XDocument)
    css::uno::Reference<css::xml::dom::XDocument> SAL_CALL createDOM() const;
    /// extract base URL (necessary for converting relative links)
    css::uno::Reference<css::beans::XPropertySet> SAL_CALL getURLProperties(
        const css::uno::Sequence<css::beans::PropertyValue> & i_rMedium) const;
    /// get text of standard meta data element
    ::rtl::OUString SAL_CALL getMetaText(const char* i_name) const;
    /// set text of standard meta data element iff not equal to existing text
    bool SAL_CALL setMetaText(const char* i_name,
        const ::rtl::OUString & i_rValue);
    /// set text of standard meta data element iff not equal to existing text
    void SAL_CALL setMetaTextAndNotify(const char* i_name,
        const ::rtl::OUString & i_rValue);
    /// get text of standard meta data element's attribute
    ::rtl::OUString SAL_CALL getMetaAttr(const char* i_name,
        const char* i_attr) const;
    /// get text of a list of standard meta data elements (multiple occ.)
    css::uno::Sequence< ::rtl::OUString > SAL_CALL getMetaList(
        const char* i_name) const;
    /// set text of a list of standard meta data elements (multiple occ.)
    bool SAL_CALL setMetaList(const char* i_name,
        const css::uno::Sequence< ::rtl::OUString > & i_rValue,
        AttrVector const* = 0);
    void createUserDefined();
};

typedef ::cppu::ImplInheritanceHelper1< SfxDocumentMetaData, css::document::XCompatWriterDocProperties > CompatWriterDocPropsImpl_BASE;

class CompatWriterDocPropsImpl : public CompatWriterDocPropsImpl_BASE
{
    rtl::OUString msManager;
    rtl::OUString msCategory;
    rtl::OUString msCompany;
protected:
    virtual SfxDocumentMetaData* createMe( css::uno::Reference< css::uno::XComponentContext > const & context ) { return new CompatWriterDocPropsImpl( context ); };
public:
    CompatWriterDocPropsImpl( css::uno::Reference< css::uno::XComponentContext > const & context) : CompatWriterDocPropsImpl_BASE( context ) {}
// XCompatWriterDocPropsImpl
    virtual ::rtl::OUString SAL_CALL getManager() throw (::com::sun::star::uno::RuntimeException) { return msManager; }
    virtual void SAL_CALL setManager( const ::rtl::OUString& _manager ) throw (::com::sun::star::uno::RuntimeException) { msManager = _manager; }
    virtual ::rtl::OUString SAL_CALL getCategory() throw (::com::sun::star::uno::RuntimeException){ return msCategory; }
    virtual void SAL_CALL setCategory( const ::rtl::OUString& _category ) throw (::com::sun::star::uno::RuntimeException){ msCategory = _category; }
    virtual ::rtl::OUString SAL_CALL getCompany() throw (::com::sun::star::uno::RuntimeException){ return msCompany; }
    virtual void SAL_CALL setCompany( const ::rtl::OUString& _company ) throw (::com::sun::star::uno::RuntimeException){ msCompany = _company; }

// XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException)
    {
        return comp_CompatWriterDocProps::_getImplementationName();
    }

    virtual ::sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException)
    {
        css::uno::Sequence< rtl::OUString > sServiceNames= getSupportedServiceNames();
        sal_Int32 nLen = sServiceNames.getLength();
        rtl::OUString* pIt = sServiceNames.getArray();
        rtl::OUString* pEnd = ( pIt + nLen );
        sal_Bool bRes = sal_False;
        for ( ; pIt != pEnd; ++pIt )
        {
            if ( pIt->equals( ServiceName ) )
            {
                bRes = sal_True;
                break;
            }
        }
        return bRes;
    }

    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw (::com::sun::star::uno::RuntimeException)
    {
        return comp_CompatWriterDocProps::_getSupportedServiceNames();
    }
};

bool operator== (const css::util::DateTime &i_rLeft,
                 const css::util::DateTime &i_rRight)
{
    return i_rLeft.Year             == i_rRight.Year
        && i_rLeft.Month            == i_rRight.Month
        && i_rLeft.Day              == i_rRight.Day
        && i_rLeft.Hours            == i_rRight.Hours
        && i_rLeft.Minutes          == i_rRight.Minutes
        && i_rLeft.Seconds          == i_rRight.Seconds
        && i_rLeft.HundredthSeconds == i_rRight.HundredthSeconds;
}

// NB: keep these two arrays in sync!
const char* s_stdStatAttrs[] = {
    "meta:page-count",
    "meta:table-count",
    "meta:draw-count",
    "meta:image-count",
    "meta:object-count",
    "meta:ole-object-count",
    "meta:paragraph-count",
    "meta:word-count",
    "meta:character-count",
    "meta:row-count",
    "meta:frame-count",
    "meta:sentence-count",
    "meta:syllable-count",
    "meta:non-whitespace-character-count",
    "meta:cell-count",
    0
};

// NB: keep these two arrays in sync!
const char* s_stdStats[] = {
    "PageCount",
    "TableCount",
    "DrawCount",
    "ImageCount",
    "ObjectCount",
    "OLEObjectCount",
    "ParagraphCount",
    "WordCount",
    "CharacterCount",
    "RowCount",
    "FrameCount",
    "SentenceCount",
    "SyllableCount",
    "NonWhitespaceCharacterCount",
    "CellCount",
    0
};

const char* s_stdMeta[] = {
    "meta:generator",           // string
    "dc:title",                 // string
    "dc:description",           // string
    "dc:subject",               // string
    "meta:initial-creator",     // string
    "dc:creator",               // string
    "meta:printed-by",          // string
    "meta:creation-date",       // dateTime
    "dc:date",                  // dateTime
    "meta:print-date",          // dateTime
    "meta:template",            // XLink
    "meta:auto-reload",         // ...
    "meta:hyperlink-behaviour", // ...
    "dc:language",              // language
    "meta:editing-cycles",      // nonNegativeInteger
    "meta:editing-duration",    // duration
    "meta:document-statistic",  // ... // note: statistic is singular, no s!
    0
};

const char* s_stdMetaList[] = {
    "meta:keyword",             // string*
    "meta:user-defined",        // ...*
    0
};

const char* s_nsXLink   = "http://www.w3.org/1999/xlink";
const char* s_nsDC      = "http://purl.org/dc/elements/1.1/";
const char* s_nsODF     = "urn:oasis:names:tc:opendocument:xmlns:office:1.0";
const char* s_nsODFMeta = "urn:oasis:names:tc:opendocument:xmlns:meta:1.0";
// const char* s_nsOOo     = "http://openoffice.org/2004/office"; // not used (yet?)

static const char s_meta    [] = "meta.xml";

bool isValidDate(const css::util::Date & i_rDate)
{
    return i_rDate.Month > 0;
}

bool isValidDateTime(const css::util::DateTime & i_rDateTime)
{
    return i_rDateTime.Month > 0;
}

std::pair< ::rtl::OUString, ::rtl::OUString > SAL_CALL
getQualifier(const char* i_name) {
    ::rtl::OUString nm = ::rtl::OUString::createFromAscii(i_name);
    sal_Int32 ix = nm.indexOf(static_cast<sal_Unicode> (':'));
    if (ix == -1) {
        return std::make_pair(::rtl::OUString(), nm);
    } else {
        return std::make_pair(nm.copy(0,ix), nm.copy(ix+1));
    }
}

// get namespace for standard qualified names
// NB: only call this with statically known strings!
::rtl::OUString SAL_CALL getNameSpace(const char* i_qname) throw ()
{
    DBG_ASSERT(i_qname, "SfxDocumentMetaData: getNameSpace: argument is null");
    const char * ns = "";
    ::rtl::OUString n = getQualifier(i_qname).first;
    if ( n == "xlink" ) ns = s_nsXLink;
    if ( n == "dc" ) ns = s_nsDC;
    if ( n == "office" ) ns = s_nsODF;
    if ( n == "meta" ) ns = s_nsODFMeta;
    DBG_ASSERT(*ns, "SfxDocumentMetaData: unknown namespace prefix");
    return ::rtl::OUString::createFromAscii(ns);
}

bool SAL_CALL
textToDateOrDateTime(css::util::Date & io_rd, css::util::DateTime & io_rdt,
        bool & o_rIsDateTime, ::rtl::OUString i_text) throw ()
{
    if (::sax::Converter::convertDateOrDateTime(
                io_rd, io_rdt, o_rIsDateTime, i_text)) {
        return true;
    } else {
        DBG_WARNING1("SfxDocumentMetaData: invalid date: %s",
            OUStringToOString(i_text, RTL_TEXTENCODING_UTF8).getStr());
        return false;
    }
}

// convert string to date/time
bool SAL_CALL
textToDateTime(css::util::DateTime & io_rdt, ::rtl::OUString i_text) throw ()
{
    if (::sax::Converter::convertDateTime(io_rdt, i_text)) {
        return true;
    } else {
        DBG_WARNING1("SfxDocumentMetaData: invalid date: %s",
            OUStringToOString(i_text, RTL_TEXTENCODING_UTF8).getStr());
        return false;
    }
}

// convert string to date/time with default return value
css::util::DateTime SAL_CALL
textToDateTimeDefault(::rtl::OUString i_text) throw ()
{
    css::util::DateTime dt;
    static_cast<void> (textToDateTime(dt, i_text));
    // on conversion error: return default value (unchanged)
    return dt;
}

// convert date to string
::rtl::OUString SAL_CALL
dateToText(css::util::Date const& i_rd) throw ()
{
    if (isValidDate(i_rd)) {
        ::rtl::OUStringBuffer buf;
        ::sax::Converter::convertDate(buf, i_rd);
        return buf.makeStringAndClear();
    } else {
        return ::rtl::OUString();
    }
}


// convert date/time to string
::rtl::OUString SAL_CALL
dateTimeToText(css::util::DateTime const& i_rdt) throw ()
{
    if (isValidDateTime(i_rdt)) {
        ::rtl::OUStringBuffer buf;
        ::sax::Converter::convertDateTime(buf, i_rdt, true);
        return buf.makeStringAndClear();
    } else {
        return ::rtl::OUString();
    }
}

// convert string to duration
bool
textToDuration(css::util::Duration& io_rDur, ::rtl::OUString const& i_rText)
throw ()
{
    if (::sax::Converter::convertDuration(io_rDur, i_rText)) {
        return true;
    } else {
        DBG_WARNING1("SfxDocumentMetaData: invalid duration: %s",
            OUStringToOString(i_rText, RTL_TEXTENCODING_UTF8).getStr());
        return false;
    }
}

sal_Int32 textToDuration(::rtl::OUString const& i_rText) throw ()
{
    css::util::Duration d;
    if (textToDuration(d, i_rText)) {
        // #i107372#: approximate years/months
        const sal_Int32 days( (d.Years * 365) + (d.Months * 30) + d.Days );
        return  (days * (24*3600))
                + (d.Hours * 3600) + (d.Minutes * 60) + d.Seconds;
    } else {
        return 0; // default
    }
}

// convert duration to string
::rtl::OUString durationToText(css::util::Duration const& i_rDur) throw ()
{
    ::rtl::OUStringBuffer buf;
    ::sax::Converter::convertDuration(buf, i_rDur);
    return buf.makeStringAndClear();
}

// convert duration to string
::rtl::OUString SAL_CALL durationToText(sal_Int32 i_value) throw ()
{
    css::util::Duration ud;
    ud.Days    = static_cast<sal_Int16>(i_value / (24 * 3600));
    ud.Hours   = static_cast<sal_Int16>((i_value % (24 * 3600)) / 3600);
    ud.Minutes = static_cast<sal_Int16>((i_value % 3600) / 60);
    ud.Seconds = static_cast<sal_Int16>(i_value % 60);
    ud.MilliSeconds = 0;
    return durationToText(ud);
}

// extract base URL (necessary for converting relative links)
css::uno::Reference< css::beans::XPropertySet > SAL_CALL
SfxDocumentMetaData::getURLProperties(
    const css::uno::Sequence< css::beans::PropertyValue > & i_rMedium) const
{
    css::uno::Reference<css::lang::XMultiComponentFactory> xMsf (
        m_xContext->getServiceManager());
    css::uno::Reference< css::beans::XPropertyContainer> xPropArg(
        xMsf->createInstanceWithContext(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                "com.sun.star.beans.PropertyBag")), m_xContext),
        css::uno::UNO_QUERY_THROW);
    try {
        ::rtl::OUString dburl =
            ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("DocumentBaseURL"));
        ::rtl::OUString hdn =
            ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("HierarchicalDocumentName"));
        for (sal_Int32 i = 0; i < i_rMedium.getLength(); ++i) {
            if (i_rMedium[i].Name.equals(dburl)) {
                xPropArg->addProperty(
                    ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("BaseURI")),
                    css::beans::PropertyAttribute::MAYBEVOID,
                    i_rMedium[i].Value);
            } else if (i_rMedium[i].Name.equals(hdn)) {
                xPropArg->addProperty(
                    ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("StreamRelPath")),
                    css::beans::PropertyAttribute::MAYBEVOID,
                    i_rMedium[i].Value);
            }
        }
        xPropArg->addProperty(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("StreamName")),
                css::beans::PropertyAttribute::MAYBEVOID,
                css::uno::makeAny(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(s_meta))));
    } catch (const css::uno::Exception &) {
        // ignore
    }
    return css::uno::Reference< css::beans::XPropertySet>(xPropArg,
                css::uno::UNO_QUERY_THROW);
}

// return the text of the (hopefully unique, i.e., normalize first!) text
// node _below_ the given node
::rtl::OUString SAL_CALL
getNodeText(css::uno::Reference<css::xml::dom::XNode> i_xNode)
        throw (css::uno::RuntimeException)
{
    if (!i_xNode.is()) throw css::uno::RuntimeException(
        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                "SfxDocumentMetaData::getNodeText: argument is null")), i_xNode);
    for (css::uno::Reference<css::xml::dom::XNode> c = i_xNode->getFirstChild();
            c.is();
            c = c->getNextSibling()) {
        if (c->getNodeType() == css::xml::dom::NodeType_TEXT_NODE) {
            try {
                return c->getNodeValue();
            } catch (const css::xml::dom::DOMException &) { // too big?
                return ::rtl::OUString();
            }
        }
    }
    return ::rtl::OUString();
}

::rtl::OUString SAL_CALL
SfxDocumentMetaData::getMetaText(const char* i_name) const
//        throw (css::uno::RuntimeException)
{
    checkInit();

    const ::rtl::OUString name( ::rtl::OUString::createFromAscii(i_name) );
    DBG_ASSERT(m_meta.find(name) != m_meta.end(),
        "SfxDocumentMetaData::getMetaText: not found");
    css::uno::Reference<css::xml::dom::XNode> xNode = m_meta.find(name)->second;
    return (xNode.is()) ? getNodeText(xNode) : ::rtl::OUString();
}

bool SAL_CALL
SfxDocumentMetaData::setMetaText(const char* i_name,
        const ::rtl::OUString & i_rValue)
    // throw (css::uno::RuntimeException)
{
    checkInit();

    const ::rtl::OUString name( ::rtl::OUString::createFromAscii(i_name) );
    DBG_ASSERT(m_meta.find(name) != m_meta.end(),
        "SfxDocumentMetaData::setMetaText: not found");
    css::uno::Reference<css::xml::dom::XNode> xNode = m_meta.find(name)->second;

    try {
        if (i_rValue.isEmpty()) {
            if (xNode.is()) { // delete
                m_xParent->removeChild(xNode);
                xNode.clear();
                m_meta[name] = xNode;
                return true;
            } else {
                return false;
            }
        } else {
            if (xNode.is()) { // update
                for (css::uno::Reference<css::xml::dom::XNode> c =
                            xNode->getFirstChild();
                        c.is();
                        c = c->getNextSibling()) {
                    if (c->getNodeType() == css::xml::dom::NodeType_TEXT_NODE) {
                        if (!c->getNodeValue().equals(i_rValue)) {
                            c->setNodeValue(i_rValue);
                            return true;
                        } else {
                            return false;
                        }
                    }
                }
            } else { // insert
                xNode.set(m_xDoc->createElementNS(getNameSpace(i_name), name),
                            css::uno::UNO_QUERY_THROW);
                m_xParent->appendChild(xNode);
                m_meta[name] = xNode;
            }
            css::uno::Reference<css::xml::dom::XNode> xTextNode(
                m_xDoc->createTextNode(i_rValue), css::uno::UNO_QUERY_THROW);
            xNode->appendChild(xTextNode);
            return true;
        }
    } catch (const css::xml::dom::DOMException & e) {
        css::uno::Any a(e);
        throw css::lang::WrappedTargetRuntimeException(
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                        "SfxDocumentMetaData::setMetaText: DOM exception")),
                css::uno::Reference<css::uno::XInterface>(*this), a);
    }
}

void SAL_CALL
SfxDocumentMetaData::setMetaTextAndNotify(const char* i_name,
        const ::rtl::OUString & i_rValue)
    // throw (css::uno::RuntimeException)
{
    ::osl::ClearableMutexGuard g(m_aMutex);
    if (setMetaText(i_name, i_rValue)) {
        g.clear();
        setModified(true);
    }
}

::rtl::OUString SAL_CALL
SfxDocumentMetaData::getMetaAttr(const char* i_name, const char* i_attr) const
//        throw (css::uno::RuntimeException)
{
    ::rtl::OUString name = ::rtl::OUString::createFromAscii(i_name);
    DBG_ASSERT(m_meta.find(name) != m_meta.end(),
        "SfxDocumentMetaData::getMetaAttr: not found");
    css::uno::Reference<css::xml::dom::XNode> xNode = m_meta.find(name)->second;
    if (xNode.is()) {
        css::uno::Reference<css::xml::dom::XElement> xElem(xNode,
            css::uno::UNO_QUERY_THROW);
        return xElem->getAttributeNS(getNameSpace(i_attr),
                    getQualifier(i_attr).second);
    } else {
        return ::rtl::OUString();
    }
}

css::uno::Sequence< ::rtl::OUString> SAL_CALL
SfxDocumentMetaData::getMetaList(const char* i_name) const
//        throw (css::uno::RuntimeException)
{
    checkInit();
    ::rtl::OUString name = ::rtl::OUString::createFromAscii(i_name);
    DBG_ASSERT(m_metaList.find(name) != m_metaList.end(),
        "SfxDocumentMetaData::getMetaList: not found");
    std::vector<css::uno::Reference<css::xml::dom::XNode> > const & vec =
        m_metaList.find(name)->second;
    css::uno::Sequence< ::rtl::OUString> ret(vec.size());
    for (size_t i = 0; i < vec.size(); ++i) {
        ret[i] = getNodeText(vec.at(i));
    }
    return ret;
}

bool SAL_CALL
SfxDocumentMetaData::setMetaList(const char* i_name,
        const css::uno::Sequence< ::rtl::OUString> & i_rValue,
        AttrVector const* i_pAttrs)
    // throw (css::uno::RuntimeException)
{
    checkInit();
    DBG_ASSERT((i_pAttrs == 0) ||
               (static_cast<size_t>(i_rValue.getLength()) == i_pAttrs->size()),
        "SfxDocumentMetaData::setMetaList: invalid args");

    try {
        ::rtl::OUString name = ::rtl::OUString::createFromAscii(i_name);
        DBG_ASSERT(m_metaList.find(name) != m_metaList.end(),
            "SfxDocumentMetaData::setMetaList: not found");
        std::vector<css::uno::Reference<css::xml::dom::XNode> > & vec =
            m_metaList[name];

        // if nothing changed, do nothing
        // alas, this does not check for permutations, or attributes...
        if ((0 == i_pAttrs)) {
            if (static_cast<size_t>(i_rValue.getLength()) == vec.size()) {
                bool isEqual(true);
                for (sal_Int32 i = 0; i < i_rValue.getLength(); ++i) {
                    css::uno::Reference<css::xml::dom::XNode> xNode(vec.at(i));
                    if (xNode.is()) {
                        ::rtl::OUString val = getNodeText(xNode);
                        if (!val.equals(i_rValue[i])) {
                            isEqual = false;
                            break;
                        }
                    }
                }
                if (isEqual) return false;
            }
        }

        // remove old meta data nodes
        {
            std::vector<css::uno::Reference<css::xml::dom::XNode> >
                ::reverse_iterator it(vec.rbegin());
            try {
                for ( ;it != vec.rend(); ++it)
                {
                    m_xParent->removeChild(*it);
                }
            }
            catch (...)
            {
                // Clean up already removed nodes
                vec.erase(it.base(), vec.end());
                throw;
            }
            vec.clear();
        }

        // insert new meta data nodes into DOM tree
        for (sal_Int32 i = 0; i < i_rValue.getLength(); ++i) {
            css::uno::Reference<css::xml::dom::XElement> xElem(
                m_xDoc->createElementNS(getNameSpace(i_name), name),
                css::uno::UNO_QUERY_THROW);
            css::uno::Reference<css::xml::dom::XNode> xNode(xElem,
                css::uno::UNO_QUERY_THROW);
            css::uno::Reference<css::xml::dom::XNode> xTextNode(
                m_xDoc->createTextNode(i_rValue[i]), css::uno::UNO_QUERY_THROW);
            // set attributes
            if (i_pAttrs != 0) {
                for (std::vector<std::pair<const char*, ::rtl::OUString> >
                                ::const_iterator it = (*i_pAttrs)[i].begin();
                        it != (*i_pAttrs)[i].end(); ++it) {
                    xElem->setAttributeNS(getNameSpace(it->first),
                        ::rtl::OUString::createFromAscii(it->first),
                        it->second);
                }
            }
            xNode->appendChild(xTextNode);
            m_xParent->appendChild(xNode);
            vec.push_back(xNode);
        }

        return true;
    } catch (const css::xml::dom::DOMException & e) {
        css::uno::Any a(e);
        throw css::lang::WrappedTargetRuntimeException(
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                        "SfxDocumentMetaData::setMetaList: DOM exception")),
                css::uno::Reference<css::uno::XInterface>(*this), a);
    }
}

// convert property list to string list and attribute list
std::pair<css::uno::Sequence< ::rtl::OUString>, AttrVector> SAL_CALL
propsToStrings(css::uno::Reference<css::beans::XPropertySet> const & i_xPropSet)
{
    ::comphelper::SequenceAsVector< ::rtl::OUString > values;
    AttrVector attrs;

    css::uno::Reference<css::beans::XPropertySetInfo> xSetInfo
        = i_xPropSet->getPropertySetInfo();
    css::uno::Sequence<css::beans::Property> props = xSetInfo->getProperties();

    for (sal_Int32 i = 0; i < props.getLength(); ++i) {
        if (props[i].Attributes & css::beans::PropertyAttribute::TRANSIENT) {
            continue;
        }
        const ::rtl::OUString name = props[i].Name;
        css::uno::Any any;
        try {
            any = i_xPropSet->getPropertyValue(name);
        } catch (const css::uno::Exception &) {
            // ignore
        }
        const css::uno::Type & type = any.getValueType();
        std::vector<std::pair<const char*, ::rtl::OUString> > as;
        as.push_back(std::make_pair(static_cast<const char*>("meta:name"),
                                        name));
        const char* vt = "meta:value-type";

        // convert according to type
        if (type == ::cppu::UnoType<bool>::get()) {
            bool b = false;
            any >>= b;
            ::rtl::OUStringBuffer buf;
            ::sax::Converter::convertBool(buf, b);
            values.push_back(buf.makeStringAndClear());
            as.push_back(std::make_pair(vt,
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("boolean"))));
        } else if (type == ::cppu::UnoType< ::rtl::OUString>::get()) {
            ::rtl::OUString s;
            any >>= s;
            values.push_back(s);
// #i90847# OOo 2.x does stupid things if value-type="string";
// fortunately string is default anyway, so we can just omit it
// #i107502#: however, OOo 2.x only reads 4 user-defined without @value-type
// => best backward compatibility: first 4 without @value-type, rest with
            if (4 <= i)
            {
                as.push_back(std::make_pair(vt,
                    ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("string"))));
            }
        } else if (type == ::cppu::UnoType<css::util::DateTime>::get()) {
            css::util::DateTime dt;
            any >>= dt;
            values.push_back(dateTimeToText(dt));
            as.push_back(std::make_pair(vt,
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("date"))));
        } else if (type == ::cppu::UnoType<css::util::Date>::get()) {
            css::util::Date d;
            any >>= d;
            values.push_back(dateToText(d));
            as.push_back(std::make_pair(vt,
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("date"))));
        } else if (type == ::cppu::UnoType<css::util::Time>::get()) {
            // #i97029#: replaced by Duration
            // Time is supported for backward compatibility with OOo 3.x, x<=2
            css::util::Time ut;
            any >>= ut;
            css::util::Duration ud;
            ud.Hours   = ut.Hours;
            ud.Minutes = ut.Minutes;
            ud.Seconds = ut.Seconds;
            ud.MilliSeconds = 10 * ut.HundredthSeconds;
            values.push_back(durationToText(ud));
            as.push_back(std::make_pair(vt,
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("time"))));
        } else if (type == ::cppu::UnoType<css::util::Duration>::get()) {
            css::util::Duration ud;
            any >>= ud;
            values.push_back(durationToText(ud));
            as.push_back(std::make_pair(vt,
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("time"))));
        } else if (::cppu::UnoType<double>::get().isAssignableFrom(type)) {
            // support not just double, but anything that can be converted
            double d = 0;
            any >>= d;
            ::rtl::OUStringBuffer buf;
            ::sax::Converter::convertDouble(buf, d);
            values.push_back(buf.makeStringAndClear());
            as.push_back(std::make_pair(vt,
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("float"))));
        } else {
            DBG_WARNING1("SfxDocumentMetaData: unsupported property type: %s",
                OUStringToOString(any.getValueTypeName(),
                    RTL_TEXTENCODING_UTF8).getStr());
            continue;
        }
        attrs.push_back(as);
    }

    return std::make_pair(values.getAsConstList(), attrs);
}

// remove the given element from the DOM, and iff i_pAttrs != 0 insert new one
void SAL_CALL
SfxDocumentMetaData::updateElement(const char *i_name,
        std::vector<std::pair<const char *, ::rtl::OUString> >* i_pAttrs)
{
    ::rtl::OUString name = ::rtl::OUString::createFromAscii(i_name);
    try {
        // remove old element
        css::uno::Reference<css::xml::dom::XNode> xNode =
            m_meta.find(name)->second;
        if (xNode.is()) {
            m_xParent->removeChild(xNode);
            xNode.clear();
        }
        // add new element
        if (0 != i_pAttrs) {
            css::uno::Reference<css::xml::dom::XElement> xElem(
                m_xDoc->createElementNS(getNameSpace(i_name), name),
                    css::uno::UNO_QUERY_THROW);
            xNode.set(xElem, css::uno::UNO_QUERY_THROW);
            // set attributes
            for (std::vector<std::pair<const char *, ::rtl::OUString> >
                    ::const_iterator it = i_pAttrs->begin();
                    it != i_pAttrs->end(); ++it) {
                xElem->setAttributeNS(getNameSpace(it->first),
                    ::rtl::OUString::createFromAscii(it->first), it->second);
            }
            m_xParent->appendChild(xNode);
        }
        m_meta[name] = xNode;
    } catch (const css::xml::dom::DOMException & e) {
        css::uno::Any a(e);
        throw css::lang::WrappedTargetRuntimeException(
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                    "SfxDocumentMetaData::updateElement: DOM exception")),
                css::uno::Reference<css::uno::XInterface>(*this), a);
    }
}

// update user-defined meta data in DOM tree
void SAL_CALL SfxDocumentMetaData::updateUserDefinedAndAttributes()
{
    createUserDefined();
    const css::uno::Reference<css::beans::XPropertySet> xPSet(m_xUserDefined,
            css::uno::UNO_QUERY_THROW);
    const std::pair<css::uno::Sequence< ::rtl::OUString>, AttrVector>
        udStringsAttrs( propsToStrings(xPSet) );
    (void) setMetaList("meta:user-defined", udStringsAttrs.first,
            &udStringsAttrs.second);

    // update elements with attributes
    std::vector<std::pair<const char *, ::rtl::OUString> > attributes;
    if (!m_TemplateName.isEmpty() || !m_TemplateURL.isEmpty()
            || isValidDateTime(m_TemplateDate)) {
        attributes.push_back(std::make_pair(
                static_cast<const char*>("xlink:type"),
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("simple"))));
        attributes.push_back(std::make_pair(
                static_cast<const char*>("xlink:actuate"),
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("onRequest"))));
        attributes.push_back(std::make_pair(
                static_cast<const char*>("xlink:title"), m_TemplateName));
        attributes.push_back(std::make_pair(
                static_cast<const char*>("xlink:href" ), m_TemplateURL ));
        if (isValidDateTime(m_TemplateDate)) {
            attributes.push_back(std::make_pair(
                static_cast<const char*>("meta:date"  ),
                dateTimeToText(m_TemplateDate)));
        }
        updateElement("meta:template", &attributes);
    } else {
        updateElement("meta:template");
    }
    attributes.clear();

    if (!m_AutoloadURL.isEmpty() || (0 != m_AutoloadSecs)) {
        attributes.push_back(std::make_pair(
                static_cast<const char*>("xlink:href" ), m_AutoloadURL ));
        attributes.push_back(std::make_pair(
                static_cast<const char*>("meta:delay" ),
                durationToText(m_AutoloadSecs)));
        updateElement("meta:auto-reload", &attributes);
    } else {
        updateElement("meta:auto-reload");
    }
    attributes.clear();

    if (!m_DefaultTarget.isEmpty()) {
        attributes.push_back(std::make_pair(
                static_cast<const char*>("office:target-frame-name"),
                m_DefaultTarget));
        // xlink:show: _blank -> new, any other value -> replace
        const sal_Char* show = m_DefaultTarget == "_blank" ? "new" : "replace";
        attributes.push_back(std::make_pair(
                static_cast<const char*>("xlink:show"),
                ::rtl::OUString::createFromAscii(show)));
        updateElement("meta:hyperlink-behaviour", &attributes);
    } else {
        updateElement("meta:hyperlink-behaviour");
    }
    attributes.clear();
}

// create empty DOM tree (XDocument)
css::uno::Reference<css::xml::dom::XDocument> SAL_CALL
SfxDocumentMetaData::createDOM() const // throw (css::uno::RuntimeException)
{
    css::uno::Reference<css::lang::XMultiComponentFactory> xMsf (
        m_xContext->getServiceManager());
    css::uno::Reference<css::xml::dom::XDocumentBuilder> xBuilder(
        xMsf->createInstanceWithContext(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                "com.sun.star.xml.dom.DocumentBuilder")), m_xContext),
        css::uno::UNO_QUERY_THROW );
    if (!xBuilder.is()) throw css::uno::RuntimeException(
        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SfxDocumentMetaData::createDOM: "
                "cannot create DocumentBuilder service")),
                *const_cast<SfxDocumentMetaData*>(this));
    css::uno::Reference<css::xml::dom::XDocument> xDoc =
                xBuilder->newDocument();
    if (!xDoc.is()) throw css::uno::RuntimeException(
        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SfxDocumentMetaData::createDOM: "
                "cannot create new document")),
                *const_cast<SfxDocumentMetaData*>(this));
    return xDoc;
}

void SAL_CALL
SfxDocumentMetaData::checkInit() const // throw (css::uno::RuntimeException)
{
    if (!m_isInitialized) {
        throw css::uno::RuntimeException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                "SfxDocumentMetaData::checkInit: not initialized")),
                *const_cast<SfxDocumentMetaData*>(this));
    }
    DBG_ASSERT((m_xDoc.is() && m_xParent.is() ),
                "SfxDocumentMetaData::checkInit: reference is null");
}

// initialize state from DOM tree
void SAL_CALL SfxDocumentMetaData::init(
        css::uno::Reference<css::xml::dom::XDocument> i_xDoc)
{
    if (!i_xDoc.is()) throw css::uno::RuntimeException(
        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                "SfxDocumentMetaData::init: no DOM tree given")), *this);

    css::uno::Reference<css::lang::XMultiComponentFactory> xMsf (
        m_xContext->getServiceManager());
    css::uno::Reference<css::xml::xpath::XXPathAPI> xPath(
        xMsf->createInstanceWithContext(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                "com.sun.star.xml.xpath.XPathAPI")), m_xContext),
        css::uno::UNO_QUERY_THROW );
    if (!xPath.is()) throw css::uno::RuntimeException(
        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SfxDocumentMetaData::init:"
                " cannot create XPathAPI service")), *this);

    m_isInitialized = false;
    m_xDoc = i_xDoc;

    // select nodes for standard meta data stuff
    xPath->registerNS(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("xlink")),
        ::rtl::OUString::createFromAscii(s_nsXLink));
    xPath->registerNS(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("dc")),
        ::rtl::OUString::createFromAscii(s_nsDC));
    xPath->registerNS(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("office")),
        ::rtl::OUString::createFromAscii(s_nsODF));
    xPath->registerNS(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("meta")),
        ::rtl::OUString::createFromAscii(s_nsODFMeta));
    // NB: we do not handle the single-XML-file ODF variant, which would
    //     have the root element office:document.
    //     The root of such documents must be converted in the importer!
    ::rtl::OUString prefix(RTL_CONSTASCII_USTRINGPARAM(
        "/child::office:document-meta/child::office:meta"));
    css::uno::Reference<css::xml::dom::XNode> xDocNode(
        m_xDoc, css::uno::UNO_QUERY_THROW);
    m_xParent.clear();
    try {
        m_xParent = xPath->selectSingleNode(xDocNode, prefix);
    } catch (const com::sun::star::uno::Exception &) {
    }

    if (!m_xParent.is()) {
        // all this create/append stuff may throw DOMException
        try {
            css::uno::Reference<css::xml::dom::XElement> xRElem;
            css::uno::Reference<css::xml::dom::XNode> xNode(
                i_xDoc->getFirstChild());
            while (xNode.is()) {
                if (css::xml::dom::NodeType_ELEMENT_NODE ==xNode->getNodeType())
                {
                    if ( xNode->getNamespaceURI().equalsAscii(s_nsODF) && xNode->getLocalName() == "document-meta" )
                    {
                        xRElem.set(xNode, css::uno::UNO_QUERY_THROW);
                        break;
                    }
                    else
                    {
                        OSL_TRACE("SfxDocumentMetaData::init(): "
                                "deleting unexpected root element: %s",
                            ::rtl::OUStringToOString(xNode->getLocalName(),
                                RTL_TEXTENCODING_UTF8).getStr());
                        i_xDoc->removeChild(xNode);
                        xNode = i_xDoc->getFirstChild(); // start over
                    }
                } else {
                    xNode = xNode->getNextSibling();
                }
            }
            if (!xRElem.is()) {
                xRElem = i_xDoc->createElementNS(
                    ::rtl::OUString::createFromAscii(s_nsODF),
                    ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("office:document-meta")));
                css::uno::Reference<css::xml::dom::XNode> xRNode(xRElem,
                    css::uno::UNO_QUERY_THROW);
                i_xDoc->appendChild(xRNode);
            }
            xRElem->setAttributeNS(::rtl::OUString::createFromAscii(s_nsODF),
                        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("office:version")),
                        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("1.0")));
            // does not exist, otherwise m_xParent would not be null
            css::uno::Reference<css::xml::dom::XNode> xParent (
                i_xDoc->createElementNS(
                    ::rtl::OUString::createFromAscii(s_nsODF),
                    ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("office:meta"))),
            css::uno::UNO_QUERY_THROW);
            xRElem->appendChild(xParent);
            m_xParent = xParent;
        } catch (const css::xml::dom::DOMException & e) {
            css::uno::Any a(e);
            throw css::lang::WrappedTargetRuntimeException(
                    ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                            "SfxDocumentMetaData::init: DOM exception")),
                    css::uno::Reference<css::uno::XInterface>(*this), a);
        }
    }


    // select nodes for elements of which we only handle one occurrence
    for (const char **pName = s_stdMeta; *pName != 0; ++pName) {
        ::rtl::OUString name = ::rtl::OUString::createFromAscii(*pName);
        // NB: If a document contains more than one occurrence of a
        // meta-data element, we arbitrarily pick one of them here.
        // We do not remove the others, i.e., when we write the
        // document, it will contain the duplicates unchanged.
        // The ODF spec says that handling multiple occurrences is
        // application-specific.
        css::uno::Reference<css::xml::dom::XNode> xNode =
            xPath->selectSingleNode(m_xParent,
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("child::")) + name);
        // Do not create an empty element if it is missing;
        // for certain elements, such as dateTime, this would be invalid
        m_meta[name] = xNode;
    }

    // select nodes for elements of which we handle all occurrences
    for (const char **pName = s_stdMetaList; *pName != 0; ++pName) {
        ::rtl::OUString name = ::rtl::OUString::createFromAscii(*pName);
        css::uno::Reference<css::xml::dom::XNodeList> nodes =
            xPath->selectNodeList(m_xParent,
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("child::")) + name);
        std::vector<css::uno::Reference<css::xml::dom::XNode> > v;
        for (sal_Int32 i = 0; i < nodes->getLength(); ++i) {
            v.push_back(nodes->item(i));
        }
        m_metaList[name] = v;
    }

    // initialize members corresponding to attributes from DOM nodes
    m_TemplateName  = getMetaAttr("meta:template", "xlink:title");
    m_TemplateURL   = getMetaAttr("meta:template", "xlink:href");
    m_TemplateDate  =
        textToDateTimeDefault(getMetaAttr("meta:template", "meta:date"));
    m_AutoloadURL   = getMetaAttr("meta:auto-reload", "xlink:href");
    m_AutoloadSecs  =
        textToDuration(getMetaAttr("meta:auto-reload", "meta:delay"));
    m_DefaultTarget =
        getMetaAttr("meta:hyperlink-behaviour", "office:target-frame-name");


    std::vector<css::uno::Reference<css::xml::dom::XNode> > & vec =
        m_metaList[::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("meta:user-defined"))];
    m_xUserDefined.clear(); // #i105826#: reset (may be re-initialization)
    if ( !vec.empty() )
    {
        createUserDefined();
    }

    // user-defined meta data: initialize PropertySet from DOM nodes
    for (std::vector<css::uno::Reference<css::xml::dom::XNode> >::iterator
            it = vec.begin(); it != vec.end(); ++it) {
        css::uno::Reference<css::xml::dom::XElement> xElem(*it,
            css::uno::UNO_QUERY_THROW);
        css::uno::Any any;
        ::rtl::OUString name = xElem->getAttributeNS(
                ::rtl::OUString::createFromAscii(s_nsODFMeta),
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("name")));
        ::rtl::OUString type = xElem->getAttributeNS(
                ::rtl::OUString::createFromAscii(s_nsODFMeta),
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("value-type")));
        ::rtl::OUString text = getNodeText(*it);
        if ( type == "float" ) {
            double d;
            if (::sax::Converter::convertDouble(d, text)) {
                any <<= d;
            } else {
                DBG_WARNING1("SfxDocumentMetaData: invalid float: %s",
                    OUStringToOString(text, RTL_TEXTENCODING_UTF8).getStr());
                continue;
            }
        } else if ( type == "date" ) {
            bool isDateTime;
            css::util::Date d;
            css::util::DateTime dt;
            if (textToDateOrDateTime(d, dt, isDateTime, text)) {
                if (isDateTime) {
                    any <<= dt;
                } else {
                    any <<= d;
                }
            } else {
                DBG_WARNING1("SfxDocumentMetaData: invalid date: %s",
                    OUStringToOString(text, RTL_TEXTENCODING_UTF8).getStr());
                continue;
            }
        } else if ( type == "time" ) {
            css::util::Duration ud;
            if (textToDuration(ud, text)) {
                any <<= ud;
            } else {
                DBG_WARNING1("SfxDocumentMetaData: invalid time: %s",
                    OUStringToOString(text, RTL_TEXTENCODING_UTF8).getStr());
                continue;
            }
        } else if ( type == "boolean" ) {
            bool b;
            if (::sax::Converter::convertBool(b, text)) {
                any <<= b;
            } else {
                DBG_WARNING1("SfxDocumentMetaData: invalid boolean: %s",
                    OUStringToOString(text, RTL_TEXTENCODING_UTF8).getStr());
                continue;
            }
        } else if ( type == "string" || true) { // default
            any <<= text;
        }
        try {
            m_xUserDefined->addProperty(name,
                css::beans::PropertyAttribute::REMOVEABLE, any);
        } catch (const css::beans::PropertyExistException &) {
            DBG_WARNING1("SfxDocumentMetaData: duplicate: %s",
                    OUStringToOString(name, RTL_TEXTENCODING_UTF8).getStr());
            // ignore; duplicate
        } catch (const css::beans::IllegalTypeException &) {
            OSL_TRACE("SfxDocumentMetaData: illegal type: %s",
                    OUStringToOString(name, RTL_TEXTENCODING_UTF8).getStr());
        } catch (const css::lang::IllegalArgumentException &) {
            OSL_TRACE("SfxDocumentMetaData: illegal arg: %s",
                    OUStringToOString(name, RTL_TEXTENCODING_UTF8).getStr());
        }
    }

    m_isModified = false;
    m_isInitialized = true;
}



SfxDocumentMetaData::SfxDocumentMetaData(
        css::uno::Reference< css::uno::XComponentContext > const & context)
    : BaseMutex()
    , SfxDocumentMetaData_Base(m_aMutex)
    , m_xContext(context)
    , m_NotifyListeners(m_aMutex)
    , m_isInitialized(false)
    , m_isModified(false)
    , m_AutoloadSecs(0)
{
    DBG_ASSERT(context.is(), "SfxDocumentMetaData: context is null");
    DBG_ASSERT(context->getServiceManager().is(),
        "SfxDocumentMetaData: context has no service manager");
    init(createDOM());
}

// com.sun.star.uno.XServiceInfo:
::rtl::OUString SAL_CALL
SfxDocumentMetaData::getImplementationName() throw (css::uno::RuntimeException)
{
    return comp_SfxDocumentMetaData::_getImplementationName();
}

::sal_Bool SAL_CALL
SfxDocumentMetaData::supportsService(::rtl::OUString const & serviceName)
        throw (css::uno::RuntimeException)
{
    css::uno::Sequence< ::rtl::OUString > serviceNames =
        comp_SfxDocumentMetaData::_getSupportedServiceNames();
    for (::sal_Int32 i = 0; i < serviceNames.getLength(); ++i) {
        if (serviceNames[i] == serviceName)
            return sal_True;
    }
    return sal_False;
}

css::uno::Sequence< ::rtl::OUString > SAL_CALL
SfxDocumentMetaData::getSupportedServiceNames()
        throw (css::uno::RuntimeException)
{
    return comp_SfxDocumentMetaData::_getSupportedServiceNames();
}


// ::com::sun::star::lang::XComponent:
void SAL_CALL SfxDocumentMetaData::dispose() throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    if (!m_isInitialized) {
        return;
    }
    WeakComponentImplHelperBase::dispose(); // superclass
    m_NotifyListeners.disposeAndClear(css::lang::EventObject(
            static_cast< ::cppu::OWeakObject* >(this)));
    m_isInitialized = false;
    m_meta.clear();
    m_metaList.clear();
    m_xParent.clear();
    m_xDoc.clear();
    m_xUserDefined.clear();
}


// ::com::sun::star::document::XDocumentProperties:
::rtl::OUString SAL_CALL
SfxDocumentMetaData::getAuthor() throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    return getMetaText("meta:initial-creator");
}

void SAL_CALL SfxDocumentMetaData::setAuthor(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException)
{
    setMetaTextAndNotify("meta:initial-creator", the_value);
}


::rtl::OUString SAL_CALL
SfxDocumentMetaData::getGenerator() throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    return getMetaText("meta:generator");
}

void SAL_CALL
SfxDocumentMetaData::setGenerator(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException)
{
    setMetaTextAndNotify("meta:generator", the_value);
}

css::util::DateTime SAL_CALL
SfxDocumentMetaData::getCreationDate() throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    return textToDateTimeDefault(getMetaText("meta:creation-date"));
}

void SAL_CALL
SfxDocumentMetaData::setCreationDate(const css::util::DateTime & the_value)
        throw (css::uno::RuntimeException)
{
    setMetaTextAndNotify("meta:creation-date", dateTimeToText(the_value));
}

::rtl::OUString SAL_CALL
SfxDocumentMetaData::getTitle() throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    return getMetaText("dc:title");
}

void SAL_CALL SfxDocumentMetaData::setTitle(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException)
{
    setMetaTextAndNotify("dc:title", the_value);
}

::rtl::OUString SAL_CALL
SfxDocumentMetaData::getSubject() throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    return getMetaText("dc:subject");
}

void SAL_CALL
SfxDocumentMetaData::setSubject(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException)
{
    setMetaTextAndNotify("dc:subject", the_value);
}

::rtl::OUString SAL_CALL
SfxDocumentMetaData::getDescription() throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    return getMetaText("dc:description");
}

void SAL_CALL
SfxDocumentMetaData::setDescription(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException)
{
    setMetaTextAndNotify("dc:description", the_value);
}

css::uno::Sequence< ::rtl::OUString >
SAL_CALL SfxDocumentMetaData::getKeywords() throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    return getMetaList("meta:keyword");
}

void SAL_CALL
SfxDocumentMetaData::setKeywords(
        const css::uno::Sequence< ::rtl::OUString > & the_value)
        throw (css::uno::RuntimeException)
{
    ::osl::ClearableMutexGuard g(m_aMutex);
    if (setMetaList("meta:keyword", the_value)) {
        g.clear();
        setModified(true);
    }
}

css::lang::Locale SAL_CALL
        SfxDocumentMetaData::getLanguage() throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    css::lang::Locale loc;
    ::rtl::OUString text = getMetaText("dc:language");
    sal_Int32 ix = text.indexOf(static_cast<sal_Unicode> ('-'));
    if (ix == -1) {
        loc.Language = text;
    } else {
        loc.Language = text.copy(0, ix);
        loc.Country = text.copy(ix+1);
    }
    return loc;
}

void SAL_CALL
SfxDocumentMetaData::setLanguage(const css::lang::Locale & the_value)
        throw (css::uno::RuntimeException)
{
    ::rtl::OUString text = the_value.Language;
    if (!the_value.Country.isEmpty()) {
        text += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("-")).concat(the_value.Country);
    }
    setMetaTextAndNotify("dc:language", text);
}

::rtl::OUString SAL_CALL
SfxDocumentMetaData::getModifiedBy() throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    return getMetaText("dc:creator");
}

void SAL_CALL
SfxDocumentMetaData::setModifiedBy(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException)
{
    setMetaTextAndNotify("dc:creator", the_value);
}

css::util::DateTime SAL_CALL
SfxDocumentMetaData::getModificationDate() throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    return textToDateTimeDefault(getMetaText("dc:date"));
}

void SAL_CALL
SfxDocumentMetaData::setModificationDate(const css::util::DateTime & the_value)
        throw (css::uno::RuntimeException)
{
    setMetaTextAndNotify("dc:date", dateTimeToText(the_value));
}

::rtl::OUString SAL_CALL
SfxDocumentMetaData::getPrintedBy() throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    return getMetaText("meta:printed-by");
}

void SAL_CALL
SfxDocumentMetaData::setPrintedBy(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException)
{
    setMetaTextAndNotify("meta:printed-by", the_value);
}

css::util::DateTime SAL_CALL
SfxDocumentMetaData::getPrintDate() throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    return textToDateTimeDefault(getMetaText("meta:print-date"));
}

void SAL_CALL
SfxDocumentMetaData::setPrintDate(const css::util::DateTime & the_value)
        throw (css::uno::RuntimeException)
{
    setMetaTextAndNotify("meta:print-date", dateTimeToText(the_value));
}

::rtl::OUString SAL_CALL
SfxDocumentMetaData::getTemplateName() throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    checkInit();
    return m_TemplateName;
}

void SAL_CALL
SfxDocumentMetaData::setTemplateName(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException)
{
    ::osl::ClearableMutexGuard g(m_aMutex);
    checkInit();
    if (m_TemplateName != the_value) {
        m_TemplateName = the_value;
        g.clear();
        setModified(true);
    }
}

::rtl::OUString SAL_CALL
SfxDocumentMetaData::getTemplateURL() throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    checkInit();
    return m_TemplateURL;
}

void SAL_CALL
SfxDocumentMetaData::setTemplateURL(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException)
{
    ::osl::ClearableMutexGuard g(m_aMutex);
    checkInit();
    if (m_TemplateURL != the_value) {
        m_TemplateURL = the_value;
        g.clear();
        setModified(true);
    }
}

css::util::DateTime SAL_CALL
SfxDocumentMetaData::getTemplateDate() throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    checkInit();
    return m_TemplateDate;
}

void SAL_CALL
SfxDocumentMetaData::setTemplateDate(const css::util::DateTime & the_value)
        throw (css::uno::RuntimeException)
{
    ::osl::ClearableMutexGuard g(m_aMutex);
    checkInit();
    if (!(m_TemplateDate == the_value)) {
        m_TemplateDate = the_value;
        g.clear();
        setModified(true);
    }
}

::rtl::OUString SAL_CALL
SfxDocumentMetaData::getAutoloadURL() throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    checkInit();
    return m_AutoloadURL;
}

void SAL_CALL
SfxDocumentMetaData::setAutoloadURL(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException)
{
    ::osl::ClearableMutexGuard g(m_aMutex);
    checkInit();
    if (m_AutoloadURL != the_value) {
        m_AutoloadURL = the_value;
        g.clear();
        setModified(true);
    }
}

::sal_Int32 SAL_CALL
SfxDocumentMetaData::getAutoloadSecs() throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    checkInit();
    return m_AutoloadSecs;
}

void SAL_CALL
SfxDocumentMetaData::setAutoloadSecs(::sal_Int32 the_value)
        throw (css::uno::RuntimeException, css::lang::IllegalArgumentException)
{
    if (the_value < 0) throw css::lang::IllegalArgumentException(
        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
            "SfxDocumentMetaData::setAutoloadSecs: argument is negative")),
            *this, 0);
    ::osl::ClearableMutexGuard g(m_aMutex);
    checkInit();
    if (m_AutoloadSecs != the_value) {
        m_AutoloadSecs = the_value;
        g.clear();
        setModified(true);
    }
}

::rtl::OUString SAL_CALL
SfxDocumentMetaData::getDefaultTarget() throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    checkInit();
    return m_DefaultTarget;
}

void SAL_CALL
SfxDocumentMetaData::setDefaultTarget(const ::rtl::OUString & the_value)
        throw (css::uno::RuntimeException)
{
    ::osl::ClearableMutexGuard g(m_aMutex);
    checkInit();
    if (m_DefaultTarget != the_value) {
        m_DefaultTarget = the_value;
        g.clear();
        setModified(true);
    }
}

css::uno::Sequence< css::beans::NamedValue > SAL_CALL
SfxDocumentMetaData::getDocumentStatistics() throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    checkInit();
    ::comphelper::SequenceAsVector<css::beans::NamedValue> stats;
    for (size_t i = 0; s_stdStats[i] != 0; ++i) {
        const char * aName = s_stdStatAttrs[i];
        ::rtl::OUString text = getMetaAttr("meta:document-statistic", aName);
        if (text.isEmpty()) continue;
        css::beans::NamedValue stat;
        stat.Name = ::rtl::OUString::createFromAscii(s_stdStats[i]);
        sal_Int32 val;
        css::uno::Any any;
        if (!::sax::Converter::convertNumber(val, text, 0,
                std::numeric_limits<sal_Int32>::max()) || (val < 0)) {
            val = 0;
            DBG_WARNING1("SfxDocumentMetaData: invalid number: %s",
                OUStringToOString(text, RTL_TEXTENCODING_UTF8).getStr());
        }
        any <<= val;
        stat.Value = any;
        stats.push_back(stat);
    }

    return stats.getAsConstList();
}

void SAL_CALL
SfxDocumentMetaData::setDocumentStatistics(
        const css::uno::Sequence< css::beans::NamedValue > & the_value)
        throw (css::uno::RuntimeException)
{
    ::osl::ClearableMutexGuard g(m_aMutex);
    checkInit();
    std::vector<std::pair<const char *, ::rtl::OUString> > attributes;
    for (sal_Int32 i = 0; i < the_value.getLength(); ++i) {
        const ::rtl::OUString name = the_value[i].Name;
        // inefficently search for matching attribute
        for (size_t j = 0; s_stdStats[j] != 0; ++j) {
            if (name.equalsAscii(s_stdStats[j])) {
                const css::uno::Any any = the_value[i].Value;
                sal_Int32 val = 0;
                if (any >>= val) {
                    ::rtl::OUStringBuffer buf;
                    ::sax::Converter::convertNumber(buf, val);
                    attributes.push_back(std::make_pair(s_stdStatAttrs[j],
                                buf.makeStringAndClear()));
                } else {
                    DBG_WARNING1("SfxDocumentMetaData: invalid statistic: %s",
                        OUStringToOString(name, RTL_TEXTENCODING_UTF8)
                            .getStr());
                }
                break;
            }
        }
    }
    updateElement("meta:document-statistic", &attributes);
    g.clear();
    setModified(true);
}

::sal_Int16 SAL_CALL
SfxDocumentMetaData::getEditingCycles() throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    ::rtl::OUString text = getMetaText("meta:editing-cycles");
    sal_Int32 ret;
    if (::sax::Converter::convertNumber(ret, text,
            0, std::numeric_limits<sal_Int16>::max())) {
        return static_cast<sal_Int16>(ret);
    } else {
        return 0;
    }
}

void SAL_CALL
SfxDocumentMetaData::setEditingCycles(::sal_Int16 the_value)
        throw (css::uno::RuntimeException, css::lang::IllegalArgumentException)
{
    if (the_value < 0) throw css::lang::IllegalArgumentException(
        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                "SfxDocumentMetaData::setEditingCycles: argument is negative")),
                *this, 0);
    ::rtl::OUStringBuffer buf;
    ::sax::Converter::convertNumber(buf, the_value);
    setMetaTextAndNotify("meta:editing-cycles", buf.makeStringAndClear());
}

::sal_Int32 SAL_CALL
SfxDocumentMetaData::getEditingDuration() throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    return textToDuration(getMetaText("meta:editing-duration"));
}

void SAL_CALL
SfxDocumentMetaData::setEditingDuration(::sal_Int32 the_value)
        throw (css::uno::RuntimeException, css::lang::IllegalArgumentException)
{
    if (the_value < 0) throw css::lang::IllegalArgumentException(
        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
            "SfxDocumentMetaData::setEditingDuration: argument is negative")),
            *this, 0);
    setMetaTextAndNotify("meta:editing-duration", durationToText(the_value));
}

void SAL_CALL
SfxDocumentMetaData::resetUserData(const ::rtl::OUString & the_value)
    throw (css::uno::RuntimeException)
{
    ::osl::ClearableMutexGuard g(m_aMutex);

    bool bModified( false );
    bModified |= setMetaText("meta:initial-creator", the_value);
    ::DateTime now( ::DateTime::SYSTEM );
    css::util::DateTime uDT(now.Get100Sec(), now.GetSec(), now.GetMin(),
        now.GetHour(), now.GetDay(), now.GetMonth(), now.GetYear());
    bModified |= setMetaText("meta:creation-date", dateTimeToText(uDT));
    bModified |= setMetaText("dc:creator", ::rtl::OUString());
    bModified |= setMetaText("meta:printed-by", ::rtl::OUString());
    bModified |= setMetaText("dc:date", dateTimeToText(css::util::DateTime()));
    bModified |= setMetaText("meta:print-date",
        dateTimeToText(css::util::DateTime()));
    bModified |= setMetaText("meta:editing-duration", durationToText(0));
    bModified |= setMetaText("meta:editing-cycles",
        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("1")));

    if (bModified) {
        g.clear();
        setModified(true);
    }
}


css::uno::Reference< css::beans::XPropertyContainer > SAL_CALL
SfxDocumentMetaData::getUserDefinedProperties()
        throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    checkInit();
    createUserDefined();
    return m_xUserDefined;
}


void SAL_CALL
SfxDocumentMetaData::loadFromStorage(
        const css::uno::Reference< css::embed::XStorage > & xStorage,
        const css::uno::Sequence< css::beans::PropertyValue > & Medium)
    throw (css::uno::RuntimeException, css::lang::IllegalArgumentException,
           css::io::WrongFormatException,
           css::lang::WrappedTargetException, css::io::IOException)
{
    if (!xStorage.is()) throw css::lang::IllegalArgumentException(
        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SfxDocumentMetaData::loadFromStorage:"
                " argument is null")), *this, 0);
    ::osl::MutexGuard g(m_aMutex);

    // open meta data file
    css::uno::Reference<css::io::XStream> xStream(
        xStorage->openStreamElement(
            ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(s_meta)),
            css::embed::ElementModes::READ) );
    if (!xStream.is()) throw css::uno::RuntimeException();
    css::uno::Reference<css::io::XInputStream> xInStream =
        xStream->getInputStream();
    if (!xInStream.is()) throw css::uno::RuntimeException();

    // create DOM parser service
    css::uno::Reference<css::lang::XMultiComponentFactory> xMsf (
        m_xContext->getServiceManager());
    css::uno::Reference<css::xml::sax::XParser> xParser (
        xMsf->createInstanceWithContext(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                "com.sun.star.xml.sax.Parser")), m_xContext),
        css::uno::UNO_QUERY_THROW);
    if (!xParser.is()) throw css::uno::RuntimeException(
        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SfxDocumentMetaData::loadFromStorage:"
                " cannot create Parser service")), *this);
    css::xml::sax::InputSource input;
    input.aInputStream = xInStream;

    sal_uInt64 version = SotStorage::GetVersion( xStorage );
    // Oasis is also the default (0)
    sal_Bool bOasis = ( version > SOFFICE_FILEFORMAT_60 || version == 0 );
    const sal_Char *pServiceName = bOasis
        ? "com.sun.star.document.XMLOasisMetaImporter"
        : "com.sun.star.document.XMLMetaImporter";

    // set base URL
    css::uno::Reference<css::beans::XPropertySet> xPropArg =
        getURLProperties(Medium);
    try {
        xPropArg->getPropertyValue(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("BaseURI")))
            >>= input.sSystemId;
        input.sSystemId += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/")).concat(
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(s_meta)));
    } catch (const css::uno::Exception &) {
        input.sSystemId = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(s_meta));
    }
    css::uno::Sequence< css::uno::Any > args(1);
    args[0] <<= xPropArg;

    css::uno::Reference<css::xml::sax::XDocumentHandler> xDocHandler (
        xMsf->createInstanceWithArgumentsAndContext(
            ::rtl::OUString::createFromAscii(pServiceName), args, m_xContext),
        css::uno::UNO_QUERY_THROW);
    if (!xDocHandler.is()) throw css::uno::RuntimeException(
        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SfxDocumentMetaData::loadFromStorage:"
                " cannot create XMLOasisMetaImporter service")), *this);
    css::uno::Reference<css::document::XImporter> xImp (xDocHandler,
        css::uno::UNO_QUERY_THROW);
    xImp->setTargetDocument(css::uno::Reference<css::lang::XComponent>(this));
    xParser->setDocumentHandler(xDocHandler);
    try {
        xParser->parseStream(input);
    } catch (const css::xml::sax::SAXException &) {
        throw css::io::WrongFormatException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                "SfxDocumentMetaData::loadFromStorage:"
                " XML parsing exception")), *this);
    }
    // NB: the implementation of XMLOasisMetaImporter calls initialize
    checkInit();
}

void SAL_CALL
SfxDocumentMetaData::storeToStorage(
        const css::uno::Reference< css::embed::XStorage > & xStorage,
        const css::uno::Sequence< css::beans::PropertyValue > & Medium)
    throw (css::uno::RuntimeException, css::lang::IllegalArgumentException,
           css::lang::WrappedTargetException, css::io::IOException)
{
    if (!xStorage.is()) throw css::lang::IllegalArgumentException(
        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SfxDocumentMetaData::storeToStorage:"
                " argument is null")), *this, 0);
    ::osl::MutexGuard g(m_aMutex);
    checkInit();

    // update user-defined meta data in DOM tree
//    updateUserDefinedAndAttributes(); // this will be done in serialize!

    // write into storage
    css::uno::Reference<css::io::XStream> xStream =
        xStorage->openStreamElement(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(s_meta)),
            css::embed::ElementModes::WRITE
            | css::embed::ElementModes::TRUNCATE);
    if (!xStream.is()) throw css::uno::RuntimeException();
    css::uno::Reference< css::beans::XPropertySet > xStreamProps(xStream,
        css::uno::UNO_QUERY_THROW);
    xStreamProps->setPropertyValue(
        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("MediaType")),
        css::uno::makeAny(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("text/xml"))));
    xStreamProps->setPropertyValue(
        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Compressed")),
        css::uno::makeAny(static_cast<sal_Bool> (sal_False)));
    xStreamProps->setPropertyValue(
        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("UseCommonStoragePasswordEncryption")),
        css::uno::makeAny(static_cast<sal_Bool> (sal_False)));
    css::uno::Reference<css::io::XOutputStream> xOutStream =
        xStream->getOutputStream();
    if (!xOutStream.is()) throw css::uno::RuntimeException();
    css::uno::Reference<css::lang::XMultiComponentFactory> xMsf (
        m_xContext->getServiceManager());
    css::uno::Reference<css::io::XActiveDataSource> xSaxWriter(
        xMsf->createInstanceWithContext(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                "com.sun.star.xml.sax.Writer")), m_xContext),
        css::uno::UNO_QUERY_THROW);
    xSaxWriter->setOutputStream(xOutStream);
    css::uno::Reference<css::xml::sax::XDocumentHandler> xDocHandler (
        xSaxWriter, css::uno::UNO_QUERY_THROW);

    const sal_uInt64 version = SotStorage::GetVersion( xStorage );
    // Oasis is also the default (0)
    const sal_Bool bOasis = ( version > SOFFICE_FILEFORMAT_60 || version == 0 );
    const sal_Char *pServiceName = bOasis
        ? "com.sun.star.document.XMLOasisMetaExporter"
        : "com.sun.star.document.XMLMetaExporter";

    // set base URL
    css::uno::Reference<css::beans::XPropertySet> xPropArg =
        getURLProperties(Medium);
    css::uno::Sequence< css::uno::Any > args(2);
    args[0] <<= xDocHandler;
    args[1] <<= xPropArg;

    css::uno::Reference<css::document::XExporter> xExp(
        xMsf->createInstanceWithArgumentsAndContext(
            ::rtl::OUString::createFromAscii(pServiceName), args, m_xContext),
        css::uno::UNO_QUERY_THROW);
    xExp->setSourceDocument(css::uno::Reference<css::lang::XComponent>(this));
    css::uno::Reference<css::document::XFilter> xFilter(xExp,
        css::uno::UNO_QUERY_THROW);
    if (xFilter->filter(css::uno::Sequence< css::beans::PropertyValue >())) {
        css::uno::Reference<css::embed::XTransactedObject> xTransaction(
            xStorage, css::uno::UNO_QUERY);
        if (xTransaction.is()) {
            xTransaction->commit();
        }
    } else {
        throw css::io::IOException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                "SfxDocumentMetaData::storeToStorage: cannot filter")), *this);
    }
}

void SAL_CALL
SfxDocumentMetaData::loadFromMedium(const ::rtl::OUString & URL,
        const css::uno::Sequence< css::beans::PropertyValue > & Medium)
    throw (css::uno::RuntimeException, css::io::WrongFormatException,
           css::lang::WrappedTargetException, css::io::IOException)
{
    css::uno::Reference<css::io::XInputStream> xIn;
    ::comphelper::MediaDescriptor md(Medium);
    // if we have an URL parameter, it replaces the one in the media descriptor
    if (!URL.isEmpty()) {
        md[ ::comphelper::MediaDescriptor::PROP_URL() ] <<= URL;
    }
    if (sal_True == md.addInputStream()) {
        md[ ::comphelper::MediaDescriptor::PROP_INPUTSTREAM() ] >>= xIn;
    }
    css::uno::Reference<css::embed::XStorage> xStorage;
    css::uno::Reference<css::lang::XMultiServiceFactory> xMsf (
        m_xContext->getServiceManager(), css::uno::UNO_QUERY_THROW);
    try {
        if (xIn.is()) {
            xStorage = ::comphelper::OStorageHelper::GetStorageFromInputStream(
                            xIn, xMsf);
        } else { // fallback to url parameter
            xStorage = ::comphelper::OStorageHelper::GetStorageFromURL(
                            URL, css::embed::ElementModes::READ, xMsf);
        }
    } catch (const css::uno::RuntimeException &) {
        throw;
    } catch (const css::io::IOException &) {
        throw;
    } catch (const css::uno::Exception & e) {
        throw css::lang::WrappedTargetException(
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                    "SfxDocumentMetaData::loadFromMedium: exception")),
                css::uno::Reference<css::uno::XInterface>(*this),
                css::uno::makeAny(e));
    }
    if (!xStorage.is()) {
        throw css::uno::RuntimeException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                "SfxDocumentMetaData::loadFromMedium: cannot get Storage")),
                *this);
    }
    loadFromStorage(xStorage, md.getAsConstPropertyValueList());
}

void SAL_CALL
SfxDocumentMetaData::storeToMedium(const ::rtl::OUString & URL,
        const css::uno::Sequence< css::beans::PropertyValue > & Medium)
    throw (css::uno::RuntimeException,
           css::lang::WrappedTargetException, css::io::IOException)
{
    ::comphelper::MediaDescriptor md(Medium);
    if (!URL.isEmpty()) {
        md[ ::comphelper::MediaDescriptor::PROP_URL() ] <<= URL;
    }
    SfxMedium aMedium(md.getAsConstPropertyValueList());
    css::uno::Reference<css::embed::XStorage> xStorage
        = aMedium.GetOutputStorage();


    if (!xStorage.is()) {
        throw css::uno::RuntimeException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                "SfxDocumentMetaData::storeToMedium: cannot get Storage")),
                *this);
    }
    // set MIME type of the storage
    ::comphelper::MediaDescriptor::const_iterator iter
        = md.find(::comphelper::MediaDescriptor::PROP_MEDIATYPE());
    if (iter != md.end()) {
        css::uno::Reference< css::beans::XPropertySet > xProps(xStorage,
            css::uno::UNO_QUERY_THROW);
        xProps->setPropertyValue(
            ::comphelper::MediaDescriptor::PROP_MEDIATYPE(),
            iter->second);
    }
    storeToStorage(xStorage, md.getAsConstPropertyValueList());


    const sal_Bool bOk = aMedium.Commit();
    aMedium.Close();
    if ( !bOk ) {
        sal_uInt32 nError = aMedium.GetError();
        if ( nError == ERRCODE_NONE ) {
            nError = ERRCODE_IO_GENERAL;
        }

        throw css::task::ErrorCodeIOException( ::rtl::OUString(),
                css::uno::Reference< css::uno::XInterface >(), nError);

    }
}

// ::com::sun::star::lang::XInitialization:
void SAL_CALL
SfxDocumentMetaData::initialize(
        const css::uno::Sequence< ::com::sun::star::uno::Any > & aArguments)
    throw (css::uno::RuntimeException, css::uno::Exception)
{
    // possible arguments:
    // - no argument: default initialization (empty DOM)
    // - 1 argument, XDocument: initialize with given DOM and empty base URL
    // NB: links in document must be absolute

    ::osl::MutexGuard g(m_aMutex);
    css::uno::Reference<css::xml::dom::XDocument> xDoc;

    for (sal_Int32 i = 0; i < aArguments.getLength(); ++i) {
        const css::uno::Any any = aArguments[i];
        if (any >>= xDoc) {
            if (!xDoc.is()) {
                throw css::lang::IllegalArgumentException(
                    ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SfxDocumentMetaData::"
                        "initialize: argument is null")),
                    *this, static_cast<sal_Int16>(i));
            }
        } else {
            throw css::lang::IllegalArgumentException(
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SfxDocumentMetaData::"
                    "initialize: argument must be XDocument")),
                *this, static_cast<sal_Int16>(i));
        }
    }

    if (!xDoc.is()) {
        // For a new document, we create a new DOM tree here.
        xDoc = createDOM();
    }

    init(xDoc);
}

// ::com::sun::star::util::XCloneable:
css::uno::Reference<css::util::XCloneable> SAL_CALL
SfxDocumentMetaData::createClone()
    throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    checkInit();

    SfxDocumentMetaData *pNew = createMe(m_xContext);

    // NB: do not copy the modification listeners, only DOM
    css::uno::Reference<css::xml::dom::XDocument> xDoc = createDOM();
    try {
        updateUserDefinedAndAttributes();
        // deep copy of root node
        css::uno::Reference<css::xml::dom::XNode> xRoot(
            m_xDoc->getDocumentElement(), css::uno::UNO_QUERY_THROW);
        css::uno::Reference<css::xml::dom::XNode> xRootNew(
            xDoc->importNode(xRoot, true));
        xDoc->appendChild(xRootNew);
        pNew->init(xDoc);
    } catch (const css::uno::RuntimeException &) {
        throw;<--- Memory leak: pNew
    } catch (const css::uno::Exception & e) {
        css::uno::Any a(e);
        throw css::lang::WrappedTargetRuntimeException(
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                    "SfxDocumentMetaData::createClone: exception")),
                css::uno::Reference<css::uno::XInterface>(*this), a);
    }
    return css::uno::Reference<css::util::XCloneable> (pNew);
}

// ::com::sun::star::util::XModifiable:
::sal_Bool SAL_CALL SfxDocumentMetaData::isModified(  )
        throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    checkInit();
    css::uno::Reference<css::util::XModifiable> xMB(m_xUserDefined,
        css::uno::UNO_QUERY);
    return m_isModified || (xMB.is() ? xMB->isModified() : sal_False);
}

void SAL_CALL SfxDocumentMetaData::setModified( ::sal_Bool bModified )
        throw (css::beans::PropertyVetoException, css::uno::RuntimeException)
{
    css::uno::Reference<css::util::XModifiable> xMB;
    { // do not lock mutex while notifying (#i93514#) to prevent deadlock
        ::osl::MutexGuard g(m_aMutex);
        checkInit();
        m_isModified = bModified;
        if ( !bModified && m_xUserDefined.is() )
        {
            xMB.set(m_xUserDefined, css::uno::UNO_QUERY);
            DBG_ASSERT(xMB.is(),
                "SfxDocumentMetaData::setModified: PropertyBag not Modifiable?");
        }
    }
    if (bModified) {
        try {
            css::uno::Reference<css::uno::XInterface> xThis(*this);
            css::lang::EventObject event(xThis);
            m_NotifyListeners.notifyEach(&css::util::XModifyListener::modified,
                event);
        } catch (const css::uno::RuntimeException &) {
            throw;
        } catch (const css::uno::Exception & e) {
            // ignore
            DBG_WARNING1("SfxDocumentMetaData::setModified: exception:\n%s",
                OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8).getStr());
            (void) e;
        }
    } else {
        if (xMB.is()) {
            xMB->setModified(false);
        }
    }
}

// ::com::sun::star::util::XModifyBroadcaster:
void SAL_CALL SfxDocumentMetaData::addModifyListener(
        const css::uno::Reference< css::util::XModifyListener > & xListener)
        throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    checkInit();
    m_NotifyListeners.addInterface(xListener);
    css::uno::Reference<css::util::XModifyBroadcaster> xMB(m_xUserDefined,
        css::uno::UNO_QUERY);
    if (xMB.is()) {
        xMB->addModifyListener(xListener);
    }
}

void SAL_CALL SfxDocumentMetaData::removeModifyListener(
        const css::uno::Reference< css::util::XModifyListener > & xListener)
        throw (css::uno::RuntimeException)
{
    ::osl::MutexGuard g(m_aMutex);
    checkInit();
    m_NotifyListeners.removeInterface(xListener);
    css::uno::Reference<css::util::XModifyBroadcaster> xMB(m_xUserDefined,
        css::uno::UNO_QUERY);
    if (xMB.is()) {
        xMB->removeModifyListener(xListener);
    }
}

// ::com::sun::star::xml::sax::XSAXSerializable
void SAL_CALL SfxDocumentMetaData::serialize(
    const css::uno::Reference<css::xml::sax::XDocumentHandler>& i_xHandler,
    const css::uno::Sequence< css::beans::StringPair >& i_rNamespaces)
    throw (css::uno::RuntimeException, css::xml::sax::SAXException)
{
    ::osl::MutexGuard g(m_aMutex);
    checkInit();
    updateUserDefinedAndAttributes();
    css::uno::Reference<css::xml::sax::XSAXSerializable> xSAXable(m_xDoc,
        css::uno::UNO_QUERY_THROW);
    xSAXable->serialize(i_xHandler, i_rNamespaces);
}

void SfxDocumentMetaData::createUserDefined()
{
    // user-defined meta data: create PropertyBag which only accepts property
    // values of allowed types
    if ( !m_xUserDefined.is() )
    {
        css::uno::Sequence<css::uno::Type> types(11);
        types[0] = ::cppu::UnoType<bool>::get();
        types[1] = ::cppu::UnoType< ::rtl::OUString>::get();
        types[2] = ::cppu::UnoType<css::util::DateTime>::get();
        types[3] = ::cppu::UnoType<css::util::Date>::get();
        types[4] = ::cppu::UnoType<css::util::Duration>::get();
        types[5] = ::cppu::UnoType<float>::get();
        types[6] = ::cppu::UnoType<double>::get();
        types[7] = ::cppu::UnoType<sal_Int16>::get();
        types[8] = ::cppu::UnoType<sal_Int32>::get();
        types[9] = ::cppu::UnoType<sal_Int64>::get();
        // Time is supported for backward compatibility with OOo 3.x, x<=2
        types[10] = ::cppu::UnoType<css::util::Time>::get();
        css::uno::Sequence<css::uno::Any> args(2);
        args[0] <<= css::beans::NamedValue(
            ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AllowedTypes")),
            css::uno::makeAny(types));
        // #i94175#:  ODF allows empty user-defined property names!
        args[1] <<= css::beans::NamedValue( ::rtl::OUString(
                        RTL_CONSTASCII_USTRINGPARAM("AllowEmptyPropertyName")),
            css::uno::makeAny(sal_True));

        const css::uno::Reference<css::lang::XMultiComponentFactory> xMsf(
                m_xContext->getServiceManager());
        m_xUserDefined.set(
            xMsf->createInstanceWithContext(
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
                    "com.sun.star.beans.PropertyBag")), m_xContext),
            css::uno::UNO_QUERY_THROW);
        const css::uno::Reference<css::lang::XInitialization> xInit(
            m_xUserDefined, css::uno::UNO_QUERY);
        if (xInit.is()) {
            xInit->initialize(args);
        }

        const css::uno::Reference<css::util::XModifyBroadcaster> xMB(
            m_xUserDefined, css::uno::UNO_QUERY);
        if (xMB.is())
        {
            const css::uno::Sequence<css::uno::Reference<css::uno::XInterface> >
                listeners(m_NotifyListeners.getElements());
            for (css::uno::Reference< css::uno::XInterface > const * iter =
                                ::comphelper::stl_begin(listeners);
                        iter != ::comphelper::stl_end(listeners); ++iter) {
                xMB->addModifyListener(
                    css::uno::Reference< css::util::XModifyListener >(*iter,
                        css::uno::UNO_QUERY));
            }
        }
    }
}

} // closing anonymous implementation namespace


// component helper namespace
namespace comp_CompatWriterDocProps {

    ::rtl::OUString SAL_CALL _getImplementationName() {
        return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
            "CompatWriterDocPropsImpl"));
}

   css::uno::Sequence< ::rtl::OUString > SAL_CALL _getSupportedServiceNames()
   {
        css::uno::Sequence< rtl::OUString > aServiceNames(1);
        aServiceNames[ 0 ] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.writer.DocumentProperties" ) );
        return aServiceNames;
   }
    css::uno::Reference< css::uno::XInterface > SAL_CALL _create(
        const css::uno::Reference< css::uno::XComponentContext > & context)
            SAL_THROW((css::uno::Exception))
    {
        return static_cast< ::cppu::OWeakObject * >
                    (new CompatWriterDocPropsImpl(context));
    }

}
namespace comp_SfxDocumentMetaData {

::rtl::OUString SAL_CALL _getImplementationName() {
    return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
        "SfxDocumentMetaData"));
}

css::uno::Sequence< ::rtl::OUString > SAL_CALL _getSupportedServiceNames()
{
    css::uno::Sequence< ::rtl::OUString > s(1);
    s[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
        "com.sun.star.document.DocumentProperties"));
    return s;
}

css::uno::Reference< css::uno::XInterface > SAL_CALL _create(
    const css::uno::Reference< css::uno::XComponentContext > & context)
        SAL_THROW((css::uno::Exception))
{
    return static_cast< ::cppu::OWeakObject * >
                (new SfxDocumentMetaData(context));
}

} // closing component helper namespace

static ::cppu::ImplementationEntry const entries[] = {
    { &comp_SfxDocumentMetaData::_create,
      &comp_SfxDocumentMetaData::_getImplementationName,
      &comp_SfxDocumentMetaData::_getSupportedServiceNames,
      &::cppu::createSingleComponentFactory, 0, 0 },
    { 0, 0, 0, 0, 0, 0 }
};

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