KTWebDAVServer.inc.php 94.4 KB
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
<?php

/**
 * $Id$
 *
 * KnowledgeTree Open Source Edition
 * Document Management Made Simple
 * Copyright (C) 2004 - 2007 The Jam Warehouse Software (Pty) Limited
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License version 3 as published by the
 * Free Software Foundation.
 * 
 * This program 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 General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * You can contact The Jam Warehouse Software (Pty) Limited, Unit 1, Tramber Place,
 * Blake Street, Observatory, 7925 South Africa. or email info@knowledgetree.com.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * KnowledgeTree" logo and retain the original copyright notice. If the display of the 
 * logo is not reasonably feasible for technical reasons, the Appropriate Legal Notices
 * must display the words "Powered by KnowledgeTree" and retain the original 
 * copyright notice. 
 * Contributor( s): ______________________________________
 *
 */

require_once 'HTTP/WebDAV/Server.php'; // thirdparty PEAR
require_once 'Config.php';             // thirdparty PEAR
require_once 'Log.php';                // thirdparty PEAR

require_once '../config/dmsDefaults.php'; // This is our plug into KT.


DEFINE('STATUS_WEBDAV', 5);  // Status code to handle 0 byte PUT    FIXME: Do we still need this!

/**
 * KnowledgeTree access using WebDAV protocol
 *
 * @access public
 */
class KTWebDAVServer extends HTTP_WebDAV_Server
{
    /**
     * String to be used in "X-Dav-Powered-By" header
     *
     * @var string
     */
    var $dav_powered_by = 'KTWebDAV (1.0.0)';

    /**
     * Realm string to be used in authentication
     *
     * @var string
     */
    var $http_auth_realm = 'KTWebDAV Server';

    /**
     * Path to KT install root
     *
     * @var string
     */
    var $ktdmsPath = '';

    /**
     * Debug Info Toggle
     *
     * @var string
     */
    var $debugInfo = 'off';

    /**
     * Safe Mode Toggle
     *
     * @var string
     */
    var $safeMode = 'on';

    /**
     * Configuration Array
     *
     * @var array
     */
    var $config = array();

    /**
     * Settings Section Configuration Array
     *
     * @var array
     */
    var $settings = array();

    /**
     * Current User ID
     *
     * @var int
     */
    var $userID;

    /**
     * Current Method
     *
     * @var string
     */
    var $currentMethod;

    /**
     * Last Created Folder ID
     *
     * @var string
     */
    var $lastFolderID;

    /**
     * DAV Client
     *
     * @var String
     */
    var $dav_client;

    /**
     * Root Folder Name
     *
     * @var String
     */
    var $rootFolder = 'Root Folder';

    /**
     * Last Message
     *
     * @var String
     */
    var $lastMsg = '';

    /**
     * Constructor
     *
     * @param void
     * @return void
     */
    function KTWebDAVServer() {

        // CGI compatible auth setup
        $altinfo = KTUtil::arrayGet( $_SERVER, 'kt_auth', KTUtil::arrayGet( $_SERVER, 'REDIRECT_kt_auth'));
        if ( !empty( $altinfo) && !isset( $_SERVER['PHP_AUTH_USER'])) {
            $val = $altinfo;
            $pieces = explode( ' ', $val);   // bad.
            if ( $pieces[0] == 'Basic') {
                $chunk = $pieces[1];
                $decoded = base64_decode( $chunk);
                $credential_info = explode( ':', $decoded);
                if ( count( $credential_info) == 2) {
                    $_SERVER['PHP_AUTH_USER'] = $credential_info[0];
                    $_SERVER['PHP_AUTH_PW'] = $credential_info[1];
                    $_SERVER["AUTH_TYPE"] = 'Basic';
                }
            }
        }

        // Let the base class do it's thing
        parent::HTTP_WebDAV_Server();

        // Load KTWebDAV config
        if (!$this->initConfig()) {
            $this->ktwebdavLog('Could not load configuration.', 'error');
            exit(0);
        }

        if ($this->debugInfo == 'on') {

            $this->ktwebdavLog('=====================');
            $this->ktwebdavLog('  Debug Info is : ' . $this->debugInfo);
            $this->ktwebdavLog('    SafeMode is : ' . $this->safeMode);
            $this->ktwebdavLog(' Root Folder is : ' . $this->rootFolder);
            $this->ktwebdavLog('=====================');
        }

    }

    /**
     * Load KTWebDAV configuration from conf file
     *
     * @param void
     * @return bool	true on success
     */
    function initConfig() {

        global $default;
        $oConfig =& KTConfig::getSingleton();

        // Assign Content
        $this->debugInfo = $oConfig->get('KTWebDAVSettings/debug', 'off');
        $this->safeMode = $oConfig->get('KTWebDAVSettings/safemode', 'on');
        $this->rootFolder = $oConfig->get('KTWebDAVSettings/rootfolder', 'Root Folder');
        $this->kt_version = $default->systemVersion;

        return true;
    }

    /**
     * Log to the KTWebDAV logfile
     *
     * @todo Add other log levels for warning, profile, etc
     * @param string    log message
     * @param bool    debug only?
     * @return bool	true on success
     */
    function ktwebdavLog($entry, $type = 'info', $debug_only = false) {

        if ($debug_only && $this->debugInfo != 'on') return false;

        $ident = 'KTWEBDAV';
        $conf = array('mode' => 0644, 'timeFormat' => '%X %x');
        $logger = &Log::singleton('file', '../var/log/ktwebdav-' . date('Y-m-d') . '.txt', $ident, $conf);
        if ($type == 'error') $logger->log($entry, PEAR_LOG_ERR);
        else $logger->log($entry, PEAR_LOG_INFO);
        return true;
    }

    /**
     * Get the current UserID
     *
     * @access private
     * @param  void
     * @return int userID
     */
    function _getUserID() {
        return $this->userID;
    }

    /**
     * Set the current UserID
     *
     * @access private
     * @param  void
     * @return int UserID
     */
    function _setUserID($iUserID) {
        return $this->userID = $iUserID;
    }

