Source

perl-XML-LibXML / LibXML.pm

   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
# $Id$
#
#
# This is free software, you may use it and distribute it under the same terms as
# Perl itself.
#
# Copyright 2001-2003 AxKit.com Ltd., 2002-2006 Christian Glahn, 2006-2009 Petr Pajas
#
#

package XML::LibXML;

use strict;
use vars qw($VERSION $ABI_VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS
            $skipDTD $skipXMLDeclaration $setTagCompression
            $MatchCB $ReadCB $OpenCB $CloseCB %PARSER_FLAGS
	    $XML_LIBXML_PARSE_DEFAULTS
            );
use Carp;

use constant XML_XMLNS_NS => 'http://www.w3.org/2000/xmlns/';
use constant XML_XML_NS => 'http://www.w3.org/XML/1998/namespace';

use XML::LibXML::Error;
use XML::LibXML::NodeList;
use XML::LibXML::XPathContext;
use IO::Handle; # for FH reads called as methods

BEGIN {
$VERSION = "2.0003"; # VERSION TEMPLATE: DO NOT CHANGE
$ABI_VERSION = 2;
require Exporter;
require DynaLoader;
@ISA = qw(DynaLoader Exporter);

use vars qw($__PROXY_NODE_REGISTRY $__threads_shared $__PROXY_NODE_REGISTRY_MUTEX $__loaded);

sub VERSION {
  my $class = shift;
  my ($caller) = caller;
  my $req_abi = $ABI_VERSION;
  if (UNIVERSAL::can($caller,'REQUIRE_XML_LIBXML_ABI_VERSION')) {
    $req_abi = $caller->REQUIRE_XML_LIBXML_ABI_VERSION();
  } elsif ($caller eq 'XML::LibXSLT') {
    # XML::LibXSLT without REQUIRE_XML_LIBXML_ABI_VERSION is an old and incompatible version
    $req_abi = 1;
  }
  unless ($req_abi == $ABI_VERSION) {
    my $ver = @_ ? ' '.$_[0] : '';
    die ("This version of $caller requires XML::LibXML$ver (ABI $req_abi), which is incompatible with currently installed XML::LibXML $VERSION (ABI $ABI_VERSION). Please upgrade $caller, XML::LibXML, or both!");
  }
  return $class->UNIVERSAL::VERSION(@_)
}

#-------------------------------------------------------------------------#
# export information                                                      #
#-------------------------------------------------------------------------#
%EXPORT_TAGS = (
                all => [qw(
                           XML_ELEMENT_NODE
                           XML_ATTRIBUTE_NODE
                           XML_TEXT_NODE
                           XML_CDATA_SECTION_NODE
                           XML_ENTITY_REF_NODE
                           XML_ENTITY_NODE
                           XML_PI_NODE
                           XML_COMMENT_NODE
                           XML_DOCUMENT_NODE
                           XML_DOCUMENT_TYPE_NODE
                           XML_DOCUMENT_FRAG_NODE
                           XML_NOTATION_NODE
                           XML_HTML_DOCUMENT_NODE
                           XML_DTD_NODE
                           XML_ELEMENT_DECL
                           XML_ATTRIBUTE_DECL
                           XML_ENTITY_DECL
                           XML_NAMESPACE_DECL
                           XML_XINCLUDE_END
                           XML_XINCLUDE_START
                           encodeToUTF8
                           decodeFromUTF8
		           XML_XMLNS_NS
		           XML_XML_NS
                          )],
                libxml => [qw(
                           XML_ELEMENT_NODE
                           XML_ATTRIBUTE_NODE
                           XML_TEXT_NODE
                           XML_CDATA_SECTION_NODE
                           XML_ENTITY_REF_NODE
                           XML_ENTITY_NODE
                           XML_PI_NODE
                           XML_COMMENT_NODE
                           XML_DOCUMENT_NODE
                           XML_DOCUMENT_TYPE_NODE
                           XML_DOCUMENT_FRAG_NODE
                           XML_NOTATION_NODE
                           XML_HTML_DOCUMENT_NODE
                           XML_DTD_NODE
                           XML_ELEMENT_DECL
                           XML_ATTRIBUTE_DECL
                           XML_ENTITY_DECL
                           XML_NAMESPACE_DECL
                           XML_XINCLUDE_END
                           XML_XINCLUDE_START
                          )],
                encoding => [qw(
                                encodeToUTF8
                                decodeFromUTF8
                               )],
		ns => [qw(
		           XML_XMLNS_NS
		           XML_XML_NS
		 )],
               );

@EXPORT_OK = (
              @{$EXPORT_TAGS{all}},
             );

@EXPORT = (
           @{$EXPORT_TAGS{all}},
          );

#-------------------------------------------------------------------------#
# initialization of the global variables                                  #
#-------------------------------------------------------------------------#
$skipDTD            = 0;
$skipXMLDeclaration = 0;
$setTagCompression  = 0;

$MatchCB = undef;
$ReadCB  = undef;
$OpenCB  = undef;
$CloseCB = undef;

# if ($threads::threads) {
#   our $__THREADS_TID = 0;
#   eval q{
#     use threads::shared;
#     our $__PROXY_NODE_REGISTRY_MUTEX :shared = 0;
#   };
#   die $@ if $@;
# }
#-------------------------------------------------------------------------#
# bootstrapping                                                           #
#-------------------------------------------------------------------------#
bootstrap XML::LibXML $VERSION;
undef &AUTOLOAD;

*encodeToUTF8 = \&XML::LibXML::Common::encodeToUTF8;
*decodeFromUTF8 = \&XML::LibXML::Common::decodeFromUTF8;

} # BEGIN


#-------------------------------------------------------------------------#
# libxml2 node names (see also XML::LibXML::Common                        #
#-------------------------------------------------------------------------#
use constant XML_ELEMENT_NODE            => 1;
use constant XML_ATTRIBUTE_NODE          => 2;
use constant XML_TEXT_NODE               => 3;
use constant XML_CDATA_SECTION_NODE      => 4;
use constant XML_ENTITY_REF_NODE         => 5;
use constant XML_ENTITY_NODE             => 6;
use constant XML_PI_NODE                 => 7;
use constant XML_COMMENT_NODE            => 8;
use constant XML_DOCUMENT_NODE           => 9;
use constant XML_DOCUMENT_TYPE_NODE      => 10;
use constant XML_DOCUMENT_FRAG_NODE      => 11;
use constant XML_NOTATION_NODE           => 12;
use constant XML_HTML_DOCUMENT_NODE      => 13;
use constant XML_DTD_NODE                => 14;
use constant XML_ELEMENT_DECL            => 15;
use constant XML_ATTRIBUTE_DECL          => 16;
use constant XML_ENTITY_DECL             => 17;
use constant XML_NAMESPACE_DECL          => 18;
use constant XML_XINCLUDE_START          => 19;
use constant XML_XINCLUDE_END            => 20;


sub import {
  my $package=shift;
  if (grep /^:threads_shared$/, @_) {
    require threads;
    if (!defined($__threads_shared)) {
      if (INIT_THREAD_SUPPORT()) {
	eval q{
          use threads::shared;
          share($__PROXY_NODE_REGISTRY_MUTEX);
        };
	if ($@) { # something went wrong
	  DISABLE_THREAD_SUPPORT(); # leave the library in a usable state
	  die $@; # and die
	}
	$__PROXY_NODE_REGISTRY = XML::LibXML::HashTable->new();
	$__threads_shared=1;
      } else {
	croak("XML::LibXML or Perl compiled without ithread support!");
      }
    } elsif (!$__threads_shared) {
      croak("XML::LibXML already loaded without thread support. Too late to enable thread support!");
    }
  } elsif (defined $XML::LibXML::__loaded) {
    $__threads_shared=0 if not defined $__threads_shared;
  }
  __PACKAGE__->export_to_level(1,$package,grep !/^:threads(_shared)?$/,@_);
}

sub threads_shared_enabled {
  return $__threads_shared ? 1 : 0;
}

# if ($threads::threads) {
#   our $__PROXY_NODE_REGISTRY = XML::LibXML::HashTable->new();
# }

#-------------------------------------------------------------------------#
# test exact version (up to patch-level)                                  #
#-------------------------------------------------------------------------#
{
  my ($runtime_version) = LIBXML_RUNTIME_VERSION() =~ /^(\d+)/;
  if ( $runtime_version < LIBXML_VERSION ) {
    warn "Warning: XML::LibXML compiled against libxml2 ".LIBXML_VERSION.
      ", but runtime libxml2 is older $runtime_version\n";
  }
}


#-------------------------------------------------------------------------#
# parser flags                                                            #
#-------------------------------------------------------------------------#

