3 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
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.
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.
30 * Moodle modifications:
31 * * Moodle 3.4: Add support for OAuth 2 bearer token-based authentication
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
45 private $_debug = false;
48 private $_protocol = 'HTTP/1.1';
50 private $_socket = '';
52 private $_auth = false;
56 private $_socket_timeout = 5;
59 private $_user_agent = 'Moodle WebDav Client';
60 private $_crlf = "\r\n";
62 private $_resp_status;
67 private $_ls = array();
69 private $_ls_ref_cdata;
70 private $_delete = array();
72 private $_delete_ref_cdata;
73 private $_lock = array();
75 private $_lock_rec_cdata;
76 private $_null = NULL;
79 private $_connection_closed = false;
80 private $_maxheaderlenth = 65536;
81 private $_digestchallenge = null;
82 private $_cnonce = '';
86 * OAuth token used for bearer auth.
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)
102 public function __construct($server = '', $user = '', $pass = '', $auth = false, $socket = '', $oauthtoken = '') {
103 if (!empty($server)) {
104 $this->_server
= $server;
106 if (!empty($user) && !empty($pass)) {
110 $this->_auth
= $auth;
111 $this->_socket
= $socket;
112 if ($auth == 'bearer') {
113 $this->oauthtoken
= $oauthtoken;
116 public function __set($key, $value) {
117 $property = '_' . $key;
118 $this->$property = $value;
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.
127 function set_protocol($version) {
129 $this->_protocol
= 'HTTP/1.1';
131 $this->_protocol
= 'HTTP/1.0';
136 * Convert ISO 8601 Date and Time Profile used in RFC 2518 to an unix timestamp.
138 * @param string iso8601
139 * @return unixtimestamp on sucess. Otherwise false.
141 function iso8601totime($iso8601) {
144 date-time = full-date "T" full-time
146 full-date = date-fullyear "-" date-month "-" date-mday
147 full-time = partial-time time-offset
149 date-fullyear = 4DIGIT
150 date-month = 2DIGIT ; 01-12
151 date-mday = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on
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
160 partial-time = time-hour ":" time-minute ":" time-second
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]);
169 // to be done: regex for partial-time...apache webdav mod never returns partial-time
175 * Open's a socket to a webdav server
176 * @return bool true on success. Otherwise false.
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
);
189 $this->_error_log("$this->_errstr ($this->_errno)\n");
195 * Closes an open socket.
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.
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.
212 function check_webdav() {
213 $resp = $this->options();
217 $this->_error_log($resp['header']['DAV']);
219 if (preg_match('/1,2/', $resp['header']['DAV'])) {
222 // otherwise return false
228 * Get options from webdav server.
229 * @return array with all header fields returned from webdav server. false if server does not speak http.
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') {
243 $this->_error_log('Response was not even http');
249 * Public method mkcol
251 * Creates a new collection/directory on a webdav server
253 * @return int status code received as response from webdav server (see rfc 2518)
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
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.
280 return $response['status']['status-code'];
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.
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();
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 ) {
311 $this->_error_log('file created with ' . $stat['size'] . ' bytes.');
313 $this->_error_log('returning buffer with ' . strlen($response['body']) . ' bytes.');
314 $buffer = $response['body'];
317 return $response['status']['status-code'];
319 // ups: no http status was returned ?
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.
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');
339 $this->send_request();
340 // send the rest (data)
341 fputs($this->sock
, $data);
342 $this->get_respond();
343 $response = $this->process_respond();
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'];
355 // ups: no http status was returned ?
360 * Public method put_file
362 * Read a file as stream and puts it chunk by chunk into webdav server collection.
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.
367 * @param string targetpath, string filename
368 * @return int status code. False on error.
370 function put_file($path, $filename) {
371 // try to open the file ...
374 $handle = @fopen
($filename, 'r');
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');
385 $this->send_request();
386 while (!feof($handle)) {
387 fputs($this->sock
,fgets($handle,4096));
390 $this->get_respond();
391 $response = $this->process_respond();
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'];
403 // ups: no http status was returned ?
406 $this->_error_log('put_file: could not open ' . $filename);
413 * Public method get_file
415 * Gets a file from a collection into local filesystem.
418 * @param string $srcpath
419 * @param string $localpath
420 * @return bool true on success. false on error.
422 function get_file($srcpath, $localpath) {
424 $localpath = $this->utf_decode_path($localpath);
426 $handle = fopen($localpath, 'wb');
429 $ret = $this->get($srcpath, $unused, $handle);
439 * Public method copy_file
441 * Copies a file on a webdav server
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.
447 * @param string src_path, string dest_path, bool overwrite
448 * @return int status code (look at rfc 2518). false on error.
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)));
456 $this->header_add('Overwrite: T');
458 $this->header_add('Overwrite: F');
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.
481 return $response['status']['status-code'];
487 * Public method copy_coll
489 * Copies a collection on a webdav server
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.
495 * @param string src_path, string dest_path, bool overwrite
496 * @return int status code (look at rfc 2518). false on error.
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');
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";
510 $this->header_add('Content-length: ' . strlen($xml));
511 $this->header_add('Content-type: application/xml');
512 $this->send_request();
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.
534 return $response['status']['status-code'];
542 * Moves a file or collection on webdav server (serverside)
544 * If you set param overwrite as true, the target will be overwritten.
546 * @param string src_path, string dest_path, bool overwrite
547 * @return int status code (look at rfc 2518). false on error.
549 // --------------------------------------------------------------------------
550 // public method move
551 // move/rename a file/collection on webdav server
552 function move($src_path,$dst_path, $overwrite) {
554 $this->_path
= $this->translate_uri($src_path);
555 $this->header_unset();
557 $this->create_basic_request('MOVE');
558 $this->header_add(sprintf('Destination: http://%s%s', $this->_server
, $this->translate_uri($dst_path)));
560 $this->header_add('Overwrite: T');
562 $this->header_add('Overwrite: F');
564 $this->header_add('');
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.
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.
592 return $response['status']['status-code'];
600 * Locks a file or collection.
602 * Lock uses this->_user as lock owner.
605 * @return int status code (look at rfc 2518). false on error.
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();
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
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.
640 switch($response['status']['status-code']) {
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");
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
)));
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
];
669 print 'Missing Content-Type: text/xml header in response.<br>';
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'];
686 * Public method unlock
688 * Unlocks a file or collection.
690 * @param string path, string locktoken
691 * @return int status code (look at rfc 2518). false on error.
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
705 204 (OK) - The 204 (No Content) status code is used instead of 200 (OK) because there is no response entity body.
707 return $response['status']['status-code'];
713 * Public method delete
715 * deletes a collection/directory on a webdav server
717 * @return int status code (look at rfc 2518). false on error.
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();
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>';
737 switch ($response['status']['status-code']) {
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");
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
)));
763 xml_parser_free($this->_parser
);
764 $this->_delete
[$this->_parserid
]['status'] = $response['status']['status-code'];
765 return $this->_delete
[$this->_parserid
];
768 print 'Missing Content-Type: text/xml header in response.<br>';
773 // collection or file was successfully deleted
774 $this->_delete
['status'] = $response['status']['status-code'];
775 return $this->_delete
;
786 * Get's directory information from webdav server into flat a array using PROPFIND
788 * All filenames are UTF-8 encoded.
789 * Have a look at _propfind_startElement what keys are used in array returned.
791 * @return array dirinfo, false on error
795 if (trim($path) == '') {
796 $this->_error_log('Missing a path in method ls');
799 $this->_path
= $this->translate_uri($path);
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...
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:"/>
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 ) {
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");
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
)));
855 xml_parser_free($this->_parser
);
856 $arr = $this->_ls
[$this->_parserid
];
859 $this->_error_log('Missing Content-Type: text/xml header in response!!');
863 // return status code ...
864 return $response['status']['status-code'];
868 // response was not http
869 $this->_error_log('Ups in method ls: error in response from server');
877 * Get's path information from webdav server for one element.
880 * @return array dirinfo. false on error
882 function gpi($path) {
884 // split path by last "/"
885 $path = rtrim($path, "/");
886 $item = basename($path);
887 $dir = dirname($path);
889 $list = $this->ls($dir);
891 // be sure it is an array
892 if (is_array($list)) {
893 foreach($list as $e) {
895 $fullpath = urldecode($e['href']);
896 $filename = basename($fullpath);
898 if ($filename == $item && $filename != "" and $fullpath != $dir."/") {
907 * Public method is_file
909 * Gathers whether a path points to a file or not.
912 * @return bool true or false
914 function is_file($path) {
916 $item = $this->gpi($path);
918 if ($item === false) {
921 return ($item['resourcetype'] != 'collection');
926 * Public method is_dir
928 * Gather whether a path points to a directory
930 * return bool true or false
932 function is_dir($path) {
934 // be sure path is utf-8
935 $item = $this->gpi($path);
937 if ($item === false) {
940 return ($item['resourcetype'] == 'collection');
948 * Puts multiple files and/or directories onto a webdav server.
950 * Filenames should be allready UTF-8 encoded.
951 * Param fileList must be in format array("localpath" => "destpath").
953 * @param array filelist
954 * @return bool true on success. otherwise int status code on error
956 function mput($filelist) {
960 foreach ($filelist as $localpath => $destpath) {
962 $localpath = rtrim($localpath, "/");
963 $destpath = rtrim($destpath, "/");
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
969 $pathparts = explode("/", $destpath);
972 for ($i=1; $i<sizeof($pathparts)-1; $i++
) {
973 $checkpath .= "/" . $pathparts[$i];
974 if (!($this->is_dir($checkpath))) {
976 $result &= ($this->mkcol($checkpath) == 201 );
981 // recurse directories
982 if (is_dir($localpath)) {
983 if (!$dp = opendir($localpath)) {
984 $this->_error_log("Could not open localpath for reading");
988 while($filename = readdir($dp)) {
989 if ((is_file($localpath."/".$filename) ||
is_dir($localpath."/".$filename)) && $filename!="." && $filename != "..") {
990 $fl[$localpath."/".$filename] = $destpath."/".$filename;
993 $result &= $this->mput($fl);
995 $result &= ($this->put_file($destpath, $localpath) == 201);
1003 * Public method mget
1005 * Gets multiple files and directories.
1007 * FileList must be in format array("remotepath" => "localpath").
1008 * Filenames are UTF-8 encoded.
1010 * @param array filelist
1011 * @return bool true on succes, other int status code on error
1013 function mget($filelist) {
1017 foreach ($filelist as $remotepath => $localpath) {
1019 $localpath = rtrim($localpath, "/");
1020 $remotepath = rtrim($remotepath, "/");
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
1026 $pathparts = explode("/", $localpath);
1029 for ($i=1; $i<sizeof($pathparts)-1; $i++
) {
1030 $checkpath .= "/" . $pathparts[$i];
1031 if (!is_dir($checkpath)) {
1033 $result &= mkdir($checkpath);
1038 // recurse directories
1039 if ($this->is_dir($remotepath)) {
1040 $list = $this->ls($remotepath);
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;
1050 $result &= $this->mget($fl);
1052 $result &= ($this->get_file($remotepath, $localpath));
1059 // --------------------------------------------------------------------------
1060 // private xml callback and helper functions starting here
1061 // --------------------------------------------------------------------------
1065 * Private method _endelement
1067 * a generic endElement method (used for all xml callbacks).
1069 * @param resource parser, string name
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));
1080 * Private method _propfind_startElement
1082 * Is needed by public method ls.
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
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);
1093 $propname = strtolower($name);
1094 if (!empty($this->_xmltree
[$parserid])) {
1095 $this->_xmltree
[$parserid] .= $propname . '_';
1097 $this->_xmltree
[$parserid] = $propname . '_';
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][];
1106 case 'dav::multistatus_dav::response_dav::href_':
1107 $this->_ls_ref_cdata
= &$this->_ls_ref
['href'];
1109 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::creationdate_':
1110 $this->_ls_ref_cdata
= &$this->_ls_ref
['creationdate'];
1112 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getlastmodified_':
1113 $this->_ls_ref_cdata
= &$this->_ls_ref
['lastmodified'];
1115 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getcontenttype_':
1116 $this->_ls_ref_cdata
= &$this->_ls_ref
['getcontenttype'];
1118 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getcontentlength_':
1119 $this->_ls_ref_cdata
= &$this->_ls_ref
['getcontentlength'];
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'];
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'];
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'];
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'];
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'];
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
;
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
;
1146 case 'dav::multistatus_dav::response_dav::propstat_dav::status_':
1147 $this->_ls_ref_cdata
= &$this->_ls_ref
['status'];
1151 // handle unknown xml elements...
1152 $this->_ls_ref_cdata
= &$this->_ls_ref
[$this->_xmltree
[$parserid]];
1157 * Private method _propfind_cData
1159 * Is needed by public method ls.
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
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;
1177 * Private method _delete_startElement
1179 * Is used by public method delete.
1181 * Will be called by php xml_parse.
1182 * @param resource parser, string name, string attrs)
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 . '_';
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][];
1197 case 'dav::multistatus_dav::response_dav::href_':
1198 $this->_delete_ref_cdata
= &$this->_ls_ref
['href'];
1202 // handle unknown xml elements...
1203 $this->_delete_cdata
= &$this->_delete_ref
[$this->_xmltree
[$parserid]];
1209 * Private method _delete_cData
1211 * Is used by public method delete.
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
1218 private function _delete_cData($parser, $cdata) {
1219 if (trim($cdata) <> '') {
1220 $this->_delete_ref_cdata
.= $cdata;
1228 * Private method _lock_startElement
1230 * Is needed by public method lock.
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
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 . '_';
1243 // translate xml tree to a flat array ...
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_=
1250 switch($this->_xmltree
[$parserid]) {
1251 case 'dav::prop_dav::lockdiscovery_dav::activelock_':
1253 $this->_lock_ref
=& $this->_lock
[$parserid][];
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
;
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
;
1265 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_':
1266 $this->_lock_ref_cdata
= &$this->_lock_ref
['depth'];
1268 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_':
1269 $this->_lock_ref_cdata
= &$this->_lock_ref
['owner'];
1271 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_':
1272 $this->_lock_ref_cdata
= &$this->_lock_ref
['timeout'];
1274 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_':
1275 $this->_lock_ref_cdata
= &$this->_lock_ref
['locktoken'];
1278 // handle unknown xml elements...
1279 $this->_lock_cdata
= &$this->_lock_ref
[$this->_xmltree
[$parserid]];
1285 * Private method _lock_cData
1287 * Is used by public method lock.
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
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;
1306 * Private method header_add
1308 * extends class var array _req
1309 * @param string string
1312 private function header_add($string) {
1313 $this->_req
[] = $string;
1317 * Private method header_unset
1319 * unsets class var array _req
1323 private function header_unset() {
1328 * Private method create_basic_request
1330 * creates by using private method header_add an general request header.
1331 * @param string method
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);
1347 } else if ($this->_auth
== 'bearer') {
1348 $this->header_add(sprintf('Authorization: Bearer %s', $this->oauthtoken
));
1353 * Reads the header, stores the challenge information
1357 private function digest_auth() {
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);
1367 // Reads the headers.
1371 $header .= fread($this->sock
, 1);
1373 } while (!preg_match('/\\r\\n\\r\\n$/', $header, $matches) && $i < $this->_maxheaderlenth
);
1375 // Analyse the headers.
1377 $splitheaders = explode("\r\n", $header);
1378 foreach ($splitheaders as $line) {
1379 if (!preg_match('/^WWW-Authenticate: Digest/', $line)) {
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, '"');
1391 $this->_digestchallenge
= $digest;
1395 * Generates the digest signature
1397 * @return string signature to add to the headers
1400 private function digest_signature($method) {
1401 if (!$this->_digestchallenge
) {
1402 $this->digest_auth();
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
. '"';
1411 if (isset($this->_digestchallenge
['algorithm']) && $this->_digestchallenge
['algorithm'] != 'MD5') {
1412 $this->_error_log('Algorithm other than MD5 are not supported');
1416 $a1 = $this->_user
. ':' . $this->_digestchallenge
['realm'] . ':' . $this->_pass
;
1417 $a2 = $method . ':' . $this->_path
;
1419 if (!isset($this->_digestchallenge
['qop'])) {
1420 $signature['response'] = '"' . md5(md5($a1) . ':' . $this->_digestchallenge
['nonce'] . ':' . md5($a2)) . '"';
1422 // Assume QOP is auth
1423 if (empty($this->_cnonce
)) {
1424 $this->_cnonce
= random_string();
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)) . '"';
1436 $response = array();
1437 foreach ($signature as $key => $value) {
1438 $response[] = "$key=$value";
1440 return 'Authorization: Digest ' . implode(', ', $response);
1444 * Private method send_request
1446 * Sends a ready formed http/webdav request to webdav server.
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
) {
1455 // be sure to close the open socket.
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);
1468 * Private method get_respond
1470 * Reads the response from the webdav server.
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.
1477 * @param resource $fp optional the file handle to write the body content to (stored internally in the '_body' if not set)
1479 private function get_respond($fp = null) {
1480 $this->_error_log('get_respond()');
1481 // init vars (good coding style ;-)
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');
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);
1497 // read stream one byte by another until http header ends
1501 $header.=fread($this->sock
, 1);
1503 } while (!preg_match('/\\r\\n\\r\\n$/',$header, $matches) && $i < $this->_maxheaderlenth
);
1505 $this->_error_log($header);
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');
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)
1520 case (preg_match('/Transfer\\-Encoding:\\s+chunked\\r\\n/',$header)):
1521 $this->_error_log('Getting HTTP/1.1 chunked data...');
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');
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) {
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);
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)
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]);
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;
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]);
1569 self
::update_file_or_buffer($chunk, $fp, $buffer);
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;
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);
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..');
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);
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);
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
);
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)
1628 static private function update_file_or_buffer($chunk, $fp, &$buffer) {
1630 fwrite($fp, $chunk);
1637 * Private method process_respond
1639 * Processes the webdav server respond and detects its components (header, body).
1640 * and returns data array structure.
1641 * @return array ret_struct
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);
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>";
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();
1671 if (empty($ret_struct['header'][$fieldname])) {
1672 $ret_struct['header'][$fieldname] = trim($fieldvalue);
1674 $ret_struct['header'][$fieldname] .= ',' . trim($fieldvalue);
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));
1687 * Private method reopen
1689 * Reopens a socket, if 'connection: closed'-header was received from server.
1691 * Uses public method open.
1694 private function reopen() {
1695 // let's try to reopen a socket
1696 $this->_error_log('reopen a socket connection');
1697 return $this->open();
1702 * Private method translate_uri
1704 * translates an uri to raw url encoded string.
1705 * Removes any html entity in uri
1707 * @return string translated_uri
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]);
1719 $parts[$i] = rawurlencode(utf8_encode($parts[$i]));
1722 return implode('/', $parts);
1726 * Private method utf_decode_path
1728 * decodes a UTF-8 encoded string
1729 * @return string decodedstring
1732 private function utf_decode_path($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);
1742 * Private method _error_log
1744 * a simple php error_log wrapper.
1745 * @param string err_string
1748 private function _error_log($err_string) {
1749 if ($this->_debug
) {
1750 error_log($err_string);
1755 * Helper method to get the parser id for both PHP 7 and 8.
1757 * @param resource|object $parser
1760 private function get_parser_id($parser): int {
1761 if (is_object($parser)) {
1762 return spl_object_id($parser);
1764 return (int) $parser;