    /**
     * Serve a webdav request
     *
     * @access public
     * @param  void
     * @return void
     */
    function ServeRequest()	{

        global $default;

        if ($this->debugInfo == 'on') {

            $this->ktwebdavLog('_SERVER is ' . print_r($_SERVER, true), 'info', true);
        }

        // Get the client info
        $this->checkSafeMode();

        // identify ourselves
        $this->ktwebdavLog('WebDAV Server : ' . $this->dav_powered_by . ' [KT:'.$default->systemVersion."]", 'info', true);
        header('X-Dav-Powered-By: '.$this->dav_powered_by . ' [KT:'.$default->systemVersion.']');

        // check authentication
        if (!$this->_check_auth()) {
            $this->ktwebdavLog('401 Unauthorized - Authorisation failed.' .$this->lastMsg, 'info', true);
            $this->ktwebdavLog('----------------------------------------', 'info', true);
            $this->http_status('401 Unauthorized - Authorisation failed. ' .$this->lastMsg);

            // RFC2518 says we must use Digest instead of Basic
            // but Microsoft Clients do not support Digest
            // and we don't support NTLM and Kerberos
            // so we are stuck with Basic here
            header('WWW-Authenticate: Basic realm="'.($this->http_auth_realm).'"');

            return;
        }

        // check
        if(! $this->_check_if_header_conditions()) {
            $this->http_status('412 Precondition failed');
            return;
        }

        // set path
        $request_uri = $this->_urldecode(!empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/');
        $this->path = str_replace($_SERVER['SCRIPT_NAME'], '', $request_uri);
        if(ini_get('magic_quotes_gpc')) {
            $this->path = stripslashes($this->path);
        }

        $this->ktwebdavLog('PATH_INFO is ' . $_SERVER['PATH_INFO'], 'info', true);
        $this->ktwebdavLog('REQUEST_URI is ' . $_SERVER['REQUEST_URI'], 'info', true);
        $this->ktwebdavLog('SCRIPT_NAME is ' . $_SERVER['SCRIPT_NAME'], 'info', true);
        $this->ktwebdavLog('PHP_SELF is ' . $_SERVER['PHP_SELF'], 'info', true);
        $this->ktwebdavLog('path set to ' . $this->path, 'info', true);

        // detect requested method names
        $method = strtolower($_SERVER['REQUEST_METHOD']);
        $wrapper = 'http_'.$method;

        $this->currentMethod = $method;
        // activate HEAD emulation by GET if no HEAD method found
        if ($method == 'head' && !method_exists($this, 'head')) {
            // rfc2068 Sec: 10.2.1
            //HEAD the entity-header fields corresponding to the requested resource
            //     are sent in the response without any message-body
            $method = 'get';
        }
        $this->ktwebdavLog("Entering $method request", 'info', true);

        if (method_exists($this, $wrapper) && ($method == 'options' || method_exists($this, $method))) {
            $this->$wrapper();  // call method by name
        } else { // method not found/implemented
            if ($_SERVER['REQUEST_METHOD'] == 'LOCK') {
                $this->http_status('412 Precondition failed');
            } else {
                $this->http_status('405 Method not allowed');
                header('Allow: '.join(', ', $this->_allow()));  // tell client what's allowed
            }
        }

        $this->ktwebdavLog("Exiting $method request", 'info', true);

    }


    /**
     * check authentication if check is implemented
     *
     * @param  void
     * @return bool  true if authentication succeded or not necessary
     */
    function _check_auth()
    {
        $this->ktwebdavLog('Entering _check_auth...', 'info', true);

        if (method_exists($this, 'checkAuth')) {
            // PEAR style method name
            return $this->checkAuth(@$_SERVER['AUTH_TYPE'],
                    @$_SERVER['PHP_AUTH_USER'],
                    @$_SERVER['PHP_AUTH_PW']);
        } else if (method_exists($this, 'check_auth')) {
            // old (pre 1.0) method name
            return $this->check_auth(@$_SERVER['AUTH_TYPE'],
                    @$_SERVER['PHP_AUTH_USER'],
                    @$_SERVER['PHP_AUTH_PW']);
        } else {
            // no method found -> no authentication required
            return true;
        }
    }

    /**
     * Authenticate user
     *
     * @access private
     * @param  string  HTTP Authentication type (Basic, Digest, ...)
     * @param  string  Username
     * @param  string  Password
     * @return bool    true on successful authentication
     */
    function checkAuth($sType, $sUser, $sPass) {

        $this->ktwebdavLog('Entering checkAuth params are: ', 'info', true);
        $this->ktwebdavLog('sType: ' . $sType, 'info', true);
        $this->ktwebdavLog('sUser: ' . $sUser, 'info', true);
        $this->ktwebdavLog('sPass: ' . $sPass, 'info', true);

        // Authenticate user

        require_once(KT_LIB_DIR . '/authentication/authenticationutil.inc.php');

        if ( empty($sUser) ) {
            $this->ktwebdavLog('sUser is empty, returning false.', 'info', true);
            return false;
        }

        if ( empty($sPass) ) {
            $this->ktwebdavLog('sPass is empty, returning false.', 'info', true);
            return false;
        }

        $sUser = iconv('ISO-8859-1', 'UTF-8', $sUser);
        $sPass = iconv('ISO-8859-1', 'UTF-8', $sPass);
        $oUser =& User::getByUsername($sUser);
        if (PEAR::isError($oUser) || ($oUser === false)) {
            $this->ktwebdavLog('User not found: ' . $sUser . '.', 'error');
            $this->lastMsg = 'User not found: ' . $sUser . '.';
            return false;
        }
        $authenticated = KTAuthenticationUtil::checkPassword($oUser, $sPass);

        if ($authenticated === false) {
            $this->ktwebdavLog('Password incorrect for ' . $sUser . '.', 'error');
            $this->lastMsg = 'Password incorrect for ' . $sUser . '.';
            return false;
        }

        if (PEAR::isError($authenticated)) {
            $this->ktwebdavLog('Password incorrect for ' . $sUser . '.', 'error');
            $this->lastMsg = 'Password incorrect for ' . $sUser . '.';
            return false;
        }

        $this->ktwebdavLog('UserID is: ' . $oUser->getId(), 'info', true );
        $this->_setUserID($oUser->getId());
        $_SESSION['userID'] = $this->_getUserID();
        $this->ktwebdavLog('SESSION UserID is: ' . $_SESSION['userID'], 'info', true );

        $this->ktwebdavLog("Authentication Success.", 'info', true);

        return true;
    }

    /**
     * PROPFIND method handler
     *
     * @param  array  options
     * @param  array  return array for file properties
     * @return bool   true on success
     */
    function PROPFIND(&$options, &$files) {

        $this->ktwebdavLog("Entering PROPFIND. options are " . print_r($options, true), 'info', true);

        global $default;

        $fspath = $default->documentRoot . "/" . $this->rootFolder . $options["path"];
        $this->ktwebdavLog("fspath is " . $fspath, 'info', true);

        $path = $options["path"];

        // Fix for Mac Clients
        // Mac adds DS_Store files when folders are added and ._filename files when files are added
        // The PUT function doesn't add these files to the dms but PROPFIND still looks for the .DS_Store file,
        // and returns an error if not found. We emulate its existence by returning a positive result.
        if($this->dav_client == 'MC' || $this->dav_client == 'MG'){
            // Remove filename from path
            $aPath = explode('/', $path);
            $fileName = $aPath[count($aPath)-1];
            
            if(strtolower($fileName) == '.ds_store'){
            $this->ktwebdavLog("Using a Mac client. Filename is .DS_Store so we emulate a positive result.", 'info', true);
                // ignore
                return true;
            }
        }

        list($iFolderID, $iDocumentID) = $this->_folderOrDocument($path);
        $this->ktwebdavLog("Folder/Doc is " . print_r(array($iFolderID, $iDocumentID), true), 'info', true);

        // Folder does not exist
        if($iFolderID == '') return false;

        if (is_null($iDocumentID)) {
            return $this->_PROPFINDFolder($options, $files, $iFolderID);
        }
        return $this->_PROPFINDDocument($options, $files, $iDocumentID);

    }

    /**
     * PROPFIND helper for Folders
     *
     * @param array  options
     * @param array  Return array for file props
     * @param int  Folder ID
     * @return bool   true on success
     */
    function _PROPFINDFolder(&$options, &$files, $iFolderID) {

        global $default;

        $this->ktwebdavLog("Entering PROPFINDFolder. options are " . print_r($options, true), 'info', true);

        $folder_path = $options["path"];
        if (substr($folder_path, -1) != "/") {
            $folder_path .= "/";
        }
        $options["path"] = $folder_path;

        $files["files"] = array();
        $files["files"][] = $this->_fileinfoForFolderID($iFolderID, $folder_path);

        $oPerm =& KTPermission::getByName('ktcore.permissions.read');
        $oUser =& User::get($this->userID);

        if (!empty($options["depth"])) {
            $aChildren = Folder::getList(array('parent_id = ?', $iFolderID));
            // FIXME: Truncation Time Workaround
            //foreach (array_slice($aChildren, 0, 50) as $oChildFolder) {
            foreach ($aChildren as $oChildFolder) {
                // Check if the user has permissions to view this folder
                $oFolderDetailsPerm =& KTPermission::getByName('ktcore.permissions.folder_details');

                if(KTPermissionUtil::userHasPermissionOnItem($oUser, $oFolderDetailsPerm, $oChildFolder))
                {
                    $this->ktwebdavLog("Folder Details permissions GRANTED for user ". $_SESSION["userID"] ." on folder " . $oChildFolder->getName(), 'info', true);
                    $files["files"][] = $this->_fileinfoForFolder($oChildFolder, $folder_path . $oChildFolder->getName());
                }
                else
                {
                    $this->ktwebdavLog("Folder Details permissions DENIED for ". $_SESSION["userID"] ." on folder " . $oChildFolder->getName(), 'info', true);
                }
            }
            $aDocumentChildren = Document::getList(array('folder_id = ? AND status_id = 1', $iFolderID));
            // FIXME: Truncation Time Workaround
            //foreach (array_slice($aDocumentChildren, 0, 50) as $oChildDocument) {
            foreach ($aDocumentChildren as $oChildDocument) {
                // Check if the user has permissions to view this document
                if (KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oChildDocument)) {
                    $this->ktwebdavLog("Read permissions GRANTED for ". $_SESSION["userID"] ." on document " . $oChildDocument->getName(), 'info', true);
                    $files["files"][] = $this->_fileinfoForDocument($oChildDocument, $folder_path . $oChildDocument->getFileName());
                } else $this->ktwebdavLog("Read permissions DENIED for ". $_SESSION["userID"] ." on document " . $oChildDocument->getName(), 'info', true);
            }
        }
        return true;
        }

        /**
         * PROPFIND helper for Documents
         *
         * @param array  options
         * @param array  Return array for file props
         * @param int  Document ID
         * @return bool   true on success
         */
        function _PROPFINDDocument(&$options, &$files, $iDocumentID) {

            global $default;

            $this->ktwebdavLog("Entering PROPFINDDocument. files are " . print_r($files, true), 'info', true);

            $res = $this->_fileinfoForDocumentID($iDocumentID, $options["path"]);
            $this->ktwebdavLog("_fileinfoForDocumentID result is " . print_r($res, true), 'info', true);
            if ($res === false) {
                return false;
            }
            $files["files"] = array();
            $files["files"][] = $res;
            return true;
        }

        /**
         * PROPFIND helper for Document Info
         *
         * @param Document  Document Object
         * @param string    Path
         * @return array    Doc info array
         */
        function _fileinfoForDocument(&$oDocument, $path) {

            global $default;

            $this->ktwebdavLog("Entering _fileinfoForDocument. Document is " . print_r($oDocument, true), 'info', true);

            $fspath = $default->documentRoot . "/" . $this->rootFolder . $path;
            $this->ktwebdavLog("fspath is " . $fspath, 'info', true);

            // create result array
            $info = array();
            $info["path"]  = $path;
            $info["props"] = array();

            // no special beautified displayname here ...
            $info["props"][] = $this->mkprop("displayname", $oDocument->getName());

            // creation and modification time
            $info["props"][] = $this->mkprop("creationdate", strtotime($oDocument->getCreatedDateTime()));
            $info["props"][] = $this->mkprop("getlastmodified", strtotime($oDocument->getVersionCreated()));

            // plain file (WebDAV resource)
            $info["props"][] = $this->mkprop("resourcetype", '');
            // FIXME: Direct database access
            $sQuery = array("SELECT mimetypes FROM $default->mimetypes_table WHERE id = ?", array($oDocument->getMimeTypeID()));
            $res = DBUtil::getOneResultKey($sQuery, 'mimetypes');
            $info["props"][] = $this->mkprop("getcontenttype", $res);

            $info["props"][] = $this->mkprop("getcontentlength", $oDocument->getFileSize());

            // explorer wants these?
            $info["props"][] = $this->mkprop("name", '');
            $info["props"][] = $this->mkprop("parentname", '');
            $info["props"][] = $this->mkprop("href", '');
            $info["props"][] = $this->mkprop("ishidden", '');
            $info["props"][] = $this->mkprop("iscollection", '');
            $info["props"][] = $this->mkprop("isreadonly", '');
            $info["props"][] = $this->mkprop("contentclass", '');
            $info["props"][] = $this->mkprop("getcontentlanguage", '');
            $info["props"][] = $this->mkprop("lastaccessed", '');
            $info["props"][] = $this->mkprop("isstructureddocument", '');
            $info["props"][] = $this->mkprop("defaultdocument", '');
            $info["props"][] = $this->mkprop("isroot", '');

            return $info;
        }


        /**
         * PROPFIND helper for Document Info
         *
         * @param int  Document ID
         * @param string  path
         * @return array   Doc info array
         */
        function _fileinfoForDocumentID($iDocumentID, $path) {

            global $default;

            $this->ktwebdavLog("Entering _fileinfoForDocumentID. DocumentID is " . print_r($iDocumentID, true), 'info', true);

            if ($iDocumentID == '') return false;

            $oDocument =& Document::get($iDocumentID);

            if (is_null($oDocument) || ($oDocument === false) || PEAR::isError($oDocument)) {
                return false;
            }

            return $this->_fileinfoForDocument($oDocument, $path);

        }