# Copied directly from http://xmlsoft.org/html/libxml-parser.html#xmlParserOption
use constant {
  XML_PARSE_RECOVER	  => 1,	       # recover on errors
  XML_PARSE_NOENT	  => 2,	       # substitute entities
  XML_PARSE_DTDLOAD	  => 4,	       # load the external subset
  XML_PARSE_DTDATTR	  => 8,	       # default DTD attributes
  XML_PARSE_DTDVALID	  => 16,       # validate with the DTD
  XML_PARSE_NOERROR	  => 32,       # suppress error reports
  XML_PARSE_NOWARNING	  => 64,       # suppress warning reports
  XML_PARSE_PEDANTIC	  => 128,      # pedantic error reporting
  XML_PARSE_NOBLANKS	  => 256,      # remove blank nodes
  XML_PARSE_SAX1	  => 512,      # use the SAX1 interface internally
  XML_PARSE_XINCLUDE	  => 1024,     # Implement XInclude substitition
  XML_PARSE_NONET	  => 2048,     # Forbid network access
  XML_PARSE_NODICT	  => 4096,     # Do not reuse the context dictionnary
  XML_PARSE_NSCLEAN	  => 8192,     # remove redundant namespaces declarations
  XML_PARSE_NOCDATA	  => 16384,    # merge CDATA as text nodes
  XML_PARSE_NOXINCNODE	  => 32768,    # do not generate XINCLUDE START/END nodes
  XML_PARSE_COMPACT	  => 65536,    # compact small text nodes; no modification of the tree allowed afterwards
                                       # (will possibly crash if you try to modify the tree)
  XML_PARSE_OLD10	  => 131072,   # parse using XML-1.0 before update 5
  XML_PARSE_NOBASEFIX	  => 262144,   # do not fixup XINCLUDE xml#base uris
  XML_PARSE_HUGE	  => 524288,   # relax any hardcoded limit from the parser
  XML_PARSE_OLDSAX	  => 1048576,  # parse using SAX2 interface from before 2.7.0
};

$XML_LIBXML_PARSE_DEFAULTS = ( XML_PARSE_NODICT | XML_PARSE_HUGE | XML_PARSE_DTDLOAD | XML_PARSE_NOENT );

# this hash is made global so that applications can add names for new
# libxml2 parser flags as temporary workaround

%PARSER_FLAGS = (
  recover		 => XML_PARSE_RECOVER,
  expand_entities	 => XML_PARSE_NOENT,
  load_ext_dtd	         => XML_PARSE_DTDLOAD,
  complete_attributes	 => XML_PARSE_DTDATTR,
  validation		 => XML_PARSE_DTDVALID,
  suppress_errors	 => XML_PARSE_NOERROR,
  suppress_warnings	 => XML_PARSE_NOWARNING,
  pedantic_parser	 => XML_PARSE_PEDANTIC,
  no_blanks		 => XML_PARSE_NOBLANKS,
  expand_xinclude	 => XML_PARSE_XINCLUDE,
  xinclude		 => XML_PARSE_XINCLUDE,
  no_network		 => XML_PARSE_NONET,
  clean_namespaces	 => XML_PARSE_NSCLEAN,
  no_cdata		 => XML_PARSE_NOCDATA,
  no_xinclude_nodes	 => XML_PARSE_NOXINCNODE,
  old10		         => XML_PARSE_OLD10,
  no_base_fix		 => XML_PARSE_NOBASEFIX,
  huge		         => XML_PARSE_HUGE,
  oldsax		 => XML_PARSE_OLDSAX,
);

my %OUR_FLAGS = (
  recover => 'XML_LIBXML_RECOVER',
  line_numbers => 'XML_LIBXML_LINENUMBERS',
  URI => 'XML_LIBXML_BASE_URI',
  base_uri => 'XML_LIBXML_BASE_URI',
  gdome => 'XML_LIBXML_GDOME',
  ext_ent_handler => 'ext_ent_handler',
);

sub _parser_options {
  my ($self, $opts) = @_;

  # currently dictionaries break XML::LibXML memory management

  my $flags;

  if (ref($self)) {
    $flags = ($self->{XML_LIBXML_PARSER_OPTIONS}||0);
  } else {
    $flags = $XML_LIBXML_PARSE_DEFAULTS;		# safety precaution
  }

  my ($key, $value);
  while (($key,$value) = each %$opts) {
    my $f = $PARSER_FLAGS{ $key };
    if (defined $f) {
      if ($value) {
	$flags |= $f
      } else {
	$flags &= ~$f;
      }
    } elsif ($key eq 'set_parser_flags') { # this can be used to pass flags XML::LibXML does not yet know about
      $flags |= $value;
    } elsif ($key eq 'unset_parser_flags') {
      $flags &= ~$value;
    }

  }
  return $flags;
}

my %compatibility_flags = (
  XML_LIBXML_VALIDATION => 'validation',
  XML_LIBXML_EXPAND_ENTITIES => 'expand_entities',
  XML_LIBXML_PEDANTIC => 'pedantic_parser',
  XML_LIBXML_NONET => 'no_network',
  XML_LIBXML_EXT_DTD => 'load_ext_dtd',
  XML_LIBXML_COMPLETE_ATTR => 'complete_attributes',
  XML_LIBXML_EXPAND_XINCLUDE => 'expand_xinclude',
  XML_LIBXML_NSCLEAN => 'clean_namespaces',
  XML_LIBXML_KEEP_BLANKS => 'keep_blanks',
  XML_LIBXML_LINENUMBERS => 'line_numbers',
);

#-------------------------------------------------------------------------#
# parser constructor                                                      #
#-------------------------------------------------------------------------#


sub new {
    my $class = shift;
    my $self = bless {
    }, $class;
    if (@_) {
      my %opts = ();
      if (ref($_[0]) eq 'HASH') {
	%opts = %{$_[0]};
      } else {
	# old interface
	my %args = @_;
	%opts=(
	  map {
	    (($compatibility_flags{ $_ }||$_) => $args{ $_ })
	  } keys %args
	);
      }
      # parser flags
      $opts{no_blanks} = !$opts{keep_blanks} if exists($opts{keep_blanks}) and !exists($opts{no_blanks});

      for (keys %OUR_FLAGS) {
	$self->{$OUR_FLAGS{$_}} = delete $opts{$_};
      }
      $class->load_catalog(delete($opts{catalog})) if $opts{catalog};

      $self->{XML_LIBXML_PARSER_OPTIONS} = XML::LibXML->_parser_options(\%opts);

      # store remaining unknown options directly in $self
      for (keys %opts) {
	$self->{$_}=$opts{$_} unless exists $PARSER_FLAGS{$_};
      }
    } else {
      $self->{XML_LIBXML_PARSER_OPTIONS} = $XML_LIBXML_PARSE_DEFAULTS;
    }
    if ( defined $self->{Handler} ) {
      $self->set_handler( $self->{Handler} );
    }

    $self->{_State_} = 0;
    return $self;
}

sub _clone {
  my ($self)=@_;
  my $new = ref($self)->new({
      recover => $self->{XML_LIBXML_RECOVER},
      line_nubers => $self->{XML_LIBXML_LINENUMBERS},
      base_uri => $self->{XML_LIBXML_BASE_URI},
      gdome => $self->{XML_LIBXML_GDOME},
      set_parser_flags => $self->{XML_LIBXML_PARSER_OPTIONS},
    });
  $new->input_callbacks($self->input_callbacks());
  return $new;
}

#-------------------------------------------------------------------------#
# Threads support methods                                                 #
#-------------------------------------------------------------------------#

# threads doc says CLONE's API may change in future, which would break
# an XS method prototype
sub CLONE {
  if ($XML::LibXML::__threads_shared) {
    XML::LibXML::_CLONE( $_[0] );
  }
}

sub CLONE_SKIP {
  return $XML::LibXML::__threads_shared ? 0 : 1;
}

sub __proxy_registry {
  my ($class)=caller;
  die "This version of $class uses API of XML::LibXML 1.66 which is not compatible with XML::LibXML $VERSION. Please upgrade $class!\n";
}

#-------------------------------------------------------------------------#
# DOM Level 2 document constructor                                        #
#-------------------------------------------------------------------------#

sub createDocument {
   my $self = shift;
   if (!@_ or $_[0] =~ m/^\d\.\d$/) {
     # for backward compatibility
     return XML::LibXML::Document->new(@_);
   }
   else {
     # DOM API: createDocument(namespaceURI, qualifiedName, doctype?)
     my $doc = XML::LibXML::Document-> new;
     my $el = $doc->createElementNS(shift, shift);
     $doc->setDocumentElement($el);
     $doc->setExternalSubset(shift) if @_;
     return $doc;
   }
}

#-------------------------------------------------------------------------#
# callback functions                                                      #
#-------------------------------------------------------------------------#

sub externalEntityLoader(&)
{
    return _externalEntityLoader($_[0]);
}

sub input_callbacks {
    my $self     = shift;
    my $icbclass = shift;

    if ( defined $icbclass ) {
        $self->{XML_LIBXML_CALLBACK_STACK} = $icbclass;
    }
    return $self->{XML_LIBXML_CALLBACK_STACK};
}

