Merge branch 'MDL-32509' of git://github.com/danpoltawski/moodle
[moodle.git] / lib / webdavlib.php
blob70bff78a18377e8cf80b7c153aaa4b3f10042141
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
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/>.
18 /**
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.
29 * @package moodlecore
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
33 * @version 0.1.5
36 class webdav_client {
38 /**#@+
39 * @access private
40 * @var string
42 private $_debug = false;
43 private $sock;
44 private $_server;
45 private $_protocol = 'HTTP/1.1';
46 private $_port = 80;
47 private $_path ='/';
48 private $_auth = false;
49 private $_user;
50 private $_pass;
52 private $_socket_timeout = 5;
53 private $_errno;
54 private $_errstr;
55 private $_user_agent = 'Moodle WebDav Client';
56 private $_crlf = "\r\n";
57 private $_req;
58 private $_resp_status;
59 private $_parser;
60 private $_xmltree;
61 private $_tree;
62 private $_ls = array();
63 private $_ls_ref;
64 private $_ls_ref_cdata;
65 private $_delete = array();
66 private $_delete_ref;
67 private $_delete_ref_cdata;
68 private $_lock = array();
69 private $_lock_ref;
70 private $_lock_rec_cdata;
71 private $_null = NULL;
72 private $_header='';
73 private $_body='';
74 private $_connection_closed = false;
75 private $_maxheaderlenth = 1000;
77 /**#@-*/
79 /**
80 * Constructor - Initialise class variables
82 function __construct($server = '', $user = '', $pass = '', $auth = false) {
83 if (!empty($server)) {
84 $this->_server = $server;
86 if (!empty($user) && !empty($pass)) {
87 $this->user = $user;
88 $this->pass = $pass;
90 $this->_auth = $auth;
92 public function __set($key, $value) {
93 $property = '_' . $key;
94 $this->$property = $value;
97 /**
98 * Set which HTTP protocol will be used.
99 * Value 1 defines that HTTP/1.1 should be used (Keeps Connection to webdav server alive).
100 * Otherwise HTTP/1.0 will be used.
101 * @param int version
103 function set_protocol($version) {
104 if ($version == 1) {
105 $this->_protocol = 'HTTP/1.1';
106 } else {
107 $this->_protocol = 'HTTP/1.0';
112 * Convert ISO 8601 Date and Time Profile used in RFC 2518 to an unix timestamp.
113 * @access private
114 * @param string iso8601
115 * @return unixtimestamp on sucess. Otherwise false.
117 function iso8601totime($iso8601) {
120 date-time = full-date "T" full-time
122 full-date = date-fullyear "-" date-month "-" date-mday
123 full-time = partial-time time-offset
125 date-fullyear = 4DIGIT
126 date-month = 2DIGIT ; 01-12
127 date-mday = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on
128 month/year
129 time-hour = 2DIGIT ; 00-23
130 time-minute = 2DIGIT ; 00-59
131 time-second = 2DIGIT ; 00-59, 00-60 based on leap second rules
132 time-secfrac = "." 1*DIGIT
133 time-numoffset = ("+" / "-") time-hour ":" time-minute
134 time-offset = "Z" / time-numoffset
136 partial-time = time-hour ":" time-minute ":" time-second
137 [time-secfrac]
140 $regs = array();
141 /* [1] [2] [3] [4] [5] [6] */
142 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)) {
143 return mktime($regs[4],$regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
145 // to be done: regex for partial-time...apache webdav mod never returns partial-time
147 return false;
151 * Open's a socket to a webdav server
152 * @return bool true on success. Otherwise false.
154 function open() {
155 // let's try to open a socket
156 $this->_error_log('open a socket connection');
157 $this->sock = fsockopen($this->_server, $this->_port, $this->_errno, $this->_errstr, $this->_socket_timeout);
158 set_time_limit(30);
159 if (is_resource($this->sock)) {
160 socket_set_blocking($this->sock, true);
161 $this->_connection_closed = false;
162 $this->_error_log('socket is open: ' . $this->sock);
163 return true;
164 } else {
165 $this->_error_log("$this->_errstr ($this->_errno)\n");
166 return false;
171 * Closes an open socket.
173 function close() {
174 $this->_error_log('closing socket ' . $this->sock);
175 $this->_connection_closed = true;
176 fclose($this->sock);
180 * Check's if server is a webdav compliant server.
181 * True if server returns a DAV Element in Header and when
182 * schema 1,2 is supported.
183 * @return bool true if server is webdav server. Otherwise false.
185 function check_webdav() {
186 $resp = $this->options();
187 if (!$resp) {
188 return false;
190 $this->_error_log($resp['header']['DAV']);
191 // check schema
192 if (preg_match('/1,2/', $resp['header']['DAV'])) {
193 return true;
195 // otherwise return false
196 return false;
201 * Get options from webdav server.
202 * @return array with all header fields returned from webdav server. false if server does not speak http.
204 function options() {
205 $this->header_unset();
206 $this->create_basic_request('OPTIONS');
207 $this->send_request();
208 $this->get_respond();
209 $response = $this->process_respond();
210 // validate the response ...
211 // check http-version
212 if ($response['status']['http-version'] == 'HTTP/1.1' ||
213 $response['status']['http-version'] == 'HTTP/1.0') {
214 return $response;
216 $this->_error_log('Response was not even http');
217 return false;
222 * Public method mkcol
224 * Creates a new collection/directory on a webdav server
225 * @param string path
226 * @return int status code received as reponse from webdav server (see rfc 2518)
228 function mkcol($path) {
229 $this->_path = $this->translate_uri($path);
230 $this->header_unset();
231 $this->create_basic_request('MKCOL');
232 $this->send_request();
233 $this->get_respond();
234 $response = $this->process_respond();
235 // validate the response ...
236 // check http-version
237 $http_version = $response['status']['http-version'];
238 if ($http_version == 'HTTP/1.1' || $http_version == 'HTTP/1.0') {
239 /** seems to be http ... proceed
240 * just return what server gave us
241 * rfc 2518 says:
242 * 201 (Created) - The collection or structured resource was created in its entirety.
243 * 403 (Forbidden) - This indicates at least one of two conditions:
244 * 1) the server does not allow the creation of collections at the given location in its namespace, or
245 * 2) the parent collection of the Request-URI exists but cannot accept members.
246 * 405 (Method Not Allowed) - MKCOL can only be executed on a deleted/non-existent resource.
247 * 409 (Conflict) - A collection cannot be made at the Request-URI until one or more intermediate
248 * collections have been created.
249 * 415 (Unsupported Media Type)- The server does not support the request type of the body.
250 * 507 (Insufficient Storage) - The resource does not have sufficient space to record the state of the
251 * resource after the execution of this method.
253 return $response['status']['status-code'];
259 * Public method get
261 * Gets a file from a webdav collection.
262 * @param string path, string &buffer
263 * @return status code and &$buffer (by reference) with response data from server on success. False on error.
265 function get($path, &$buffer) {
266 $this->_path = $this->translate_uri($path);
267 $this->header_unset();
268 $this->create_basic_request('GET');
269 $this->send_request();
270 $this->get_respond();
271 $response = $this->process_respond();
273 $http_version = $response['status']['http-version'];
274 // validate the response
275 // check http-version
276 if ($http_version == 'HTTP/1.1' || $http_version == 'HTTP/1.0') {
277 // seems to be http ... proceed
278 // We expect a 200 code
279 if ($response['status']['status-code'] == 200 ) {
280 $this->_error_log('returning buffer with ' . strlen($response['body']) . ' bytes.');
281 $buffer = $response['body'];
283 return $response['status']['status-code'];
285 // ups: no http status was returned ?
286 return false;
290 * Public method put
292 * Puts a file into a collection.
293 * Data is putted as one chunk!
294 * @param string path, string data
295 * @return int status-code read from webdavserver. False on error.
297 function put($path, $data ) {
298 $this->_path = $this->translate_uri($path);
299 $this->header_unset();
300 $this->create_basic_request('PUT');
301 // add more needed header information ...
302 $this->header_add('Content-length: ' . strlen($data));
303 $this->header_add('Content-type: application/octet-stream');
304 // send header
305 $this->send_request();
306 // send the rest (data)
307 fputs($this->sock, $data);
308 $this->get_respond();
309 $response = $this->process_respond();
311 // validate the response
312 // check http-version
313 if ($response['status']['http-version'] == 'HTTP/1.1' ||
314 $response['status']['http-version'] == 'HTTP/1.0') {
315 // seems to be http ... proceed
316 // We expect a 200 or 204 status code
317 // see rfc 2068 - 9.6 PUT...
318 // print 'http ok<br>';
319 return $response['status']['status-code'];
321 // ups: no http status was returned ?
322 return false;
326 * Public method put_file
328 * Read a file as stream and puts it chunk by chunk into webdav server collection.
330 * Look at php documenation for legal filenames with fopen();
331 * The filename will be translated into utf-8 if not allready in utf-8.
333 * @param string targetpath, string filename
334 * @return int status code. False on error.
336 function put_file($path, $filename) {
337 // try to open the file ...
340 $handle = @fopen ($filename, 'r');
342 if ($handle) {
343 // $this->sock = pfsockopen ($this->_server, $this->_port, $this->_errno, $this->_errstr, $this->_socket_timeout);
344 $this->_path = $this->translate_uri($path);
345 $this->header_unset();
346 $this->create_basic_request('PUT');
347 // add more needed header information ...
348 $this->header_add('Content-length: ' . filesize($filename));
349 $this->header_add('Content-type: application/octet-stream');
350 // send header
351 $this->send_request();
352 while (!feof($handle)) {
353 fputs($this->sock,fgets($handle,4096));
355 fclose($handle);
356 $this->get_respond();
357 $response = $this->process_respond();
359 // validate the response
360 // check http-version
361 if ($response['status']['http-version'] == 'HTTP/1.1' ||
362 $response['status']['http-version'] == 'HTTP/1.0') {
363 // seems to be http ... proceed
364 // We expect a 200 or 204 status code
365 // see rfc 2068 - 9.6 PUT...
366 // print 'http ok<br>';
367 return $response['status']['status-code'];
369 // ups: no http status was returned ?
370 return false;
371 } else {
372 $this->_error_log('put_file: could not open ' . $filename);
373 return false;
379 * Public method get_file
381 * Gets a file from a collection into local filesystem.
383 * fopen() is used.
384 * @param string srcpath, string localpath
385 * @return true on success. false on error.
387 function get_file($srcpath, $localpath) {
389 if ($this->get($srcpath, $buffer)) {
390 // convert utf-8 filename to iso-8859-1
392 $localpath = $this->utf_decode_path($localpath);
394 $handle = fopen ($localpath, 'w');
395 if ($handle) {
396 fwrite($handle, $buffer);
397 fclose($handle);
398 return true;
399 } else {
400 return false;
402 } else {
403 return false;
408 * Public method copy_file
410 * Copies a file on a webdav server
412 * Duplicates a file on the webdav server (serverside).
413 * All work is done on the webdav server. If you set param overwrite as true,
414 * the target will be overwritten.
416 * @param string src_path, string dest_path, bool overwrite
417 * @return int status code (look at rfc 2518). false on error.
419 function copy_file($src_path, $dst_path, $overwrite) {
420 $this->_path = $this->translate_uri($src_path);
421 $this->header_unset();
422 $this->create_basic_request('COPY');
423 $this->header_add(sprintf('Destination: http://%s%s', $this->_server, $this->translate_uri($dst_path)));
424 if ($overwrite) {
425 $this->header_add('Overwrite: T');
426 } else {
427 $this->header_add('Overwrite: F');
429 $this->header_add('');
430 $this->send_request();
431 $this->get_respond();
432 $response = $this->process_respond();
433 // validate the response ...
434 // check http-version
435 if ($response['status']['http-version'] == 'HTTP/1.1' ||
436 $response['status']['http-version'] == 'HTTP/1.0') {
437 /* seems to be http ... proceed
438 just return what server gave us (as defined in rfc 2518) :
439 201 (Created) - The source resource was successfully copied. The copy operation resulted in the creation of a new resource.
440 204 (No Content) - The source resource was successfully copied to a pre-existing destination resource.
441 403 (Forbidden) - The source and destination URIs are the same.
442 409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created.
443 412 (Precondition Failed) - The server was unable to maintain the liveness of the properties listed in the propertybehavior XML element
444 or the Overwrite header is "F" and the state of the destination resource is non-null.
445 423 (Locked) - The destination resource was locked.
446 502 (Bad Gateway) - This may occur when the destination is on another server and the destination server refuses to accept the resource.
447 507 (Insufficient Storage) - The destination resource does not have sufficient space to record the state of the resource after the
448 execution of this method.
450 return $response['status']['status-code'];
452 return false;
456 * Public method copy_coll
458 * Copies a collection on a webdav server
460 * Duplicates a collection on the webdav server (serverside).
461 * All work is done on the webdav server. If you set param overwrite as true,
462 * the target will be overwritten.
464 * @param string src_path, string dest_path, bool overwrite
465 * @return int status code (look at rfc 2518). false on error.
467 function copy_coll($src_path, $dst_path, $overwrite) {
468 $this->_path = $this->translate_uri($src_path);
469 $this->header_unset();
470 $this->create_basic_request('COPY');
471 $this->header_add(sprintf('Destination: http://%s%s', $this->_server, $this->translate_uri($dst_path)));
472 $this->header_add('Depth: Infinity');
474 $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n";
475 $xml .= "<d:propertybehavior xmlns:d=\"DAV:\">\r\n";
476 $xml .= " <d:keepalive>*</d:keepalive>\r\n";
477 $xml .= "</d:propertybehavior>\r\n";
479 $this->header_add('Content-length: ' . strlen($xml));
480 $this->header_add('Content-type: application/xml');
481 $this->send_request();
482 // send also xml
483 fputs($this->sock, $xml);
484 $this->get_respond();
485 $response = $this->process_respond();
486 // validate the response ...
487 // check http-version
488 if ($response['status']['http-version'] == 'HTTP/1.1' ||
489 $response['status']['http-version'] == 'HTTP/1.0') {
490 /* seems to be http ... proceed
491 just return what server gave us (as defined in rfc 2518) :
492 201 (Created) - The source resource was successfully copied. The copy operation resulted in the creation of a new resource.
493 204 (No Content) - The source resource was successfully copied to a pre-existing destination resource.
494 403 (Forbidden) - The source and destination URIs are the same.
495 409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created.
496 412 (Precondition Failed) - The server was unable to maintain the liveness of the properties listed in the propertybehavior XML element
497 or the Overwrite header is "F" and the state of the destination resource is non-null.
498 423 (Locked) - The destination resource was locked.
499 502 (Bad Gateway) - This may occur when the destination is on another server and the destination server refuses to accept the resource.
500 507 (Insufficient Storage) - The destination resource does not have sufficient space to record the state of the resource after the
501 execution of this method.
503 return $response['status']['status-code'];
505 return false;
509 * Public method move
511 * Moves a file or collection on webdav server (serverside)
513 * If you set param overwrite as true, the target will be overwritten.
515 * @param string src_path, string dest_path, bool overwrite
516 * @return int status code (look at rfc 2518). false on error.
518 // --------------------------------------------------------------------------
519 // public method move
520 // move/rename a file/collection on webdav server
521 function move($src_path,$dst_path, $overwrite) {
523 $this->_path = $this->translate_uri($src_path);
524 $this->header_unset();
526 $this->create_basic_request('MOVE');
527 $this->header_add(sprintf('Destination: http://%s%s', $this->_server, $this->translate_uri($dst_path)));
528 if ($overwrite) {
529 $this->header_add('Overwrite: T');
530 } else {
531 $this->header_add('Overwrite: F');
533 $this->header_add('');
535 $this->send_request();
536 $this->get_respond();
537 $response = $this->process_respond();
538 // validate the response ...
539 // check http-version
540 if ($response['status']['http-version'] == 'HTTP/1.1' ||
541 $response['status']['http-version'] == 'HTTP/1.0') {
542 /* seems to be http ... proceed
543 just return what server gave us (as defined in rfc 2518) :
544 201 (Created) - The source resource was successfully moved, and a new resource was created at the destination.
545 204 (No Content) - The source resource was successfully moved to a pre-existing destination resource.
546 403 (Forbidden) - The source and destination URIs are the same.
547 409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created.
548 412 (Precondition Failed) - The server was unable to maintain the liveness of the properties listed in the propertybehavior XML element
549 or the Overwrite header is "F" and the state of the destination resource is non-null.
550 423 (Locked) - The source or the destination resource was locked.
551 502 (Bad Gateway) - This may occur when the destination is on another server and the destination server refuses to accept the resource.
553 201 (Created) - The collection or structured resource was created in its entirety.
554 403 (Forbidden) - This indicates at least one of two conditions: 1) the server does not allow the creation of collections at the given
555 location in its namespace, or 2) the parent collection of the Request-URI exists but cannot accept members.
556 405 (Method Not Allowed) - MKCOL can only be executed on a deleted/non-existent resource.
557 409 (Conflict) - A collection cannot be made at the Request-URI until one or more intermediate collections have been created.
558 415 (Unsupported Media Type)- The server does not support the request type of the body.
559 507 (Insufficient Storage) - The resource does not have sufficient space to record the state of the resource after the execution of this method.
561 return $response['status']['status-code'];
563 return false;
567 * Public method lock
569 * Locks a file or collection.
571 * Lock uses this->_user as lock owner.
573 * @param string path
574 * @return int status code (look at rfc 2518). false on error.
576 function lock($path) {
577 $this->_path = $this->translate_uri($path);
578 $this->header_unset();
579 $this->create_basic_request('LOCK');
580 $this->header_add('Timeout: Infinite');
581 $this->header_add('Content-type: text/xml');
582 // create the xml request ...
583 $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n";
584 $xml .= "<D:lockinfo xmlns:D='DAV:'\r\n>";
585 $xml .= " <D:lockscope><D:exclusive/></D:lockscope>\r\n";
586 $xml .= " <D:locktype><D:write/></D:locktype>\r\n";
587 $xml .= " <D:owner>\r\n";
588 $xml .= " <D:href>".($this->_user)."</D:href>\r\n";
589 $xml .= " </D:owner>\r\n";
590 $xml .= "</D:lockinfo>\r\n";
591 $this->header_add('Content-length: ' . strlen($xml));
592 $this->send_request();
593 // send also xml
594 fputs($this->sock, $xml);
595 $this->get_respond();
596 $response = $this->process_respond();
597 // validate the response ... (only basic validation)
598 // check http-version
599 if ($response['status']['http-version'] == 'HTTP/1.1' ||
600 $response['status']['http-version'] == 'HTTP/1.0') {
601 /* seems to be http ... proceed
602 rfc 2518 says:
603 200 (OK) - The lock request succeeded and the value of the lockdiscovery property is included in the body.
604 412 (Precondition Failed) - The included lock token was not enforceable on this resource or the server could not satisfy the
605 request in the lockinfo XML element.
606 423 (Locked) - The resource is locked, so the method has been rejected.
609 switch($response['status']['status-code']) {
610 case 200:
611 // collection was successfully locked... see xml response to get lock token...
612 if (strcmp($response['header']['Content-Type'], 'text/xml; charset="utf-8"') == 0) {
613 // ok let's get the content of the xml stuff
614 $this->_parser = xml_parser_create_ns();
615 // forget old data...
616 unset($this->_lock[$this->_parser]);
617 unset($this->_xmltree[$this->_parser]);
618 xml_parser_set_option($this->_parser,XML_OPTION_SKIP_WHITE,0);
619 xml_parser_set_option($this->_parser,XML_OPTION_CASE_FOLDING,0);
620 xml_set_object($this->_parser, $this);
621 xml_set_element_handler($this->_parser, "_lock_startElement", "_endElement");
622 xml_set_character_data_handler($this->_parser, "_lock_cdata");
624 if (!xml_parse($this->_parser, $response['body'])) {
625 die(sprintf("XML error: %s at line %d",
626 xml_error_string(xml_get_error_code($this->_parser)),
627 xml_get_current_line_number($this->_parser)));
630 // Free resources
631 xml_parser_free($this->_parser);
632 // add status code to array
633 $this->_lock[$this->_parser]['status'] = 200;
634 return $this->_lock[$this->_parser];
636 } else {
637 print 'Missing Content-Type: text/xml header in response.<br>';
639 return false;
641 default:
642 // hmm. not what we expected. Just return what we got from webdav server
643 // someone else has to handle it.
644 $this->_lock['status'] = $response['status']['status-code'];
645 return $this->_lock;
654 * Public method unlock
656 * Unlocks a file or collection.
658 * @param string path, string locktoken
659 * @return int status code (look at rfc 2518). false on error.
661 function unlock($path, $locktoken) {
662 $this->_path = $this->translate_uri($path);
663 $this->header_unset();
664 $this->create_basic_request('UNLOCK');
665 $this->header_add(sprintf('Lock-Token: <%s>', $locktoken));
666 $this->send_request();
667 $this->get_respond();
668 $response = $this->process_respond();
669 if ($response['status']['http-version'] == 'HTTP/1.1' ||
670 $response['status']['http-version'] == 'HTTP/1.0') {
671 /* seems to be http ... proceed
672 rfc 2518 says:
673 204 (OK) - The 204 (No Content) status code is used instead of 200 (OK) because there is no response entity body.
675 return $response['status']['status-code'];
677 return false;
681 * Public method delete
683 * deletes a collection/directory on a webdav server
684 * @param string path
685 * @return int status code (look at rfc 2518). false on error.
687 function delete($path) {
688 $this->_path = $this->translate_uri($path);
689 $this->header_unset();
690 $this->create_basic_request('DELETE');
691 /* $this->header_add('Content-Length: 0'); */
692 $this->header_add('');
693 $this->send_request();
694 $this->get_respond();
695 $response = $this->process_respond();
697 // validate the response ...
698 // check http-version
699 if ($response['status']['http-version'] == 'HTTP/1.1' ||
700 $response['status']['http-version'] == 'HTTP/1.0') {
701 // seems to be http ... proceed
702 // We expect a 207 Multi-Status status code
703 // print 'http ok<br>';
705 switch ($response['status']['status-code']) {
706 case 207:
707 // collection was NOT deleted... see xml response for reason...
708 // next there should be a Content-Type: text/xml; charset="utf-8" header line
709 if (strcmp($response['header']['Content-Type'], 'text/xml; charset="utf-8"') == 0) {
710 // ok let's get the content of the xml stuff
711 $this->_parser = xml_parser_create_ns();
712 // forget old data...
713 unset($this->_delete[$this->_parser]);
714 unset($this->_xmltree[$this->_parser]);
715 xml_parser_set_option($this->_parser,XML_OPTION_SKIP_WHITE,0);
716 xml_parser_set_option($this->_parser,XML_OPTION_CASE_FOLDING,0);
717 xml_set_object($this->_parser, $this);
718 xml_set_element_handler($this->_parser, "_delete_startElement", "_endElement");
719 xml_set_character_data_handler($this->_parser, "_delete_cdata");
721 if (!xml_parse($this->_parser, $response['body'])) {
722 die(sprintf("XML error: %s at line %d",
723 xml_error_string(xml_get_error_code($this->_parser)),
724 xml_get_current_line_number($this->_parser)));
727 print "<br>";
729 // Free resources
730 xml_parser_free($this->_parser);
731 $this->_delete[$this->_parser]['status'] = $response['status']['status-code'];
732 return $this->_delete[$this->_parser];
734 } else {
735 print 'Missing Content-Type: text/xml header in response.<br>';
737 return false;
739 default:
740 // collection or file was successfully deleted
741 $this->_delete['status'] = $response['status']['status-code'];
742 return $this->_delete;
751 * Public method ls
753 * Get's directory information from webdav server into flat a array using PROPFIND
755 * All filenames are UTF-8 encoded.
756 * Have a look at _propfind_startElement what keys are used in array returned.
757 * @param string path
758 * @return array dirinfo, false on error
760 function ls($path) {
762 if (trim($path) == '') {
763 $this->_error_log('Missing a path in method ls');
764 return false;
766 $this->_path = $this->translate_uri($path);
768 $this->header_unset();
769 $this->create_basic_request('PROPFIND');
770 $this->header_add('Depth: 1');
771 $this->header_add('Content-type: application/xml');
772 // create profind xml request...
773 $xml = <<<EOD
774 <?xml version="1.0" encoding="utf-8"?>
775 <propfind xmlns="DAV:"><prop>
776 <getcontentlength xmlns="DAV:"/>
777 <getlastmodified xmlns="DAV:"/>
778 <executable xmlns="http://apache.org/dav/props/"/>
779 <resourcetype xmlns="DAV:"/>
780 <checked-in xmlns="DAV:"/>
781 <checked-out xmlns="DAV:"/>
782 </prop></propfind>
783 EOD;
784 $this->header_add('Content-length: ' . strlen($xml));
785 $this->send_request();
786 $this->_error_log($xml);
787 fputs($this->sock, $xml);
788 $this->get_respond();
789 $response = $this->process_respond();
790 // validate the response ... (only basic validation)
791 // check http-version
792 if ($response['status']['http-version'] == 'HTTP/1.1' ||
793 $response['status']['http-version'] == 'HTTP/1.0') {
794 // seems to be http ... proceed
795 // We expect a 207 Multi-Status status code
796 // print 'http ok<br>';
797 if (strcmp($response['status']['status-code'],'207') == 0 ) {
798 // ok so far
799 // next there should be a Content-Type: text/xml; charset="utf-8" header line
800 if (preg_match('#(application|text)/xml;\s?charset=[\'\"]?utf-8[\'\"]?#i', $response['header']['Content-Type'])) {
801 // ok let's get the content of the xml stuff
802 $this->_parser = xml_parser_create_ns('UTF-8');
803 // forget old data...
804 unset($this->_ls[$this->_parser]);
805 unset($this->_xmltree[$this->_parser]);
806 xml_parser_set_option($this->_parser,XML_OPTION_SKIP_WHITE,0);
807 xml_parser_set_option($this->_parser,XML_OPTION_CASE_FOLDING,0);
808 // xml_parser_set_option($this->_parser,XML_OPTION_TARGET_ENCODING,'UTF-8');
809 xml_set_object($this->_parser, $this);
810 xml_set_element_handler($this->_parser, "_propfind_startElement", "_endElement");
811 xml_set_character_data_handler($this->_parser, "_propfind_cdata");
814 if (!xml_parse($this->_parser, $response['body'])) {
815 die(sprintf("XML error: %s at line %d",
816 xml_error_string(xml_get_error_code($this->_parser)),
817 xml_get_current_line_number($this->_parser)));
820 // Free resources
821 xml_parser_free($this->_parser);
822 $arr = $this->_ls[$this->_parser];
823 return $arr;
824 } else {
825 $this->_error_log('Missing Content-Type: text/xml header in response!!');
826 return false;
828 } else {
829 // return status code ...
830 return $response['status']['status-code'];
834 // response was not http
835 $this->_error_log('Ups in method ls: error in response from server');
836 return false;
841 * Public method gpi
843 * Get's path information from webdav server for one element.
845 * @param string path
846 * @return array dirinfo. false on error
848 function gpi($path) {
850 // split path by last "/"
851 $path = rtrim($path, "/");
852 $item = basename($path);
853 $dir = dirname($path);
855 $list = $this->ls($dir);
857 // be sure it is an array
858 if (is_array($list)) {
859 foreach($list as $e) {
861 $fullpath = urldecode($e['href']);
862 $filename = basename($fullpath);
864 if ($filename == $item && $filename != "" and $fullpath != $dir."/") {
865 return $e;
869 return false;
873 * Public method is_file
875 * Gathers whether a path points to a file or not.
877 * @param string path
878 * @return bool true or false
880 function is_file($path) {
882 $item = $this->gpi($path);
884 if ($item === false) {
885 return false;
886 } else {
887 return ($item['resourcetype'] != 'collection');
892 * Public method is_dir
894 * Gather whether a path points to a directory
895 * @param string path
896 * return bool true or false
898 function is_dir($path) {
900 // be sure path is utf-8
901 $item = $this->gpi($path);
903 if ($item === false) {
904 return false;
905 } else {
906 return ($item['resourcetype'] == 'collection');
912 * Public method mput
914 * Puts multiple files and/or directories onto a webdav server.
916 * Filenames should be allready UTF-8 encoded.
917 * Param fileList must be in format array("localpath" => "destpath").
919 * @param array filelist
920 * @return bool true on success. otherwise int status code on error
922 function mput($filelist) {
924 $result = true;
926 while (list($localpath, $destpath) = each($filelist)) {
928 $localpath = rtrim($localpath, "/");
929 $destpath = rtrim($destpath, "/");
931 // attempt to create target path
932 if (is_dir($localpath)) {
933 $pathparts = explode("/", $destpath."/ "); // add one level, last level will be created as dir
934 } else {
935 $pathparts = explode("/", $destpath);
937 $checkpath = "";
938 for ($i=1; $i<sizeof($pathparts)-1; $i++) {
939 $checkpath .= "/" . $pathparts[$i];
940 if (!($this->is_dir($checkpath))) {
942 $result &= ($this->mkcol($checkpath) == 201 );
946 if ($result) {
947 // recurse directories
948 if (is_dir($localpath)) {
949 $dp = opendir($localpath);
950 $fl = array();
951 while($filename = readdir($dp)) {
952 if ((is_file($localpath."/".$filename) || is_dir($localpath."/".$filename)) && $filename!="." && $filename != "..") {
953 $fl[$localpath."/".$filename] = $destpath."/".$filename;
956 $result &= $this->mput($fl);
957 } else {
958 $result &= ($this->put_file($destpath, $localpath) == 201);
962 return $result;
966 * Public method mget
968 * Gets multiple files and directories.
970 * FileList must be in format array("remotepath" => "localpath").
971 * Filenames are UTF-8 encoded.
973 * @param array filelist
974 * @return bool true on succes, other int status code on error
976 function mget($filelist) {
978 $result = true;
980 while (list($remotepath, $localpath) = each($filelist)) {
982 $localpath = rtrim($localpath, "/");
983 $remotepath = rtrim($remotepath, "/");
985 // attempt to create local path
986 if ($this->is_dir($remotepath)) {
987 $pathparts = explode("/", $localpath."/ "); // add one level, last level will be created as dir
988 } else {
989 $pathparts = explode("/", $localpath);
991 $checkpath = "";
992 for ($i=1; $i<sizeof($pathparts)-1; $i++) {
993 $checkpath .= "/" . $pathparts[$i];
994 if (!is_dir($checkpath)) {
996 $result &= mkdir($checkpath);
1000 if ($result) {
1001 // recurse directories
1002 if ($this->is_dir($remotepath)) {
1003 $list = $this->ls($remotepath);
1005 $fl = array();
1006 foreach($list as $e) {
1007 $fullpath = urldecode($e['href']);
1008 $filename = basename($fullpath);
1009 if ($filename != '' and $fullpath != $remotepath . '/') {
1010 $fl[$remotepath."/".$filename] = $localpath."/".$filename;
1013 $result &= $this->mget($fl);
1014 } else {
1015 $result &= ($this->get_file($remotepath, $localpath));
1019 return $result;
1022 // --------------------------------------------------------------------------
1023 // private xml callback and helper functions starting here
1024 // --------------------------------------------------------------------------
1028 * Private method _endelement
1030 * a generic endElement method (used for all xml callbacks).
1032 * @param resource parser, string name
1033 * @access private
1036 private function _endElement($parser, $name) {
1037 // end tag was found...
1038 $this->_xmltree[$parser] = substr($this->_xmltree[$parser],0, strlen($this->_xmltree[$parser]) - (strlen($name) + 1));
1042 * Private method _propfind_startElement
1044 * Is needed by public method ls.
1046 * Generic method will called by php xml_parse when a xml start element tag has been detected.
1047 * The xml tree will translated into a flat php array for easier access.
1048 * @param resource parser, string name, string attrs
1049 * @access private
1051 private function _propfind_startElement($parser, $name, $attrs) {
1052 // lower XML Names... maybe break a RFC, don't know ...
1054 $propname = strtolower($name);
1055 if (!empty($this->_xmltree[$parser])) {
1056 $this->_xmltree[$parser] .= $propname . '_';
1057 } else {
1058 $this->_xmltree[$parser] = $propname . '_';
1061 // translate xml tree to a flat array ...
1062 switch($this->_xmltree[$parser]) {
1063 case 'dav::multistatus_dav::response_':
1064 // new element in mu
1065 $this->_ls_ref =& $this->_ls[$parser][];
1066 break;
1067 case 'dav::multistatus_dav::response_dav::href_':
1068 $this->_ls_ref_cdata = &$this->_ls_ref['href'];
1069 break;
1070 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::creationdate_':
1071 $this->_ls_ref_cdata = &$this->_ls_ref['creationdate'];
1072 break;
1073 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getlastmodified_':
1074 $this->_ls_ref_cdata = &$this->_ls_ref['lastmodified'];
1075 break;
1076 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getcontenttype_':
1077 $this->_ls_ref_cdata = &$this->_ls_ref['getcontenttype'];
1078 break;
1079 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getcontentlength_':
1080 $this->_ls_ref_cdata = &$this->_ls_ref['getcontentlength'];
1081 break;
1082 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_':
1083 $this->_ls_ref_cdata = &$this->_ls_ref['activelock_depth'];
1084 break;
1085 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_':
1086 $this->_ls_ref_cdata = &$this->_ls_ref['activelock_owner'];
1087 break;
1088 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_':
1089 $this->_ls_ref_cdata = &$this->_ls_ref['activelock_owner'];
1090 break;
1091 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_':
1092 $this->_ls_ref_cdata = &$this->_ls_ref['activelock_timeout'];
1093 break;
1094 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_':
1095 $this->_ls_ref_cdata = &$this->_ls_ref['activelock_token'];
1096 break;
1097 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::locktype_dav::write_':
1098 $this->_ls_ref_cdata = &$this->_ls_ref['activelock_type'];
1099 $this->_ls_ref_cdata = 'write';
1100 $this->_ls_ref_cdata = &$this->_null;
1101 break;
1102 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::resourcetype_dav::collection_':
1103 $this->_ls_ref_cdata = &$this->_ls_ref['resourcetype'];
1104 $this->_ls_ref_cdata = 'collection';
1105 $this->_ls_ref_cdata = &$this->_null;
1106 break;
1107 case 'dav::multistatus_dav::response_dav::propstat_dav::status_':
1108 $this->_ls_ref_cdata = &$this->_ls_ref['status'];
1109 break;
1111 default:
1112 // handle unknown xml elements...
1113 $this->_ls_ref_cdata = &$this->_ls_ref[$this->_xmltree[$parser]];
1118 * Private method _propfind_cData
1120 * Is needed by public method ls.
1122 * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
1123 * Stores data found into class var _ls_ref_cdata
1124 * @param resource parser, string cdata
1125 * @access private
1127 private function _propfind_cData($parser, $cdata) {
1128 if (trim($cdata) <> '') {
1129 // cdata must be appended, because sometimes the php xml parser makes multiple calls
1130 // to _propfind_cData before the xml end tag was reached...
1131 $this->_ls_ref_cdata .= $cdata;
1132 } else {
1133 // do nothing
1138 * Private method _delete_startElement
1140 * Is used by public method delete.
1142 * Will be called by php xml_parse.
1143 * @param resource parser, string name, string attrs)
1144 * @access private
1146 private function _delete_startElement($parser, $name, $attrs) {
1147 // lower XML Names... maybe break a RFC, don't know ...
1148 $propname = strtolower($name);
1149 $this->_xmltree[$parser] .= $propname . '_';
1151 // translate xml tree to a flat array ...
1152 switch($this->_xmltree[$parser]) {
1153 case 'dav::multistatus_dav::response_':
1154 // new element in mu
1155 $this->_delete_ref =& $this->_delete[$parser][];
1156 break;
1157 case 'dav::multistatus_dav::response_dav::href_':
1158 $this->_delete_ref_cdata = &$this->_ls_ref['href'];
1159 break;
1161 default:
1162 // handle unknown xml elements...
1163 $this->_delete_cdata = &$this->_delete_ref[$this->_xmltree[$parser]];
1169 * Private method _delete_cData
1171 * Is used by public method delete.
1173 * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
1174 * Stores data found into class var _delete_ref_cdata
1175 * @param resource parser, string cdata
1176 * @access private
1178 private function _delete_cData($parser, $cdata) {
1179 if (trim($cdata) <> '') {
1180 $this->_delete_ref_cdata .= $cdata;
1181 } else {
1182 // do nothing
1188 * Private method _lock_startElement
1190 * Is needed by public method lock.
1192 * Mmethod will called by php xml_parse when a xml start element tag has been detected.
1193 * The xml tree will translated into a flat php array for easier access.
1194 * @param resource parser, string name, string attrs
1195 * @access private
1197 private function _lock_startElement($parser, $name, $attrs) {
1198 // lower XML Names... maybe break a RFC, don't know ...
1199 $propname = strtolower($name);
1200 $this->_xmltree[$parser] .= $propname . '_';
1202 // translate xml tree to a flat array ...
1204 dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_=
1205 dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_=
1206 dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_=
1207 dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_=
1209 switch($this->_xmltree[$parser]) {
1210 case 'dav::prop_dav::lockdiscovery_dav::activelock_':
1211 // new element
1212 $this->_lock_ref =& $this->_lock[$parser][];
1213 break;
1214 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::locktype_dav::write_':
1215 $this->_lock_ref_cdata = &$this->_lock_ref['locktype'];
1216 $this->_lock_cdata = 'write';
1217 $this->_lock_cdata = &$this->_null;
1218 break;
1219 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::lockscope_dav::exclusive_':
1220 $this->_lock_ref_cdata = &$this->_lock_ref['lockscope'];
1221 $this->_lock_ref_cdata = 'exclusive';
1222 $this->_lock_ref_cdata = &$this->_null;
1223 break;
1224 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_':
1225 $this->_lock_ref_cdata = &$this->_lock_ref['depth'];
1226 break;
1227 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_':
1228 $this->_lock_ref_cdata = &$this->_lock_ref['owner'];
1229 break;
1230 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_':
1231 $this->_lock_ref_cdata = &$this->_lock_ref['timeout'];
1232 break;
1233 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_':
1234 $this->_lock_ref_cdata = &$this->_lock_ref['locktoken'];
1235 break;
1236 default:
1237 // handle unknown xml elements...
1238 $this->_lock_cdata = &$this->_lock_ref[$this->_xmltree[$parser]];
1244 * Private method _lock_cData
1246 * Is used by public method lock.
1248 * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
1249 * Stores data found into class var _lock_ref_cdata
1250 * @param resource parser, string cdata
1251 * @access private
1253 private function _lock_cData($parser, $cdata) {
1254 if (trim($cdata) <> '') {
1255 // $this->_error_log(($this->_xmltree[$parser]) . '='. htmlentities($cdata));
1256 $this->_lock_ref_cdata .= $cdata;
1257 } else {
1258 // do nothing
1264 * Private method header_add
1266 * extends class var array _req
1267 * @param string string
1268 * @access private
1270 private function header_add($string) {
1271 $this->_req[] = $string;
1275 * Private method header_unset
1277 * unsets class var array _req
1278 * @access private
1281 private function header_unset() {
1282 unset($this->_req);
1286 * Private method create_basic_request
1288 * creates by using private method header_add an general request header.
1289 * @param string method
1290 * @access private
1292 private function create_basic_request($method) {
1293 $request = '';
1294 $this->header_add(sprintf('%s %s %s', $method, $this->_path, $this->_protocol));
1295 $this->header_add(sprintf('Host: %s:%s', $this->_server, $this->_port));
1296 //$request .= sprintf('Connection: Keep-Alive');
1297 $this->header_add(sprintf('User-Agent: %s', $this->_user_agent));
1298 $this->header_add('Connection: TE');
1299 $this->header_add('TE: Trailers');
1300 if ($this->_auth == 'basic') {
1301 $this->header_add(sprintf('Authorization: Basic %s', base64_encode("$this->_user:$this->_pass")));
1306 * Private method send_request
1308 * Sends a ready formed http/webdav request to webdav server.
1310 * @access private
1312 private function send_request() {
1313 // check if stream is declared to be open
1314 // only logical check we are not sure if socket is really still open ...
1315 if ($this->_connection_closed) {
1316 // reopen it
1317 // be sure to close the open socket.
1318 $this->close();
1319 $this->reopen();
1322 // convert array to string
1323 $buffer = implode("\r\n", $this->_req);
1324 $buffer .= "\r\n\r\n";
1325 $this->_error_log($buffer);
1326 fputs($this->sock, $buffer);
1330 * Private method get_respond
1332 * Reads the reponse from the webdav server.
1334 * Stores data into class vars _header for the header data and
1335 * _body for the rest of the response.
1336 * This routine is the weakest part of this class, because it very depends how php does handle a socket stream.
1337 * If the stream is blocked for some reason php is blocked as well.
1338 * @access private
1340 private function get_respond() {
1341 $this->_error_log('get_respond()');
1342 // init vars (good coding style ;-)
1343 $buffer = '';
1344 $header = '';
1345 // attention: do not make max_chunk_size to big....
1346 $max_chunk_size = 8192;
1347 // be sure we got a open ressource
1348 if (! $this->sock) {
1349 $this->_error_log('socket is not open. Can not process response');
1350 return false;
1353 // following code maybe helps to improve socket behaviour ... more testing needed
1354 // disabled at the moment ...
1355 // socket_set_timeout($this->sock,1 );
1356 // $socket_state = socket_get_status($this->sock);
1358 // read stream one byte by another until http header ends
1359 $i = 0;
1360 $matches = array();
1361 do {
1362 $header.=fread($this->sock, 1);
1363 $i++;
1364 } while (!preg_match('/\\r\\n\\r\\n$/',$header, $matches) && $i < $this->_maxheaderlenth);
1366 $this->_error_log($header);
1368 if (preg_match('/Connection: close\\r\\n/', $header)) {
1369 // This says that the server will close connection at the end of this stream.
1370 // Therefore we need to reopen the socket, before are sending the next request...
1371 $this->_error_log('Connection: close found');
1372 $this->_connection_closed = true;
1374 // check how to get the data on socket stream
1375 // chunked or content-length (HTTP/1.1) or
1376 // one block until feof is received (HTTP/1.0)
1377 switch(true) {
1378 case (preg_match('/Transfer\\-Encoding:\\s+chunked\\r\\n/',$header)):
1379 $this->_error_log('Getting HTTP/1.1 chunked data...');
1380 do {
1381 $byte = '';
1382 $chunk_size='';
1383 do {
1384 $chunk_size.=$byte;
1385 $byte=fread($this->sock,1);
1386 // check what happens while reading, because I do not really understand how php reads the socketstream...
1387 // but so far - it seems to work here - tested with php v4.3.1 on apache 1.3.27 and Debian Linux 3.0 ...
1388 if (strlen($byte) == 0) {
1389 $this->_error_log('get_respond: warning --> read zero bytes');
1391 } while ($byte!="\r" and strlen($byte)>0); // till we match the Carriage Return
1392 fread($this->sock, 1); // also drop off the Line Feed
1393 $chunk_size=hexdec($chunk_size); // convert to a number in decimal system
1394 if ($chunk_size > 0) {
1395 $buffer .= fread($this->sock,$chunk_size);
1397 fread($this->sock, 2); // ditch the CRLF that trails the chunk
1398 } while ($chunk_size); // till we reach the 0 length chunk (end marker)
1399 break;
1401 // check for a specified content-length
1402 case preg_match('/Content\\-Length:\\s+([0-9]*)\\r\\n/',$header,$matches):
1403 $this->_error_log('Getting data using Content-Length '. $matches[1]);
1405 // check if we the content data size is small enough to get it as one block
1406 if ($matches[1] <= $max_chunk_size ) {
1407 // only read something if Content-Length is bigger than 0
1408 if ($matches[1] > 0 ) {
1409 $buffer = fread($this->sock, $matches[1]);
1410 $loadsize = strlen($buffer);
1411 //did we realy get the full length?
1412 if ($loadsize < $matches[1]) {
1413 $max_chunk_size = $loadsize;
1414 do {
1415 $mod = $max_chunk_size % ($matches[1] - strlen($buffer));
1416 $chunk_size = ($mod == $max_chunk_size ? $max_chunk_size : $matches[1] - strlen($buffer));
1417 $buffer .= fread($this->sock, $chunk_size);
1418 $this->_error_log('mod: ' . $mod . ' chunk: ' . $chunk_size . ' total: ' . strlen($buffer));
1419 } while ($mod == $max_chunk_size);
1420 break;
1421 } else {
1422 break;
1424 } else {
1425 $buffer = '';
1426 break;
1430 // data is to big to handle it as one. Get it chunk per chunk...
1431 //trying to get the full length of max_chunk_size
1432 $buffer = fread($this->sock, $max_chunk_size);
1433 $loadsize = strlen($buffer);
1434 if ($loadsize < $max_chunk_size) {
1435 $max_chunk_size = $loadsize;
1437 do {
1438 $mod = $max_chunk_size % ($matches[1] - strlen($buffer));
1439 $chunk_size = ($mod == $max_chunk_size ? $max_chunk_size : $matches[1] - strlen($buffer));
1440 $buffer .= fread($this->sock, $chunk_size);
1441 $this->_error_log('mod: ' . $mod . ' chunk: ' . $chunk_size . ' total: ' . strlen($buffer));
1442 } while ($mod == $max_chunk_size);
1443 $loadsize = strlen($buffer);
1444 if ($loadsize < $matches[1]) {
1445 $buffer .= fread($this->sock, $matches[1] - $loadsize);
1447 break;
1449 // check for 204 No Content
1450 // 204 responds have no body.
1451 // Therefore we do not need to read any data from socket stream.
1452 case preg_match('/HTTP\/1\.1\ 204/',$header):
1453 // nothing to do, just proceed
1454 $this->_error_log('204 No Content found. No further data to read..');
1455 break;
1456 default:
1457 // just get the data until foef appears...
1458 $this->_error_log('reading until feof...' . $header);
1459 socket_set_timeout($this->sock, 0, 0);
1460 while (!feof($this->sock)) {
1461 $buffer .= fread($this->sock, 4096);
1463 // renew the socket timeout...does it do something ???? Is it needed. More debugging needed...
1464 socket_set_timeout($this->sock, $this->_socket_timeout, 0);
1467 $this->_header = $header;
1468 $this->_body = $buffer;
1469 // $this->_buffer = $header . "\r\n\r\n" . $buffer;
1470 $this->_error_log($this->_header);
1471 $this->_error_log($this->_body);
1476 * Private method process_respond
1478 * Processes the webdav server respond and detects its components (header, body).
1479 * and returns data array structure.
1480 * @return array ret_struct
1481 * @access private
1483 private function process_respond() {
1484 $lines = explode("\r\n", $this->_header);
1485 $header_done = false;
1486 // $this->_error_log($this->_buffer);
1487 // First line should be a HTTP status line (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6)
1488 // Format is: HTTP-Version SP Status-Code SP Reason-Phrase CRLF
1489 list($ret_struct['status']['http-version'],
1490 $ret_struct['status']['status-code'],
1491 $ret_struct['status']['reason-phrase']) = explode(' ', $lines[0],3);
1493 // print "HTTP Version: '$http_version' Status-Code: '$status_code' Reason Phrase: '$reason_phrase'<br>";
1494 // get the response header fields
1495 // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6
1496 for($i=1; $i<count($lines); $i++) {
1497 if (rtrim($lines[$i]) == '' && !$header_done) {
1498 $header_done = true;
1499 // print "--- response header end ---<br>";
1502 if (!$header_done ) {
1503 // store all found headers in array ...
1504 list($fieldname, $fieldvalue) = explode(':', $lines[$i]);
1505 // check if this header was allready set (apache 2.0 webdav module does this....).
1506 // If so we add the the value to the end the fieldvalue, separated by comma...
1507 if (empty($ret_struct['header'])) {
1508 $ret_struct['header'] = array();
1510 if (empty($ret_struct['header'][$fieldname])) {
1511 $ret_struct['header'][$fieldname] = trim($fieldvalue);
1512 } else {
1513 $ret_struct['header'][$fieldname] .= ',' . trim($fieldvalue);
1517 // print 'string len of response_body:'. strlen($response_body);
1518 // print '[' . htmlentities($response_body) . ']';
1519 $ret_struct['body'] = $this->_body;
1520 $this->_error_log('process_respond: ' . var_export($ret_struct,true));
1521 return $ret_struct;
1526 * Private method reopen
1528 * Reopens a socket, if 'connection: closed'-header was received from server.
1530 * Uses public method open.
1531 * @access private
1533 private function reopen() {
1534 // let's try to reopen a socket
1535 $this->_error_log('reopen a socket connection');
1536 return $this->open();
1541 * Private method translate_uri
1543 * translates an uri to raw url encoded string.
1544 * Removes any html entity in uri
1545 * @param string uri
1546 * @return string translated_uri
1547 * @access private
1549 private function translate_uri($uri) {
1550 // remove all html entities...
1551 $native_path = html_entity_decode($uri);
1552 $parts = explode('/', $native_path);
1553 for ($i = 0; $i < count($parts); $i++) {
1554 // check if part is allready utf8
1555 if (iconv('UTF-8', 'UTF-8', $parts[$i]) == $parts[$i]) {
1556 $parts[$i] = rawurlencode($parts[$i]);
1557 } else {
1558 $parts[$i] = rawurlencode(utf8_encode($parts[$i]));
1561 return implode('/', $parts);
1565 * Private method utf_decode_path
1567 * decodes a UTF-8 encoded string
1568 * @return string decodedstring
1569 * @access private
1571 private function utf_decode_path($path) {
1572 $fullpath = $path;
1573 if (iconv('UTF-8', 'UTF-8', $fullpath) == $fullpath) {
1574 $this->_error_log("filename is utf-8. Needs conversion...");
1575 $fullpath = utf8_decode($fullpath);
1577 return $fullpath;
1581 * Private method _error_log
1583 * a simple php error_log wrapper.
1584 * @param string err_string
1585 * @access private
1587 private function _error_log($err_string) {
1588 if ($this->_debug) {
1589 error_log($err_string);