        /**
         * PROPFIND helper for Folder Info
         *
         * @param Folder  Folder Object
         * @param string  $path
         * @return array  Folder info array
         */
        function _fileinfoForFolder($oFolder, $path) {

            global $default;

            $this->ktwebdavLog("Entering _fileinfoForFolder. Folder is " . print_r($oFolder, true), 'info', true);

            // create result array
            $info = array();
            $info["path"]  = $path;
            $fspath = $default->documentRoot . "/" . $this->rootFolder . $path;
            //$fspath = $default->documentRoot . '/' . $oFolder->generateFolderPath($oFolder->getID());
            $info["props"] = array();

            // no special beautified displayname here ...
            $info["props"][] = $this->mkprop("displayname", $oFolder->getName());

            // creation and modification time
            //$info["props"][] = $this->mkprop("creationdate", strtotime($oFolder->getCreatedDateTime()));
            //$info["props"][] = $this->mkprop("getlastmodified", strtotime($oFolder->getVersionCreated()));

            // directory (WebDAV collection)
            $info["props"][] = $this->mkprop("resourcetype", "collection");
            $info["props"][] = $this->mkprop("getcontenttype", "httpd/unix-directory");
            $info["props"][] = $this->mkprop("getcontentlength", 0);

            return $info;
        }

        /**
         * PROPFIND method handler
         *
         * @param  void
         * @return void
         */
        function http_PROPFIND()
        {
            $options = Array();
            $options["path"] = $this->path;

            // search depth from header (default is "infinity)
            if (isset($_SERVER['HTTP_DEPTH'])) {
                $options["depth"] = $_SERVER["HTTP_DEPTH"];
            } else {
                $options["depth"] = "infinity";
            }
            
            // analyze request payload
            $propinfo = new _parse_propfind("php://input");
            if (!$propinfo->success) {
                $this->http_status("400 Error");
                return;
            }
            $options['props'] = $propinfo->props;

            // call user handler
            if (!$this->PROPFIND($options, $files)) {
                $this->http_status("404 Not Found");
                return;
            }

            // collect namespaces here
            $ns_hash = array();

            // Microsoft Clients need this special namespace for date and time values
            $ns_defs = "xmlns:ns0=\"urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/\"";

            // now we loop over all returned file entries
            foreach($files["files"] as $filekey => $file) {

                // nothing to do if no properties were returned for a file
                if (!isset($file["props"]) || !is_array($file["props"])) {
                    continue;
                }

                // now loop over all returned properties
                foreach($file["props"] as $key => $prop) {
                    // as a convenience feature we do not require that user handlers
                    // restrict returned properties to the requested ones
                    // here we strip all unrequested entries out of the response

                    switch($options['props']) {
                        case "all":
                            // nothing to remove
                            break;

                        case "names":
                            // only the names of all existing properties were requested
                            // so we remove all values
                            unset($files["files"][$filekey]["props"][$key]["val"]);
                        break;

                        default:
                        $found = false;

                        // search property name in requested properties
                        foreach((array)$options["props"] as $reqprop) {
                            if (   $reqprop["name"]  == $prop["name"]
                                    && $reqprop["xmlns"] == $prop["ns"]) {
                                $found = true;
                                break;
                            }
                        }

                        // unset property and continue with next one if not found/requested
                        if (!$found) {
                            $files["files"][$filekey]["props"][$key]='';
                            continue(2);
                        }
                        break;
                    }

                    // namespace handling
                    if (empty($prop["ns"])) continue; // no namespace
                    $ns = $prop["ns"];
                    if ($ns == "DAV:") continue; // default namespace
                    if (isset($ns_hash[$ns])) continue; // already known

                    // register namespace
                    $ns_name = "ns".(count($ns_hash) + 1);
                    $ns_hash[$ns] = $ns_name;
                    $ns_defs .= " xmlns:$ns_name=\"$ns\"";
                }

                // we also need to add empty entries for properties that were requested
                // but for which no values where returned by the user handler
                if (is_array($options['props'])) {
                    foreach($options["props"] as $reqprop) {
                        if($reqprop['name']=='') continue; // skip empty entries

                        $found = false;

                        // check if property exists in result
                        foreach($file["props"] as $prop) {
                            if (   $reqprop["name"]  == $prop["name"]
                                    && $reqprop["xmlns"] == $prop["ns"]) {
                                $found = true;
                                break;
                            }
                        }

                        if (!$found) {
                            if($reqprop["xmlns"]==="DAV:" && $reqprop["name"]==="lockdiscovery") {
                                // lockdiscovery is handled by the base class
                                $files["files"][$filekey]["props"][]
                                    = $this->mkprop("DAV:",
                                            "lockdiscovery" ,
                                            $this->lockdiscovery($files["files"][$filekey]['path']));
                            } else {
                                // add empty value for this property
                                $files["files"][$filekey]["noprops"][] = $this->mkprop($reqprop["xmlns"], $reqprop["name"], '');

                                // register property namespace if not known yet
                                if ($reqprop["xmlns"] != "DAV:" && !isset($ns_hash[$reqprop["xmlns"]])) {
                                    $ns_name = "ns".(count($ns_hash) + 1);
                                    $ns_hash[$reqprop["xmlns"]] = $ns_name;
                                    $ns_defs .= " xmlns:$ns_name=\"$reqprop[xmlns]\"";
                                }
                            }
                        }
                    }
                }
            }

            // now we generate the reply header ...
            $this->http_status("207 Multi-Status");
            header('Content-Type: text/xml; charset="utf-8"');

            // ... and payload
            echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
            echo "<D:multistatus xmlns:D=\"DAV:\">\n";

            foreach($files["files"] as $file) {
                // ignore empty or incomplete entries
                if(!is_array($file) || empty($file) || !isset($file["path"])) continue;
                $path = $file['path'];
                if(!is_string($path) || $path==='') continue;

                echo " <D:response $ns_defs>\n";

                $tempHref = $this->_mergePathes($_SERVER['SCRIPT_NAME'], $path);
                
                // Ensure collections end in a slash
                if(isset($file['props'])){
                    foreach($file['props'] as $v){
                        if($v['name'] == 'resourcetype'){
                            if($v['val'] == 'collection'){
                                $tempHref = $this->_slashify($tempHref);
                                continue;
                            }
                        }
                    }
                }
                
                $href = htmlspecialchars($tempHref);
                
                echo "  <D:href>$href</D:href>\n";

                $this->ktwebdavLog("\nfile is: " . print_r($file, true), 'info', true);

                // report all found properties and their values (if any)
                if (isset($file["props"]) && is_array($file["props"])) {
                    echo "   <D:propstat>\n";
                    echo "    <D:prop>\n";

                    foreach($file["props"] as $key => $prop) {

                        if (!is_array($prop)) continue;
                        if (!isset($prop["name"])) continue;

                        $this->ktwebdavLog("Namespace is " . $prop["ns"], 'info', true);

                        if (!isset($prop["val"]) || $prop["val"] === '' || $prop["val"] === false) {
                            // empty properties (cannot use empty() for check as "0" is a legal value here)
                            if($prop["ns"]=="DAV:") {
                                echo "     <D:$prop[name]/>\n";
                            } else if(!empty($prop["ns"])) {
                                echo "     <".$ns_hash[$prop["ns"]].":$prop[name]/>\n";
                            } else {
                                echo "     <$prop[name] xmlns=\"\"/>";
                            }
                        } else if ($prop["ns"] == "DAV:") {
                            $this->ktwebdavLog("Getting DAV: Properties...", 'info', true);
                            // some WebDAV properties need special treatment
                            switch ($prop["name"]) {
                                case "creationdate":
                                    $this->ktwebdavLog("Getting creationdate...", 'info', true);
                                echo "     <D:creationdate ns0:dt=\"dateTime.tz\">"
                                    . gmdate("Y-m-d\\TH:i:s\\Z",$prop['val'])
                                    . "</D:creationdate>\n";
                                break;
                                case "getlastmodified":
                                    $this->ktwebdavLog("Getting getlastmodified...", 'info', true);
                                echo "     <D:getlastmodified ns0:dt=\"dateTime.rfc1123\">"
                                    . gmdate("D, d M Y H:i:s ", $prop['val'])
                                    . "GMT</D:getlastmodified>\n";
                                break;
                                case "resourcetype":
                                    $this->ktwebdavLog("Getting resourcetype...", 'info', true);
                                echo "     <D:resourcetype><D:$prop[val]/></D:resourcetype>\n";
                                break;
                                case "supportedlock":
                                    $this->ktwebdavLog("Getting supportedlock...", 'info', true);
                                echo "     <D:supportedlock>$prop[val]</D:supportedlock>\n";
                                break;
                                case "lockdiscovery":
                                    $this->ktwebdavLog("Getting lockdiscovery...", 'info', true);
                                echo "     <D:lockdiscovery>\n";
                                echo $prop["val"];
                                echo "     </D:lockdiscovery>\n";
                                break;
                                default:
                                $this->ktwebdavLog("Getting default...", 'info', true);
                                $this->ktwebdavLog("name is: " . $prop['name'], 'info', true);
                                $this->ktwebdavLog("val is: " . $this->_prop_encode(htmlspecialchars($prop['val'])), 'info', true);
                                echo "     <D:" . $prop['name'] .">"
                                    . $this->_prop_encode(htmlspecialchars($prop['val']))
                                    .     "</D:" . $prop['name'] . ">\n";
                                break;
                            }
                        } else {
                            // properties from namespaces != "DAV:" or without any namespace
                            $this->ktwebdavLog('Getting != "DAV:" or without any namespace Properties...', 'info', true);
                            if ($prop["ns"]) {
                                echo "     <" . $ns_hash[$prop["ns"]] . ":$prop[name]>"
                                    . $this->_prop_encode(htmlspecialchars($prop['val']))
                                    . "</" . $ns_hash[$prop["ns"]] . ":$prop[name]>\n";
                            } else {
                                echo "     <$prop[name] xmlns=\"\">"
                                    . $this->_prop_encode(htmlspecialchars($prop['val']))
                                    . "</$prop[name]>\n";
                            }
                        }
                    }

                    echo "   </D:prop>\n";
                    echo "   <D:status>HTTP/1.1 200 OK</D:status>\n";
                    echo "  </D:propstat>\n";
                }

                // now report all properties requested but not found
                $this->ktwebdavLog('Getting all properties requested but not found...', 'info', true);
                if (isset($file["noprops"])) {
                    echo "   <D:propstat>\n";
                    echo "    <D:prop>\n";

                    foreach($file["noprops"] as $key => $prop) {
                        if ($prop["ns"] == "DAV:") {
                            echo "     <D:$prop[name]/>\n";
                        } else if ($prop["ns"] == '') {
                            echo "     <$prop[name] xmlns=\"\"/>\n";
                        } else {
                            echo "     <" . $ns_hash[$prop["ns"]] . ":$prop[name]/>\n";
                        }
                    }

                    echo "   </D:prop>\n";
                    echo "   <D:status>HTTP/1.1 404 Not Found</D:status>\n";
                    echo "  </D:propstat>\n";
                }

                echo " </D:response>\n";
            }

            echo "</D:multistatus>\n";
        }