sub match_callback {
    my $self = shift;
    if ( ref $self ) {
        if ( scalar @_ ) {
            $self->{XML_LIBXML_MATCH_CB} = shift;
            $self->{XML_LIBXML_CALLBACK_STACK} = undef;
        }
        return $self->{XML_LIBXML_MATCH_CB};
    }
    else {
        $MatchCB = shift if scalar @_;
        return $MatchCB;
    }
}

sub read_callback {
    my $self = shift;
    if ( ref $self ) {
        if ( scalar @_ ) {
            $self->{XML_LIBXML_READ_CB} = shift;
            $self->{XML_LIBXML_CALLBACK_STACK} = undef;
        }
        return $self->{XML_LIBXML_READ_CB};
    }
    else {
        $ReadCB = shift if scalar @_;
        return $ReadCB;
    }
}

sub close_callback {
    my $self = shift;
    if ( ref $self ) {
        if ( scalar @_ ) {
            $self->{XML_LIBXML_CLOSE_CB} = shift;
            $self->{XML_LIBXML_CALLBACK_STACK} = undef;
        }
        return $self->{XML_LIBXML_CLOSE_CB};
    }
    else {
        $CloseCB = shift if scalar @_;
        return $CloseCB;
    }
}

sub open_callback {
    my $self = shift;
    if ( ref $self ) {
        if ( scalar @_ ) {
            $self->{XML_LIBXML_OPEN_CB} = shift;
            $self->{XML_LIBXML_CALLBACK_STACK} = undef;
        }
        return $self->{XML_LIBXML_OPEN_CB};
    }
    else {
        $OpenCB = shift if scalar @_;
        return $OpenCB;
    }
}

sub callbacks {
    my $self = shift;
    if ( ref $self ) {
        if (@_) {
            my ($match, $open, $read, $close) = @_;
            @{$self}{qw(XML_LIBXML_MATCH_CB XML_LIBXML_OPEN_CB XML_LIBXML_READ_CB XML_LIBXML_CLOSE_CB)} = ($match, $open, $read, $close);
            $self->{XML_LIBXML_CALLBACK_STACK} = undef;
        }
        else {
            return @{$self}{qw(XML_LIBXML_MATCH_CB XML_LIBXML_OPEN_CB XML_LIBXML_READ_CB XML_LIBXML_CLOSE_CB)};
        }
    }
    else {
        if (@_) {
           ( $MatchCB, $OpenCB, $ReadCB, $CloseCB ) = @_;
        }
        else {
            return ( $MatchCB, $OpenCB, $ReadCB, $CloseCB );
        }
    }
}

#-------------------------------------------------------------------------#
# internal member variable manipulation                                   #
#-------------------------------------------------------------------------#
sub __parser_option {
  my ($self, $opt) = @_;
  if (@_>2) {
    if ($_[2]) {
      $self->{XML_LIBXML_PARSER_OPTIONS} |= $opt;
      return 1;
    } else {
      $self->{XML_LIBXML_PARSER_OPTIONS} &= ~$opt;
      return 0;
    }
  } else {
    return ($self->{XML_LIBXML_PARSER_OPTIONS} & $opt) ? 1 : 0;
  }
}

sub option_exists {
    my ($self,$name)=@_;
    return ($PARSER_FLAGS{$name} || $OUR_FLAGS{$name}) ? 1 : 0;
}
sub get_option {
    my ($self,$name)=@_;
    my $flag = $OUR_FLAGS{$name};
    return $self->{$flag} if $flag;
    $flag = $PARSER_FLAGS{$name};
    return $self->__parser_option($flag) if $flag;
    warn "XML::LibXML::get_option: unknown parser option $name\n";
    return undef;
}
sub set_option {
    my ($self,$name,$value)=@_;
    my $flag = $OUR_FLAGS{$name};
    return ($self->{$flag}=$value) if $flag;
    $flag = $PARSER_FLAGS{$name};
    return $self->__parser_option($flag,$value) if $flag;
    warn "XML::LibXML::get_option: unknown parser option $name\n";
    return undef;
}
sub set_options {
  my $self=shift;
  my $opts;
  if (@_==1 and ref($_[0]) eq 'HASH') {
    $opts = $_[0];
  } elsif (@_ % 2 == 0) {
    $opts={@_};
  } else {
    croak("Odd number of elements passed to set_options");
  }
  $self->set_option($_=>$opts->{$_}) foreach keys %$opts;
  return;
}

sub validation {
    my $self = shift;
    return $self->__parser_option(XML_PARSE_DTDVALID,@_);
}

sub recover {
    my $self = shift;
    if (scalar @_) {
      $self->{XML_LIBXML_RECOVER} = $_[0];
      $self->__parser_option(XML_PARSE_RECOVER,@_);
    }
    return $self->{XML_LIBXML_RECOVER};
}

sub recover_silently {
    my $self = shift;
    my $arg = shift;
    (($arg == 1) ? $self->recover(2) : $self->recover($arg)) if defined($arg);
    return (($self->recover()||0) == 2) ? 1 : 0;
}

sub expand_entities {
    my $self = shift;
    if (scalar(@_) and $_[0]) {
      return $self->__parser_option(XML_PARSE_NOENT | XML_PARSE_DTDLOAD,1);
    }
    return $self->__parser_option(XML_PARSE_NOENT,@_);
}

sub keep_blanks {
    my $self = shift;
    my @args; # we have to negate the argument and return negated value, since
              # the actual flag is no_blanks
    if (scalar @_) {
      @args=($_[0] ? 0 : 1);
    }
    return $self->__parser_option(XML_PARSE_NOBLANKS,@args) ? 0 : 1;
}

sub pedantic_parser {
    my $self = shift;
    return $self->__parser_option(XML_PARSE_PEDANTIC,@_);
}

sub line_numbers {
    my $self = shift;
    $self->{XML_LIBXML_LINENUMBERS} = shift if scalar @_;
    return $self->{XML_LIBXML_LINENUMBERS};
}

sub no_network {
    my $self = shift;
    return $self->__parser_option(XML_PARSE_NONET,@_);
}

sub load_ext_dtd {
    my $self = shift;
    return $self->__parser_option(XML_PARSE_DTDLOAD,@_);
}

sub complete_attributes {
    my $self = shift;
    return $self->__parser_option(XML_PARSE_DTDATTR,@_);
}

sub expand_xinclude  {
    my $self = shift;
    return $self->__parser_option(XML_PARSE_XINCLUDE,@_);
}

sub base_uri {
    my $self = shift;
    $self->{XML_LIBXML_BASE_URI} = shift if scalar @_;
    return $self->{XML_LIBXML_BASE_URI};
}

sub gdome_dom {
    my $self = shift;
    $self->{XML_LIBXML_GDOME} = shift if scalar @_;
    return $self->{XML_LIBXML_GDOME};
}

sub clean_namespaces {
    my $self = shift;
    return $self->__parser_option(XML_PARSE_NSCLEAN,@_);
}

#-------------------------------------------------------------------------#
# set the optional SAX(2) handler                                         #
#-------------------------------------------------------------------------#
sub set_handler {
    my $self = shift;
    if ( defined $_[0] ) {
        $self->{HANDLER} = $_[0];

        $self->{SAX_ELSTACK} = [];
        $self->{SAX} = {State => 0};
    }
    else {
        # undef SAX handling
        $self->{SAX_ELSTACK} = [];
        delete $self->{HANDLER};
        delete $self->{SAX};
    }
}

#-------------------------------------------------------------------------#
# helper functions                                                        #
#-------------------------------------------------------------------------#
sub _auto_expand {
    my ( $self, $result, $uri ) = @_;

    $result->setBaseURI( $uri ) if defined $uri;

    if ( $self->expand_xinclude ) {
        $self->{_State_} = 1;
        eval { $self->processXIncludes($result); };
        my $err = $@;
        $self->{_State_} = 0;
        if ($err) {
            $self->_cleanup_callbacks();
            $result = undef;
            croak $err;
        }
    }
    return $result;
}

sub _init_callbacks {
    my $self = shift;
    my $icb = $self->{XML_LIBXML_CALLBACK_STACK};
    unless ( defined $icb ) {
        $self->{XML_LIBXML_CALLBACK_STACK} = XML::LibXML::InputCallback->new();
        $icb = $self->{XML_LIBXML_CALLBACK_STACK};
    }

    $icb->init_callbacks($self);
}

sub _cleanup_callbacks {
    my $self = shift;
    $self->{XML_LIBXML_CALLBACK_STACK}->cleanup_callbacks();
}

sub __read {
    read($_[0], $_[1], $_[2]);
}

sub __write {
    if ( ref( $_[0] ) ) {
        $_[0]->write( $_[1], $_[2] );
    }
    else {
        $_[0]->write( $_[1] );
    }
}

