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 * webdav_client v0.1.5, a php based webdav client class.
20 * class webdav client. a php based nearly RFC 2518 conforming client.
22 * This class implements methods to get access to an webdav server.
23 * Most of the methods are returning boolean false on error, an integer status (http response status) on success
24 * or an array in case of a multistatus response (207) from the webdav server. Look at the code which keys are used in arrays.
25 * It's your responsibility to handle the webdav server responses in an proper manner.
26 * Please notice that all Filenames coming from or going to the webdav server should be UTF-8 encoded (see RFC 2518).
27 * This class tries to convert all you filenames into utf-8 when it's needed.
30 * @author Christian Juerges <christian.juerges@xwave.ch>, Xwave GmbH, Josefstr. 92, 8005 Zuerich - Switzerland
31 * @copyright (C) 2003/2004, Christian Juerges
32 * @license http://opensource.org/licenses/lgpl-license.php GNU Lesser General Public License
42 private $_debug = false;
45 private $_protocol = 'HTTP/1.1';
47 private $_socket = '';
49 private $_auth = false;
53 private $_socket_timeout = 5;
56 private $_user_agent = 'Moodle WebDav Client';
57 private $_crlf = "\r\n";
59 private $_resp_status;
64 private $_ls = array();
66 private $_ls_ref_cdata;
67 private $_delete = array();
69 private $_delete_ref_cdata;
70 private $_lock = array();
72 private $_lock_rec_cdata;
73 private $_null = NULL;
76 private $_connection_closed = false;
77 private $_maxheaderlenth = 1000;
78 private $_digestchallenge = null;
79 private $_cnonce = '';
85 * Constructor - Initialise class variables
87 function __construct($server = '', $user = '', $pass = '', $auth = false, $socket = '') {
88 if (!empty($server)) {
89 $this->_server
= $server;
91 if (!empty($user) && !empty($pass)) {
96 $this->_socket
= $socket;
98 public function __set($key, $value) {
99 $property = '_' . $key;
100 $this->$property = $value;
104 * Set which HTTP protocol will be used.
105 * Value 1 defines that HTTP/1.1 should be used (Keeps Connection to webdav server alive).
106 * Otherwise HTTP/1.0 will be used.
109 function set_protocol($version) {
111 $this->_protocol
= 'HTTP/1.1';
113 $this->_protocol
= 'HTTP/1.0';
118 * Convert ISO 8601 Date and Time Profile used in RFC 2518 to an unix timestamp.
120 * @param string iso8601
121 * @return unixtimestamp on sucess. Otherwise false.
123 function iso8601totime($iso8601) {
126 date-time = full-date "T" full-time
128 full-date = date-fullyear "-" date-month "-" date-mday
129 full-time = partial-time time-offset
131 date-fullyear = 4DIGIT
132 date-month = 2DIGIT ; 01-12
133 date-mday = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on
135 time-hour = 2DIGIT ; 00-23
136 time-minute = 2DIGIT ; 00-59
137 time-second = 2DIGIT ; 00-59, 00-60 based on leap second rules
138 time-secfrac = "." 1*DIGIT
139 time-numoffset = ("+" / "-") time-hour ":" time-minute
140 time-offset = "Z" / time-numoffset
142 partial-time = time-hour ":" time-minute ":" time-second
147 /* [1] [2] [3] [4] [5] [6] */
148 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)) {
149 return mktime($regs[4],$regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
151 // to be done: regex for partial-time...apache webdav mod never returns partial-time
157 * Open's a socket to a webdav server
158 * @return bool true on success. Otherwise false.
161 // let's try to open a socket
162 $this->_error_log('open a socket connection');
163 $this->sock
= fsockopen($this->_socket
. $this->_server
, $this->_port
, $this->_errno
, $this->_errstr
, $this->_socket_timeout
);
165 if (is_resource($this->sock
)) {
166 socket_set_blocking($this->sock
, true);
167 $this->_connection_closed
= false;
168 $this->_error_log('socket is open: ' . $this->sock
);
171 $this->_error_log("$this->_errstr ($this->_errno)\n");
177 * Closes an open socket.
180 $this->_error_log('closing socket ' . $this->sock
);
181 $this->_connection_closed
= true;
186 * Check's if server is a webdav compliant server.
187 * True if server returns a DAV Element in Header and when
188 * schema 1,2 is supported.
189 * @return bool true if server is webdav server. Otherwise false.
191 function check_webdav() {
192 $resp = $this->options();
196 $this->_error_log($resp['header']['DAV']);
198 if (preg_match('/1,2/', $resp['header']['DAV'])) {
201 // otherwise return false
207 * Get options from webdav server.
208 * @return array with all header fields returned from webdav server. false if server does not speak http.
211 $this->header_unset();
212 $this->create_basic_request('OPTIONS');
213 $this->send_request();
214 $this->get_respond();
215 $response = $this->process_respond();
216 // validate the response ...
217 // check http-version
218 if ($response['status']['http-version'] == 'HTTP/1.1' ||
219 $response['status']['http-version'] == 'HTTP/1.0') {
222 $this->_error_log('Response was not even http');
228 * Public method mkcol
230 * Creates a new collection/directory on a webdav server
232 * @return int status code received as reponse from webdav server (see rfc 2518)
234 function mkcol($path) {
235 $this->_path
= $this->translate_uri($path);
236 $this->header_unset();
237 $this->create_basic_request('MKCOL');
238 $this->send_request();
239 $this->get_respond();
240 $response = $this->process_respond();
241 // validate the response ...
242 // check http-version
243 $http_version = $response['status']['http-version'];
244 if ($http_version == 'HTTP/1.1' ||
$http_version == 'HTTP/1.0') {
245 /** seems to be http ... proceed
246 * just return what server gave us
248 * 201 (Created) - The collection or structured resource was created in its entirety.
249 * 403 (Forbidden) - This indicates at least one of two conditions:
250 * 1) the server does not allow the creation of collections at the given location in its namespace, or
251 * 2) the parent collection of the Request-URI exists but cannot accept members.
252 * 405 (Method Not Allowed) - MKCOL can only be executed on a deleted/non-existent resource.
253 * 409 (Conflict) - A collection cannot be made at the Request-URI until one or more intermediate
254 * collections have been created.
255 * 415 (Unsupported Media Type)- The server does not support the request type of the body.
256 * 507 (Insufficient Storage) - The resource does not have sufficient space to record the state of the
257 * resource after the execution of this method.
259 return $response['status']['status-code'];
267 * Gets a file from a webdav collection.
268 * @param string path, string &buffer
269 * @return status code and &$buffer (by reference) with response data from server on success. False on error.
271 function get($path, &$buffer) {
272 $this->_path
= $this->translate_uri($path);
273 $this->header_unset();
274 $this->create_basic_request('GET');
275 $this->send_request();
276 $this->get_respond();
277 $response = $this->process_respond();
279 $http_version = $response['status']['http-version'];
280 // validate the response
281 // check http-version
282 if ($http_version == 'HTTP/1.1' ||
$http_version == 'HTTP/1.0') {
283 // seems to be http ... proceed
284 // We expect a 200 code
285 if ($response['status']['status-code'] == 200 ) {
286 $this->_error_log('returning buffer with ' . strlen($response['body']) . ' bytes.');
287 $buffer = $response['body'];
289 return $response['status']['status-code'];
291 // ups: no http status was returned ?
298 * Puts a file into a collection.
299 * Data is putted as one chunk!
300 * @param string path, string data
301 * @return int status-code read from webdavserver. False on error.
303 function put($path, $data ) {
304 $this->_path
= $this->translate_uri($path);
305 $this->header_unset();
306 $this->create_basic_request('PUT');
307 // add more needed header information ...
308 $this->header_add('Content-length: ' . strlen($data));
309 $this->header_add('Content-type: application/octet-stream');
311 $this->send_request();
312 // send the rest (data)
313 fputs($this->sock
, $data);
314 $this->get_respond();
315 $response = $this->process_respond();
317 // validate the response
318 // check http-version
319 if ($response['status']['http-version'] == 'HTTP/1.1' ||
320 $response['status']['http-version'] == 'HTTP/1.0') {
321 // seems to be http ... proceed
322 // We expect a 200 or 204 status code
323 // see rfc 2068 - 9.6 PUT...
324 // print 'http ok<br>';
325 return $response['status']['status-code'];
327 // ups: no http status was returned ?
332 * Public method put_file
334 * Read a file as stream and puts it chunk by chunk into webdav server collection.
336 * Look at php documenation for legal filenames with fopen();
337 * The filename will be translated into utf-8 if not allready in utf-8.
339 * @param string targetpath, string filename
340 * @return int status code. False on error.
342 function put_file($path, $filename) {
343 // try to open the file ...
346 $handle = @fopen
($filename, 'r');
349 // $this->sock = pfsockopen ($this->_server, $this->_port, $this->_errno, $this->_errstr, $this->_socket_timeout);
350 $this->_path
= $this->translate_uri($path);
351 $this->header_unset();
352 $this->create_basic_request('PUT');
353 // add more needed header information ...
354 $this->header_add('Content-length: ' . filesize($filename));
355 $this->header_add('Content-type: application/octet-stream');
357 $this->send_request();
358 while (!feof($handle)) {
359 fputs($this->sock
,fgets($handle,4096));
362 $this->get_respond();
363 $response = $this->process_respond();
365 // validate the response
366 // check http-version
367 if ($response['status']['http-version'] == 'HTTP/1.1' ||
368 $response['status']['http-version'] == 'HTTP/1.0') {
369 // seems to be http ... proceed
370 // We expect a 200 or 204 status code
371 // see rfc 2068 - 9.6 PUT...
372 // print 'http ok<br>';
373 return $response['status']['status-code'];
375 // ups: no http status was returned ?
378 $this->_error_log('put_file: could not open ' . $filename);
385 * Public method get_file
387 * Gets a file from a collection into local filesystem.
390 * @param string srcpath, string localpath
391 * @return true on success. false on error.
393 function get_file($srcpath, $localpath) {
395 if ($this->get($srcpath, $buffer)) {
396 // convert utf-8 filename to iso-8859-1
398 $localpath = $this->utf_decode_path($localpath);
400 $handle = fopen ($localpath, 'w');
402 fwrite($handle, $buffer);
414 * Public method copy_file
416 * Copies a file on a webdav server
418 * Duplicates a file on the webdav server (serverside).
419 * All work is done on the webdav server. If you set param overwrite as true,
420 * the target will be overwritten.
422 * @param string src_path, string dest_path, bool overwrite
423 * @return int status code (look at rfc 2518). false on error.
425 function copy_file($src_path, $dst_path, $overwrite) {
426 $this->_path
= $this->translate_uri($src_path);
427 $this->header_unset();
428 $this->create_basic_request('COPY');
429 $this->header_add(sprintf('Destination: http://%s%s', $this->_server
, $this->translate_uri($dst_path)));
431 $this->header_add('Overwrite: T');
433 $this->header_add('Overwrite: F');
435 $this->header_add('');
436 $this->send_request();
437 $this->get_respond();
438 $response = $this->process_respond();
439 // validate the response ...
440 // check http-version
441 if ($response['status']['http-version'] == 'HTTP/1.1' ||
442 $response['status']['http-version'] == 'HTTP/1.0') {
443 /* seems to be http ... proceed
444 just return what server gave us (as defined in rfc 2518) :
445 201 (Created) - The source resource was successfully copied. The copy operation resulted in the creation of a new resource.
446 204 (No Content) - The source resource was successfully copied to a pre-existing destination resource.
447 403 (Forbidden) - The source and destination URIs are the same.
448 409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created.
449 412 (Precondition Failed) - The server was unable to maintain the liveness of the properties listed in the propertybehavior XML element
450 or the Overwrite header is "F" and the state of the destination resource is non-null.
451 423 (Locked) - The destination resource was locked.
452 502 (Bad Gateway) - This may occur when the destination is on another server and the destination server refuses to accept the resource.
453 507 (Insufficient Storage) - The destination resource does not have sufficient space to record the state of the resource after the
454 execution of this method.
456 return $response['status']['status-code'];
462 * Public method copy_coll
464 * Copies a collection on a webdav server
466 * Duplicates a collection on the webdav server (serverside).
467 * All work is done on the webdav server. If you set param overwrite as true,
468 * the target will be overwritten.
470 * @param string src_path, string dest_path, bool overwrite
471 * @return int status code (look at rfc 2518). false on error.
473 function copy_coll($src_path, $dst_path, $overwrite) {
474 $this->_path
= $this->translate_uri($src_path);
475 $this->header_unset();
476 $this->create_basic_request('COPY');
477 $this->header_add(sprintf('Destination: http://%s%s', $this->_server
, $this->translate_uri($dst_path)));
478 $this->header_add('Depth: Infinity');
480 $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n";
481 $xml .= "<d:propertybehavior xmlns:d=\"DAV:\">\r\n";
482 $xml .= " <d:keepalive>*</d:keepalive>\r\n";
483 $xml .= "</d:propertybehavior>\r\n";
485 $this->header_add('Content-length: ' . strlen($xml));
486 $this->header_add('Content-type: application/xml');
487 $this->send_request();
489 fputs($this->sock
, $xml);
490 $this->get_respond();
491 $response = $this->process_respond();
492 // validate the response ...
493 // check http-version
494 if ($response['status']['http-version'] == 'HTTP/1.1' ||
495 $response['status']['http-version'] == 'HTTP/1.0') {
496 /* seems to be http ... proceed
497 just return what server gave us (as defined in rfc 2518) :
498 201 (Created) - The source resource was successfully copied. The copy operation resulted in the creation of a new resource.
499 204 (No Content) - The source resource was successfully copied to a pre-existing destination resource.
500 403 (Forbidden) - The source and destination URIs are the same.
501 409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created.
502 412 (Precondition Failed) - The server was unable to maintain the liveness of the properties listed in the propertybehavior XML element
503 or the Overwrite header is "F" and the state of the destination resource is non-null.
504 423 (Locked) - The destination resource was locked.
505 502 (Bad Gateway) - This may occur when the destination is on another server and the destination server refuses to accept the resource.
506 507 (Insufficient Storage) - The destination resource does not have sufficient space to record the state of the resource after the
507 execution of this method.
509 return $response['status']['status-code'];
517 * Moves a file or collection on webdav server (serverside)
519 * If you set param overwrite as true, the target will be overwritten.
521 * @param string src_path, string dest_path, bool overwrite
522 * @return int status code (look at rfc 2518). false on error.
524 // --------------------------------------------------------------------------
525 // public method move
526 // move/rename a file/collection on webdav server
527 function move($src_path,$dst_path, $overwrite) {
529 $this->_path
= $this->translate_uri($src_path);
530 $this->header_unset();
532 $this->create_basic_request('MOVE');
533 $this->header_add(sprintf('Destination: http://%s%s', $this->_server
, $this->translate_uri($dst_path)));
535 $this->header_add('Overwrite: T');
537 $this->header_add('Overwrite: F');
539 $this->header_add('');
541 $this->send_request();
542 $this->get_respond();
543 $response = $this->process_respond();
544 // validate the response ...
545 // check http-version
546 if ($response['status']['http-version'] == 'HTTP/1.1' ||
547 $response['status']['http-version'] == 'HTTP/1.0') {
548 /* seems to be http ... proceed
549 just return what server gave us (as defined in rfc 2518) :
550 201 (Created) - The source resource was successfully moved, and a new resource was created at the destination.
551 204 (No Content) - The source resource was successfully moved to a pre-existing destination resource.
552 403 (Forbidden) - The source and destination URIs are the same.
553 409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created.
554 412 (Precondition Failed) - The server was unable to maintain the liveness of the properties listed in the propertybehavior XML element
555 or the Overwrite header is "F" and the state of the destination resource is non-null.
556 423 (Locked) - The source or the destination resource was locked.
557 502 (Bad Gateway) - This may occur when the destination is on another server and the destination server refuses to accept the resource.
559 201 (Created) - The collection or structured resource was created in its entirety.
560 403 (Forbidden) - This indicates at least one of two conditions: 1) the server does not allow the creation of collections at the given
561 location in its namespace, or 2) the parent collection of the Request-URI exists but cannot accept members.
562 405 (Method Not Allowed) - MKCOL can only be executed on a deleted/non-existent resource.
563 409 (Conflict) - A collection cannot be made at the Request-URI until one or more intermediate collections have been created.
564 415 (Unsupported Media Type)- The server does not support the request type of the body.
565 507 (Insufficient Storage) - The resource does not have sufficient space to record the state of the resource after the execution of this method.
567 return $response['status']['status-code'];
575 * Locks a file or collection.
577 * Lock uses this->_user as lock owner.
580 * @return int status code (look at rfc 2518). false on error.
582 function lock($path) {
583 $this->_path
= $this->translate_uri($path);
584 $this->header_unset();
585 $this->create_basic_request('LOCK');
586 $this->header_add('Timeout: Infinite');
587 $this->header_add('Content-type: text/xml');
588 // create the xml request ...
589 $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n";
590 $xml .= "<D:lockinfo xmlns:D='DAV:'\r\n>";
591 $xml .= " <D:lockscope><D:exclusive/></D:lockscope>\r\n";
592 $xml .= " <D:locktype><D:write/></D:locktype>\r\n";
593 $xml .= " <D:owner>\r\n";
594 $xml .= " <D:href>".($this->_user
)."</D:href>\r\n";
595 $xml .= " </D:owner>\r\n";
596 $xml .= "</D:lockinfo>\r\n";
597 $this->header_add('Content-length: ' . strlen($xml));
598 $this->send_request();
600 fputs($this->sock
, $xml);
601 $this->get_respond();
602 $response = $this->process_respond();
603 // validate the response ... (only basic validation)
604 // check http-version
605 if ($response['status']['http-version'] == 'HTTP/1.1' ||
606 $response['status']['http-version'] == 'HTTP/1.0') {
607 /* seems to be http ... proceed
609 200 (OK) - The lock request succeeded and the value of the lockdiscovery property is included in the body.
610 412 (Precondition Failed) - The included lock token was not enforceable on this resource or the server could not satisfy the
611 request in the lockinfo XML element.
612 423 (Locked) - The resource is locked, so the method has been rejected.
615 switch($response['status']['status-code']) {
617 // collection was successfully locked... see xml response to get lock token...
618 if (strcmp($response['header']['Content-Type'], 'text/xml; charset="utf-8"') == 0) {
619 // ok let's get the content of the xml stuff
620 $this->_parser
= xml_parser_create_ns();
621 $this->_parserid
= (int) $this->_parser
;
622 // forget old data...
623 unset($this->_lock
[$this->_parserid
]);
624 unset($this->_xmltree
[$this->_parserid
]);
625 xml_parser_set_option($this->_parser
,XML_OPTION_SKIP_WHITE
,0);
626 xml_parser_set_option($this->_parser
,XML_OPTION_CASE_FOLDING
,0);
627 xml_set_object($this->_parser
, $this);
628 xml_set_element_handler($this->_parser
, "_lock_startElement", "_endElement");
629 xml_set_character_data_handler($this->_parser
, "_lock_cdata");
631 if (!xml_parse($this->_parser
, $response['body'])) {
632 die(sprintf("XML error: %s at line %d",
633 xml_error_string(xml_get_error_code($this->_parser
)),
634 xml_get_current_line_number($this->_parser
)));
638 xml_parser_free($this->_parser
);
639 // add status code to array
640 $this->_lock
[$this->_parserid
]['status'] = 200;
641 return $this->_lock
[$this->_parserid
];
644 print 'Missing Content-Type: text/xml header in response.<br>';
649 // hmm. not what we expected. Just return what we got from webdav server
650 // someone else has to handle it.
651 $this->_lock
['status'] = $response['status']['status-code'];
661 * Public method unlock
663 * Unlocks a file or collection.
665 * @param string path, string locktoken
666 * @return int status code (look at rfc 2518). false on error.
668 function unlock($path, $locktoken) {
669 $this->_path
= $this->translate_uri($path);
670 $this->header_unset();
671 $this->create_basic_request('UNLOCK');
672 $this->header_add(sprintf('Lock-Token: <%s>', $locktoken));
673 $this->send_request();
674 $this->get_respond();
675 $response = $this->process_respond();
676 if ($response['status']['http-version'] == 'HTTP/1.1' ||
677 $response['status']['http-version'] == 'HTTP/1.0') {
678 /* seems to be http ... proceed
680 204 (OK) - The 204 (No Content) status code is used instead of 200 (OK) because there is no response entity body.
682 return $response['status']['status-code'];
688 * Public method delete
690 * deletes a collection/directory on a webdav server
692 * @return int status code (look at rfc 2518). false on error.
694 function delete($path) {
695 $this->_path
= $this->translate_uri($path);
696 $this->header_unset();
697 $this->create_basic_request('DELETE');
698 /* $this->header_add('Content-Length: 0'); */
699 $this->header_add('');
700 $this->send_request();
701 $this->get_respond();
702 $response = $this->process_respond();
704 // validate the response ...
705 // check http-version
706 if ($response['status']['http-version'] == 'HTTP/1.1' ||
707 $response['status']['http-version'] == 'HTTP/1.0') {
708 // seems to be http ... proceed
709 // We expect a 207 Multi-Status status code
710 // print 'http ok<br>';
712 switch ($response['status']['status-code']) {
714 // collection was NOT deleted... see xml response for reason...
715 // next there should be a Content-Type: text/xml; charset="utf-8" header line
716 if (strcmp($response['header']['Content-Type'], 'text/xml; charset="utf-8"') == 0) {
717 // ok let's get the content of the xml stuff
718 $this->_parser
= xml_parser_create_ns();
719 $this->_parserid
= (int) $this->_parser
;
720 // forget old data...
721 unset($this->_delete
[$this->_parserid
]);
722 unset($this->_xmltree
[$this->_parserid
]);
723 xml_parser_set_option($this->_parser
,XML_OPTION_SKIP_WHITE
,0);
724 xml_parser_set_option($this->_parser
,XML_OPTION_CASE_FOLDING
,0);
725 xml_set_object($this->_parser
, $this);
726 xml_set_element_handler($this->_parser
, "_delete_startElement", "_endElement");
727 xml_set_character_data_handler($this->_parser
, "_delete_cdata");
729 if (!xml_parse($this->_parser
, $response['body'])) {
730 die(sprintf("XML error: %s at line %d",
731 xml_error_string(xml_get_error_code($this->_parser
)),
732 xml_get_current_line_number($this->_parser
)));
738 xml_parser_free($this->_parser
);
739 $this->_delete
[$this->_parserid
]['status'] = $response['status']['status-code'];
740 return $this->_delete
[$this->_parserid
];
743 print 'Missing Content-Type: text/xml header in response.<br>';
748 // collection or file was successfully deleted
749 $this->_delete
['status'] = $response['status']['status-code'];
750 return $this->_delete
;
761 * Get's directory information from webdav server into flat a array using PROPFIND
763 * All filenames are UTF-8 encoded.
764 * Have a look at _propfind_startElement what keys are used in array returned.
766 * @return array dirinfo, false on error
770 if (trim($path) == '') {
771 $this->_error_log('Missing a path in method ls');
774 $this->_path
= $this->translate_uri($path);
776 $this->header_unset();
777 $this->create_basic_request('PROPFIND');
778 $this->header_add('Depth: 1');
779 $this->header_add('Content-type: application/xml');
780 // create profind xml request...
782 <?xml version="1.0" encoding="utf-8"?>
783 <propfind xmlns="DAV:"><prop>
784 <getcontentlength xmlns="DAV:"/>
785 <getlastmodified xmlns="DAV:"/>
786 <executable xmlns="http://apache.org/dav/props/"/>
787 <resourcetype xmlns="DAV:"/>
788 <checked-in xmlns="DAV:"/>
789 <checked-out xmlns="DAV:"/>
792 $this->header_add('Content-length: ' . strlen($xml));
793 $this->send_request();
794 $this->_error_log($xml);
795 fputs($this->sock
, $xml);
796 $this->get_respond();
797 $response = $this->process_respond();
798 // validate the response ... (only basic validation)
799 // check http-version
800 if ($response['status']['http-version'] == 'HTTP/1.1' ||
801 $response['status']['http-version'] == 'HTTP/1.0') {
802 // seems to be http ... proceed
803 // We expect a 207 Multi-Status status code
804 // print 'http ok<br>';
805 if (strcmp($response['status']['status-code'],'207') == 0 ) {
807 // next there should be a Content-Type: text/xml; charset="utf-8" header line
808 if (preg_match('#(application|text)/xml;\s?charset=[\'\"]?utf-8[\'\"]?#i', $response['header']['Content-Type'])) {
809 // ok let's get the content of the xml stuff
810 $this->_parser
= xml_parser_create_ns('UTF-8');
811 $this->_parserid
= (int) $this->_parser
;
812 // forget old data...
813 unset($this->_ls
[$this->_parserid
]);
814 unset($this->_xmltree
[$this->_parserid
]);
815 xml_parser_set_option($this->_parser
,XML_OPTION_SKIP_WHITE
,0);
816 xml_parser_set_option($this->_parser
,XML_OPTION_CASE_FOLDING
,0);
817 // xml_parser_set_option($this->_parser,XML_OPTION_TARGET_ENCODING,'UTF-8');
818 xml_set_object($this->_parser
, $this);
819 xml_set_element_handler($this->_parser
, "_propfind_startElement", "_endElement");
820 xml_set_character_data_handler($this->_parser
, "_propfind_cdata");
823 if (!xml_parse($this->_parser
, $response['body'])) {
824 die(sprintf("XML error: %s at line %d",
825 xml_error_string(xml_get_error_code($this->_parser
)),
826 xml_get_current_line_number($this->_parser
)));
830 xml_parser_free($this->_parser
);
831 $arr = $this->_ls
[$this->_parserid
];
834 $this->_error_log('Missing Content-Type: text/xml header in response!!');
838 // return status code ...
839 return $response['status']['status-code'];
843 // response was not http
844 $this->_error_log('Ups in method ls: error in response from server');
852 * Get's path information from webdav server for one element.
855 * @return array dirinfo. false on error
857 function gpi($path) {
859 // split path by last "/"
860 $path = rtrim($path, "/");
861 $item = basename($path);
862 $dir = dirname($path);
864 $list = $this->ls($dir);
866 // be sure it is an array
867 if (is_array($list)) {
868 foreach($list as $e) {
870 $fullpath = urldecode($e['href']);
871 $filename = basename($fullpath);
873 if ($filename == $item && $filename != "" and $fullpath != $dir."/") {
882 * Public method is_file
884 * Gathers whether a path points to a file or not.
887 * @return bool true or false
889 function is_file($path) {
891 $item = $this->gpi($path);
893 if ($item === false) {
896 return ($item['resourcetype'] != 'collection');
901 * Public method is_dir
903 * Gather whether a path points to a directory
905 * return bool true or false
907 function is_dir($path) {
909 // be sure path is utf-8
910 $item = $this->gpi($path);
912 if ($item === false) {
915 return ($item['resourcetype'] == 'collection');
923 * Puts multiple files and/or directories onto a webdav server.
925 * Filenames should be allready UTF-8 encoded.
926 * Param fileList must be in format array("localpath" => "destpath").
928 * @param array filelist
929 * @return bool true on success. otherwise int status code on error
931 function mput($filelist) {
935 while (list($localpath, $destpath) = each($filelist)) {
937 $localpath = rtrim($localpath, "/");
938 $destpath = rtrim($destpath, "/");
940 // attempt to create target path
941 if (is_dir($localpath)) {
942 $pathparts = explode("/", $destpath."/ "); // add one level, last level will be created as dir
944 $pathparts = explode("/", $destpath);
947 for ($i=1; $i<sizeof($pathparts)-1; $i++
) {
948 $checkpath .= "/" . $pathparts[$i];
949 if (!($this->is_dir($checkpath))) {
951 $result &= ($this->mkcol($checkpath) == 201 );
956 // recurse directories
957 if (is_dir($localpath)) {
958 $dp = opendir($localpath);
960 while($filename = readdir($dp)) {
961 if ((is_file($localpath."/".$filename) ||
is_dir($localpath."/".$filename)) && $filename!="." && $filename != "..") {
962 $fl[$localpath."/".$filename] = $destpath."/".$filename;
965 $result &= $this->mput($fl);
967 $result &= ($this->put_file($destpath, $localpath) == 201);
977 * Gets multiple files and directories.
979 * FileList must be in format array("remotepath" => "localpath").
980 * Filenames are UTF-8 encoded.
982 * @param array filelist
983 * @return bool true on succes, other int status code on error
985 function mget($filelist) {
989 while (list($remotepath, $localpath) = each($filelist)) {
991 $localpath = rtrim($localpath, "/");
992 $remotepath = rtrim($remotepath, "/");
994 // attempt to create local path
995 if ($this->is_dir($remotepath)) {
996 $pathparts = explode("/", $localpath."/ "); // add one level, last level will be created as dir
998 $pathparts = explode("/", $localpath);
1001 for ($i=1; $i<sizeof($pathparts)-1; $i++
) {
1002 $checkpath .= "/" . $pathparts[$i];
1003 if (!is_dir($checkpath)) {
1005 $result &= mkdir($checkpath);
1010 // recurse directories
1011 if ($this->is_dir($remotepath)) {
1012 $list = $this->ls($remotepath);
1015 foreach($list as $e) {
1016 $fullpath = urldecode($e['href']);
1017 $filename = basename($fullpath);
1018 if ($filename != '' and $fullpath != $remotepath . '/') {
1019 $fl[$remotepath."/".$filename] = $localpath."/".$filename;
1022 $result &= $this->mget($fl);
1024 $result &= ($this->get_file($remotepath, $localpath));
1031 // --------------------------------------------------------------------------
1032 // private xml callback and helper functions starting here
1033 // --------------------------------------------------------------------------
1037 * Private method _endelement
1039 * a generic endElement method (used for all xml callbacks).
1041 * @param resource parser, string name
1045 private function _endElement($parser, $name) {
1046 // end tag was found...
1047 $parserid = (int) $parser;
1048 $this->_xmltree
[$parserid] = substr($this->_xmltree
[$parserid],0, strlen($this->_xmltree
[$parserid]) - (strlen($name) +
1));
1052 * Private method _propfind_startElement
1054 * Is needed by public method ls.
1056 * Generic method will called by php xml_parse when a xml start element tag has been detected.
1057 * The xml tree will translated into a flat php array for easier access.
1058 * @param resource parser, string name, string attrs
1061 private function _propfind_startElement($parser, $name, $attrs) {
1062 // lower XML Names... maybe break a RFC, don't know ...
1063 $parserid = (int) $parser;
1065 $propname = strtolower($name);
1066 if (!empty($this->_xmltree
[$parserid])) {
1067 $this->_xmltree
[$parserid] .= $propname . '_';
1069 $this->_xmltree
[$parserid] = $propname . '_';
1072 // translate xml tree to a flat array ...
1073 switch($this->_xmltree
[$parserid]) {
1074 case 'dav::multistatus_dav::response_':
1075 // new element in mu
1076 $this->_ls_ref
=& $this->_ls
[$parserid][];
1078 case 'dav::multistatus_dav::response_dav::href_':
1079 $this->_ls_ref_cdata
= &$this->_ls_ref
['href'];
1081 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::creationdate_':
1082 $this->_ls_ref_cdata
= &$this->_ls_ref
['creationdate'];
1084 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getlastmodified_':
1085 $this->_ls_ref_cdata
= &$this->_ls_ref
['lastmodified'];
1087 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getcontenttype_':
1088 $this->_ls_ref_cdata
= &$this->_ls_ref
['getcontenttype'];
1090 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getcontentlength_':
1091 $this->_ls_ref_cdata
= &$this->_ls_ref
['getcontentlength'];
1093 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_':
1094 $this->_ls_ref_cdata
= &$this->_ls_ref
['activelock_depth'];
1096 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_':
1097 $this->_ls_ref_cdata
= &$this->_ls_ref
['activelock_owner'];
1099 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_':
1100 $this->_ls_ref_cdata
= &$this->_ls_ref
['activelock_owner'];
1102 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_':
1103 $this->_ls_ref_cdata
= &$this->_ls_ref
['activelock_timeout'];
1105 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_':
1106 $this->_ls_ref_cdata
= &$this->_ls_ref
['activelock_token'];
1108 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::locktype_dav::write_':
1109 $this->_ls_ref_cdata
= &$this->_ls_ref
['activelock_type'];
1110 $this->_ls_ref_cdata
= 'write';
1111 $this->_ls_ref_cdata
= &$this->_null
;
1113 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::resourcetype_dav::collection_':
1114 $this->_ls_ref_cdata
= &$this->_ls_ref
['resourcetype'];
1115 $this->_ls_ref_cdata
= 'collection';
1116 $this->_ls_ref_cdata
= &$this->_null
;
1118 case 'dav::multistatus_dav::response_dav::propstat_dav::status_':
1119 $this->_ls_ref_cdata
= &$this->_ls_ref
['status'];
1123 // handle unknown xml elements...
1124 $this->_ls_ref_cdata
= &$this->_ls_ref
[$this->_xmltree
[$parserid]];
1129 * Private method _propfind_cData
1131 * Is needed by public method ls.
1133 * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
1134 * Stores data found into class var _ls_ref_cdata
1135 * @param resource parser, string cdata
1138 private function _propfind_cData($parser, $cdata) {
1139 if (trim($cdata) <> '') {
1140 // cdata must be appended, because sometimes the php xml parser makes multiple calls
1141 // to _propfind_cData before the xml end tag was reached...
1142 $this->_ls_ref_cdata
.= $cdata;
1149 * Private method _delete_startElement
1151 * Is used by public method delete.
1153 * Will be called by php xml_parse.
1154 * @param resource parser, string name, string attrs)
1157 private function _delete_startElement($parser, $name, $attrs) {
1158 // lower XML Names... maybe break a RFC, don't know ...
1159 $parserid = (int) $parser;
1160 $propname = strtolower($name);
1161 $this->_xmltree
[$parserid] .= $propname . '_';
1163 // translate xml tree to a flat array ...
1164 switch($this->_xmltree
[$parserid]) {
1165 case 'dav::multistatus_dav::response_':
1166 // new element in mu
1167 $this->_delete_ref
=& $this->_delete
[$parserid][];
1169 case 'dav::multistatus_dav::response_dav::href_':
1170 $this->_delete_ref_cdata
= &$this->_ls_ref
['href'];
1174 // handle unknown xml elements...
1175 $this->_delete_cdata
= &$this->_delete_ref
[$this->_xmltree
[$parserid]];
1181 * Private method _delete_cData
1183 * Is used by public method delete.
1185 * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
1186 * Stores data found into class var _delete_ref_cdata
1187 * @param resource parser, string cdata
1190 private function _delete_cData($parser, $cdata) {
1191 if (trim($cdata) <> '') {
1192 $this->_delete_ref_cdata
.= $cdata;
1200 * Private method _lock_startElement
1202 * Is needed by public method lock.
1204 * Mmethod will called by php xml_parse when a xml start element tag has been detected.
1205 * The xml tree will translated into a flat php array for easier access.
1206 * @param resource parser, string name, string attrs
1209 private function _lock_startElement($parser, $name, $attrs) {
1210 // lower XML Names... maybe break a RFC, don't know ...
1211 $parserid = (int) $parser;
1212 $propname = strtolower($name);
1213 $this->_xmltree
[$parserid] .= $propname . '_';
1215 // translate xml tree to a flat array ...
1217 dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_=
1218 dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_=
1219 dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_=
1220 dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_=
1222 switch($this->_xmltree
[$parserid]) {
1223 case 'dav::prop_dav::lockdiscovery_dav::activelock_':
1225 $this->_lock_ref
=& $this->_lock
[$parserid][];
1227 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::locktype_dav::write_':
1228 $this->_lock_ref_cdata
= &$this->_lock_ref
['locktype'];
1229 $this->_lock_cdata
= 'write';
1230 $this->_lock_cdata
= &$this->_null
;
1232 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::lockscope_dav::exclusive_':
1233 $this->_lock_ref_cdata
= &$this->_lock_ref
['lockscope'];
1234 $this->_lock_ref_cdata
= 'exclusive';
1235 $this->_lock_ref_cdata
= &$this->_null
;
1237 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_':
1238 $this->_lock_ref_cdata
= &$this->_lock_ref
['depth'];
1240 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_':
1241 $this->_lock_ref_cdata
= &$this->_lock_ref
['owner'];
1243 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_':
1244 $this->_lock_ref_cdata
= &$this->_lock_ref
['timeout'];
1246 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_':
1247 $this->_lock_ref_cdata
= &$this->_lock_ref
['locktoken'];
1250 // handle unknown xml elements...
1251 $this->_lock_cdata
= &$this->_lock_ref
[$this->_xmltree
[$parserid]];
1257 * Private method _lock_cData
1259 * Is used by public method lock.
1261 * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
1262 * Stores data found into class var _lock_ref_cdata
1263 * @param resource parser, string cdata
1266 private function _lock_cData($parser, $cdata) {
1267 $parserid = (int) $parser;
1268 if (trim($cdata) <> '') {
1269 // $this->_error_log(($this->_xmltree[$parserid]) . '='. htmlentities($cdata));
1270 $this->_lock_ref_cdata
.= $cdata;
1278 * Private method header_add
1280 * extends class var array _req
1281 * @param string string
1284 private function header_add($string) {
1285 $this->_req
[] = $string;
1289 * Private method header_unset
1291 * unsets class var array _req
1295 private function header_unset() {
1300 * Private method create_basic_request
1302 * creates by using private method header_add an general request header.
1303 * @param string method
1306 private function create_basic_request($method) {
1307 $this->header_add(sprintf('%s %s %s', $method, $this->_path
, $this->_protocol
));
1308 $this->header_add(sprintf('Host: %s:%s', $this->_server
, $this->_port
));
1309 //$request .= sprintf('Connection: Keep-Alive');
1310 $this->header_add(sprintf('User-Agent: %s', $this->_user_agent
));
1311 $this->header_add('Connection: TE');
1312 $this->header_add('TE: Trailers');
1313 if ($this->_auth
== 'basic') {
1314 $this->header_add(sprintf('Authorization: Basic %s', base64_encode("$this->_user:$this->_pass")));
1315 } else if ($this->_auth
== 'digest') {
1316 if ($signature = $this->digest_signature($method)){
1317 $this->header_add($signature);
1323 * Reads the header, stores the challenge information
1327 private function digest_auth() {
1330 $headers[] = sprintf('%s %s %s', 'HEAD', $this->_path
, $this->_protocol
);
1331 $headers[] = sprintf('Host: %s:%s', $this->_server
, $this->_port
);
1332 $headers[] = sprintf('User-Agent: %s', $this->_user_agent
);
1333 $headers = implode("\r\n", $headers);
1334 $headers .= "\r\n\r\n";
1335 fputs($this->sock
, $headers);
1337 // Reads the headers.
1341 $header .= fread($this->sock
, 1);
1343 } while (!preg_match('/\\r\\n\\r\\n$/', $header, $matches) && $i < $this->_maxheaderlenth
);
1345 // Analyse the headers.
1347 $splitheaders = explode("\r\n", $header);
1348 foreach ($splitheaders as $line) {
1349 if (!preg_match('/^WWW-Authenticate: Digest/', $line)) {
1352 $line = substr($line, strlen('WWW-Authenticate: Digest '));
1353 $params = explode(',', $line);
1354 foreach ($params as $param) {
1355 list($key, $value) = explode('=', trim($param), 2);
1356 $digest[$key] = trim($value, '"');
1361 $this->_digestchallenge
= $digest;
1365 * Generates the digest signature
1367 * @return string signature to add to the headers
1370 private function digest_signature($method) {
1371 if (!$this->_digestchallenge
) {
1372 $this->digest_auth();
1375 $signature = array();
1376 $signature['username'] = '"' . $this->_user
. '"';
1377 $signature['realm'] = '"' . $this->_digestchallenge
['realm'] . '"';
1378 $signature['nonce'] = '"' . $this->_digestchallenge
['nonce'] . '"';
1379 $signature['uri'] = '"' . $this->_path
. '"';
1381 if (isset($this->_digestchallenge
['algorithm']) && $this->_digestchallenge
['algorithm'] != 'MD5') {
1382 $this->_error_log('Algorithm other than MD5 are not supported');
1386 $a1 = $this->_user
. ':' . $this->_digestchallenge
['realm'] . ':' . $this->_pass
;
1387 $a2 = $method . ':' . $this->_path
;
1389 if (!isset($this->_digestchallenge
['qop'])) {
1390 $signature['response'] = '"' . md5(md5($a1) . ':' . $this->_digestchallenge
['nonce'] . ':' . md5($a2)) . '"';
1392 // Assume QOP is auth
1393 if (empty($this->_cnonce
)) {
1394 $this->_cnonce
= random_string();
1398 $nc = sprintf('%08d', $this->_nc
);
1399 $signature['cnonce'] = '"' . $this->_cnonce
. '"';
1400 $signature['nc'] = '"' . $nc . '"';
1401 $signature['qop'] = '"' . $this->_digestchallenge
['qop'] . '"';
1402 $signature['response'] = '"' . md5(md5($a1) . ':' . $this->_digestchallenge
['nonce'] . ':' .
1403 $nc . ':' . $this->_cnonce
. ':' . $this->_digestchallenge
['qop'] . ':' . md5($a2)) . '"';
1406 $response = array();
1407 foreach ($signature as $key => $value) {
1408 $response[] = "$key=$value";
1410 return 'Authorization: Digest ' . implode(', ', $response);
1414 * Private method send_request
1416 * Sends a ready formed http/webdav request to webdav server.
1420 private function send_request() {
1421 // check if stream is declared to be open
1422 // only logical check we are not sure if socket is really still open ...
1423 if ($this->_connection_closed
) {
1425 // be sure to close the open socket.
1430 // convert array to string
1431 $buffer = implode("\r\n", $this->_req
);
1432 $buffer .= "\r\n\r\n";
1433 $this->_error_log($buffer);
1434 fputs($this->sock
, $buffer);
1438 * Private method get_respond
1440 * Reads the reponse from the webdav server.
1442 * Stores data into class vars _header for the header data and
1443 * _body for the rest of the response.
1444 * This routine is the weakest part of this class, because it very depends how php does handle a socket stream.
1445 * If the stream is blocked for some reason php is blocked as well.
1448 private function get_respond() {
1449 $this->_error_log('get_respond()');
1450 // init vars (good coding style ;-)
1453 // attention: do not make max_chunk_size to big....
1454 $max_chunk_size = 8192;
1455 // be sure we got a open ressource
1456 if (! $this->sock
) {
1457 $this->_error_log('socket is not open. Can not process response');
1461 // following code maybe helps to improve socket behaviour ... more testing needed
1462 // disabled at the moment ...
1463 // socket_set_timeout($this->sock,1 );
1464 // $socket_state = socket_get_status($this->sock);
1466 // read stream one byte by another until http header ends
1470 $header.=fread($this->sock
, 1);
1472 } while (!preg_match('/\\r\\n\\r\\n$/',$header, $matches) && $i < $this->_maxheaderlenth
);
1474 $this->_error_log($header);
1476 if (preg_match('/Connection: close\\r\\n/', $header)) {
1477 // This says that the server will close connection at the end of this stream.
1478 // Therefore we need to reopen the socket, before are sending the next request...
1479 $this->_error_log('Connection: close found');
1480 $this->_connection_closed
= true;
1481 } else if (preg_match('@^HTTP/1\.(1|0) 401 @', $header)) {
1482 $this->_error_log('The server requires an authentication');
1485 // check how to get the data on socket stream
1486 // chunked or content-length (HTTP/1.1) or
1487 // one block until feof is received (HTTP/1.0)
1489 case (preg_match('/Transfer\\-Encoding:\\s+chunked\\r\\n/',$header)):
1490 $this->_error_log('Getting HTTP/1.1 chunked data...');
1496 $byte=fread($this->sock
,1);
1497 // check what happens while reading, because I do not really understand how php reads the socketstream...
1498 // but so far - it seems to work here - tested with php v4.3.1 on apache 1.3.27 and Debian Linux 3.0 ...
1499 if (strlen($byte) == 0) {
1500 $this->_error_log('get_respond: warning --> read zero bytes');
1502 } while ($byte!="\r" and strlen($byte)>0); // till we match the Carriage Return
1503 fread($this->sock
, 1); // also drop off the Line Feed
1504 $chunk_size=hexdec($chunk_size); // convert to a number in decimal system
1505 if ($chunk_size > 0) {
1507 // Reading the chunk in one bite is not secure, we read it byte by byte.
1508 while ($read < $chunk_size) {
1509 $buffer .= fread($this->sock
, 1);
1513 fread($this->sock
, 2); // ditch the CRLF that trails the chunk
1514 } while ($chunk_size); // till we reach the 0 length chunk (end marker)
1517 // check for a specified content-length
1518 case preg_match('/Content\\-Length:\\s+([0-9]*)\\r\\n/',$header,$matches):
1519 $this->_error_log('Getting data using Content-Length '. $matches[1]);
1521 // check if we the content data size is small enough to get it as one block
1522 if ($matches[1] <= $max_chunk_size ) {
1523 // only read something if Content-Length is bigger than 0
1524 if ($matches[1] > 0 ) {
1525 $buffer = fread($this->sock
, $matches[1]);
1526 $loadsize = strlen($buffer);
1527 //did we realy get the full length?
1528 if ($loadsize < $matches[1]) {
1529 $max_chunk_size = $loadsize;
1531 $mod = $max_chunk_size %
($matches[1] - strlen($buffer));
1532 $chunk_size = ($mod == $max_chunk_size ?
$max_chunk_size : $matches[1] - strlen($buffer));
1533 $buffer .= fread($this->sock
, $chunk_size);
1534 $this->_error_log('mod: ' . $mod . ' chunk: ' . $chunk_size . ' total: ' . strlen($buffer));
1535 } while ($mod == $max_chunk_size);
1546 // data is to big to handle it as one. Get it chunk per chunk...
1547 //trying to get the full length of max_chunk_size
1548 $buffer = fread($this->sock
, $max_chunk_size);
1549 $loadsize = strlen($buffer);
1550 if ($loadsize < $max_chunk_size) {
1551 $max_chunk_size = $loadsize;
1554 $mod = $max_chunk_size %
($matches[1] - strlen($buffer));
1555 $chunk_size = ($mod == $max_chunk_size ?
$max_chunk_size : $matches[1] - strlen($buffer));
1556 $buffer .= fread($this->sock
, $chunk_size);
1557 $this->_error_log('mod: ' . $mod . ' chunk: ' . $chunk_size . ' total: ' . strlen($buffer));
1558 } while ($mod == $max_chunk_size);
1559 $loadsize = strlen($buffer);
1560 if ($loadsize < $matches[1]) {
1561 $buffer .= fread($this->sock
, $matches[1] - $loadsize);
1565 // check for 204 No Content
1566 // 204 responds have no body.
1567 // Therefore we do not need to read any data from socket stream.
1568 case preg_match('/HTTP\/1\.1\ 204/',$header):
1569 // nothing to do, just proceed
1570 $this->_error_log('204 No Content found. No further data to read..');
1573 // just get the data until foef appears...
1574 $this->_error_log('reading until feof...' . $header);
1575 socket_set_timeout($this->sock
, 0, 0);
1576 while (!feof($this->sock
)) {
1577 $buffer .= fread($this->sock
, 4096);
1579 // renew the socket timeout...does it do something ???? Is it needed. More debugging needed...
1580 socket_set_timeout($this->sock
, $this->_socket_timeout
, 0);
1583 $this->_header
= $header;
1584 $this->_body
= $buffer;
1585 // $this->_buffer = $header . "\r\n\r\n" . $buffer;
1586 $this->_error_log($this->_header
);
1587 $this->_error_log($this->_body
);
1593 * Private method process_respond
1595 * Processes the webdav server respond and detects its components (header, body).
1596 * and returns data array structure.
1597 * @return array ret_struct
1600 private function process_respond() {
1601 $lines = explode("\r\n", $this->_header
);
1602 $header_done = false;
1603 // $this->_error_log($this->_buffer);
1604 // First line should be a HTTP status line (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6)
1605 // Format is: HTTP-Version SP Status-Code SP Reason-Phrase CRLF
1606 list($ret_struct['status']['http-version'],
1607 $ret_struct['status']['status-code'],
1608 $ret_struct['status']['reason-phrase']) = explode(' ', $lines[0],3);
1610 // print "HTTP Version: '$http_version' Status-Code: '$status_code' Reason Phrase: '$reason_phrase'<br>";
1611 // get the response header fields
1612 // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6
1613 for($i=1; $i<count($lines); $i++
) {
1614 if (rtrim($lines[$i]) == '' && !$header_done) {
1615 $header_done = true;
1616 // print "--- response header end ---<br>";
1619 if (!$header_done ) {
1620 // store all found headers in array ...
1621 list($fieldname, $fieldvalue) = explode(':', $lines[$i]);
1622 // check if this header was allready set (apache 2.0 webdav module does this....).
1623 // If so we add the the value to the end the fieldvalue, separated by comma...
1624 if (empty($ret_struct['header'])) {
1625 $ret_struct['header'] = array();
1627 if (empty($ret_struct['header'][$fieldname])) {
1628 $ret_struct['header'][$fieldname] = trim($fieldvalue);
1630 $ret_struct['header'][$fieldname] .= ',' . trim($fieldvalue);
1634 // print 'string len of response_body:'. strlen($response_body);
1635 // print '[' . htmlentities($response_body) . ']';
1636 $ret_struct['body'] = $this->_body
;
1637 $this->_error_log('process_respond: ' . var_export($ret_struct,true));
1643 * Private method reopen
1645 * Reopens a socket, if 'connection: closed'-header was received from server.
1647 * Uses public method open.
1650 private function reopen() {
1651 // let's try to reopen a socket
1652 $this->_error_log('reopen a socket connection');
1653 return $this->open();
1658 * Private method translate_uri
1660 * translates an uri to raw url encoded string.
1661 * Removes any html entity in uri
1663 * @return string translated_uri
1666 private function translate_uri($uri) {
1667 // remove all html entities...
1668 $native_path = html_entity_decode($uri);
1669 $parts = explode('/', $native_path);
1670 for ($i = 0; $i < count($parts); $i++
) {
1671 // check if part is allready utf8
1672 if (iconv('UTF-8', 'UTF-8', $parts[$i]) == $parts[$i]) {
1673 $parts[$i] = rawurlencode($parts[$i]);
1675 $parts[$i] = rawurlencode(utf8_encode($parts[$i]));
1678 return implode('/', $parts);
1682 * Private method utf_decode_path
1684 * decodes a UTF-8 encoded string
1685 * @return string decodedstring
1688 private function utf_decode_path($path) {
1690 if (iconv('UTF-8', 'UTF-8', $fullpath) == $fullpath) {
1691 $this->_error_log("filename is utf-8. Needs conversion...");
1692 $fullpath = utf8_decode($fullpath);
1698 * Private method _error_log
1700 * a simple php error_log wrapper.
1701 * @param string err_string
1704 private function _error_log($err_string) {
1705 if ($this->_debug
) {
1706 error_log($err_string);