        /**
         * PROPFIND helper for Folder Info
         *
         * @param int  Folder ID
         * @param string path
         * @return array   Folder info array
         */
        function _fileinfoForFolderID($iFolderID, $path) {

            global $default;

            $this->ktwebdavLog("Entering _fileinfoForFolderID. FolderID is " . $iFolderID, 'info', true);

            if($iFolderID == '') return false;

            $oFolder =& Folder::get($iFolderID);

            if (is_null($oFolder) || ($oFolder === false)) {
                $this->ktwebdavLog("oFolderID error. ", 'info', true);
                return false;
            }

            return $this->_fileinfoForFolder($oFolder, $path);
        }

        /**
         * GET method handler
         *
         * @param  array  parameter passing array
         * @return bool   true on success
         */
        function GET(&$options)
        {
            // required for KT
            global $default;

            $this->ktwebdavLog("Entering GET. options are " .  print_r($options, true), 'info', true);

            // Get the client info
            $this->checkSafeMode();

            // get path to requested resource
            $path = $options["path"];

            list($iFolderID, $iDocumentID) = $this->_folderOrDocument($path);

            if ($iDocumentID === false) {
                $this->ktwebdavLog("Document not found.", 'info', true);
                return "404 Not found - Document not found.";
            }

            if (is_null($iDocumentID)) {
                return $this->_GETFolder($options, $iFolderID);
            }
            return $this->_GETDocument($options, $iDocumentID);

        }

        /**
         * GET method helper
         *
         * @param  array  parameter passing array
         * @param  int    MainFolder ID
         * @return bool   true on success
         */
        function _GETFolder(&$options, $iMainFolderID) {

            global $default;

            $this->ktwebdavLog("Entering _GETFolder. options are " . print_r($options, true), 'info', true);

            $oMainFolder =& Folder::get($iMainFolderID);
            $aFolderID = array();
            $aChildren = Folder::getList(array('parent_id = ?', $iMainFolderID));
            //        $sFolderName = $oMainFolder->getName();

            if (is_writeable("../var") && is_writeable("../var/log")) {
                $writeperms = "<font color=\"green\"><b>OK</b></font>";
            }else {
                $writeperms = "<font color=\"red\"><b>NOT SET</b></font>";
            }

            if ($this->ktdmsPath != '') {
                $ktdir = $this->ktdmsPath;
            }

            $srv_proto = split('/', $_SERVER['SERVER_PROTOCOL']);

            $data = "<html><head><title>KTWebDAV - The KnowledgeTree WebDAV Server</title></head>";
            $data .= "<body>";
            $data .= "<div align=\"center\"><IMG src=\"../resources/graphics/ktlogo-topbar_base.png\" width=\"308\" height=\"61\" border=\"0\"></div><br>";
            $data .= "<div align=\"center\"><h2><strong>Welcome to KnowledgeTree WebDAV Server</strong></h2></div><br><br>";
            $data .= "<div align=\"center\">To access KTWebDAV copy the following URL and paste it into your WebDAV enabled client...</div><br><br>";
            $data .= "<div align=\"center\"><strong>" . strtolower($srv_proto[0]) . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . "</strong></div>";
            $data .= "</body>";

            $options['mimetype'] = 'text/html';
            $options["data"] = $data;
            return true;
        }

        /**
         * GET method helper
         *
         * @param  array  parameter passing array
         * @param  int  Document ID
         * @return bool   true on success
         */
        function _GETDocument(&$options, $iDocumentID) {
            global $default;

            $oDocument =& Document::get($iDocumentID);

            // get a temp file, and read.  NOTE: NEVER WRITE TO THIS
            $oStorage =& KTStorageManagerUtil::getSingleton();
            $fspath = $oStorage->temporaryFile($oDocument);

            $this->ktwebdavLog("Filesystem Path is " . $fspath, 'info', true );

            // detect resource type
            $mimetype = KTMime::getMimeTypeName($oDocument->getMimeTypeID());
            $options['mimetype'] = KTMime::getFriendlyNameForString($mimetype);
            // detect modification time
            // see rfc2518, section 13.7
            // some clients seem to treat this as a reverse rule
            // requiering a Last-Modified header if the getlastmodified header was set

            $options['mtime'] = $oDocument->getVersionCreated();

            // detect resource size
            $options['size'] = $oDocument->getFileSize();

            // no need to check result here, it is handled by the base class
            $options['stream'] = fopen($fspath, "r");

            $this->ktwebdavLog("Method is " . $this->currentMethod, 'info', true );

            if ($this->currentMethod == "get") {

                // create the document transaction record
                include_once(KT_LIB_DIR . '/documentmanagement/DocumentTransaction.inc');
                $oDocumentTransaction = & new DocumentTransaction($oDocument, "Document viewed via KTWebDAV", 'ktcore.transactions.view');
                $oDocumentTransaction->iUserID = $this->userID;
                $oDocumentTransaction->create();

            }
            return true;
        }

        /**
         * GET method helper
         *
         * @param  string  directory path
         * @return array  or false
         */
        function _folderOrDocument($path) {

            global $default;

            $this->ktwebdavLog("Entering _folderOrDocument. path is " . $path, 'info', true);

            if ( !(strstr($path,"__BAOBABCLIENT__") === false) ) {
                return array(0, 1);
            }

            $sFileName = basename($path);
            // for windows replace backslash with forwardslash
            $sFolderPath = str_replace("\\", '/', dirname($path) );

            if ($sFolderPath == "/" || $sFolderPath == "/ktwebdav") {
                $this->ktwebdavLog("This is the root folder.", 'info', true);
                $sFolderPath = $this->rootFolder;
                $iFolderID = 0;
            } else $iFolderID = 1;
            if ($sFileName == "ktwebdav.php") {
                $this->ktwebdavLog("This is the root folder file.", 'info', true);
                $sFileName = '';
            }

            $this->ktwebdavLog("sFileName is " . $sFileName, 'info', true);
            $this->ktwebdavLog("sFolderName is " . $sFolderPath, 'info', true);
            $this->ktwebdavLog("iFolderID is " . $iFolderID, 'info', true);

            $aFolderNames = split('/', $sFolderPath);

            $this->ktwebdavLog("aFolderNames are: " . print_r($aFolderNames, true), 'info', true);
            $aRemaining = $aFolderNames;
            while (count($aRemaining)) {
                $sFolderName = $aRemaining[0];
                $aRemaining = array_slice($aRemaining, 1);
                if (empty($sFolderName)) {
                    continue;
                }
                // FIXME: Direct database access
                if($iFolderID == 0){
                    $sQuery = "SELECT id FROM folders WHERE parent_id is null AND name = ?";
                    $aParams = array($sFolderName);
                }else{
                    $sQuery = "SELECT id FROM folders WHERE parent_id = ? AND name = ?";
                    $aParams = array($iFolderID, $sFolderName);
                }
                $id = DBUtil::getOneResultKey(array($sQuery, $aParams), 'id');
                if (PEAR::isError($id)) {
                    $this->ktwebdavLog("A DB error occurred in _folderOrDocument", 'info', true);
                    return false;
                }
                if (is_null($id)) {
                    // Some intermediary folder path doesn't exist
                    $this->ktwebdavLog("Some intermediary folder does not exist in _folderOrDocument", 'error', true);
                    return array(false, false);
                }
                $iFolderID = (int)$id;
                $this->ktwebdavLog("iFolderID set to " . $iFolderID, 'info', true);
            }

            // FIXME: Direct database access
            //        $sQuery = "SELECT id FROM documents WHERE folder_id = ? AND filename = ? AND status_id = 1";
            $sQuery = "SELECT D.id ";
            $sQuery .= "FROM documents AS D ";
            $sQuery .= "LEFT JOIN document_metadata_version AS DM ";
            $sQuery .= "ON D.metadata_version_id = DM.id ";
            $sQuery .= "LEFT JOIN document_content_version AS DC ";
            $sQuery .= "ON DM.content_version_id = DC.id ";
            $sQuery .= "WHERE D.folder_id = ? AND DC.filename = ?";

            $aParams = array($iFolderID, $sFileName);
            $iDocumentID = DBUtil::getOneResultKey(array($sQuery, $aParams), 'id');

            if (PEAR::isError($iDocumentID)) {
                $this->ktwebdavLog("iDocumentID error in _folderOrDocument", 'info', true);
                return false;
            }

            if ($iDocumentID === null) {
                $this->ktwebdavLog("iDocumentID is null", 'info', true);
                // FIXME: Direct database access
                $sQuery = "SELECT id FROM folders WHERE parent_id = ? AND name = ?";
                $aParams = array($iFolderID, $sFileName);
                $id = DBUtil::getOneResultKey(array($sQuery, $aParams), 'id');
                if (PEAR::isError($id)) {
                    $this->ktwebdavLog("A DB(2) error occurred in _folderOrDocument", 'info', true);
                    return false;
                }
                if (is_null($id)) {
                    if ($sFileName == '') {
                        return array($iFolderID, null);
                    }
                    $this->ktwebdavLog("id is null in _folderOrDocument", 'info', true);
                    return array($iFolderID, false);
                }
                if (substr($path, -1) !== "/") {
                    $this->ktwebdavLog("Setting Location Header to " . "Location: " . $_SERVER["PHP_SELF"] . "/", 'info', true);
                    header("Location: " . $_SERVER["PHP_SELF"] . "/");
                }
                return array($id, null);
            }

            return array($iFolderID, (int)$iDocumentID);
        }