sub load_xml {
  my $class_or_self = shift;
  my %args = map { ref($_) eq 'HASH' ? (%$_) : $_ } @_;

  my $URI = delete($args{URI});
  $URI = "$URI"  if defined $URI; # stringify in case it is an URI object
  my $parser;
  if (ref($class_or_self)) {
    $parser = $class_or_self->_clone();
    $parser->{XML_LIBXML_PARSER_OPTIONS} = $parser->_parser_options(\%args);
  } else {
    $parser = $class_or_self->new(\%args);
  }
  my $dom;
  if ( defined $args{location} ) {
    $dom = $parser->parse_file( "$args{location}" );
  }
  elsif ( defined $args{string} ) {
    $dom = $parser->parse_string( $args{string}, $URI );
  }
  elsif ( defined $args{IO} ) {
    $dom = $parser->parse_fh( $args{IO}, $URI );
  }
  else {
    croak("XML::LibXML->load: specify location, string, or IO");
  }
  return $dom;
}

sub load_html {
  my ($class_or_self) = shift;
  my %args = map { ref($_) eq 'HASH' ? (%$_) : $_ } @_;
  my $URI = delete($args{URI});
  $URI = "$URI"  if defined $URI; # stringify in case it is an URI object
  my $parser;
  if (ref($class_or_self)) {
    $parser = $class_or_self->_clone();
  } else {
    $parser = $class_or_self->new();
  }
  my $dom;
  if ( defined $args{location} ) {
    $dom = $parser->parse_html_file( "$args{location}", \%args );
  }
  elsif ( defined $args{string} ) {
    $dom = $parser->parse_html_string( $args{string}, \%args );
  }
  elsif ( defined $args{IO} ) {
    $dom = $parser->parse_html_fh( $args{IO}, \%args );
  }
  else {
    croak("XML::LibXML->load: specify location, string, or IO");
  }
  return $dom;
}

#-------------------------------------------------------------------------#
# parsing functions                                                       #
#-------------------------------------------------------------------------#
# all parsing functions handle normal as SAX parsing at the same time.
# note that SAX parsing is handled incomplete! use XML::LibXML::SAX for
# complete parsing sequences
#-------------------------------------------------------------------------#
sub parse_string {
    my $self = shift;
    croak("parse_string is not a class method! Create a parser object with XML::LibXML->new first!") unless ref $self;
    croak("parse already in progress") if $self->{_State_};

    unless ( defined $_[0] and length $_[0] ) {
        croak("Empty String");
    }

    $self->{_State_} = 1;
    my $result;

    $self->_init_callbacks();

    if ( defined $self->{SAX} ) {
        my $string = shift;
        $self->{SAX_ELSTACK} = [];
        eval { $result = $self->_parse_sax_string($string); };
        my $err = $@;
        $self->{_State_} = 0;
        if ($err) {
            chomp $err unless ref $err;
            $self->_cleanup_callbacks();
            croak $err;
        }
    }
    else {
        eval { $result = $self->_parse_string( @_ ); };

        my $err = $@;
        $self->{_State_} = 0;
        if ($err) {
            chomp $err unless ref $err;
            $self->_cleanup_callbacks();
            croak $err;
        }

        $result = $self->_auto_expand( $result, $self->{XML_LIBXML_BASE_URI} );
    }
    $self->_cleanup_callbacks();

    return $result;
}

sub parse_fh {
    my $self = shift;
    croak("parse_fh is not a class method! Create a parser object with XML::LibXML->new first!") unless ref $self;
    croak("parse already in progress") if $self->{_State_};
    $self->{_State_} = 1;
    my $result;

    $self->_init_callbacks();

    if ( defined $self->{SAX} ) {
        $self->{SAX_ELSTACK} = [];
        eval { $self->_parse_sax_fh( @_ );  };
        my $err = $@;
        $self->{_State_} = 0;
        if ($err) {
	    chomp $err unless ref $err;
            $self->_cleanup_callbacks();
            croak $err;
        }
    }
    else {
        eval { $result = $self->_parse_fh( @_ ); };
        my $err = $@;
        $self->{_State_} = 0;
        if ($err) {
	    chomp $err unless ref $err;
            $self->_cleanup_callbacks();
            croak $err;
        }

        $result = $self->_auto_expand( $result, $self->{XML_LIBXML_BASE_URI} );
    }

    $self->_cleanup_callbacks();

    return $result;
}

sub parse_file {
    my $self = shift;
    croak("parse_file is not a class method! Create a parser object with XML::LibXML->new first!") unless ref $self;
    croak("parse already in progress") if $self->{_State_};

    $self->{_State_} = 1;
    my $result;

    $self->_init_callbacks();

    if ( defined $self->{SAX} ) {
        $self->{SAX_ELSTACK} = [];
        eval { $self->_parse_sax_file( @_ );  };
        my $err = $@;
        $self->{_State_} = 0;
        if ($err) {
	    chomp $err unless ref $err;
            $self->_cleanup_callbacks();
            croak $err;
        }
    }
    else {
        eval { $result = $self->_parse_file(@_); };
        my $err = $@;
        $self->{_State_} = 0;
        if ($err) {
	    chomp $err unless ref $err;
            $self->_cleanup_callbacks();
            croak $err;
        }

        $result = $self->_auto_expand( $result );
    }
    $self->_cleanup_callbacks();

    return $result;
}

sub parse_xml_chunk {
    my $self = shift;
    # max 2 parameter:
    # 1: the chunk
    # 2: the encoding of the string
    croak("parse_xml_chunk is not a class method! Create a parser object with XML::LibXML->new first!") unless ref $self;
    croak("parse already in progress") if $self->{_State_};    my $result;

    unless ( defined $_[0] and length $_[0] ) {
        croak("Empty String");
    }

    $self->{_State_} = 1;

    $self->_init_callbacks();

    if ( defined $self->{SAX} ) {
        eval {
            $self->_parse_sax_xml_chunk( @_ );

            # this is required for XML::GenericChunk.
            # in normal case is_filter is not defined, an thus the parsing
            # will be terminated. in case of a SAX filter the parsing is not
            # finished at that state. therefore we must not reset the parsing
            unless ( $self->{IS_FILTER} ) {
	      $result = $self->{HANDLER}->end_document();
	    }
        };
    }
    else {
        eval { $result = $self->_parse_xml_chunk( @_ ); };
    }

    $self->_cleanup_callbacks();

    my $err = $@;
    $self->{_State_} = 0;
    if ($err) {
        chomp $err unless ref $err;
        croak $err;
    }

    return $result;
}

sub parse_balanced_chunk {
    my $self = shift;
    $self->_init_callbacks();
    my $rv;
    eval {
        $rv = $self->parse_xml_chunk( @_ );
    };
    my $err = $@;
    $self->_cleanup_callbacks();
    if ( $err ) {
        chomp $err unless ref $err;
        croak $err;
    }
    return $rv
}

# java style
sub processXIncludes {
    my $self = shift;
    my $doc = shift;
    my $opts = shift;
    my $options = $self->_parser_options($opts);
    if ( $self->{_State_} != 1 ) {
        $self->_init_callbacks();
    }
    my $rv;
    eval {
        $rv = $self->_processXIncludes($doc || " ", $options);
    };
    my $err = $@;
    if ( $self->{_State_} != 1 ) {
        $self->_cleanup_callbacks();
    }

    if ( $err ) {
        chomp $err unless ref $err;
        croak $err;
    }
    return $rv;
}

# perl style
sub process_xincludes {
    my $self = shift;
    my $doc = shift;
    my $opts = shift;
    my $options = $self->_parser_options($opts);

    my $rv;
    $self->_init_callbacks();
    eval {
        $rv = $self->_processXIncludes($doc || " ", $options);
    };
    my $err = $@;
    $self->_cleanup_callbacks();
    if ( $err ) {
        chomp $err unless ref $err;
        croak $@;
    }
    return $rv;
}

#-------------------------------------------------------------------------#
# HTML parsing functions                                                  #
#-------------------------------------------------------------------------#

sub _html_options {
  my ($self,$opts)=@_;
  $opts = {} unless ref $opts;
  #  return (undef,undef) unless ref $opts;
  my $flags = 0;
  $flags |=     1 if exists $opts->{recover} ? $opts->{recover} : $self->recover;
  $flags |=     4 if $opts->{no_defdtd}; # default is ON: injects DTD as needed
  $flags |=    32 if exists $opts->{suppress_errors} ? $opts->{suppress_errors} : $self->get_option('suppress_errors');
  # This is to fix https://rt.cpan.org/Ticket/Display.html?id=58024 :
  # <quote> 
  # In XML::LibXML, warnings are not suppressed when specifying the recover
  # or recover_silently flags as per the following excerpt from the manpage:
  # </quote>
  if ($self->recover_silently)
  {
      $flags |= 32;
  }
  $flags |=    64 if $opts->{suppress_warnings};
  $flags |=   128 if exists $opts->{pedantic_parser} ? $opts->{pedantic_parser} : $self->pedantic_parser;
  $flags |=   256 if exists $opts->{no_blanks} ? $opts->{no_blanks} : !$self->keep_blanks;
  $flags |=  2048 if exists $opts->{no_network} ? $opts->{no_network} : !$self->no_network;
  $flags |= 16384 if $opts->{no_cdata};
  $flags |= 65536 if $opts->{compact}; # compact small text nodes; no modification
                                         # of the tree allowed afterwards
                                         # (WILL possibly CRASH IF YOU try to MODIFY THE TREE)
  $flags |= 524288 if $opts->{huge}; # relax any hardcoded limit from the parser
  $flags |= 1048576 if $opts->{oldsax}; # parse using SAX2 interface from before 2.7.0

  return ($opts->{URI},$opts->{encoding},$flags);
}

