Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.
/lib/ -> webdavlib.php (source)

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 and 403]

   1  <?php
   2  
   3  // This file is part of Moodle - http://moodle.org/
   4  //
   5  // Moodle is free software: you can redistribute it and/or modify
   6  // it under the terms of the GNU General Public License as published by
   7  // the Free Software Foundation, either version 3 of the License, or
   8  // (at your option) any later version.
   9  //
  10  // Moodle is distributed in the hope that it will be useful,
  11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13  // GNU General Public License for more details.
  14  //
  15  // You should have received a copy of the GNU General Public License
  16  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  17  
  18  /**
  19   * A Moodle-modified WebDAV client, based on
  20   * webdav_client v0.1.5, a php based webdav client class.
  21   * class webdav client. a php based nearly RFC 2518 conforming client.
  22   *
  23   * This class implements methods to get access to an webdav server.
  24   * Most of the methods are returning boolean false on error, an integer status (http response status) on success
  25   * or an array in case of a multistatus response (207) from the webdav server. Look at the code which keys are used in arrays.
  26   * It's your responsibility to handle the webdav server responses in an proper manner.
  27   * Please notice that all Filenames coming from or going to the webdav server should be UTF-8 encoded (see RFC 2518).
  28   * This class tries to convert all you filenames into utf-8 when it's needed.
  29   *
  30   * Moodle modifications:
  31   * * Moodle 3.4: Add support for OAuth 2 bearer token-based authentication
  32   *
  33   * @package moodlecore
  34   * @author Christian Juerges <christian.juerges@xwave.ch>, Xwave GmbH, Josefstr. 92, 8005 Zuerich - Switzerland
  35   * @copyright (C) 2003/2004, Christian Juerges
  36   * @license http://opensource.org/licenses/lgpl-license.php GNU Lesser General Public License
  37   */
  38  
  39  class webdav_client {
  40  
  41      /**#@+
  42       * @access private
  43       * @var string
  44       */
  45      private $_debug = false;
  46      private $sock;
  47      private $_server;
  48      private $_protocol = 'HTTP/1.1';
  49      private $_port = 80;
  50      private $_socket = '';
  51      private $_path ='/';
  52      private $_auth = false;
  53      private $_user;
  54      private $_pass;
  55  
  56      private $_socket_timeout = 5;
  57      private $_errno;
  58      private $_errstr;
  59      private $_user_agent = 'Moodle WebDav Client';
  60      private $_crlf = "\r\n";
  61      private $_req;
  62      private $_resp_status;
  63      private $_parser;
  64      private $_parserid;
  65      private $_xmltree;
  66      private $_tree;
  67      private $_ls = array();
  68      private $_ls_ref;
  69      private $_ls_ref_cdata;
  70      private $_delete = array();
  71      private $_delete_ref;
  72      private $_delete_ref_cdata;
  73      private $_lock = array();
  74      private $_lock_ref;
  75      private $_lock_rec_cdata;
  76      private $_null = NULL;
  77      private $_header='';
  78      private $_body='';
  79      private $_connection_closed = false;
  80      private $_maxheaderlenth = 65536;
  81      private $_digestchallenge = null;
  82      private $_cnonce = '';
  83      private $_nc = 0;
  84  
  85      /**
  86       * OAuth token used for bearer auth.
  87       * @var string
  88       */
  89      private $oauthtoken;
  90  
  91      /**#@-*/
  92  
  93      /**
  94       * Constructor - Initialise class variables
  95       * @param string $server Hostname of the server to connect to
  96       * @param string $user Username (for basic/digest auth, see $auth)
  97       * @param string $pass Password (for basic/digest auth, see $auth)
  98       * @param bool $auth Authentication type; one of ['basic', 'digest', 'bearer']
  99       * @param string $socket Used protocol for fsockopen, usually: '' (empty) or 'ssl://'
 100       * @param string $oauthtoken OAuth 2 bearer token (for bearer auth, see $auth)
 101       */
 102      public function __construct($server = '', $user = '', $pass = '', $auth = false, $socket = '', $oauthtoken = '') {
 103          if (!empty($server)) {
 104              $this->_server = $server;
 105          }
 106          if (!empty($user) && !empty($pass)) {
 107              $this->user = $user;
 108              $this->pass = $pass;
 109          }
 110          $this->_auth = $auth;
 111          $this->_socket = $socket;
 112          if ($auth == 'bearer') {
 113              $this->oauthtoken = $oauthtoken;
 114          }
 115      }
 116      public function __set($key, $value) {
 117          $property = '_' . $key;
 118          $this->$property = $value;
 119      }
 120  
 121      /**
 122       * Set which HTTP protocol will be used.
 123       * Value 1 defines that HTTP/1.1 should be used (Keeps Connection to webdav server alive).
 124       * Otherwise HTTP/1.0 will be used.
 125       * @param int version
 126       */
 127      function set_protocol($version) {
 128          if ($version == 1) {
 129              $this->_protocol = 'HTTP/1.1';
 130          } else {
 131              $this->_protocol = 'HTTP/1.0';
 132          }
 133      }
 134  
 135      /**
 136       * Convert ISO 8601 Date and Time Profile used in RFC 2518 to an unix timestamp.
 137       * @access private
 138       * @param string iso8601
 139       * @return unixtimestamp on sucess. Otherwise false.
 140       */
 141      function iso8601totime($iso8601) {
 142          /*
 143  
 144           date-time       = full-date "T" full-time
 145  
 146           full-date       = date-fullyear "-" date-month "-" date-mday
 147           full-time       = partial-time time-offset
 148  
 149           date-fullyear   = 4DIGIT
 150           date-month      = 2DIGIT  ; 01-12
 151           date-mday       = 2DIGIT  ; 01-28, 01-29, 01-30, 01-31 based on
 152           month/year
 153           time-hour       = 2DIGIT  ; 00-23
 154           time-minute     = 2DIGIT  ; 00-59
 155           time-second     = 2DIGIT  ; 00-59, 00-60 based on leap second rules
 156           time-secfrac    = "." 1*DIGIT
 157           time-numoffset  = ("+" / "-") time-hour ":" time-minute
 158           time-offset     = "Z" / time-numoffset
 159  
 160           partial-time    = time-hour ":" time-minute ":" time-second
 161                                              [time-secfrac]
 162           */
 163  
 164          $regs = array();
 165          /*         [1]        [2]        [3]        [4]        [5]        [6]  */
 166          if (preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z$/', $iso8601, $regs)) {
 167              return mktime($regs[4],$regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
 168          }
 169          // to be done: regex for partial-time...apache webdav mod never returns partial-time
 170  
 171          return false;
 172      }
 173  
 174      /**
 175       * Open's a socket to a webdav server
 176       * @return bool true on success. Otherwise false.
 177       */
 178      function open() {
 179          // let's try to open a socket
 180          $this->_error_log('open a socket connection');
 181          $this->sock = fsockopen($this->_socket . $this->_server, $this->_port, $this->_errno, $this->_errstr, $this->_socket_timeout);
 182          core_php_time_limit::raise(30);
 183          if (is_resource($this->sock)) {
 184              socket_set_blocking($this->sock, true);
 185              $this->_connection_closed = false;
 186              $this->_error_log('socket is open: ' . $this->sock);
 187              return true;
 188          } else {
 189              $this->_error_log("$this->_errstr ($this->_errno)\n");
 190              return false;
 191          }
 192      }
 193  
 194      /**
 195       * Closes an open socket.
 196       */
 197      function close() {
 198          $this->_error_log('closing socket ' . $this->sock);
 199          $this->_connection_closed = true;
 200          if (is_resource($this->sock)) {
 201              // Only close the socket if it is a resource.
 202              fclose($this->sock);
 203          }
 204      }
 205  
 206      /**
 207       * Check's if server is a webdav compliant server.
 208       * True if server returns a DAV Element in Header and when
 209       * schema 1,2 is supported.
 210       * @return bool true if server is webdav server. Otherwise false.
 211       */
 212      function check_webdav() {
 213          $resp = $this->options();
 214          if (!$resp) {
 215              return false;
 216          }
 217          $this->_error_log($resp['header']['DAV']);
 218          // check schema
 219          if (preg_match('/1,2/', $resp['header']['DAV'])) {
 220              return true;
 221          }
 222          // otherwise return false
 223          return false;
 224      }
 225  
 226  
 227      /**
 228       * Get options from webdav server.
 229       * @return array with all header fields returned from webdav server. false if server does not speak http.
 230       */
 231      function options() {
 232          $this->header_unset();
 233          $this->create_basic_request('OPTIONS');
 234          $this->send_request();
 235          $this->get_respond();
 236          $response = $this->process_respond();
 237          // validate the response ...
 238          // check http-version
 239          if ($response['status']['http-version'] == 'HTTP/1.1' ||
 240              $response['status']['http-version'] == 'HTTP/1.0') {
 241                  return $response;
 242              }
 243          $this->_error_log('Response was not even http');
 244          return false;
 245  
 246      }
 247  
 248      /**
 249       * Public method mkcol
 250       *
 251       * Creates a new collection/directory on a webdav server
 252       * @param string path
 253       * @return int status code received as response from webdav server (see rfc 2518)
 254       */
 255      function mkcol($path) {
 256          $this->_path = $this->translate_uri($path);
 257          $this->header_unset();
 258          $this->create_basic_request('MKCOL');
 259          $this->send_request();
 260          $this->get_respond();
 261          $response = $this->process_respond();
 262          // validate the response ...
 263          // check http-version
 264          $http_version = $response['status']['http-version'];
 265          if ($http_version == 'HTTP/1.1' || $http_version == 'HTTP/1.0') {
 266              /** seems to be http ... proceed
 267               * just return what server gave us
 268               * rfc 2518 says:
 269               * 201 (Created) - The collection or structured resource was created in its entirety.
 270               * 403 (Forbidden) - This indicates at least one of two conditions:
 271               *    1) the server does not allow the creation of collections at the given location in its namespace, or
 272               *    2) the parent collection of the Request-URI exists but cannot accept members.
 273               * 405 (Method Not Allowed) - MKCOL can only be executed on a deleted/non-existent resource.
 274               * 409 (Conflict) - A collection cannot be made at the Request-URI until one or more intermediate
 275               *                  collections have been created.
 276               * 415 (Unsupported Media Type)- The server does not support the request type of the body.
 277               * 507 (Insufficient Storage) - The resource does not have sufficient space to record the state of the
 278               *                              resource after the execution of this method.
 279               */
 280              return $response['status']['status-code'];
 281          }
 282  
 283      }
 284  
 285      /**
 286       * Public method get
 287       *
 288       * Gets a file from a webdav collection.
 289       * @param string $path the path to the file on the webdav server
 290       * @param string &$buffer the buffer to store the data in
 291       * @param resource $fp optional if included, the data is written directly to this resource and not to the buffer
 292       * @return string|bool status code and &$buffer (by reference) with response data from server on success. False on error.
 293       */
 294      function get($path, &$buffer, $fp = null) {
 295          $this->_path = $this->translate_uri($path);
 296          $this->header_unset();
 297          $this->create_basic_request('GET');
 298          $this->send_request();
 299          $this->get_respond($fp);
 300          $response = $this->process_respond();
 301  
 302          $http_version = $response['status']['http-version'];
 303          // validate the response
 304          // check http-version
 305          if ($http_version == 'HTTP/1.1' || $http_version == 'HTTP/1.0') {
 306                  // seems to be http ... proceed
 307                  // We expect a 200 code
 308                  if ($response['status']['status-code'] == 200 ) {
 309                      if (!is_null($fp)) {
 310                          $stat = fstat($fp);
 311                          $this->_error_log('file created with ' . $stat['size'] . ' bytes.');
 312                      } else {
 313                          $this->_error_log('returning buffer with ' . strlen($response['body']) . ' bytes.');
 314                          $buffer = $response['body'];
 315                      }
 316                  }
 317                  return $response['status']['status-code'];
 318              }
 319          // ups: no http status was returned ?
 320          return false;
 321      }
 322  
 323      /**
 324       * Public method put
 325       *
 326       * Puts a file into a collection.
 327       *	 Data is putted as one chunk!
 328       * @param string path, string data
 329       * @return int status-code read from webdavserver. False on error.
 330       */
 331      function put($path, $data ) {
 332          $this->_path = $this->translate_uri($path);
 333          $this->header_unset();
 334          $this->create_basic_request('PUT');
 335          // add more needed header information ...
 336          $this->header_add('Content-length: ' . strlen($data));
 337          $this->header_add('Content-type: application/octet-stream');
 338          // send header
 339          $this->send_request();
 340          // send the rest (data)
 341          fputs($this->sock, $data);
 342          $this->get_respond();
 343          $response = $this->process_respond();
 344  
 345          // validate the response
 346          // check http-version
 347          if ($response['status']['http-version'] == 'HTTP/1.1' ||
 348              $response['status']['http-version'] == 'HTTP/1.0') {
 349                  // seems to be http ... proceed
 350                  // We expect a 200 or 204 status code
 351                  // see rfc 2068 - 9.6 PUT...
 352                  // print 'http ok<br>';
 353                  return $response['status']['status-code'];
 354              }
 355          // ups: no http status was returned ?
 356          return false;
 357      }
 358  
 359      /**
 360       * Public method put_file
 361       *
 362       * Read a file as stream and puts it chunk by chunk into webdav server collection.
 363       *
 364       * Look at php documenation for legal filenames with fopen();
 365       * The filename will be translated into utf-8 if not allready in utf-8.
 366       *
 367       * @param string targetpath, string filename
 368       * @return int status code. False on error.
 369       */
 370      function put_file($path, $filename) {
 371          // try to open the file ...
 372  
 373  
 374          $handle = @fopen ($filename, 'r');
 375  
 376          if ($handle) {
 377              // $this->sock = pfsockopen ($this->_server, $this->_port, $this->_errno, $this->_errstr, $this->_socket_timeout);
 378              $this->_path = $this->translate_uri($path);
 379              $this->header_unset();
 380              $this->create_basic_request('PUT');
 381              // add more needed header information ...
 382              $this->header_add('Content-length: ' . filesize($filename));
 383              $this->header_add('Content-type: application/octet-stream');
 384              // send header
 385              $this->send_request();
 386              while (!feof($handle)) {
 387                  fputs($this->sock,fgets($handle,4096));
 388              }
 389              fclose($handle);
 390              $this->get_respond();
 391              $response = $this->process_respond();
 392  
 393              // validate the response
 394              // check http-version
 395              if ($response['status']['http-version'] == 'HTTP/1.1' ||
 396                  $response['status']['http-version'] == 'HTTP/1.0') {
 397                      // seems to be http ... proceed
 398                      // We expect a 200 or 204 status code
 399                      // see rfc 2068 - 9.6 PUT...
 400                      // print 'http ok<br>';
 401                      return $response['status']['status-code'];
 402                  }
 403              // ups: no http status was returned ?
 404              return false;
 405          } else {
 406              $this->_error_log('put_file: could not open ' . $filename);
 407              return false;
 408          }
 409  
 410      }
 411  
 412      /**
 413       * Public method get_file
 414       *
 415       * Gets a file from a collection into local filesystem.
 416       *
 417       * fopen() is used.
 418       * @param string $srcpath
 419       * @param string $localpath
 420       * @return bool true on success. false on error.
 421       */
 422      function get_file($srcpath, $localpath) {
 423  
 424          $localpath = $this->utf_decode_path($localpath);
 425  
 426          $handle = fopen($localpath, 'wb');
 427          if ($handle) {
 428              $unused = '';
 429              $ret = $this->get($srcpath, $unused, $handle);
 430              fclose($handle);
 431              if ($ret) {
 432                  return true;
 433              }
 434          }
 435          return false;
 436      }
 437  
 438      /**
 439       * Public method copy_file
 440       *
 441       * Copies a file on a webdav server
 442       *
 443       * Duplicates a file on the webdav server (serverside).
 444       * All work is done on the webdav server. If you set param overwrite as true,
 445       * the target will be overwritten.
 446       *
 447       * @param string src_path, string dest_path, bool overwrite
 448       * @return int status code (look at rfc 2518). false on error.
 449       */
 450      function copy_file($src_path, $dst_path, $overwrite) {
 451          $this->_path = $this->translate_uri($src_path);
 452          $this->header_unset();
 453          $this->create_basic_request('COPY');
 454          $this->header_add(sprintf('Destination: http://%s%s', $this->_server, $this->translate_uri($dst_path)));
 455          if ($overwrite) {
 456              $this->header_add('Overwrite: T');
 457          } else {
 458              $this->header_add('Overwrite: F');
 459          }
 460          $this->header_add('');
 461          $this->send_request();
 462          $this->get_respond();
 463          $response = $this->process_respond();
 464          // validate the response ...
 465          // check http-version
 466          if ($response['status']['http-version'] == 'HTTP/1.1' ||
 467              $response['status']['http-version'] == 'HTTP/1.0') {
 468           /* seems to be http ... proceed
 469               just return what server gave us (as defined in rfc 2518) :
 470               201 (Created) - The source resource was successfully copied. The copy operation resulted in the creation of a new resource.
 471               204 (No Content) - The source resource was successfully copied to a pre-existing destination resource.
 472               403 (Forbidden) - The source and destination URIs are the same.
 473               409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created.
 474               412 (Precondition Failed) - The server was unable to maintain the liveness of the properties listed in the propertybehavior XML element
 475                       or the Overwrite header is "F" and the state of the destination resource is non-null.
 476               423 (Locked) - The destination resource was locked.
 477               502 (Bad Gateway) - This may occur when the destination is on another server and the destination server refuses to accept the resource.
 478               507 (Insufficient Storage) - The destination resource does not have sufficient space to record the state of the resource after the
 479                       execution of this method.
 480            */
 481                  return $response['status']['status-code'];
 482              }
 483          return false;
 484      }
 485  
 486      /**
 487       * Public method copy_coll
 488       *
 489       * Copies a collection on a webdav server
 490       *
 491       * Duplicates a collection on the webdav server (serverside).
 492       * All work is done on the webdav server. If you set param overwrite as true,
 493       * the target will be overwritten.
 494       *
 495       * @param string src_path, string dest_path, bool overwrite
 496       * @return int status code (look at rfc 2518). false on error.
 497       */
 498      function copy_coll($src_path, $dst_path, $overwrite) {
 499          $this->_path = $this->translate_uri($src_path);
 500          $this->header_unset();
 501          $this->create_basic_request('COPY');
 502          $this->header_add(sprintf('Destination: http://%s%s', $this->_server, $this->translate_uri($dst_path)));
 503          $this->header_add('Depth: Infinity');
 504  
 505          $xml  = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n";
 506          $xml .= "<d:propertybehavior xmlns:d=\"DAV:\">\r\n";
 507          $xml .= "  <d:keepalive>*</d:keepalive>\r\n";
 508          $xml .= "</d:propertybehavior>\r\n";
 509  
 510          $this->header_add('Content-length: ' . strlen($xml));
 511          $this->header_add('Content-type: application/xml');
 512          $this->send_request();
 513          // send also xml
 514          fputs($this->sock, $xml);
 515          $this->get_respond();
 516          $response = $this->process_respond();
 517          // validate the response ...
 518          // check http-version
 519          if ($response['status']['http-version'] == 'HTTP/1.1' ||
 520              $response['status']['http-version'] == 'HTTP/1.0') {
 521           /* seems to be http ... proceed
 522               just return what server gave us (as defined in rfc 2518) :
 523               201 (Created) - The source resource was successfully copied. The copy operation resulted in the creation of a new resource.
 524               204 (No Content) - The source resource was successfully copied to a pre-existing destination resource.
 525               403 (Forbidden) - The source and destination URIs are the same.
 526               409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created.
 527               412 (Precondition Failed) - The server was unable to maintain the liveness of the properties listed in the propertybehavior XML element
 528                       or the Overwrite header is "F" and the state of the destination resource is non-null.
 529               423 (Locked) - The destination resource was locked.
 530               502 (Bad Gateway) - This may occur when the destination is on another server and the destination server refuses to accept the resource.
 531               507 (Insufficient Storage) - The destination resource does not have sufficient space to record the state of the resource after the
 532                       execution of this method.
 533            */
 534                  return $response['status']['status-code'];
 535              }
 536          return false;
 537      }
 538  
 539      /**
 540       * Public method move
 541       *
 542       * Moves a file or collection on webdav server (serverside)
 543       *
 544       * If you set param overwrite as true, the target will be overwritten.
 545       *
 546       * @param string src_path, string dest_path, bool overwrite
 547       * @return int status code (look at rfc 2518). false on error.
 548       */
 549      // --------------------------------------------------------------------------
 550      // public method move
 551      // move/rename a file/collection on webdav server
 552      function move($src_path,$dst_path, $overwrite) {
 553  
 554          $this->_path = $this->translate_uri($src_path);
 555          $this->header_unset();
 556  
 557          $this->create_basic_request('MOVE');
 558          $this->header_add(sprintf('Destination: http://%s%s', $this->_server, $this->translate_uri($dst_path)));
 559          if ($overwrite) {
 560              $this->header_add('Overwrite: T');
 561          } else {
 562              $this->header_add('Overwrite: F');
 563          }
 564          $this->header_add('');
 565  
 566          $this->send_request();
 567          $this->get_respond();
 568          $response = $this->process_respond();
 569          // validate the response ...
 570          // check http-version
 571          if ($response['status']['http-version'] == 'HTTP/1.1' ||
 572              $response['status']['http-version'] == 'HTTP/1.0') {
 573              /* seems to be http ... proceed
 574                  just return what server gave us (as defined in rfc 2518) :
 575                  201 (Created) - The source resource was successfully moved, and a new resource was created at the destination.
 576                  204 (No Content) - The source resource was successfully moved to a pre-existing destination resource.
 577                  403 (Forbidden) - The source and destination URIs are the same.
 578                  409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created.
 579                  412 (Precondition Failed) - The server was unable to maintain the liveness of the properties listed in the propertybehavior XML element
 580                           or the Overwrite header is "F" and the state of the destination resource is non-null.
 581                  423 (Locked) - The source or the destination resource was locked.
 582                  502 (Bad Gateway) - This may occur when the destination is on another server and the destination server refuses to accept the resource.
 583  
 584                  201 (Created) - The collection or structured resource was created in its entirety.
 585                  403 (Forbidden) - This indicates at least one of two conditions: 1) the server does not allow the creation of collections at the given
 586                                                   location in its namespace, or 2) the parent collection of the Request-URI exists but cannot accept members.
 587                  405 (Method Not Allowed) - MKCOL can only be executed on a deleted/non-existent resource.
 588                  409 (Conflict) - A collection cannot be made at the Request-URI until one or more intermediate collections have been created.
 589                  415 (Unsupported Media Type)- The server does not support the request type of the body.
 590                  507 (Insufficient Storage) - The resource does not have sufficient space to record the state of the resource after the execution of this method.
 591               */
 592                  return $response['status']['status-code'];
 593              }
 594          return false;
 595      }
 596  
 597      /**
 598       * Public method lock
 599       *
 600       * Locks a file or collection.
 601       *
 602       * Lock uses this->_user as lock owner.
 603       *
 604       * @param string path
 605       * @return int status code (look at rfc 2518). false on error.
 606       */
 607      function lock($path) {
 608          $this->_path = $this->translate_uri($path);
 609          $this->header_unset();
 610          $this->create_basic_request('LOCK');
 611          $this->header_add('Timeout: Infinite');
 612          $this->header_add('Content-type: text/xml');
 613          // create the xml request ...
 614          $xml =  "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n";
 615          $xml .= "<D:lockinfo xmlns:D='DAV:'\r\n>";
 616          $xml .= "  <D:lockscope><D:exclusive/></D:lockscope>\r\n";
 617          $xml .= "  <D:locktype><D:write/></D:locktype>\r\n";
 618          $xml .= "  <D:owner>\r\n";
 619          $xml .= "    <D:href>".($this->_user)."</D:href>\r\n";
 620          $xml .= "  </D:owner>\r\n";
 621          $xml .= "</D:lockinfo>\r\n";
 622          $this->header_add('Content-length: ' . strlen($xml));
 623          $this->send_request();
 624          // send also xml
 625          fputs($this->sock, $xml);
 626          $this->get_respond();
 627          $response = $this->process_respond();
 628          // validate the response ... (only basic validation)
 629          // check http-version
 630          if ($response['status']['http-version'] == 'HTTP/1.1' ||
 631              $response['status']['http-version'] == 'HTTP/1.0') {
 632              /* seems to be http ... proceed
 633              rfc 2518 says:
 634              200 (OK) - The lock request succeeded and the value of the lockdiscovery property is included in the body.
 635              412 (Precondition Failed) - The included lock token was not enforceable on this resource or the server could not satisfy the
 636                       request in the lockinfo XML element.
 637              423 (Locked) - The resource is locked, so the method has been rejected.
 638               */
 639  
 640                  switch($response['status']['status-code']) {
 641                  case 200:
 642                      // collection was successfully locked... see xml response to get lock token...
 643                      if (strcmp($response['header']['Content-Type'], 'text/xml; charset="utf-8"') == 0) {
 644                          // ok let's get the content of the xml stuff
 645                          $this->_parser = xml_parser_create_ns();
 646                          $this->_parserid = $this->get_parser_id($this->_parser);
 647                          // forget old data...
 648                          unset($this->_lock[$this->_parserid]);
 649                          unset($this->_xmltree[$this->_parserid]);
 650                          xml_parser_set_option($this->_parser,XML_OPTION_SKIP_WHITE,0);
 651                          xml_parser_set_option($this->_parser,XML_OPTION_CASE_FOLDING,0);
 652                          xml_set_object($this->_parser, $this);
 653                          xml_set_element_handler($this->_parser, "_lock_startElement", "_endElement");
 654                          xml_set_character_data_handler($this->_parser, "_lock_cdata");
 655  
 656                          if (!xml_parse($this->_parser, $response['body'])) {
 657                              die(sprintf("XML error: %s at line %d",
 658                                  xml_error_string(xml_get_error_code($this->_parser)),
 659                                  xml_get_current_line_number($this->_parser)));
 660                          }
 661  
 662                          // Free resources
 663                          xml_parser_free($this->_parser);
 664                          // add status code to array
 665                          $this->_lock[$this->_parserid]['status'] = 200;
 666                          return $this->_lock[$this->_parserid];
 667  
 668                      } else {
 669                          print 'Missing Content-Type: text/xml header in response.<br>';
 670                      }
 671                      return false;
 672  
 673                  default:
 674                      // hmm. not what we expected. Just return what we got from webdav server
 675                      // someone else has to handle it.
 676                      $this->_lock['status'] = $response['status']['status-code'];
 677                      return $this->_lock;
 678                  }
 679              }
 680  
 681  
 682      }
 683  
 684  
 685      /**
 686       * Public method unlock
 687       *
 688       * Unlocks a file or collection.
 689       *
 690       * @param string path, string locktoken
 691       * @return int status code (look at rfc 2518). false on error.
 692       */
 693      function unlock($path, $locktoken) {
 694          $this->_path = $this->translate_uri($path);
 695          $this->header_unset();
 696          $this->create_basic_request('UNLOCK');
 697          $this->header_add(sprintf('Lock-Token: <%s>', $locktoken));
 698          $this->send_request();
 699          $this->get_respond();
 700          $response = $this->process_respond();
 701          if ($response['status']['http-version'] == 'HTTP/1.1' ||
 702              $response['status']['http-version'] == 'HTTP/1.0') {
 703              /* seems to be http ... proceed
 704              rfc 2518 says:
 705              204 (OK) - The 204 (No Content) status code is used instead of 200 (OK) because there is no response entity body.
 706               */
 707                  return $response['status']['status-code'];
 708              }
 709          return false;
 710      }
 711  
 712      /**
 713       * Public method delete
 714       *
 715       * deletes a collection/directory on a webdav server
 716       * @param string path
 717       * @return int status code (look at rfc 2518). false on error.
 718       */
 719      function delete($path) {
 720          $this->_path = $this->translate_uri($path);
 721          $this->header_unset();
 722          $this->create_basic_request('DELETE');
 723          /* $this->header_add('Content-Length: 0'); */
 724          $this->header_add('');
 725          $this->send_request();
 726          $this->get_respond();
 727          $response = $this->process_respond();
 728  
 729          // validate the response ...
 730          // check http-version
 731          if ($response['status']['http-version'] == 'HTTP/1.1' ||
 732              $response['status']['http-version'] == 'HTTP/1.0') {
 733                  // seems to be http ... proceed
 734                  // We expect a 207 Multi-Status status code
 735                  // print 'http ok<br>';
 736  
 737                  switch ($response['status']['status-code']) {
 738                  case 207:
 739                      // collection was NOT deleted... see xml response for reason...
 740                      // next there should be a Content-Type: text/xml; charset="utf-8" header line
 741                      if (strcmp($response['header']['Content-Type'], 'text/xml; charset="utf-8"') == 0) {
 742                          // ok let's get the content of the xml stuff
 743                          $this->_parser = xml_parser_create_ns();
 744                          $this->_parserid = $this->get_parser_id($this->_parser);
 745                          // forget old data...
 746                          unset($this->_delete[$this->_parserid]);
 747                          unset($this->_xmltree[$this->_parserid]);
 748                          xml_parser_set_option($this->_parser,XML_OPTION_SKIP_WHITE,0);
 749                          xml_parser_set_option($this->_parser,XML_OPTION_CASE_FOLDING,0);
 750                          xml_set_object($this->_parser, $this);
 751                          xml_set_element_handler($this->_parser, "_delete_startElement", "_endElement");
 752                          xml_set_character_data_handler($this->_parser, "_delete_cdata");
 753  
 754                          if (!xml_parse($this->_parser, $response['body'])) {
 755                              die(sprintf("XML error: %s at line %d",
 756                                  xml_error_string(xml_get_error_code($this->_parser)),
 757                                  xml_get_current_line_number($this->_parser)));
 758                          }
 759  
 760                          print "<br>";
 761  
 762                          // Free resources
 763                          xml_parser_free($this->_parser);
 764                          $this->_delete[$this->_parserid]['status'] = $response['status']['status-code'];
 765                          return $this->_delete[$this->_parserid];
 766  
 767                      } else {
 768                          print 'Missing Content-Type: text/xml header in response.<br>';
 769                      }
 770                      return false;
 771  
 772                  default:
 773                      // collection or file was successfully deleted
 774                      $this->_delete['status'] = $response['status']['status-code'];
 775                      return $this->_delete;
 776  
 777  
 778                  }
 779              }
 780  
 781      }
 782  
 783      /**
 784       * Public method ls
 785       *
 786       * Get's directory information from webdav server into flat a array using PROPFIND
 787       *
 788       * All filenames are UTF-8 encoded.
 789       * Have a look at _propfind_startElement what keys are used in array returned.
 790       * @param string path
 791       * @return array dirinfo, false on error
 792       */
 793      function ls($path) {
 794  
 795          if (trim($path) == '') {
 796              $this->_error_log('Missing a path in method ls');
 797              return false;
 798          }
 799          $this->_path = $this->translate_uri($path);
 800  
 801          $this->header_unset();
 802          $this->create_basic_request('PROPFIND');
 803          $this->header_add('Depth: 1');
 804          $this->header_add('Content-type: application/xml');
 805          // create profind xml request...
 806          $xml  = <<<EOD
 807  <?xml version="1.0" encoding="utf-8"?>
 808  <propfind xmlns="DAV:"><prop>
 809  <getcontentlength xmlns="DAV:"/>
 810  <getlastmodified xmlns="DAV:"/>
 811  <executable xmlns="http://apache.org/dav/props/"/>
 812  <resourcetype xmlns="DAV:"/>
 813  <checked-in xmlns="DAV:"/>
 814  <checked-out xmlns="DAV:"/>
 815  </prop></propfind>
 816  EOD;
 817          $this->header_add('Content-length: ' . strlen($xml));
 818          $this->send_request();
 819          $this->_error_log($xml);
 820          fputs($this->sock, $xml);
 821          $this->get_respond();
 822          $response = $this->process_respond();
 823          // validate the response ... (only basic validation)
 824          // check http-version
 825          if ($response['status']['http-version'] == 'HTTP/1.1' ||
 826              $response['status']['http-version'] == 'HTTP/1.0') {
 827                  // seems to be http ... proceed
 828                  // We expect a 207 Multi-Status status code
 829                  // print 'http ok<br>';
 830                  if (strcmp($response['status']['status-code'],'207') == 0 ) {
 831                      // ok so far
 832                      // next there should be a Content-Type: text/xml; charset="utf-8" header line
 833                      if (preg_match('#(application|text)/xml;\s?charset=[\'\"]?utf-8[\'\"]?#i', $response['header']['Content-Type'])) {
 834                          // ok let's get the content of the xml stuff
 835                          $this->_parser = xml_parser_create_ns('UTF-8');
 836                          $this->_parserid = $this->get_parser_id($this->_parser);
 837                          // forget old data...
 838                          unset($this->_ls[$this->_parserid]);
 839                          unset($this->_xmltree[$this->_parserid]);
 840                          xml_parser_set_option($this->_parser,XML_OPTION_SKIP_WHITE,0);
 841                          xml_parser_set_option($this->_parser,XML_OPTION_CASE_FOLDING,0);
 842                          // xml_parser_set_option($this->_parser,XML_OPTION_TARGET_ENCODING,'UTF-8');
 843                          xml_set_object($this->_parser, $this);
 844                          xml_set_element_handler($this->_parser, "_propfind_startElement", "_endElement");
 845                          xml_set_character_data_handler($this->_parser, "_propfind_cdata");
 846  
 847  
 848                          if (!xml_parse($this->_parser, $response['body'])) {
 849                              die(sprintf("XML error: %s at line %d",
 850                                  xml_error_string(xml_get_error_code($this->_parser)),
 851                                  xml_get_current_line_number($this->_parser)));
 852                          }
 853  
 854                          // Free resources
 855                          xml_parser_free($this->_parser);
 856                          $arr = $this->_ls[$this->_parserid];
 857                          return $arr;
 858                      } else {
 859                          $this->_error_log('Missing Content-Type: text/xml header in response!!');
 860                          return false;
 861                      }
 862                  } else {
 863                      // return status code ...
 864                      return $response['status']['status-code'];
 865                  }
 866              }
 867  
 868          // response was not http
 869          $this->_error_log('Ups in method ls: error in response from server');
 870          return false;
 871      }
 872  
 873  
 874      /**
 875       * Public method gpi
 876       *
 877       * Get's path information from webdav server for one element.
 878       *
 879       * @param string path
 880       * @return array dirinfo. false on error
 881       */
 882      function gpi($path) {
 883  
 884          // split path by last "/"
 885          $path = rtrim($path, "/");
 886          $item = basename($path);
 887          $dir  = dirname($path);
 888  
 889          $list = $this->ls($dir);
 890  
 891          // be sure it is an array
 892          if (is_array($list)) {
 893              foreach($list as $e) {
 894  
 895                  $fullpath = urldecode($e['href']);
 896                  $filename = basename($fullpath);
 897  
 898                  if ($filename == $item && $filename != "" and $fullpath != $dir."/") {
 899                      return $e;
 900                  }
 901              }
 902          }
 903          return false;
 904      }
 905  
 906      /**
 907       * Public method is_file
 908       *
 909       * Gathers whether a path points to a file or not.
 910       *
 911       * @param string path
 912       * @return bool true or false
 913       */
 914      function is_file($path) {
 915  
 916          $item = $this->gpi($path);
 917  
 918          if ($item === false) {
 919              return false;
 920          } else {
 921              return ($item['resourcetype'] != 'collection');
 922          }
 923      }
 924  
 925      /**
 926       * Public method is_dir
 927       *
 928       * Gather whether a path points to a directory
 929       * @param string path
 930       * return bool true or false
 931       */
 932      function is_dir($path) {
 933  
 934          // be sure path is utf-8
 935          $item = $this->gpi($path);
 936  
 937          if ($item === false) {
 938              return false;
 939          } else {
 940              return ($item['resourcetype'] == 'collection');
 941          }
 942      }
 943  
 944  
 945      /**
 946       * Public method mput
 947       *
 948       * Puts multiple files and/or directories onto a webdav server.
 949       *
 950       * Filenames should be allready UTF-8 encoded.
 951       * Param fileList must be in format array("localpath" => "destpath").
 952       *
 953       * @param array filelist
 954       * @return bool true on success. otherwise int status code on error
 955       */
 956      function mput($filelist) {
 957  
 958          $result = true;
 959  
 960          foreach ($filelist as $localpath => $destpath) {
 961  
 962              $localpath = rtrim($localpath, "/");
 963              $destpath  = rtrim($destpath, "/");
 964  
 965              // attempt to create target path
 966              if (is_dir($localpath)) {
 967                  $pathparts = explode("/", $destpath."/ "); // add one level, last level will be created as dir
 968              } else {
 969                  $pathparts = explode("/", $destpath);
 970              }
 971              $checkpath = "";
 972              for ($i=1; $i<sizeof($pathparts)-1; $i++) {
 973                  $checkpath .= "/" . $pathparts[$i];
 974                  if (!($this->is_dir($checkpath))) {
 975  
 976                      $result &= ($this->mkcol($checkpath) == 201 );
 977                  }
 978              }
 979  
 980              if ($result) {
 981                  // recurse directories
 982                  if (is_dir($localpath)) {
 983                      if (!$dp = opendir($localpath)) {
 984                          $this->_error_log("Could not open localpath for reading");
 985                          return false;
 986                      }
 987                      $fl = array();
 988                      while($filename = readdir($dp)) {
 989                          if ((is_file($localpath."/".$filename) || is_dir($localpath."/".$filename)) && $filename!="." && $filename != "..") {
 990                              $fl[$localpath."/".$filename] = $destpath."/".$filename;
 991                          }
 992                      }
 993                      $result &= $this->mput($fl);
 994                  } else {
 995                      $result &= ($this->put_file($destpath, $localpath) == 201);
 996                  }
 997              }
 998          }
 999          return $result;
1000      }
1001  
1002      /**
1003       * Public method mget
1004       *
1005       * Gets multiple files and directories.
1006       *
1007       * FileList must be in format array("remotepath" => "localpath").
1008       * Filenames are UTF-8 encoded.
1009       *
1010       * @param array filelist
1011       * @return bool true on succes, other int status code on error
1012       */
1013      function mget($filelist) {
1014  
1015          $result = true;
1016  
1017          foreach ($filelist as $remotepath => $localpath) {
1018  
1019              $localpath   = rtrim($localpath, "/");
1020              $remotepath  = rtrim($remotepath, "/");
1021  
1022              // attempt to create local path
1023              if ($this->is_dir($remotepath)) {
1024                  $pathparts = explode("/", $localpath."/ "); // add one level, last level will be created as dir
1025              } else {
1026                  $pathparts = explode("/", $localpath);
1027              }
1028              $checkpath = "";
1029              for ($i=1; $i<sizeof($pathparts)-1; $i++) {
1030                  $checkpath .= "/" . $pathparts[$i];
1031                  if (!is_dir($checkpath)) {
1032  
1033                      $result &= mkdir($checkpath);
1034                  }
1035              }
1036  
1037              if ($result) {
1038                  // recurse directories
1039                  if ($this->is_dir($remotepath)) {
1040                      $list = $this->ls($remotepath);
1041  
1042                      $fl = array();
1043                      foreach($list as $e) {
1044                          $fullpath = urldecode($e['href']);
1045                          $filename = basename($fullpath);
1046                          if ($filename != '' and $fullpath != $remotepath . '/') {
1047                              $fl[$remotepath."/".$filename] = $localpath."/".$filename;
1048                          }
1049                      }
1050                      $result &= $this->mget($fl);
1051                  } else {
1052                      $result &= ($this->get_file($remotepath, $localpath));
1053                  }
1054              }
1055          }
1056          return $result;
1057      }
1058  
1059      // --------------------------------------------------------------------------
1060      // private xml callback and helper functions starting here
1061      // --------------------------------------------------------------------------
1062  
1063  
1064      /**
1065       * Private method _endelement
1066       *
1067       * a generic endElement method  (used for all xml callbacks).
1068       *
1069       * @param resource parser, string name
1070       * @access private
1071       */
1072  
1073      private function _endElement($parser, $name) {
1074          // end tag was found...
1075          $parserid = $this->get_parser_id($parser);
1076          $this->_xmltree[$parserid] = substr($this->_xmltree[$parserid],0, strlen($this->_xmltree[$parserid]) - (strlen($name) + 1));
1077      }
1078  
1079      /**
1080       * Private method _propfind_startElement
1081       *
1082       * Is needed by public method ls.
1083       *
1084       * Generic method will called by php xml_parse when a xml start element tag has been detected.
1085       * The xml tree will translated into a flat php array for easier access.
1086       * @param resource parser, string name, string attrs
1087       * @access private
1088       */
1089      private function _propfind_startElement($parser, $name, $attrs) {
1090          // lower XML Names... maybe break a RFC, don't know ...
1091          $parserid = $this->get_parser_id($parser);
1092  
1093          $propname = strtolower($name);
1094          if (!empty($this->_xmltree[$parserid])) {
1095              $this->_xmltree[$parserid] .= $propname . '_';
1096          } else {
1097              $this->_xmltree[$parserid] = $propname . '_';
1098          }
1099  
1100          // translate xml tree to a flat array ...
1101          switch($this->_xmltree[$parserid]) {
1102          case 'dav::multistatus_dav::response_':
1103              // new element in mu
1104              $this->_ls_ref =& $this->_ls[$parserid][];
1105              break;
1106          case 'dav::multistatus_dav::response_dav::href_':
1107              $this->_ls_ref_cdata = &$this->_ls_ref['href'];
1108              break;
1109          case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::creationdate_':
1110              $this->_ls_ref_cdata = &$this->_ls_ref['creationdate'];
1111              break;
1112          case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getlastmodified_':
1113              $this->_ls_ref_cdata = &$this->_ls_ref['lastmodified'];
1114              break;
1115          case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getcontenttype_':
1116              $this->_ls_ref_cdata = &$this->_ls_ref['getcontenttype'];
1117              break;
1118          case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getcontentlength_':
1119              $this->_ls_ref_cdata = &$this->_ls_ref['getcontentlength'];
1120              break;
1121          case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_':
1122              $this->_ls_ref_cdata = &$this->_ls_ref['activelock_depth'];
1123              break;
1124          case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_':
1125              $this->_ls_ref_cdata = &$this->_ls_ref['activelock_owner'];
1126              break;
1127          case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_':
1128              $this->_ls_ref_cdata = &$this->_ls_ref['activelock_owner'];
1129              break;
1130          case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_':
1131              $this->_ls_ref_cdata = &$this->_ls_ref['activelock_timeout'];
1132              break;
1133          case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_':
1134              $this->_ls_ref_cdata = &$this->_ls_ref['activelock_token'];
1135              break;
1136          case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::locktype_dav::write_':
1137              $this->_ls_ref_cdata = &$this->_ls_ref['activelock_type'];
1138              $this->_ls_ref_cdata = 'write';
1139              $this->_ls_ref_cdata = &$this->_null;
1140              break;
1141          case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::resourcetype_dav::collection_':
1142              $this->_ls_ref_cdata = &$this->_ls_ref['resourcetype'];
1143              $this->_ls_ref_cdata = 'collection';
1144              $this->_ls_ref_cdata = &$this->_null;
1145              break;
1146          case 'dav::multistatus_dav::response_dav::propstat_dav::status_':
1147              $this->_ls_ref_cdata = &$this->_ls_ref['status'];
1148              break;
1149  
1150          default:
1151              // handle unknown xml elements...
1152              $this->_ls_ref_cdata = &$this->_ls_ref[$this->_xmltree[$parserid]];
1153          }
1154      }
1155  
1156      /**
1157       * Private method _propfind_cData
1158       *
1159       * Is needed by public method ls.
1160       *
1161       * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
1162       * Stores data found into class var _ls_ref_cdata
1163       * @param resource parser, string cdata
1164       * @access private
1165       */
1166      private function _propfind_cData($parser, $cdata) {
1167          if (trim($cdata) <> '') {
1168              // cdata must be appended, because sometimes the php xml parser makes multiple calls
1169              // to _propfind_cData before the xml end tag was reached...
1170              $this->_ls_ref_cdata .= $cdata;
1171          } else {
1172              // do nothing
1173          }
1174      }
1175  
1176      /**
1177       * Private method _delete_startElement
1178       *
1179       * Is used by public method delete.
1180       *
1181       * Will be called by php xml_parse.
1182       * @param resource parser, string name, string attrs)
1183       * @access private
1184       */
1185      private function _delete_startElement($parser, $name, $attrs) {
1186          // lower XML Names... maybe break a RFC, don't know ...
1187          $parserid = $this->get_parser_id($parser);
1188          $propname = strtolower($name);
1189          $this->_xmltree[$parserid] .= $propname . '_';
1190  
1191          // translate xml tree to a flat array ...
1192          switch($this->_xmltree[$parserid]) {
1193          case 'dav::multistatus_dav::response_':
1194              // new element in mu
1195              $this->_delete_ref =& $this->_delete[$parserid][];
1196              break;
1197          case 'dav::multistatus_dav::response_dav::href_':
1198              $this->_delete_ref_cdata = &$this->_ls_ref['href'];
1199              break;
1200  
1201          default:
1202              // handle unknown xml elements...
1203              $this->_delete_cdata = &$this->_delete_ref[$this->_xmltree[$parserid]];
1204          }
1205      }
1206  
1207  
1208      /**
1209       * Private method _delete_cData
1210       *
1211       * Is used by public method delete.
1212       *
1213       * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
1214       * Stores data found into class var _delete_ref_cdata
1215       * @param resource parser, string cdata
1216       * @access private
1217       */
1218      private function _delete_cData($parser, $cdata) {
1219          if (trim($cdata) <> '') {
1220              $this->_delete_ref_cdata .= $cdata;
1221          } else {
1222              // do nothing
1223          }
1224      }
1225  
1226  
1227      /**
1228       * Private method _lock_startElement
1229       *
1230       * Is needed by public method lock.
1231       *
1232       * Mmethod will called by php xml_parse when a xml start element tag has been detected.
1233       * The xml tree will translated into a flat php array for easier access.
1234       * @param resource parser, string name, string attrs
1235       * @access private
1236       */
1237      private function _lock_startElement($parser, $name, $attrs) {
1238          // lower XML Names... maybe break a RFC, don't know ...
1239          $parserid = $this->get_parser_id($parser);
1240          $propname = strtolower($name);
1241          $this->_xmltree[$parserid] .= $propname . '_';
1242  
1243          // translate xml tree to a flat array ...
1244          /*
1245          dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_=
1246          dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_=
1247          dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_=
1248          dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_=
1249           */
1250          switch($this->_xmltree[$parserid]) {
1251          case 'dav::prop_dav::lockdiscovery_dav::activelock_':
1252              // new element
1253              $this->_lock_ref =& $this->_lock[$parserid][];
1254              break;
1255          case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::locktype_dav::write_':
1256              $this->_lock_ref_cdata = &$this->_lock_ref['locktype'];
1257              $this->_lock_cdata = 'write';
1258              $this->_lock_cdata = &$this->_null;
1259              break;
1260          case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::lockscope_dav::exclusive_':
1261              $this->_lock_ref_cdata = &$this->_lock_ref['lockscope'];
1262              $this->_lock_ref_cdata = 'exclusive';
1263              $this->_lock_ref_cdata = &$this->_null;
1264              break;
1265          case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_':
1266              $this->_lock_ref_cdata = &$this->_lock_ref['depth'];
1267              break;
1268          case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_':
1269              $this->_lock_ref_cdata = &$this->_lock_ref['owner'];
1270              break;
1271          case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_':
1272              $this->_lock_ref_cdata = &$this->_lock_ref['timeout'];
1273              break;
1274          case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_':
1275              $this->_lock_ref_cdata = &$this->_lock_ref['locktoken'];
1276              break;
1277          default:
1278              // handle unknown xml elements...
1279              $this->_lock_cdata = &$this->_lock_ref[$this->_xmltree[$parserid]];
1280  
1281          }
1282      }
1283  
1284      /**
1285       * Private method _lock_cData
1286       *
1287       * Is used by public method lock.
1288       *
1289       * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
1290       * Stores data found into class var _lock_ref_cdata
1291       * @param resource parser, string cdata
1292       * @access private
1293       */
1294      private function _lock_cData($parser, $cdata) {
1295          $parserid = $this->get_parser_id($parser);
1296          if (trim($cdata) <> '') {
1297              // $this->_error_log(($this->_xmltree[$parserid]) . '='. htmlentities($cdata));
1298              $this->_lock_ref_cdata .= $cdata;
1299          } else {
1300              // do nothing
1301          }
1302      }
1303  
1304  
1305      /**
1306       * Private method header_add
1307       *
1308       * extends class var array _req
1309       * @param string string
1310       * @access private
1311       */
1312      private function header_add($string) {
1313          $this->_req[] = $string;
1314      }
1315  
1316      /**
1317       * Private method header_unset
1318       *
1319       * unsets class var array _req
1320       * @access private
1321       */
1322  
1323      private function header_unset() {
1324          unset($this->_req);
1325      }
1326  
1327      /**
1328       * Private method create_basic_request
1329       *
1330       * creates by using private method header_add an general request header.
1331       * @param string method
1332       * @access private
1333       */
1334      private function create_basic_request($method) {
1335          $this->header_add(sprintf('%s %s %s', $method, $this->_path, $this->_protocol));
1336          $this->header_add(sprintf('Host: %s:%s', $this->_server, $this->_port));
1337          //$request .= sprintf('Connection: Keep-Alive');
1338          $this->header_add(sprintf('User-Agent: %s', $this->_user_agent));
1339          $this->header_add('Connection: TE');
1340          $this->header_add('TE: Trailers');
1341          if ($this->_auth == 'basic') {
1342              $this->header_add(sprintf('Authorization: Basic %s', base64_encode("$this->_user:$this->_pass")));
1343          } else if ($this->_auth == 'digest') {
1344              if ($signature = $this->digest_signature($method)){
1345                  $this->header_add($signature);
1346              }
1347          } else if ($this->_auth == 'bearer') {
1348              $this->header_add(sprintf('Authorization: Bearer %s', $this->oauthtoken));
1349          }
1350      }
1351  
1352      /**
1353       * Reads the header, stores the challenge information
1354       *
1355       * @return void
1356       */
1357      private function digest_auth() {
1358  
1359          $headers = array();
1360          $headers[] = sprintf('%s %s %s', 'HEAD', $this->_path, $this->_protocol);
1361          $headers[] = sprintf('Host: %s:%s', $this->_server, $this->_port);
1362          $headers[] = sprintf('User-Agent: %s', $this->_user_agent);
1363          $headers = implode("\r\n", $headers);
1364          $headers .= "\r\n\r\n";
1365          fputs($this->sock, $headers);
1366  
1367          // Reads the headers.
1368          $i = 0;
1369          $header = '';
1370          do {
1371              $header .= fread($this->sock, 1);
1372              $i++;
1373          } while (!preg_match('/\\r\\n\\r\\n$/', $header, $matches) && $i < $this->_maxheaderlenth);
1374  
1375          // Analyse the headers.
1376          $digest = array();
1377          $splitheaders = explode("\r\n", $header);
1378          foreach ($splitheaders as $line) {
1379              if (!preg_match('/^WWW-Authenticate: Digest/', $line)) {
1380                  continue;
1381              }
1382              $line = substr($line, strlen('WWW-Authenticate: Digest '));
1383              $params = explode(',', $line);
1384              foreach ($params as $param) {
1385                  list($key, $value) = explode('=', trim($param), 2);
1386                  $digest[$key] = trim($value, '"');
1387              }
1388              break;
1389          }
1390  
1391          $this->_digestchallenge = $digest;
1392      }
1393  
1394      /**
1395       * Generates the digest signature
1396       *
1397       * @return string signature to add to the headers
1398       * @access private
1399       */
1400      private function digest_signature($method) {
1401          if (!$this->_digestchallenge) {
1402              $this->digest_auth();
1403          }
1404  
1405          $signature = array();
1406          $signature['username'] = '"' . $this->_user . '"';
1407          $signature['realm'] = '"' . $this->_digestchallenge['realm'] . '"';
1408          $signature['nonce'] = '"' . $this->_digestchallenge['nonce'] . '"';
1409          $signature['uri'] = '"' . $this->_path . '"';
1410  
1411          if (isset($this->_digestchallenge['algorithm']) && $this->_digestchallenge['algorithm'] != 'MD5') {
1412              $this->_error_log('Algorithm other than MD5 are not supported');
1413              return false;
1414          }
1415  
1416          $a1 = $this->_user . ':' . $this->_digestchallenge['realm'] . ':' . $this->_pass;
1417          $a2 = $method . ':' . $this->_path;
1418  
1419          if (!isset($this->_digestchallenge['qop'])) {
1420              $signature['response'] = '"' . md5(md5($a1) . ':' . $this->_digestchallenge['nonce'] . ':' . md5($a2)) . '"';
1421          } else {
1422              // Assume QOP is auth
1423              if (empty($this->_cnonce)) {
1424                  $this->_cnonce = random_string();
1425                  $this->_nc = 0;
1426              }
1427              $this->_nc++;
1428              $nc = sprintf('%08d', $this->_nc);
1429              $signature['cnonce'] = '"' . $this->_cnonce . '"';
1430              $signature['nc'] = '"' . $nc . '"';
1431              $signature['qop'] = '"' . $this->_digestchallenge['qop'] . '"';
1432              $signature['response'] = '"' . md5(md5($a1) . ':' . $this->_digestchallenge['nonce'] . ':' .
1433                      $nc . ':' . $this->_cnonce . ':' . $this->_digestchallenge['qop'] . ':' . md5($a2)) . '"';
1434          }
1435  
1436          $response = array();
1437          foreach ($signature as $key => $value) {
1438              $response[] = "$key=$value";
1439          }
1440          return 'Authorization: Digest ' . implode(', ', $response);
1441      }
1442  
1443      /**
1444       * Private method send_request
1445       *
1446       * Sends a ready formed http/webdav request to webdav server.
1447       *
1448       * @access private
1449       */
1450      private function send_request() {
1451          // check if stream is declared to be open
1452          // only logical check we are not sure if socket is really still open ...
1453          if ($this->_connection_closed) {
1454              // reopen it
1455              // be sure to close the open socket.
1456              $this->close();
1457              $this->reopen();
1458          }
1459  
1460          // convert array to string
1461          $buffer = implode("\r\n", $this->_req);
1462          $buffer .= "\r\n\r\n";
1463          $this->_error_log($buffer);
1464          fputs($this->sock, $buffer);
1465      }
1466  
1467      /**
1468       * Private method get_respond
1469       *
1470       * Reads the response from the webdav server.
1471       *
1472       * Stores data into class vars _header for the header data and
1473       * _body for the rest of the response.
1474       * This routine is the weakest part of this class, because it very depends how php does handle a socket stream.
1475       * If the stream is blocked for some reason php is blocked as well.
1476       * @access private
1477       * @param resource $fp optional the file handle to write the body content to (stored internally in the '_body' if not set)
1478       */
1479      private function get_respond($fp = null) {
1480          $this->_error_log('get_respond()');
1481          // init vars (good coding style ;-)
1482          $buffer = '';
1483          $header = '';
1484          // attention: do not make max_chunk_size to big....
1485          $max_chunk_size = 8192;
1486          // be sure we got a open ressource
1487          if (! $this->sock) {
1488              $this->_error_log('socket is not open. Can not process response');
1489              return false;
1490          }
1491  
1492          // following code maybe helps to improve socket behaviour ... more testing needed
1493          // disabled at the moment ...
1494          // socket_set_timeout($this->sock,1 );
1495          // $socket_state = socket_get_status($this->sock);
1496  
1497          // read stream one byte by another until http header ends
1498          $i = 0;
1499          $matches = array();
1500          do {
1501              $header.=fread($this->sock, 1);
1502              $i++;
1503          } while (!preg_match('/\\r\\n\\r\\n$/',$header, $matches) && $i < $this->_maxheaderlenth);
1504  
1505          $this->_error_log($header);
1506  
1507          if (preg_match('/Connection: close\\r\\n/', $header)) {
1508              // This says that the server will close connection at the end of this stream.
1509              // Therefore we need to reopen the socket, before are sending the next request...
1510              $this->_error_log('Connection: close found');
1511              $this->_connection_closed = true;
1512          } else if (preg_match('@^HTTP/1\.(1|0) 401 @', $header)) {
1513              $this->_error_log('The server requires an authentication');
1514          }
1515  
1516          // check how to get the data on socket stream
1517          // chunked or content-length (HTTP/1.1) or
1518          // one block until feof is received (HTTP/1.0)
1519          switch(true) {
1520          case (preg_match('/Transfer\\-Encoding:\\s+chunked\\r\\n/',$header)):
1521              $this->_error_log('Getting HTTP/1.1 chunked data...');
1522              do {
1523                  $byte = '';
1524                  $chunk_size='';
1525                  do {
1526                      $chunk_size.=$byte;
1527                      $byte=fread($this->sock,1);
1528                      // check what happens while reading, because I do not really understand how php reads the socketstream...
1529                      // but so far - it seems to work here - tested with php v4.3.1 on apache 1.3.27 and Debian Linux 3.0 ...
1530                      if (strlen($byte) == 0) {
1531                          $this->_error_log('get_respond: warning --> read zero bytes');
1532                      }
1533                  } while ($byte!="\r" and strlen($byte)>0);      // till we match the Carriage Return
1534                  fread($this->sock, 1);                           // also drop off the Line Feed
1535                  $chunk_size=hexdec($chunk_size);                // convert to a number in decimal system
1536                  if ($chunk_size > 0) {
1537                      $read = 0;
1538                      // Reading the chunk in one bite is not secure, we read it byte by byte.
1539                      while ($read < $chunk_size) {
1540                          $chunk = fread($this->sock, 1);
1541                          self::update_file_or_buffer($chunk, $fp, $buffer);
1542                          $read++;
1543                      }
1544                  }
1545                  fread($this->sock, 2);                            // ditch the CRLF that trails the chunk
1546              } while ($chunk_size);                            // till we reach the 0 length chunk (end marker)
1547              break;
1548  
1549              // check for a specified content-length
1550          case preg_match('/Content\\-Length:\\s+([0-9]*)\\r\\n/',$header,$matches):
1551              $this->_error_log('Getting data using Content-Length '. $matches[1]);
1552  
1553              // check if we the content data size is small enough to get it as one block
1554              if ($matches[1] <= $max_chunk_size ) {
1555                  // only read something if Content-Length is bigger than 0
1556                  if ($matches[1] > 0 ) {
1557                      $chunk = fread($this->sock, $matches[1]);
1558                      $loadsize = strlen($chunk);
1559                      //did we realy get the full length?
1560                      if ($loadsize < $matches[1]) {
1561                          $max_chunk_size = $loadsize;
1562                          do {
1563                              $mod = $max_chunk_size % ($matches[1] - strlen($chunk));
1564                              $chunk_size = ($mod == $max_chunk_size ? $max_chunk_size : $matches[1] - strlen($chunk));
1565                              $chunk .= fread($this->sock, $chunk_size);
1566                              $this->_error_log('mod: ' . $mod . ' chunk: ' . $chunk_size . ' total: ' . strlen($chunk));
1567                          } while (strlen($chunk) < $matches[1]);
1568                      }
1569                      self::update_file_or_buffer($chunk, $fp, $buffer);
1570                      break;
1571                  } else {
1572                      $buffer = '';
1573                      break;
1574                  }
1575              }
1576  
1577              // data is to big to handle it as one. Get it chunk per chunk...
1578              //trying to get the full length of max_chunk_size
1579              $chunk = fread($this->sock, $max_chunk_size);
1580              $loadsize = strlen($chunk);
1581              self::update_file_or_buffer($chunk, $fp, $buffer);
1582              if ($loadsize < $max_chunk_size) {
1583                  $max_chunk_size = $loadsize;
1584              }
1585              do {
1586                  $mod = $max_chunk_size % ($matches[1] - $loadsize);
1587                  $chunk_size = ($mod == $max_chunk_size ? $max_chunk_size : $matches[1] - $loadsize);
1588                  $chunk = fread($this->sock, $chunk_size);
1589                  self::update_file_or_buffer($chunk, $fp, $buffer);
1590                  $loadsize += strlen($chunk);
1591                  $this->_error_log('mod: ' . $mod . ' chunk: ' . $chunk_size . ' total: ' . $loadsize);
1592              } while ($matches[1] > $loadsize);
1593              break;
1594  
1595              // check for 204 No Content
1596              // 204 responds have no body.
1597              // Therefore we do not need to read any data from socket stream.
1598          case preg_match('/HTTP\/1\.1\ 204/',$header):
1599              // nothing to do, just proceed
1600              $this->_error_log('204 No Content found. No further data to read..');
1601              break;
1602          default:
1603              // just get the data until foef appears...
1604              $this->_error_log('reading until feof...' . $header);
1605              socket_set_timeout($this->sock, 0, 0);
1606              while (!feof($this->sock)) {
1607                  $chunk = fread($this->sock, 4096);
1608                  self::update_file_or_buffer($chunk, $fp, $buffer);
1609              }
1610              // renew the socket timeout...does it do something ???? Is it needed. More debugging needed...
1611              socket_set_timeout($this->sock, $this->_socket_timeout, 0);
1612          }
1613  
1614          $this->_header = $header;
1615          $this->_body = $buffer;
1616          // $this->_buffer = $header . "\r\n\r\n" . $buffer;
1617          $this->_error_log($this->_header);
1618          $this->_error_log($this->_body);
1619  
1620      }
1621  
1622      /**
1623       * Write the chunk to the file if $fp is set, otherwise append the data to the buffer
1624       * @param string $chunk the data to add
1625       * @param resource $fp the file handle to write to (or null)
1626       * @param string &$buffer the buffer to append to (if $fp is null)
1627       */
1628      static private function update_file_or_buffer($chunk, $fp, &$buffer) {
1629          if ($fp) {
1630              fwrite($fp, $chunk);
1631          } else {
1632              $buffer .= $chunk;
1633          }
1634      }
1635  
1636      /**
1637       * Private method process_respond
1638       *
1639       * Processes the webdav server respond and detects its components (header, body).
1640       * and returns data array structure.
1641       * @return array ret_struct
1642       * @access private
1643       */
1644      private function process_respond() {
1645          $lines = explode("\r\n", $this->_header);
1646          $header_done = false;
1647          // $this->_error_log($this->_buffer);
1648          // First line should be a HTTP status line (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6)
1649          // Format is: HTTP-Version SP Status-Code SP Reason-Phrase CRLF
1650          list($ret_struct['status']['http-version'],
1651              $ret_struct['status']['status-code'],
1652              $ret_struct['status']['reason-phrase']) = explode(' ', $lines[0],3);
1653  
1654          // print "HTTP Version: '$http_version' Status-Code: '$status_code' Reason Phrase: '$reason_phrase'<br>";
1655          // get the response header fields
1656          // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6
1657          for($i=1; $i<count($lines); $i++) {
1658              if (rtrim($lines[$i]) == '' && !$header_done) {
1659                  $header_done = true;
1660                  // print "--- response header end ---<br>";
1661  
1662              }
1663              if (!$header_done ) {
1664                  // store all found headers in array ...
1665                  list($fieldname, $fieldvalue) = explode(':', $lines[$i]);
1666                  // check if this header was allready set (apache 2.0 webdav module does this....).
1667                  // If so we add the the value to the end the fieldvalue, separated by comma...
1668                  if (empty($ret_struct['header'])) {
1669                      $ret_struct['header'] = array();
1670                  }
1671                  if (empty($ret_struct['header'][$fieldname])) {
1672                      $ret_struct['header'][$fieldname] = trim($fieldvalue);
1673                  } else {
1674                      $ret_struct['header'][$fieldname] .= ',' . trim($fieldvalue);
1675                  }
1676              }
1677          }
1678          // print 'string len of response_body:'. strlen($response_body);
1679          // print '[' . htmlentities($response_body) . ']';
1680          $ret_struct['body'] = $this->_body;
1681          $this->_error_log('process_respond: ' . var_export($ret_struct,true));
1682          return $ret_struct;
1683  
1684      }
1685  
1686      /**
1687       * Private method reopen
1688       *
1689       * Reopens a socket, if 'connection: closed'-header was received from server.
1690       *
1691       * Uses public method open.
1692       * @access private
1693       */
1694      private function reopen() {
1695          // let's try to reopen a socket
1696          $this->_error_log('reopen a socket connection');
1697          return $this->open();
1698      }
1699  
1700  
1701      /**
1702       * Private method translate_uri
1703       *
1704       * translates an uri to raw url encoded string.
1705       * Removes any html entity in uri
1706       * @param string uri
1707       * @return string translated_uri
1708       * @access private
1709       */
1710      private function translate_uri($uri) {
1711          // remove all html entities...
1712          $native_path = html_entity_decode($uri, ENT_COMPAT);
1713          $parts = explode('/', $native_path);
1714          for ($i = 0; $i < count($parts); $i++) {
1715              // check if part is allready utf8
1716              if (iconv('UTF-8', 'UTF-8', $parts[$i]) == $parts[$i]) {
1717                  $parts[$i] = rawurlencode($parts[$i]);
1718              } else {
1719                  $parts[$i] = rawurlencode(utf8_encode($parts[$i]));
1720              }
1721          }
1722          return implode('/', $parts);
1723      }
1724  
1725      /**
1726       * Private method utf_decode_path
1727       *
1728       * decodes a UTF-8 encoded string
1729       * @return string decodedstring
1730       * @access private
1731       */
1732      private function utf_decode_path($path) {
1733          $fullpath = $path;
1734          if (iconv('UTF-8', 'UTF-8', $fullpath) == $fullpath) {
1735              $this->_error_log("filename is utf-8. Needs conversion...");
1736              $fullpath = utf8_decode($fullpath);
1737          }
1738          return $fullpath;
1739      }
1740  
1741      /**
1742       * Private method _error_log
1743       *
1744       * a simple php error_log wrapper.
1745       * @param string err_string
1746       * @access private
1747       */
1748      private function _error_log($err_string) {
1749          if ($this->_debug) {
1750              error_log($err_string);
1751          }
1752      }
1753  
1754      /**
1755       * Helper method to get the parser id for both PHP 7 and 8.
1756       *
1757       * @param resource|object $parser
1758       * @return int
1759       */
1760      private function get_parser_id($parser): int {
1761          if (is_object($parser)) {
1762              return spl_object_id($parser);
1763          } else {
1764              return (int) $parser;
1765          }
1766      }
1767  }