        /**
         *  PUT method handler
         *
         * @param  array  parameter passing array
         * @return string  HTTP status code or false
         */
        function PUT(&$options)
        {
            global $default;

            if ($this->checkSafeMode()) {

                $this->ktwebdavLog("Entering PUT. options are " .  print_r($options, true), 'info', true);
                $this->ktwebdavLog("dav_client is: " .  $this->dav_client, 'info', true);

                $path = $options["path"];
                
                // Fix for Mac
                // Mac adds DS_Store files when folders are added and ._filename files when files are added
                // we want to ignore them.
                if($this->dav_client == 'MC' || $this->dav_client == 'MG'){
                    // Remove filename from path
                    $aPath = explode('/', $path);
                    $fileName = $aPath[count($aPath)-1];
                    
                    if(strtolower($fileName) == '.ds_store'){
                        $this->ktwebdavLog("Using a mac client. Ignore the .DS_Store files created with every folder.", 'info', true);
                        // ignore
                        return "204 No Content";
                    }
                    
                    if($fileName[0] == '.' && $fileName[1] == '_'){
                        $fileName = substr($fileName, 2);
                        $this->ktwebdavLog("Using a mac client. Ignore the ._filename files created with every file.", 'info', true);
                        // ignore
                        return "204 No Content";
                    }
                }
                    

                $res = $this->_folderOrDocument($path);
                list($iFolderID, $iDocumentID) = $res;

                if ($iDocumentID === false && $iFolderID === false) {
                    // Couldn't find intermediary paths
                    /*
                     * RFC2518: 8.7.1 PUT for Non-Collection Resources
                     *
                     * 409 (Conflict) - A PUT that would result in the creation
                     * of a resource without an appropriately scoped parent collection
                     * MUST fail with a 409 (Conflict).
                     */
                    return "409 Conflict - Couldn't find intermediary paths";
                }

                $oParentFolder =& Folder::get($iFolderID);
                // Check if the user has permissions to write in this folder
                $oPerm =& KTPermission::getByName('ktcore.permissions.write');
                $oUser =& User::get($this->userID);
                if (!KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oParentFolder)) {
                    return "403 Forbidden - User does not have sufficient permissions";
                }

                $this->ktwebdavLog("iDocumentID is " . $iDocumentID, 'info', true);

                if (is_null($iDocumentID)) {
                    // This means there is a folder with the given path
                    $this->ktwebdavLog("405 Method not allowed", 'info', true);
                    return "405 Method not allowed - There is a folder with the given path";
                }

                if ($iDocumentID == false) {
                    $this->ktwebdavLog("iDocumentID is false", 'info', true);
                }

                if ($iDocumentID !== false) {
                    // This means there is a document with the given path
                    $oDocument = Document::get($iDocumentID);

                    $this->ktwebdavLog("oDocument is " .  print_r($oDocument, true), 'info', true);
                    $this->ktwebdavLog("oDocument statusid is " .  print_r($oDocument->getStatusID(), true), 'info', true);

                    if ( ( (int)$oDocument->getStatusID() != STATUS_WEBDAV ) && ( (int)$oDocument->getStatusID() != DELETED )) {
                        $this->ktwebdavLog("Trying to PUT to an existing document", 'info', true);
                        if (!$this->dav_client == "MS" && !$this->dav_client == "MC") return "409 Conflict - There is a document with the given path";
                    }

                    // FIXME: Direct filesystem access
                    $fh = $options["stream"];
                    $sTempFilename = tempnam('/tmp', 'ktwebdav_dav_put');
                    $ofh = fopen($sTempFilename, 'w');

                    $contents = '';
                    while (!feof($fh)) {
                        $contents .= fread($fh, 8192);
                    }
                    $fres = fwrite($ofh, $contents);
                    $this->ktwebdavLog("A DELETED or CHECKEDOUT document exists. Overwriting...", 'info', true);
                    $this->ktwebdavLog("Temp Filename is: " . $sTempFilename, 'info', true );
                    $this->ktwebdavLog("File write result size was: " . $fres, 'info', true );

                    fflush($fh);
                    fclose($fh);
                    fflush($ofh);
                    fclose($ofh);
                    $this->ktwebdavLog("Files have been flushed and closed.", 'info', true );

                    $name = basename($path);
                    $aFileArray = array(
                            "name" => $name,
                            "size" => filesize($sTempFilename),
                            "type" => false,
                            "userID" => $this->_getUserID(),
                            );
                    $this->ktwebdavLog("aFileArray is " .  print_r($aFileArray, true), 'info', true);

                    include_once(KT_LIB_DIR . '/filelike/fsfilelike.inc.php');
                    $aOptions = array(
                            'contents' => new KTFSFileLike($sTempFilename),
                            'metadata' => array(),
                            'novalidate' => true,
                            );
                    $oDocument =& KTDocumentUtil::add($oParentFolder, $name, $oUser, $aOptions);

                    if(PEAR::isError($oDocument)) {
                        $this->ktwebdavLog("oDocument ERROR: " .  $oDocument->getMessage(), 'info', true);
		                unlink($sTempFilename);
                        return "409 Conflict - " . $oDocument->getMessage();
                    }

                    $this->ktwebdavLog("oDocument is " .  print_r($oDocument, true), 'info', true);

                    unlink($sTempFilename);
                    return "204 No Content";
                }

                $options["new"] = true;
                // FIXME: Direct filesystem access
                $fh = $options["stream"];
                $sTempFilename = tempnam('/tmp', 'ktwebdav_dav_put');
                $ofh = fopen($sTempFilename, 'w');

                $contents = '';
                while (!feof($fh)) {
                    $contents .= fread($fh, 8192);
                }
                $fres = fwrite( $ofh, $contents);
                $this->ktwebdavLog("Content length was not 0, doing the whole thing.", 'info', true );
                $this->ktwebdavLog("Temp Filename is: " . $sTempFilename, 'info', true );
                $this->ktwebdavLog("File write result size was: " . $fres, 'info', true );

                fflush($fh);
                fclose($fh);
                fflush($ofh);
                fclose($ofh);
                $this->ktwebdavLog("Files have been flushed and closed.", 'info', true );

                $name = basename($path);
                $aFileArray = array(
                        "name" => $name,
                        "size" => filesize($sTempFilename),
                        "type" => false,
                        "userID" => $this->_getUserID(),
                        );
                $this->ktwebdavLog("aFileArray is " .  print_r($aFileArray, true), 'info', true);

                include_once(KT_LIB_DIR . '/filelike/fsfilelike.inc.php');
                $aOptions = array(
                        'contents' => new KTFSFileLike($sTempFilename),
                        'metadata' => array(),
                        'novalidate' => true,
                        );
                $oDocument =& KTDocumentUtil::add($oParentFolder, $name, $oUser, $aOptions);

                if(PEAR::isError($oDocument)) {
                    $this->ktwebdavLog("oDocument ERROR: " .  $oDocument->getMessage(), 'info', true);
                    unlink($sTempFilename);
                    return "409 Conflict - " . $oDocument->getMessage();
                }

                $this->ktwebdavLog("oDocument is " .  print_r($oDocument, true), 'info', true);

                unlink($sTempFilename);
                return "201 Created";

            }  else return "423 Locked - KTWebDAV is in SafeMode";

        }

        /**
         * MKCOL method handler
         *
         * @param  array  parameter passing array
         * @return string  HTTP status code or false
         */
        function MKCOL($options)
        {
            $this->ktwebdavLog("Entering MKCOL. options are " .  print_r($options, true), 'info', true);

            if ($this->checkSafeMode()) {

                global $default;

                if (!empty($_SERVER["CONTENT_LENGTH"])) {
                    /*
                     * RFC2518: 8.3.2 MKCOL status codes
                     *
                     * 415 (Unsupported Media Type)- The server does not support
                     * the request type of the body.
                     */
                    return "415 Unsupported media type";
                }

                // Take Windows's escapes out
                $path = str_replace('\\', '' , $options['path']);


                $res = $this->_folderOrDocument($path);
                list($iFolderID, $iDocumentID) = $res;

                if ($iDocumentID === false && $iFolderID === false) {
                    // Couldn't find intermediary paths
                    /*
                     * RFC2518: 8.3.2 MKCOL status codes
                     *
                     * 409 (Conflict) - A collection cannot be made at the
                     * Request-URI until one or more intermediate collections
                     * have been created.
                     */
                    $this->ktwebdavLog("409 Conflict in MKCOL", 'info', true);
                    return "409 Conflict - Couldn't find intermediary paths";
                }


                if (is_null($iDocumentID)) {
                    // This means there is a folder with the given path
                    /*
                     * RFC2518: 8.3.2 MKCOL status codes
                     *
                     * 405 (Method Not Allowed) - MKCOL can only be executed on
                     * a deleted/non-existent resource.
                     */
                    $this->ktwebdavLog("405 Method not allowed - There is a folder with the given path", 'info', true);
                    return "405 Method not allowed - There is a folder with the given path";
                }
                if ($iDocumentID !== false) {
                    // This means there is a document with the given path
                    /*
                     * RFC2518: 8.3.2 MKCOL status codes
                     *
                     * 405 (Method Not Allowed) - MKCOL can only be executed on
                     * a deleted/non-existent resource.
                     */
                    $this->ktwebdavLog("405 Method not allowed - There is a document with the given path", 'info', true);
                    return "405 Method not allowed - There is a document with the given path";
                }

                $sFolderName = basename($path);
                $sFolderPath = dirname($path);

                $dest_fspath = $default->documentRoot . "/" . $this->rootFolder . $path;
                $this->ktwebdavLog("Will create a physical path of " .  $dest_fspath, 'info', true);

                $oParentFolder =& Folder::get($iFolderID);
                $this->ktwebdavLog("Got an oParentFolder of " .  print_r($oParentFolder, true), 'info', true);

                // Check if the user has permissions to write in this folder
                $oPerm =& KTPermission::getByName('ktcore.permissions.addFolder');
                $oUser =& User::get($this->userID);

                $this->ktwebdavLog("oPerm is " .  print_r($oPerm, true), 'info', true);
                $this->ktwebdavLog("oUser is " .  print_r($oUser, true), 'info', true);
                $this->ktwebdavLog("oFolder is " .  print_r($oParentFolder, true), 'info', true);

                if (!KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oParentFolder)) {
                    $this->ktwebdavLog("Permission denied.", 'info', true);
                    return "403 Forbidden - User does not have sufficient permissions";
                } else $this->ktwebdavLog("Permission granted.", 'info', true);


                include_once(KT_LIB_DIR . '/foldermanagement/folderutil.inc.php');

                KTFolderUtil::add($oParentFolder, $sFolderName, $oUser);
                /*
                 * RFC 2518: 8.3.2 MKCOL status codes
                 *
                 * 201 (Created) - The collection or structured resource was
                 * created in its entirety.
                 */
                $this->ktwebdavLog("201 Created", 'info', true);
                return "201 Created";

            } else return "423 Locked - KTWebDAV is in SafeMode";
        }


        /**
         * DELETE method handler
         *
         * @param  array  parameter passing array
         * @return string  HTTP status code or false
         */
        function DELETE($options)
        {
            $this->ktwebdavLog("Entering DELETE. options are " . print_r($options, true), 'info', true);

            if ($this->checkSafeMode()) {

                $path = $options["path"];
                $res = $this->_folderOrDocument($path);
                $this->ktwebdavLog("DELETE res is " . print_r($res, true), 'info', true);
                if ($res === false) {
                    $this->ktwebdavLog("404 Not found - The Document was not found.", 'info', true);
                    return "404 Not found - The Document was not found.";
                }
                list($iFolderID, $iDocumentID) = $res;

                if ($iDocumentID === false) {
                    $this->ktwebdavLog("404 Not found - The Folder was not found.", 'info', true);
                    return "404 Not found - The Folder was not found.";
                }

                if (is_null($iDocumentID)) {
                    return $this->_DELETEFolder($options, $iFolderID);
                }
                return $this->_DELETEDocument($options, $iFolderID, $iDocumentID);

            } else return "423 Locked - KTWebDAV is in SafeMode";
        }

        /**
         * DELETE method helper for Documents
         *
         * @param  array  parameter passing array
         * @param  int    Folder ID
         * @param  int    Document ID
         * @return string  HTTP status code or false
         */
        function _DELETEDocument($options, $iFolderID, $iDocumentID) {

            $this->ktwebdavLog("Entering _DELETEDocument. options are " . print_r($options, true), 'info', true);

            global $default;

            $oDocument =& Document::get($iDocumentID);

            // Check if the user has permissions to delete this document
            $oPerm =& KTPermission::getByName('ktcore.permissions.delete');
            $oUser =& User::get($this->userID);
            if (!KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oDocument)) {
                return "403 Forbidden - The user does not have sufficient permissions";
            }

            $res = KTDocumentUtil::delete($oDocument, $_SERVER['HTTP_REASON']);

            if (PEAR::isError($res)) {
                $this->ktwebdavLog("404 Not Found - " . $res->getMessage(), 'info', true);
                return "404 Not Found - " . $res->getMessage();
            }

            $this->ktwebdavLog("204 No Content", 'info', true);
            return "204 No Content";
        }

        /**
         * DELETE method helper for Folders
         *
         * @param  array  paramter passing array
         * @param  int  Folder ID
         * @return string  HTTP status code or false
         */
        function _DELETEFolder($options, $iFolderID) {

            $this->ktwebdavLog("Entering _DELETEFolder. options are " . print_r($options, true), 'info', true);

            global $default;

            require_once(KT_LIB_DIR . "/foldermanagement/folderutil.inc.php");

            // Check if the user has permissions to delete this folder
            $oFolder =& Folder::get($iFolderID);
            $oPerm =& KTPermission::getByName('ktcore.permissions.delete');
            $oUser =& User::get($this->userID);
            if (!KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oFolder)) {
                return "403 Forbidden - The user does not have sufficient permissions";
            }
            $this->ktwebdavLog("Got an oFolder of " . print_r($oFolder, true), 'info', true);
            $this->ktwebdavLog("Got an oUser of " . print_r($oUser, true), 'info', true);
            $res = KTFolderUtil::delete($oFolder, $oUser, 'KTWebDAV Delete');

            if (PEAR::isError($res)) {
                $this->ktwebdavLog("Delete Result error " . print_r($res, true), 'info', true);
                return "403 Forbidden - ".$res->getMessage();
            }

            return "204 No Content";
        }

        /**
         * MOVE method handler
         *
         * @param  array  parameter passing array
         * @return string  HTTP status code or false
         */
        function MOVE($options)
        {
            // Use the WebDAV standards way.
            // See rfc2518 Section 8.9
            // This does a copy with delete
            // FIXME: This way does not retain document history and other info

            //return $this->COPY($options, true);

            // Use the KT way.
            // FIXME: This way does not allow overwrite

            $this->ktwebdavLog("Entering MOVE. options are " . print_r($options, true), 'info', true);

            if ($this->checkSafeMode()) {

                if (!empty($_SERVER["CONTENT_LENGTH"])) { // no body parsing yet
                    $this->ktwebdavLog("415 Unsupported media type", 'info', true);
                    return "415 Unsupported media type";
                }

                /*		// no moving to different WebDAV Servers yet
                        if (isset($options["dest_url"])) {
                        $this->ktwebdavLog("502 bad gateway - No moving to different WebDAV Servers yet", 'info', true);
                        return "502 bad gateway - No moving to different WebDAV Servers yet";
                        }
                 */
                $source_path = $options["path"];
                $source_res = $this->_folderOrDocument($source_path);
                if ($source_res === false) {
                    $this->ktwebdavLog("404 Not found - Document was not found.", 'info', true);
                    return "404 Not found - Document was not found.";
                }

                list($iFolderID, $iDocumentID) = $source_res;
                if ($iDocumentID === false) {
                    $this->ktwebdavLog("404 Not found - Folder was not found.", 'info', true);
                    return "404 Not found - Folder was not found.";
                }

                if (is_null($iDocumentID)) {
                    // Source is a folder
                    $movestat = $this->_MOVEFolder($options, $iFolderID);

                } else {
                	 // Source is a document
                	if ($this->canCopyMoveRenameDocument($iDocumentID)) {
						$movestat = $this->_MOVEDocument($options, $iFolderID, $iDocumentID);
					} else {
						return "Cannot MOVE document because it is checked out by another user.";
					}
                }

                $this->ktwebdavLog("Final movestat result is: " . $movestat, 'info', true);
                return $movestat;

            } else return "423 Locked - KTWebDAV is in SafeMode";

        }

        /**
         * MOVE method helper for Documents
         *
         * @param  array  parameter passing array
         * @param  int    Folder ID
         * @param  int    Document ID
         * @return string  HTTP status code or false
         */
        function _MOVEDocument($options, $iFolderID, $iDocumentID) {

            if ($options['dest'] == '') $options["dest"] = substr($options["dest_url"], strlen($_SERVER["SCRIPT_NAME"]));
            
            // Fix for Mac
            if($this->dav_client == 'MG'){
                $this->ktwebdavLog("Remove ktwebdav from destination path: ".$options['dest'], 'info', true);
                if(!(strpos($options['dest'], 'ktwebdav/ktwebdav.php/') === FALSE)){
                    $options['dest'] = substr($options['dest'], 22);
                }
                if($options['dest'][0] != '/'){
                   $options['dest'] = '/'.$options['dest'];
                } 
            }
            
            $this->ktwebdavLog("Entering _MOVEDocument. options are " . print_r($options, true), 'info', true);
            global $default;
            $new = true;
            //FIXME: refactor me into KTDocumentUtil

            $oDocument = Document::get($iDocumentID);
            $oSrcFolder = Folder::get($iFolderID);
            $oUser =& User::get($this->userID);

            $source_path = $options["path"];
            $dest_path = urldecode($options["dest"]);

            // Is this a rename?
            if (dirname($source_path) == dirname($dest_path)) {
                // This is a rename
                //if ($options['overwrite'] != 'T') {
                //	$this->ktwebdavLog("This is a Rename. Overwrite needs to be TRUE.", 'info', true);
                //	return "412 Precondition Failed - This is a Rename. Overwrite needs to be TRUE.";
                //}
                $this->ktwebdavLog("Got an oDocument of " . print_r($oDocument, true), 'info', true);
                $this->ktwebdavLog("Got a new name of " . basename($dest_path), 'info', true);

                // Check if the user has permissions to write this document
                $oPerm =& KTPermission::getByName('ktcore.permissions.write');
                $oUser =& User::get($this->userID);
                if (!KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oDocument)) {
                    return "403 Forbidden - User does not have sufficient permissions";
                }
                $res = KTDocumentUtil::rename($oDocument, basename($dest_path), $oUser);
                if (PEAR::isError($res) || is_null($res) || ($res === false)) {
                    return "404 Not Found - " . $res->getMessage();
                } else {
                    $this->ktwebdavLog("201 Created", 'info', true);
                    return "201 Created";
                }

            }

            list($iDestFolder, $iDestDoc) = $this->_folderOrDocument($dest_path);

            if (is_null($iDestDoc)) {
                // the dest is a folder
            } else if ($iDestDoc !== false) {
                // Document exists
                $this->ktwebdavLog("Destination Document exists.", 'info', true);
                $oReplaceDoc = Document::get($iDestDoc);
                if ($options['overwrite'] != 'T') {
                    $this->ktwebdavLog("Overwrite needs to be TRUE.", 'info', true);
                    return "412 Precondition Failed - Destination Document exists. Overwrite needs to be TRUE.";
                }
                $this->ktwebdavLog("Overwrite is TRUE, deleting Destination Document.", 'info', true);

                // Check if the user has permissions to delete this document
                $oPerm =& KTPermission::getByName('ktcore.permissions.delete');
                $oUser =& User::get($this->userID);
                if (!KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oReplaceDoc)) {
                    return "403 Forbidden - User does not have sufficient permissions";
                }
                KTDocumentUtil::delete($oReplaceDoc, 'KTWebDAV move overwrites target.');
                $new = false;
            }

            $oDestFolder = Folder::get($iDestFolder);
            $this->ktwebdavLog("Got a destination folder of " . print_r($oDestFolder, true), 'info', true);

            // Check if the user has permissions to write in this folder
            $oPerm =& KTPermission::getByName('ktcore.permissions.write');
            $oUser =& User::get($this->userID);
            if (!KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oDestFolder)) {
                return "403 Forbidden - User does not have sufficient permissions";
            }

            $oOriginalFolder = $oSrcFolder;
            $iOriginalFolderPermissionObjectId = $oOriginalFolder->getPermissionObjectId();
            $iDocumentPermissionObjectId = $oDocument->getPermissionObjectId();

            if ($iDocumentPermissionObjectId === $iOriginalFolderPermissionObjectId) {
                $oDocument->setPermissionObjectId($oDestFolder->getPermissionObjectId());
            }

            //put the document in the new folder
            $oDocument->setFolderID($oDestFolder->getId());
            if (!$oDocument->update(true)) {
                return "502 Bad Gateway - Document update failed.";
            }

            //move the document on the file system
            $oStorage =& KTStorageManagerUtil::getSingleton();
            if (!$oStorage->moveDocument($oDocument, $oSrcFolder, $oDestFolder)) {
                $oDocument->setFolderID($oSrcDocumentFolder->getId());
                $oDocument->update(true);
                return "502 Bad Gateway";
            }

            $sMoveMessage = sprintf("Moved from %s/%s to %s/%s: %s",
                    $oSrcFolder->getFullPath(),
                    $oSrcFolder->getName(),
                    $oDestFolder->getFullPath(),
                    $oDestFolder->getName(),
                    $_SERVER['HTTP_REASON']);

            // create the document transaction record
            $oDocumentTransaction = & new DocumentTransaction($oDocument, $sMoveMessage, 'ktcore.transactions.move');
            $oDocumentTransaction->create();

            $oKTTriggerRegistry = KTTriggerRegistry::getSingleton();
            $aTriggers = $oKTTriggerRegistry->getTriggers('moveDocument', 'postValidate');
            foreach ($aTriggers as $aTrigger) {
                $sTrigger = $aTrigger[0];
                $oTrigger = new $sTrigger;
                $aInfo = array(
                        "document" => $oDocument,
                        "old_folder" => $oSrcFolder,
                        "new_folder" => $oDestFolder,
                        );
                $oTrigger->setInfo($aInfo);
                $ret = $oTrigger->postValidate();
                // FIXME: handle trigger subfailures.
            }

            if ($new) {
                return "201 Created";
            } else {
                return "204 No Content";
            }
        }

        /**
         * MOVE method helper for Folders
         *
         * @param  array   parameter passing array
         * @param  int     Folder ID
         * @return string  HTTP status code or false

         */
        function _MOVEFolder($options, $iFolderID) {

            if ($options['dest'] == '') $options["dest"] = substr($options["dest_url"], strlen($_SERVER["SCRIPT_NAME"]));
            $this->ktwebdavLog("Entering _MOVEFolder. options are " . print_r($options, true), 'info', true);

            if ($options["depth"] != "infinity") {
                // RFC 2518 Section 9.2, last paragraph
                $this->ktwebdavLog("400 Bad request", 'info', true);
                return "400 Bad request - depth must be 'inifinity'.";
            }

            global $default;

            $source_path = $options["path"];
            $dest_path = urldecode($options["dest"]);

            $oSrcFolder = Folder::get($iFolderID);

            list($iDestFolder, $iDestDoc) = $this->_folderOrDocument($dest_path);

            $oDestFolder = Folder::get($iDestFolder);

            // Is this a rename?
            if (dirname($source_path) == dirname($dest_path)) {
                // This is a rename
                //if ($options['overwrite'] != 'T') {
                //	$this->ktwebdavLog("This is a Rename. Overwrite needs to be TRUE.", 'info', true);
                //	return "412 Precondition Failed - This is a Rename. Overwrite needs to be TRUE.";
                //}

                $this->ktwebdavLog("Got an oSrcFolder of " . print_r($oSrcFolder, true), 'info', true);
                $this->ktwebdavLog("Got an new name of " . basename($dest_path), 'info', true);

                include_once(KT_LIB_DIR . '/foldermanagement/folderutil.inc.php');

                // Check if the user has permissions to write this folder
                $oPerm =& KTPermission::getByName('ktcore.permissions.folder_rename');
                $oUser =& User::get($this->userID);
                if (!KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oSrcFolder)) {
                    return "403 Forbidden - User does not have sufficient permissions";
                }
                $res = KTFolderUtil::rename($oSrcFolder, basename($dest_path), $oUser);
                if (PEAR::isError($res) || is_null($res) || ($res === false)) {
                    return "404 Not Found - " . $res->getMessage();
                } else {
                    $this->ktwebdavLog("201 Created", 'info', true);
                    return "201 Created";
                }

            }

            if (is_null($iDestDoc)) {
                // the dest is a folder
            } else if ($iDestDoc !== false) {
                // Folder exists
                $this->ktwebdavLog("Destination Folder exists.", 'info', true);
                $oReplaceFolder = Folder::get($iDestDoc);
                if ($options['overwrite'] != 'T') {
                    $this->ktwebdavLog("Overwrite needs to be TRUE.", 'info', true);
                    return "412 Precondition Failed - Destination Folder exists. Overwrite needs to be TRUE.";
                }
                $this->ktwebdavLog("Overwrite is TRUE, deleting Destination Folder.", 'info', true);

                // Check if the user has permissions to delete this folder
                $oPerm =& KTPermission::getByName('ktcore.permissions.delete');
                $oUser =& User::get($this->userID);
                if (!KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oReplaceFolder)) {
                    return "403 Forbidden - User does not have sufficient permissions";
                }
                KTFolderUtil::delete($oReplaceFolder, 'KTWebDAV move overwrites target.');
                $new = false;
            }

            include_once(KT_LIB_DIR . '/foldermanagement/folderutil.inc.php');

            $oUser =& User::get($this->userID);
            $this->ktwebdavLog("Got an oSrcFolder of " . print_r($oSrcFolder, true), 'info', true);
            $this->ktwebdavLog("Got an oDestFolder of " . print_r($oDestFolder, true), 'info', true);
            $this->ktwebdavLog("Got an oUser of " . print_r($oUser, true), 'info', true);

            // Check if the user has permissions to write in this folder
            $oPerm =& KTPermission::getByName('ktcore.permissions.write');
            $oUser =& User::get($this->userID);
            if (!KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oDestFolder)) {
                return "403 Forbidden - User does not have sufficient permissions";
            }
            KTFolderUtil::move($oSrcFolder, $oDestFolder, $oUser);

            $this->ktwebdavLog("201 Created", 'info', true);
            return "201 Created";

        }

        /**
         * COPY method handler
         *
         * @param  array   parameter passing array
         * @param  string  delete source flag
         * @return string  HTTP status code or false
         */
        function COPY($options, $del = false)
        {
            $this->ktwebdavLog("Entering COPY. options are " . print_r($options, true), 'info', true);
            $this->ktwebdavLog("del is: " . $del, 'info', true);

            if ($this->checkSafeMode()) {

                if (!empty($_SERVER["CONTENT_LENGTH"])) { // no body parsing yet
                    $this->ktwebdavLog("415 Unsupported media type", 'info', true);
                    return "415 Unsupported media type - No body parsing yet";
                }

                /*		// no copying to different WebDAV Servers yet
                        if (isset($options["dest_url"])) {
                        $this->ktwebdavLog("502 bad gateway", 'info', true);
                        return "502 bad gateway - No copying to different WebDAV Servers yet";
                        }
                 */
                $source_path = $options["path"];
                $this->ktwebdavLog("SourcePath is: " . $source_path, 'info', true);
                $source_res = $this->_folderOrDocument($source_path);
                if ($source_res === false) {
                    $this->ktwebdavLog("404 Not found - The document could not be found.", 'info', true);
                    return "404 Not found - The document could not be found.";
                }

                list($iFolderID, $iDocumentID) = $source_res;
                if ($iDocumentID === false) {
                    $this->ktwebdavLog("404 Not found - The folder could not be found.", 'info', true);
                    return "404 Not found - The folder could not be found.";
                }

                if (is_null($iDocumentID)) {
                    // Source is a folder
                    $this->ktwebdavLog("Source is a Folder.", 'info', true);
                    $copystat = $this->_COPYFolder($options, $iFolderID);

                } else {
                    // Source is a document
                    $this->ktwebdavLog("Source is a Document.", 'info', true);

					if ($this->canCopyMoveRenameDocument($iDocumentID)) {
						$copystat = $this->_COPYDocument($options, $iFolderID, $iDocumentID, $dest_folder_id);
					} else {
						return "Cannot COPY document because it is checked out by another user.";
					}

                }

                // Delete the source if this is a move and the copy was ok
                if ($del && ($copystat{0} == "2")) {
                    $delstat = $this->DELETE(array("path" => $options["path"]));
                    $this->ktwebdavLog("DELETE in COPY/MOVE stat is: " . $delstat, 'info', true);
                    if (($delstat{0} != "2") && (substr($delstat, 0, 3) != "404")) {
                        return $delstat;
                    }
                }

                $this->ktwebdavLog("Final copystat result is: " . $copystat, 'info', true);
                return $copystat;

            }  else return "423 Locked - KTWebDAV is in SafeMode";
        }

        /**
         * COPY method helper for Documents
         *
         * @param  array   parameter passing array
         * @param  int     Folder ID
         * @param  int     Document ID
         * @return string  HTTP status code or false
         */
        function _COPYDocument($options, $iFolderID, $iDocumentID) {

            if ($options['dest'] == '') $options["dest"] = substr($options["dest_url"], strlen($_SERVER["SCRIPT_NAME"]));
            $this->ktwebdavLog("Entering _COPYDocument. options are " . print_r($options, true), 'info', true);

            if ($options["depth"] != "infinity") {
                // RFC 2518 Section 9.2, last paragraph
                $this->ktwebdavLog("400 Bad request", 'info', true);
                return "400 Bad request - Depth must be 'infinity'.";
            }

            global $default;

            $source_path = $options["path"];
            $dest_path = urldecode($options["dest"]);

            $oSrcFolder = Folder::get($iFolderID);

            list($iDestFolder, $iDestDoc) = $this->_folderOrDocument($dest_path);

            if (is_null($iDestDoc)) {
                // the dest is a folder
                //			$this->ktwebdavLog("400 Bad request", 'info', true);
                return "400 Bad request - Destination is a Folder";
            } else if ($iDestDoc !== false) {
                // Document exists
                $this->ktwebdavLog("Destination Document exists.", 'info', true);
                $oReplaceDoc = Document::get($iDestDoc);
                if ($options['overwrite'] != 'T') {
                    $this->ktwebdavLog("Overwrite needs to be TRUE.", 'info', true);
                    return "412 Precondition Failed - Destination Document exists. Overwrite needs to be TRUE.";
                }
                $this->ktwebdavLog("Overwrite is TRUE, deleting Destination Document.", 'info', true);

                // Check if the user has permissions to delete this document
                $oPerm =& KTPermission::getByName('ktcore.permissions.delete');
                $oUser =& User::get($this->userID);
                if (!KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oReplaceDoc)) {
                    return "403 Forbidden - User does not have sufficient permissions";
                }
                KTDocumentUtil::delete($oReplaceDoc, 'KTWebDAV copy with overwrite set.');
                $new = false;
            }

            $oDestFolder = Folder::get($iDestFolder);
            $oSrcDoc = Document::get($iDocumentID);

            include_once(KT_LIB_DIR . '/foldermanagement/folderutil.inc.php');

            $this->ktwebdavLog("Got an oSrcDoc of " . print_r($oSrcDoc, true), 'info', true);
            $this->ktwebdavLog("Got an oDestFolder of " . print_r($oDestFolder, true), 'info', true);

            // Check if the user has permissions to write in this folder
            $oPerm =& KTPermission::getByName('ktcore.permissions.write');
            $oUser =& User::get($this->userID);
            if (!KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oSrcDoc)) {
                return "403 Forbidden - User does not have sufficient permissions";
            }
            KTDocumentUtil::copy($oSrcDoc, $oDestFolder, $_SERVER['HTTP_REASON']);

            // FIXME: Do failure checking here

            $new = false;
            if ($new) {
                $this->ktwebdavLog("201 Created", 'info', true);
                return "201 Created";
            } else {
                $this->ktwebdavLog("204 No Content", 'info', true);
                return "204 No Content";
            }
        }

        /**
         * COPY method helper for Folders
         *
         * @param  array   parameter passing array
         * @param  int     Parent Folder ID
         * @return string  HTTP status code or false
         */
        function _COPYFolder($options, $iFolderID) {

            if ($options['dest'] == '') $options["dest"] = substr($options["dest_url"], strlen($_SERVER["SCRIPT_NAME"]));
            $this->ktwebdavLog("Entering _COPYFolder. options are " . print_r($options, true), 'info', true);

            if ($options["depth"] != "infinity") {
                // RFC 2518 Section 9.2, last paragraph
                $this->ktwebdavLog("400 Bad request", 'info', true);
                return "400 Bad request - Depth must be 'infinity'.";
            }

            global $default;

            $new = true;

            $source_path = $options["path"];
            $dest_path = urldecode($options["dest"]);

            $oSrcFolder = Folder::get($iFolderID);

            list($iDestFolder, $iDestDoc) = $this->_folderOrDocument($dest_path);

            $oDestFolder = Folder::get($iDestFolder);

            include_once(KT_LIB_DIR . '/foldermanagement/folderutil.inc.php');

            if (is_null($iDestDoc)) {
                // the dest is a folder
                $this->ktwebdavLog("The Destination is a Folder.", 'info', true);
            } else if ($iDestDoc !== false) {
                // Folder exists
                $this->ktwebdavLog("Destination Folder exists.", 'info', true);
                $oReplaceFolder = Folder::get($iDestDoc);
                if ($options['overwrite'] != 'T') {
                    $this->ktwebdavLog("Overwrite needs to be TRUE.", 'info', true);
                    return "412 Precondition Failed - Destination Folder exists. Overwrite needs to be TRUE.";
                }
                $this->ktwebdavLog("Overwrite is TRUE, deleting Destination Folder.", 'info', true);

                // Check if the user has permissions to delete this folder
                $oPerm =& KTPermission::getByName('ktcore.permissions.delete');
                $oUser =& User::get($this->userID);
                if (!KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oReplaceFolder)) {
                    return "403 Forbidden - User does not have sufficient permissions";
                }
                KTFolderUtil::delete($oReplaceFolder, 'KTWebDAV move overwrites target.');
                $new = false;
            }

            $oUser =& User::get($this->userID);
            $this->ktwebdavLog("Got an oSrcFolder of " . print_r($oSrcFolder, true), 'info', true);
            $this->ktwebdavLog("Got an oDestFolder of " . print_r($oDestFolder, true), 'info', true);
            $this->ktwebdavLog("Got an oUser of " . print_r($oUser, true), 'info', true);

            // Check if the user has permissions to write in this folder
            $oPerm =& KTPermission::getByName('ktcore.permissions.write');
            $oUser =& User::get($this->userID);
            if (!KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oDestFolder)) {
                return "403 Forbidden - User does not have sufficient permissions";
            }
            KTFolderUtil::copy($oSrcFolder, $oDestFolder, $oUser, 'KTWebDAV Copy.');

            if ($new) {
                $this->ktwebdavLog("201 Created", 'info', true);
                return "201 Created";
            } else {
                $this->ktwebdavLog("204 No Content", 'info', true);
                return "204 No Content";
            }

        }

        /**
         * LOCK method handler
         *
         * @param  array   parameter passing array
         * @return string  HTTP status code or false
         */
        function LOCK(&$options)
        {
            return "200 OK";
        }

        /**
         * UNLOCK method handler
         *
         * @param  array   parameter passing array
         * @return string  HTTP status code or false
         */
        function UNLOCK(&$options)
        {
            return "200 OK";
        }

        /**
         * checkLock() helper
         *
         * @param  string  resource path to check for locks
         * @return string  HTTP status code or false
         */
        function checkLock($path)
        {
            $result = false;

            return $result;
        }


		/**
         * canCopyMoveRenameDocument() helper
         * checks if document is checked out; if not, returns true
         * if checked out, cheks if checked out by same user; if yes, returns true;
         * else returns false
         *
         * @return bool  true or false
         */
        function canCopyMoveRenameDocument($iDocumentID)
        {
        	$this->ktwebdavLog("Entering canCopyMoveRenameDocument ", 'info', true);

            $oDocument =& Document::get($iDocumentID);

			if (is_null($oDocument) || ($oDocument === false) || PEAR::isError($oDocument)) {
				$this->ktwebdavLog("Document invalid ". print_r($oDocument, true), 'info', true);
				return false;
			}

			if($oDocument->getIsCheckedOut()) {
				$info = array();
				$info["props"][] = $this->mkprop($sNameSpace, 'CheckedOut', $oDocument->getCheckedOutUserID());
				//$this->ktwebdavLog("getIsCheckedOut ". print_r($info,true), 'info', true);

				$oCOUser = User::get( $oDocument->getCheckedOutUserID() );

				if (PEAR::isError($oCOUser) || is_null($oCOUser) || ($oCOUser === false)) {
					$couser_id = '0';
				} else {
					$couser_id = $oCOUser->getID();
				}

				//$this->ktwebdavLog("getCheckedOutUserID " .$couser_id, 'info', true);

				$oUser =& User::get($this->userID);

				//$this->ktwebdavLog("this UserID " .$oUser->getID(), 'info', true);

				if (PEAR::isError($oUser) || is_null($oUser) || ($oUser === false)) {
						$this->ktwebdavLog("User invalid ". print_r($oUser, true), 'info', true);
						return false;
					} else {
						$ouser_id = $oUser->getID();
					}

				//$this->ktwebdavLog("that UserID " .$oCOUser->getID(), 'info', true);

				if ($couser_id != $ouser_id) {
					$this->ktwebdavLog("Document checked out by another user $couser_id != $ouser_id", 'info', true);
					return false;
				} else {
					$this->ktwebdavLog("Document checked out by this user", 'info', true);
					return true;
				}
			} else {
				//not checked out
				$this->ktwebdavLog("Document not checked out by any user", 'info', true);
				return true;
			}
        }

        /**
         * checkSafeMode() helper
         *
         * @return bool  true or false
         */
        function checkSafeMode()
        {

            // Check/Set the WebDAV Client
            $userAgentValue = $_SERVER['HTTP_USER_AGENT'];
            // KT Explorer
            if (stristr($userAgentValue,"Microsoft Data Access Internet Publishing Provider DAV")) {
                $this->dav_client = "MS";
                $this->ktwebdavLog("WebDAV Client : " . $userAgentValue, 'info', true);
            }
            // Mac Finder
            if (stristr($userAgentValue,"Macintosh") || stristr($userAgentValue,"Darwin")) {
                $this->dav_client = "MC";
                $this->ktwebdavLog("WebDAV Client : " . $userAgentValue, 'info', true);
            }
            // Mac Goliath
            if (stristr($userAgentValue,"Goliath")) {
                $this->dav_client = "MG";
                $this->ktwebdavLog("WebDAV Client : " . $userAgentValue, 'info', true);
            }
            // Konqueror
            if (stristr($userAgentValue,"Konqueror")) {
                $this->dav_client = "KO";
                $this->ktwebdavLog("WebDAV Client : " . $userAgentValue, 'info', true);
            }
            // Neon Library ( Gnome Nautilus, cadaver, etc)
            if (stristr($userAgentValue,"neon")) {
                $this->dav_client = "NE";
                $this->ktwebdavLog("WebDAV Client : " . $userAgentValue, 'info', true);
            }
            // Windows WebDAV
            if ($this->dav_client == 'MS' && $this->safeMode == 'off') {

                $this->ktwebdavLog("This is MS type client with SafeMode Off.", 'info', true);
                return true;

            }
            if ($this->dav_client == 'MS' && $this->safeMode != 'off') {

                $this->ktwebdavLog("This is MS type client with SafeMode On.", 'info', true);
                return false;

            }
            // Mac Finder
            if ($this->dav_client == 'MC') {

                $this->ktwebdavLog("This is Mac Finder type client which only supports SafeMode.", 'info', true);
                return false;

            }
            // Mac Goliath
            if ($this->dav_client == 'MG' && $this->safeMode == 'off') {

                $this->ktwebdavLog("This is a Mac Goliath type client with SafeMode off.", 'info', true);
                return true;

            }
            // Mac Goliath
            if ($this->dav_client == 'MG' && $this->safeMode != 'off') {

                $this->ktwebdavLog("This is a Mac Goliath type client with SafeMode on.", 'info', true);
                return false;

            }
            // Konqueror
            if ($this->dav_client == 'KO' && $this->safeMode == 'off') {

                $this->ktwebdavLog("This is Konqueror type client with SafeMode Off.", 'info', true);
                return true;

            }
            if ($this->dav_client == 'KO' && $this->safeMode != 'off') {

                $this->ktwebdavLog("This is Konqueror type client with SafeMode On.", 'info', true);
                return false;

            }
            // Neon Library (Gnome Nautilus, cadaver, etc.)
            if ($this->dav_client == 'NE' && $this->safeMode == 'off') {

                $this->ktwebdavLog("This is Neon type client with SafeMode Off.", 'info', true);
                return true;

            }
            if ($this->dav_client == 'NE' && $this->safeMode != 'off') {

                $this->ktwebdavLog("This is Neon type client with SafeMode On.", 'info', true);
                return false;

            }

            $this->ktwebdavLog("Unknown client. SafeMode needed.", 'info', true);
            return false;

        }

        }


        ?>