sub parse_html_string {
    my ($self,$str,$opts) = @_;
    croak("parse_html_string is not a class method! Create a parser object with XML::LibXML->new first!") unless ref $self;
    croak("parse already in progress") if $self->{_State_};

    unless ( defined $str and length $str ) {
        croak("Empty String");
    }
    $self->{_State_} = 1;
    my $result;

    $self->_init_callbacks();
    eval { 
      $result = $self->_parse_html_string( $str,
					   $self->_html_options($opts)
					  ); 
    };
    my $err = $@;
    $self->{_State_} = 0;
    if ($err) {
      chomp $err unless ref $err;
      $self->_cleanup_callbacks();
      croak $err;
    }

    $self->_cleanup_callbacks();

    return $result;
}

sub parse_html_file {
    my ($self,$file,$opts) = @_;
    croak("parse_html_file is not a class method! Create a parser object with XML::LibXML->new first!") unless ref $self;
    croak("parse already in progress") if $self->{_State_};
    $self->{_State_} = 1;
    my $result;

    $self->_init_callbacks();
    eval { $result = $self->_parse_html_file($file,
					     $self->_html_options($opts)
					    ); };
    my $err = $@;
    $self->{_State_} = 0;
    if ($err) {
      chomp $err unless ref $err;
      $self->_cleanup_callbacks();
      croak $err;
    }
    
    $self->_cleanup_callbacks();

    return $result;
}

sub parse_html_fh {
    my ($self,$fh,$opts) = @_;
    croak("parse_html_fh is not a class method! Create a parser object with XML::LibXML->new first!") unless ref $self;
    croak("parse already in progress") if $self->{_State_};
    $self->{_State_} = 1;

    my $result;
    $self->_init_callbacks();
    eval { $result = $self->_parse_html_fh( $fh, 
					    $self->_html_options($opts)
					   ); };
    my $err = $@;
    $self->{_State_} = 0;
    if ($err) {
      chomp $err unless ref $err;
      $self->_cleanup_callbacks();
      croak $err;
    }
    $self->_cleanup_callbacks();

    return $result;
}

#-------------------------------------------------------------------------#
# push parser interface                                                   #
#-------------------------------------------------------------------------#
sub init_push {
    my $self = shift;

    if ( defined $self->{CONTEXT} ) {
        delete $self->{CONTEXT};
    }

    if ( defined $self->{SAX} ) {
        $self->{CONTEXT} = $self->_start_push(1);
    }
    else {
        $self->{CONTEXT} = $self->_start_push(0);
    }
}

sub push {
    my $self = shift;

    $self->_init_callbacks();
    
    if ( not defined $self->{CONTEXT} ) {
        $self->init_push();
    }

    eval {
        foreach ( @_ ) {
            $self->_push( $self->{CONTEXT}, $_ );
        }
    };
    my $err = $@;
    $self->_cleanup_callbacks();
    if ( $err ) {
        chomp $err unless ref $err;
        croak $err;
    }
}

# this function should be promoted!
# the reason is because libxml2 uses xmlParseChunk() for this purpose!
sub parse_chunk {
    my $self = shift;
    my $chunk = shift;
    my $terminate = shift;

    if ( not defined $self->{CONTEXT} ) {
        $self->init_push();
    }

    if ( defined $chunk and length $chunk ) {
        $self->_push( $self->{CONTEXT}, $chunk );
    }

    if ( $terminate ) {
        return $self->finish_push();
    }
}


sub finish_push {
    my $self = shift;
    my $restore = shift || 0;
    return undef unless defined $self->{CONTEXT};

    my $retval;

    if ( defined $self->{SAX} ) {
        eval {
            $self->_end_sax_push( $self->{CONTEXT} );
            $retval = $self->{HANDLER}->end_document( {} );
        };
    }
    else {
        eval { $retval = $self->_end_push( $self->{CONTEXT}, $restore ); };
    }
    my $err = $@;
    delete $self->{CONTEXT};
    if ( $err ) {
        chomp $err unless ref $err;
        croak( $err );
    }
    return $retval;
}

1;

#-------------------------------------------------------------------------#
# XML::LibXML::Node Interface                                             #
#-------------------------------------------------------------------------#
package XML::LibXML::Node;

use overload
    '""'   => sub { $_[0]->toString() },
    'bool' => sub { 1 },
    '0+'   => sub { Scalar::Util::refaddr($_[0]) },
    fallback => 1,
    ;


sub CLONE_SKIP {
  return $XML::LibXML::__threads_shared ? 0 : 1;
}

sub isSupported {
    my $self    = shift;
    my $feature = shift;
    return $self->can($feature) ? 1 : 0;
}

sub getChildNodes { my $self = shift; return $self->childNodes(); }

sub childNodes {
    my $self = shift;
    my @children = $self->_childNodes(0);
    return wantarray ? @children : XML::LibXML::NodeList->new_from_ref(\@children , 1);
}

sub nonBlankChildNodes {
    my $self = shift;
    my @children = $self->_childNodes(1);
    return wantarray ? @children : XML::LibXML::NodeList->new_from_ref(\@children , 1);
}

sub attributes {
    my $self = shift;
    my @attr = $self->_attributes();
    return wantarray ? @attr : XML::LibXML::NamedNodeMap->new( @attr );
}


sub findnodes {
    my ($node, $xpath) = @_;
    my @nodes = $node->_findnodes($xpath);
    if (wantarray) {
        return @nodes;
    }
    else {
        return XML::LibXML::NodeList->new_from_ref(\@nodes, 1);
    }
}

sub exists {
    my ($node, $xpath) = @_;
    my (undef, $value) = $node->_find($xpath,1);
    return $value;
}

sub findvalue {
    my ($node, $xpath) = @_;
    my $res;
    $res = $node->find($xpath);
    return $res->to_literal->value;
}

sub findbool {
    my ($node, $xpath) = @_;
    my ($type, @params) = $node->_find($xpath,1);
    if ($type) {
        return $type->new(@params);
    }
    return undef;
}

sub find {
    my ($node, $xpath) = @_;
    my ($type, @params) = $node->_find($xpath,0);
    if ($type) {
        return $type->new(@params);
    }
    return undef;
}

sub setOwnerDocument {
    my ( $self, $doc ) = @_;
    $doc->adoptNode( $self );
}

sub toStringC14N {
    my ($self, $comments, $xpath, $xpc) = @_;
    return $self->_toStringC14N( $comments || 0,
				 (defined $xpath ? $xpath : undef),
				 0,
				 undef,
				 (defined $xpc ? $xpc : undef)
				);
}
sub toStringEC14N {
    my ($self, $comments, $xpath, $xpc, $inc_prefix_list) = @_;
    unless (UNIVERSAL::isa($xpc,'XML::LibXML::XPathContext')) {
      if ($inc_prefix_list) {
	croak("toStringEC14N: 3rd argument is not an XML::LibXML::XPathContext");
      } else {
	$inc_prefix_list=$xpc;
	$xpc=undef;
      }
    }
    if (defined($inc_prefix_list) and !UNIVERSAL::isa($inc_prefix_list,'ARRAY')) {
      croak("toStringEC14N: inclusive_prefix_list must be undefined or ARRAY");
    }
    return $self->_toStringC14N( $comments || 0,
				 (defined $xpath ? $xpath : undef),
				 1,
				 (defined $inc_prefix_list ? $inc_prefix_list : undef),
				 (defined $xpc ? $xpc : undef)
				);
}

*serialize_c14n = \&toStringC14N;
*serialize_exc_c14n = \&toStringEC14N;

1;

#-------------------------------------------------------------------------#
# XML::LibXML::Document Interface                                         #
#-------------------------------------------------------------------------#
package XML::LibXML::Document;

use vars qw(@ISA);
@ISA = ('XML::LibXML::Node');

sub actualEncoding {
  my $doc = shift;
  my $enc = $doc->encoding;
  return (defined $enc and length $enc) ? $enc : 'UTF-8';
}

sub setDocumentElement {
    my $doc = shift;
    my $element = shift;

    my $oldelem = $doc->documentElement;
    if ( defined $oldelem ) {
        $doc->removeChild($oldelem);
    }

    $doc->_setDocumentElement($element);
}

sub toString {
    my $self = shift;
    my $flag = shift;

    my $retval = "";

    if ( defined $XML::LibXML::skipXMLDeclaration
         and $XML::LibXML::skipXMLDeclaration == 1 ) {
        foreach ( $self->childNodes ){
            next if $_->nodeType == XML::LibXML::XML_DTD_NODE()
                    and $XML::LibXML::skipDTD;
            $retval .= $_->toString;
        }
    }
    else {
        $flag ||= 0 unless defined $flag;
        $retval =  $self->_toString($flag);
    }

    return $retval;
}

sub serialize {
    my $self = shift;
    return $self->toString( @_ );
}

#-------------------------------------------------------------------------#
# bad style xinclude processing                                           #
#-------------------------------------------------------------------------#
sub process_xinclude {
    my $self = shift;
    my $opts = shift;
    XML::LibXML->new->processXIncludes( $self, $opts );
}

sub insertProcessingInstruction {
    my $self   = shift;
    my $target = shift;
    my $data   = shift;

    my $pi     = $self->createPI( $target, $data );
    my $root   = $self->documentElement;

    if ( defined $root ) {
        # this is actually not correct, but i guess it's what the user
        # intends
        $self->insertBefore( $pi, $root );
    }
    else {
        # if no documentElement was found we just append the PI
        $self->appendChild( $pi );
    }
}

sub insertPI {
    my $self = shift;
    $self->insertProcessingInstruction( @_ );
}

#-------------------------------------------------------------------------#
# DOM L3 Document functions.
# added after robins implicit feature requst
#-------------------------------------------------------------------------#
*getElementsByTagName = \&XML::LibXML::Element::getElementsByTagName;
*getElementsByTagNameNS = \&XML::LibXML::Element::getElementsByTagNameNS;
*getElementsByLocalName = \&XML::LibXML::Element::getElementsByLocalName;

1;

#-------------------------------------------------------------------------#
# XML::LibXML::DocumentFragment Interface                                 #
#-------------------------------------------------------------------------#
package XML::LibXML::DocumentFragment;

use vars qw(@ISA);
@ISA = ('XML::LibXML::Node');

sub toString {
    my $self = shift;
    my $retval = "";
    if ( $self->hasChildNodes() ) {
        foreach my $n ( $self->childNodes() ) {
            $retval .= $n->toString(@_);
        }
    }
    return $retval;
}

*serialize = \&toString;

1;

#-------------------------------------------------------------------------#
# XML::LibXML::Element Interface                                          #
#-------------------------------------------------------------------------#
package XML::LibXML::Element;

use vars qw(@ISA);
@ISA = ('XML::LibXML::Node');
use XML::LibXML qw(:ns :libxml);
use XML::LibXML::AttributeHash;
use Carp;

use Scalar::Util qw(blessed);

use overload
    '%{}'  => 'getAttributeHash',
    'eq' => '_isSameNodeLax', '==' => '_isSameNodeLax',
    'ne' => '_isNotSameNodeLax', '!=' => '_isNotSameNodeLax',
    fallback => 1,
    ;

sub _isNotSameNodeLax {
    my ($self, $other) = @_;

    return ((not $self->_isSameNodeLax($other)) ? 1 : '');
}

sub _isSameNodeLax { 
    my ($self, $other) = @_;

    if (blessed($other) and $other->isa('XML::LibXML::Element')) 
    { 
        return ($self->isSameNode($other) ? 1 : ''); 
    }
    else
    {
        return '';
    }
}

{
    my %tiecache;

    sub __destroy_tiecache
    {
        delete $tiecache{ 0+$_[0] };
    }

    sub getAttributeHash
    {
        my $self = shift;
        if (!exists $tiecache{ 0+$self }) {
            tie my %attr, 'XML::LibXML::AttributeHash', $self, weaken => 1;
            $tiecache{ 0+$self } = \%attr;
        }
        return $tiecache{ 0+$self };
    }
    sub DESTROY
    {
        my ($self) = @_;
        $self->__destroy_tiecache;
        $self->SUPER::DESTROY;
    }
}

sub setNamespace {
    my $self = shift;
    my $n = $self->nodeName;
    if ( $self->_setNamespace(@_) ){
        if ( scalar @_ < 3 || $_[2] == 1 ){
            $self->setNodeName( $n );
        }
        return 1;
    }
    return 0;
}

sub getAttribute {
    my $self = shift;
    my $name = $_[0];
    if ( $name =~ /^xmlns(?::|$)/ ) {
        # user wants to get a namespace ...
        (my $prefix = $name )=~s/^xmlns:?//;
	$self->_getNamespaceDeclURI($prefix);
    }
    else {
        $self->_getAttribute(@_);
    }
}

sub setAttribute {
    my ( $self, $name, $value ) = @_;
    if ( $name =~ /^xmlns(?::|$)/ ) {
      # user wants to set the special attribute for declaring XML namespace ...

      # this is fine but not exactly DOM conformant behavior, btw (according to DOM we should
      # probably declare an attribute which looks like XML namespace declaration
      # but isn't)
      (my $nsprefix = $name )=~s/^xmlns:?//;
      my $nn = $self->nodeName;
      if ( $nn =~ /^\Q${nsprefix}\E:/ ) {
	# the element has the same prefix
	$self->setNamespaceDeclURI($nsprefix,$value) ||
	  $self->setNamespace($value,$nsprefix,1);
        ##
        ## We set the namespace here.
        ## This is helpful, as in:
        ##
        ## |  $e = XML::LibXML::Element->new('foo:bar');
        ## |  $e->setAttribute('xmlns:foo','http://yoyodine')
        ##
      }
      else {
	# just modify the namespace
	$self->setNamespaceDeclURI($nsprefix, $value) ||
	  $self->setNamespace($value,$nsprefix,0);
      }
    }
    else {
        $self->_setAttribute($name, $value);
    }
}

sub getAttributeNS {
    my $self = shift;
    my ($nsURI, $name) = @_;
    croak("invalid attribute name") if !defined($name) or $name eq q{};
    if ( defined($nsURI) and $nsURI eq XML_XMLNS_NS ) {
	$self->_getNamespaceDeclURI($name eq 'xmlns' ? undef : $name);
    }
    else {
        $self->_getAttributeNS(@_);
    }
}

sub setAttributeNS {
  my ($self, $nsURI, $qname, $value)=@_;
  unless (defined $qname and length $qname) {
    croak("bad name");
  }
  if (defined($nsURI) and $nsURI eq XML_XMLNS_NS) {
    if ($qname !~ /^xmlns(?::|$)/) {
      croak("NAMESPACE ERROR: Namespace declarations must have the prefix 'xmlns'");
    }
    $self->setAttribute($qname,$value); # see implementation above
    return;
  }
  if ($qname=~/:/ and not (defined($nsURI) and length($nsURI))) {
    croak("NAMESPACE ERROR: Attribute without a prefix cannot be in a namespace");
  }
  if ($qname=~/^xmlns(?:$|:)/) {
    croak("NAMESPACE ERROR: 'xmlns' prefix and qualified-name are reserved for the namespace ".XML_XMLNS_NS);
  }
  if ($qname=~/^xml:/ and not (defined $nsURI and $nsURI eq XML_XML_NS)) {
    croak("NAMESPACE ERROR: 'xml' prefix is reserved for the namespace ".XML_XML_NS);
  }
  $self->_setAttributeNS( defined $nsURI ? $nsURI : undef, $qname, $value );
}

sub getElementsByTagName {
    my ( $node , $name ) = @_;
    my $xpath = $name eq '*' ? "descendant::*" : "descendant::*[name()='$name']";
    my @nodes = $node->_findnodes($xpath);
    return wantarray ? @nodes : XML::LibXML::NodeList->new_from_ref(\@nodes, 1);
}

sub  getElementsByTagNameNS {
    my ( $node, $nsURI, $name ) = @_;
    my $xpath;
    if ( $name eq '*' ) {
      if ( $nsURI eq '*' ) {
	$xpath = "descendant::*";
      } else {
	$xpath = "descendant::*[namespace-uri()='$nsURI']";
      }
    } elsif ( $nsURI eq '*' ) {
      $xpath = "descendant::*[local-name()='$name']";
    } else {
      $xpath = "descendant::*[local-name()='$name' and namespace-uri()='$nsURI']";
    }
    my @nodes = $node->_findnodes($xpath);
    return wantarray ? @nodes : XML::LibXML::NodeList->new_from_ref(\@nodes, 1);
}

sub getElementsByLocalName {
    my ( $node,$name ) = @_;
    my $xpath;
    if ($name eq '*') {
      $xpath = "descendant::*";
    } else {
      $xpath = "descendant::*[local-name()='$name']";
    }
    my @nodes = $node->_findnodes($xpath);
    return wantarray ? @nodes : XML::LibXML::NodeList->new_from_ref(\@nodes, 1);
}

sub getChildrenByTagName {
    my ( $node, $name ) = @_;
    my @nodes;
    if ($name eq '*') {
      @nodes = grep { $_->nodeType == XML_ELEMENT_NODE() }
	$node->childNodes();
    } else {
      @nodes = grep { $_->nodeName eq $name } $node->childNodes();
    }
    return wantarray ? @nodes : XML::LibXML::NodeList->new_from_ref(\@nodes, 1);
}

sub getChildrenByLocalName {
    my ( $node, $name ) = @_;
    # my @nodes;
    # if ($name eq '*') {
    #   @nodes = grep { $_->nodeType == XML_ELEMENT_NODE() }
    # 	$node->childNodes();
    # } else {
    #   @nodes = grep { $_->nodeType == XML_ELEMENT_NODE() and
    # 		      $_->localName eq $name } $node->childNodes();
    # }
    # return wantarray ? @nodes : XML::LibXML::NodeList->new_from_ref(\@nodes, 1);
    my @nodes = $node->_getChildrenByTagNameNS('*',$name);
    return wantarray ? @nodes : XML::LibXML::NodeList->new_from_ref(\@nodes, 1);
}

sub getChildrenByTagNameNS {
    my ( $node, $nsURI, $name ) = @_;
    my @nodes = $node->_getChildrenByTagNameNS($nsURI,$name);
    return wantarray ? @nodes : XML::LibXML::NodeList->new_from_ref(\@nodes, 1);
}

sub appendWellBalancedChunk {
    my ( $self, $chunk ) = @_;

    my $local_parser = XML::LibXML->new();
    my $frag = $local_parser->parse_xml_chunk( $chunk );

    $self->appendChild( $frag );
}

1;

#-------------------------------------------------------------------------#
# XML::LibXML::Text Interface                                             #
#-------------------------------------------------------------------------#
package XML::LibXML::Text;

use vars qw(@ISA);
@ISA = ('XML::LibXML::Node');

sub attributes { return undef; }

sub deleteDataString {
    my ($node, $string, $all) = @_;

    return $node->replaceDataString($string, '', $all);
}

sub replaceDataString {
    my ( $node, $left_proto, $right,$all ) = @_;

    # Assure we exchange the strings and not expressions!
    my $left = quotemeta($left_proto);

    my $datastr = $node->nodeValue();
    if ( $all ) {
        $datastr =~ s/$left/$right/g;
    }
    else{
        $datastr =~ s/$left/$right/;
    }
    $node->setData( $datastr );
}

sub replaceDataRegEx {
    my ( $node, $leftre, $rightre, $flags ) = @_;
    return unless defined $leftre;
    $rightre ||= "";

    my $datastr = $node->nodeValue();
    my $restr   = "s/" . $leftre . "/" . $rightre . "/";
    $restr .= $flags if defined $flags;

    eval '$datastr =~ '. $restr;

    $node->setData( $datastr );
}

1;

package XML::LibXML::Comment;

use vars qw(@ISA);
@ISA = ('XML::LibXML::Text');

1;

package XML::LibXML::CDATASection;

use vars qw(@ISA);
@ISA     = ('XML::LibXML::Text');

1;

#-------------------------------------------------------------------------#
# XML::LibXML::Attribute Interface                                        #
#-------------------------------------------------------------------------#
package XML::LibXML::Attr;
use vars qw( @ISA ) ;
@ISA = ('XML::LibXML::Node') ;

sub setNamespace {
    my ($self,$href,$prefix) = @_;
    my $n = $self->nodeName;
    if ( $self->_setNamespace($href,$prefix) ) {
        $self->setNodeName($n);
        return 1;
    }

    return 0;
}

1;

#-------------------------------------------------------------------------#
# XML::LibXML::Dtd Interface                                              #
#-------------------------------------------------------------------------#
# this is still under construction
#
package XML::LibXML::Dtd;
use vars qw( @ISA );
@ISA = ('XML::LibXML::Node');

# at least DESTROY and CLONE_SKIP must be inherited

1;

#-------------------------------------------------------------------------#
# XML::LibXML::PI Interface                                               #
#-------------------------------------------------------------------------#
package XML::LibXML::PI;
use vars qw( @ISA );
@ISA = ('XML::LibXML::Node');

sub setData {
    my $pi = shift;

    my $string = "";
    if ( scalar @_ == 1 ) {
        $string = shift;
    }
    else {
        my %h = @_;
        $string = join " ", map {$_.'="'.$h{$_}.'"'} keys %h;
    }

    # the spec says any char but "?>" [17]
    $pi->_setData( $string ) unless  $string =~ /\?>/;
}

1;

#-------------------------------------------------------------------------#
# XML::LibXML::Namespace Interface                                        #
#-------------------------------------------------------------------------#
package XML::LibXML::Namespace;

sub CLONE_SKIP { 1 }

# this is infact not a node!
sub prefix { return "xmlns"; }
sub getPrefix { return "xmlns"; }
sub getNamespaceURI { return "http://www.w3.org/2000/xmlns/" };

sub getNamespaces { return (); }

sub nodeName {
  my $self = shift;
  my $nsP  = $self->localname;
  return ( defined($nsP) && length($nsP) ) ? "xmlns:$nsP" : "xmlns";
}
sub name    { goto &nodeName }
sub getName { goto &nodeName }

sub isEqualNode {
    my ( $self, $ref ) = @_;
    if ( ref($ref) eq "XML::LibXML::Namespace" ) {
        return $self->_isEqual($ref);
    }
    return 0;
}

sub isSameNode {
    my ( $self, $ref ) = @_;
    if ( $$self == $$ref ){
        return 1;
    }
    return 0;
}

1;

#-------------------------------------------------------------------------#
# XML::LibXML::NamedNodeMap Interface                                     #
#-------------------------------------------------------------------------#
package XML::LibXML::NamedNodeMap;

use XML::LibXML qw(:libxml);

sub CLONE_SKIP {
  return $XML::LibXML::__threads_shared ? 0 : 1;
}

sub new {
    my $class = shift;
    my $self = bless { Nodes => [@_] }, $class;
    $self->{NodeMap} = { map { $_->nodeName => $_ } @_ };
    return $self;
}

sub length     { return scalar( @{$_[0]->{Nodes}} ); }
sub nodes      { return $_[0]->{Nodes}; }
sub item       { $_[0]->{Nodes}->[$_[1]]; }

sub getNamedItem {
    my $self = shift;
    my $name = shift;

    return $self->{NodeMap}->{$name};
}

sub setNamedItem {
    my $self = shift;
    my $node = shift;

    my $retval;
    if ( defined $node ) {
        if ( scalar @{$self->{Nodes}} ) {
            my $name = $node->nodeName();
            if ( $node->nodeType() == XML_NAMESPACE_DECL ) {
                return;
            }
            if ( defined $self->{NodeMap}->{$name} ) {
                if ( $node->isSameNode( $self->{NodeMap}->{$name} ) ) {
                    return;
                }
                $retval = $self->{NodeMap}->{$name}->replaceNode( $node );
            }
            else {
                $self->{Nodes}->[0]->addSibling($node);
            }

            $self->{NodeMap}->{$name} = $node;
            push @{$self->{Nodes}}, $node;
        }
        else {
            # not done yet
            # can this be properly be done???
            warn "not done yet\n";
        }
    }
    return $retval;
}

sub removeNamedItem {
    my $self = shift;
    my $name = shift;
    my $retval;
    if ( $name =~ /^xmlns/ ) {
        warn "not done yet\n";
    }
    elsif ( exists $self->{NodeMap}->{$name} ) {
        $retval = $self->{NodeMap}->{$name};
        $retval->unbindNode;
        delete $self->{NodeMap}->{$name};
        $self->{Nodes} = [grep {not($retval->isSameNode($_))} @{$self->{Nodes}}];
    }

    return $retval;
}

sub getNamedItemNS {
    my $self = shift;
    my $nsURI = shift;
    my $name = shift;
    return undef;
}

sub setNamedItemNS {
    my $self = shift;
    my $nsURI = shift;
    my $node = shift;
    return undef;
}

sub removeNamedItemNS {
    my $self = shift;
    my $nsURI = shift;
    my $name = shift;
    return undef;
}

1;

package XML::LibXML::_SAXParser;

# this is pseudo class!!! and it will be removed as soon all functions
# moved to XS level

use XML::SAX::Exception;

sub CLONE_SKIP {
  return $XML::LibXML::__threads_shared ? 0 : 1;
}

# these functions will use SAX exceptions as soon i know how things really work
sub warning {
    my ( $parser, $message, $line, $col ) = @_;
    my $error = XML::SAX::Exception::Parse->new( LineNumber   => $line,
                                                 ColumnNumber => $col,
                                                 Message      => $message, );
    $parser->{HANDLER}->warning( $error );
}

sub error {
    my ( $parser, $message, $line, $col ) = @_;

    my $error = XML::SAX::Exception::Parse->new( LineNumber   => $line,
                                                 ColumnNumber => $col,
                                                 Message      => $message, );
    $parser->{HANDLER}->error( $error );
}

sub fatal_error {
    my ( $parser, $message, $line, $col ) = @_;
    my $error = XML::SAX::Exception::Parse->new( LineNumber   => $line,
                                                 ColumnNumber => $col,
                                                 Message      => $message, );
    $parser->{HANDLER}->fatal_error( $error );
}

1;

package XML::LibXML::RelaxNG;

sub CLONE_SKIP { 1 }

sub new {
    my $class = shift;
    my %args = @_;

    my $self = undef;
    if ( defined $args{location} ) {
        $self = $class->parse_location( $args{location} );
    }
    elsif ( defined $args{string} ) {
        $self = $class->parse_buffer( $args{string} );
    }
    elsif ( defined $args{DOM} ) {
        $self = $class->parse_document( $args{DOM} );
    }

    return $self;
}

1;

package XML::LibXML::Schema;

sub CLONE_SKIP { 1 }

sub new {
    my $class = shift;
    my %args = @_;

    my $self = undef;
    if ( defined $args{location} ) {
        $self = $class->parse_location( $args{location} );
    }
    elsif ( defined $args{string} ) {
        $self = $class->parse_buffer( $args{string} );
    }

    return $self;
}

1;

#-------------------------------------------------------------------------#
# XML::LibXML::Pattern Interface                                          #
#-------------------------------------------------------------------------#

package XML::LibXML::Pattern;

sub CLONE_SKIP { 1 }

sub new {
  my $class = shift;
  my ($pattern,$ns_map)=@_;
  my $self = undef;
  
  unless (UNIVERSAL::can($class,'_compilePattern')) {
    croak("Cannot create XML::LibXML::Pattern - ".
	  "your libxml2 is compiled without pattern support!");
  }

  if (ref($ns_map) eq 'HASH') {
    # translate prefix=>URL hash to a (URL,prefix) list
    $self = $class->_compilePattern($pattern,0,[reverse %$ns_map]);
  } else {
    $self = $class->_compilePattern($pattern,0);
  }
  return $self;
}

1;

#-------------------------------------------------------------------------#
# XML::LibXML::RegExp Interface                                          #
#-------------------------------------------------------------------------#

package XML::LibXML::RegExp;

sub CLONE_SKIP { 1 }

sub new {
  my $class = shift;
  my ($regexp)=@_;
  unless (UNIVERSAL::can($class,'_compile')) {
    croak("Cannot create XML::LibXML::RegExp - ".
	  "your libxml2 is compiled without regexp support!");
  }
  return $class->_compile($regexp);
}

1;

#-------------------------------------------------------------------------#
# XML::LibXML::XPathExpression Interface                                  #
#-------------------------------------------------------------------------#

package XML::LibXML::XPathExpression;

sub CLONE_SKIP { 1 }

1;


#-------------------------------------------------------------------------#
# XML::LibXML::InputCallback Interface                                    #
#-------------------------------------------------------------------------#
package XML::LibXML::InputCallback;

use vars qw($_CUR_CB @_GLOBAL_CALLBACKS @_CB_STACK $_CB_NESTED_DEPTH @_CB_NESTED_STACK);

BEGIN {
  $_CUR_CB = undef;
  @_GLOBAL_CALLBACKS = ();
  @_CB_STACK = ();
  $_CB_NESTED_DEPTH = 0;
  @_CB_NESTED_STACK = ();
}

sub CLONE_SKIP {
  return $XML::LibXML::__threads_shared ? 0 : 1;
}

#-------------------------------------------------------------------------#
# global callbacks                                                        #
#-------------------------------------------------------------------------#
sub _callback_match {
    my $uri = shift;
    my $retval = 0;

    # loop through the callbacks and and find the first matching
    # The callbacks are stored in execution order (reverse stack order)
    # any new global callbacks are shifted to the callback stack.
    foreach my $cb ( @_GLOBAL_CALLBACKS ) {

        # callbacks have to return 1, 0 or undef, while 0 and undef 
        # are handled the same way. 
        # in fact, if callbacks return other values, the global match 
        # assumes silently that the callback failed.

        $retval = $cb->[0]->($uri);

        if ( defined $retval and $retval == 1 ) {
            # make the other callbacks use this callback
            $_CUR_CB = $cb;
            unshift @_CB_STACK, $cb; 
            last;
        }
    }

    return $retval;
}

sub _callback_open {
    my $uri = shift;
    my $retval = undef;
    
    # the open callback has to return a defined value. 
    # if one works on files this can be a file handle. But 
    # depending on the needs of the callback it also can be a 
    # database handle or a integer labeling a certain dataset.

    if ( defined $_CUR_CB ) {
        $retval = $_CUR_CB->[1]->( $uri );
        
        # reset the callbacks, if one callback cannot open an uri
        if ( not defined $retval or $retval == 0 ) {
            shift @_CB_STACK;
            $_CUR_CB = $_CB_STACK[0];
        }
    }
    
    return $retval;
}

sub _callback_read {
    my $fh = shift;
    my $buflen = shift;

    my $retval = undef;

    if ( defined $_CUR_CB ) {
        $retval = $_CUR_CB->[2]->( $fh, $buflen );
    }

    return $retval;
}

sub _callback_close {
    my $fh = shift;
    my $retval = 0;
    
    if ( defined $_CUR_CB ) {
        $retval = $_CUR_CB->[3]->( $fh );
        shift @_CB_STACK;
        $_CUR_CB = $_CB_STACK[0];
    }

    return $retval;
}

#-------------------------------------------------------------------------#
# member functions and methods                                            #
#-------------------------------------------------------------------------#

sub new {
    my $CLASS = shift;
    return bless {'_CALLBACKS' => []}, $CLASS;
}

# add a callback set to the callback stack
# synopsis: $icb->register_callbacks( [$match_cb, $open_cb, $read_cb, $close_cb] );
sub register_callbacks {
    my $self = shift;
    my $cbset = shift;
    
    # test if callback set is complete
    if ( ref $cbset eq "ARRAY" and scalar( @$cbset ) == 4 ) {
        unshift @{$self->{_CALLBACKS}}, $cbset;
    }
}

# remove a callback set to the callback stack
# if a callback set is passed, this function will check for the match function
sub unregister_callbacks {
    my $self = shift;
    my $cbset = shift;
    if ( ref $cbset eq "ARRAY" and scalar( @$cbset ) == 4 ) {
        $self->{_CALLBACKS} = [grep { $_->[0] != $cbset->[0] } @{$self->{_CALLBACKS}}];
    }
    else {
        shift @{$self->{_CALLBACKS}};
    }
}

# make libxml2 use the callbacks 
sub init_callbacks {
    my $self = shift;
    my $parser = shift;

    #initialize the libxml2 callbacks unless this is a nested callback
    $self->lib_init_callbacks() unless($_CB_NESTED_DEPTH);

    #store the callbacks for any outer executing parser instance
    $_CB_NESTED_DEPTH++;
    push @_CB_NESTED_STACK, [
      $_CUR_CB,
      [@_CB_STACK],
      [@_GLOBAL_CALLBACKS],
    ];

    #initialize the callback variables for the current parser
    $_CUR_CB           = undef;
    @_CB_STACK         = ();
    @_GLOBAL_CALLBACKS = @{ $self->{_CALLBACKS} };
    
    #attach parser specific callbacks
    if($parser) {
        my $mcb = $parser->match_callback();
        my $ocb = $parser->open_callback();
        my $rcb = $parser->read_callback();
        my $ccb = $parser->close_callback();
        if ( defined $mcb and defined $ocb and defined $rcb and defined $ccb ) {
            unshift @_GLOBAL_CALLBACKS, [$mcb, $ocb, $rcb, $ccb];
        }
    }

    #attach global callbacks
    if ( defined $XML::LibXML::match_cb and 
         defined $XML::LibXML::open_cb  and 
         defined $XML::LibXML::read_cb  and 
         defined $XML::LibXML::close_cb ) {
        push @_GLOBAL_CALLBACKS, [$XML::LibXML::match_cb,
                                  $XML::LibXML::open_cb,
                                  $XML::LibXML::read_cb,
                                  $XML::LibXML::close_cb];
    }
}

# reset libxml2's callbacks
sub cleanup_callbacks {
    my $self = shift;

    #restore the callbacks for the outer parser instance
    $_CB_NESTED_DEPTH--;
    my $saved          = pop @_CB_NESTED_STACK;
    $_CUR_CB           = $saved->[0];
    @_CB_STACK         = (@{$saved->[1]});
    @_GLOBAL_CALLBACKS = (@{$saved->[2]});

    #clean up the libxml2 callbacks unless there are still outer parsing instances
    $self->lib_cleanup_callbacks() unless($_CB_NESTED_DEPTH);
}

$XML::LibXML::__loaded=1;

1;

__END__
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.