MDL-32003 fix phpdocs in xmldb abstraction
[moodle.git] / lib / webdavlib.php
blob1280a3d54e6b0186fe94eef6a745522219b71631
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 if (!$dp = opendir($localpath)) {
950 $this->_error_log("Could not open localpath for reading");
951 return false;
953 $fl = array();
954 while($filename = readdir($dp)) {
955 if ((is_file($localpath."/".$filename) || is_dir($localpath."/".$filename)) && $filename!="." && $filename != "..") {
956 $fl[$localpath."/".$filename] = $destpath."/".$filename;
959 $result &= $this->mput($fl);
960 } else {
961 $result &= ($this->put_file($destpath, $localpath) == 201);
965 return $result;
969 * Public method mget
971 * Gets multiple files and directories.
973 * FileList must be in format array("remotepath" => "localpath").
974 * Filenames are UTF-8 encoded.
976 * @param array filelist
977 * @return bool true on succes, other int status code on error
979 function mget($filelist) {
981 $result = true;
983 while (list($remotepath, $localpath) = each($filelist)) {
985 $localpath = rtrim($localpath, "/");
986 $remotepath = rtrim($remotepath, "/");
988 // attempt to create local path
989 if ($this->is_dir($remotepath)) {
990 $pathparts = explode("/", $localpath."/ "); // add one level, last level will be created as dir
991 } else {
992 $pathparts = explode("/", $localpath);
994 $checkpath = "";
995 for ($i=1; $i<sizeof($pathparts)-1; $i++) {
996 $checkpath .= "/" . $pathparts[$i];
997 if (!is_dir($checkpath)) {
999 $result &= mkdir($checkpath);
1003 if ($result) {
1004 // recurse directories
1005 if ($this->is_dir($remotepath)) {
1006 $list = $this->ls($remotepath);
1008 $fl = array();
1009 foreach($list as $e) {
1010 $fullpath = urldecode($e['href']);
1011 $filename = basename($fullpath);
1012 if ($filename != '' and $fullpath != $remotepath . '/') {
1013 $fl[$remotepath."/".$filename] = $localpath."/".$filename;
1016 $result &= $this->mget($fl);
1017 } else {
1018 $result &= ($this->get_file($remotepath, $localpath));
1022 return $result;
1025 // --------------------------------------------------------------------------
1026 // private xml callback and helper functions starting here
1027 // --------------------------------------------------------------------------
1031 * Private method _endelement
1033 * a generic endElement method (used for all xml callbacks).
1035 * @param resource parser, string name
1036 * @access private
1039 private function _endElement($parser, $name) {
1040 // end tag was found...
1041 $this->_xmltree[$parser] = substr($this->_xmltree[$parser],0, strlen($this->_xmltree[$parser]) - (strlen($name) + 1));
1045 * Private method _propfind_startElement
1047 * Is needed by public method ls.
1049 * Generic method will called by php xml_parse when a xml start element tag has been detected.
1050 * The xml tree will translated into a flat php array for easier access.
1051 * @param resource parser, string name, string attrs
1052 * @access private
1054 private function _propfind_startElement($parser, $name, $attrs) {
1055 // lower XML Names... maybe break a RFC, don't know ...
1057 $propname = strtolower($name);
1058 if (!empty($this->_xmltree[$parser])) {
1059 $this->_xmltree[$parser] .= $propname . '_';
1060 } else {
1061 $this->_xmltree[$parser] = $propname . '_';
1064 // translate xml tree to a flat array ...
1065 switch($this->_xmltree[$parser]) {
1066 case 'dav::multistatus_dav::response_':
1067 // new element in mu
1068 $this->_ls_ref =& $this->_ls[$parser][];
1069 break;
1070 case 'dav::multistatus_dav::response_dav::href_':
1071 $this->_ls_ref_cdata = &$this->_ls_ref['href'];
1072 break;
1073 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::creationdate_':
1074 $this->_ls_ref_cdata = &$this->_ls_ref['creationdate'];
1075 break;
1076 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getlastmodified_':
1077 $this->_ls_ref_cdata = &$this->_ls_ref['lastmodified'];
1078 break;
1079 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getcontenttype_':
1080 $this->_ls_ref_cdata = &$this->_ls_ref['getcontenttype'];
1081 break;
1082 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getcontentlength_':
1083 $this->_ls_ref_cdata = &$this->_ls_ref['getcontentlength'];
1084 break;
1085 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_':
1086 $this->_ls_ref_cdata = &$this->_ls_ref['activelock_depth'];
1087 break;
1088 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_':
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::owner_':
1092 $this->_ls_ref_cdata = &$this->_ls_ref['activelock_owner'];
1093 break;
1094 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_':
1095 $this->_ls_ref_cdata = &$this->_ls_ref['activelock_timeout'];
1096 break;
1097 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_':
1098 $this->_ls_ref_cdata = &$this->_ls_ref['activelock_token'];
1099 break;
1100 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::locktype_dav::write_':
1101 $this->_ls_ref_cdata = &$this->_ls_ref['activelock_type'];
1102 $this->_ls_ref_cdata = 'write';
1103 $this->_ls_ref_cdata = &$this->_null;
1104 break;
1105 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::resourcetype_dav::collection_':
1106 $this->_ls_ref_cdata = &$this->_ls_ref['resourcetype'];
1107 $this->_ls_ref_cdata = 'collection';
1108 $this->_ls_ref_cdata = &$this->_null;
1109 break;
1110 case 'dav::multistatus_dav::response_dav::propstat_dav::status_':
1111 $this->_ls_ref_cdata = &$this->_ls_ref['status'];
1112 break;
1114 default:
1115 // handle unknown xml elements...
1116 $this->_ls_ref_cdata = &$this->_ls_ref[$this->_xmltree[$parser]];
1121 * Private method _propfind_cData
1123 * Is needed by public method ls.
1125 * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
1126 * Stores data found into class var _ls_ref_cdata
1127 * @param resource parser, string cdata
1128 * @access private
1130 private function _propfind_cData($parser, $cdata) {
1131 if (trim($cdata) <> '') {
1132 // cdata must be appended, because sometimes the php xml parser makes multiple calls
1133 // to _propfind_cData before the xml end tag was reached...
1134 $this->_ls_ref_cdata .= $cdata;
1135 } else {
1136 // do nothing
1141 * Private method _delete_startElement
1143 * Is used by public method delete.
1145 * Will be called by php xml_parse.
1146 * @param resource parser, string name, string attrs)
1147 * @access private
1149 private function _delete_startElement($parser, $name, $attrs) {
1150 // lower XML Names... maybe break a RFC, don't know ...
1151 $propname = strtolower($name);
1152 $this->_xmltree[$parser] .= $propname . '_';
1154 // translate xml tree to a flat array ...
1155 switch($this->_xmltree[$parser]) {
1156 case 'dav::multistatus_dav::response_':
1157 // new element in mu
1158 $this->_delete_ref =& $this->_delete[$parser][];
1159 break;
1160 case 'dav::multistatus_dav::response_dav::href_':
1161 $this->_delete_ref_cdata = &$this->_ls_ref['href'];
1162 break;
1164 default:
1165 // handle unknown xml elements...
1166 $this->_delete_cdata = &$this->_delete_ref[$this->_xmltree[$parser]];
1172 * Private method _delete_cData
1174 * Is used by public method delete.
1176 * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
1177 * Stores data found into class var _delete_ref_cdata
1178 * @param resource parser, string cdata
1179 * @access private
1181 private function _delete_cData($parser, $cdata) {
1182 if (trim($cdata) <> '') {
1183 $this->_delete_ref_cdata .= $cdata;
1184 } else {
1185 // do nothing
1191 * Private method _lock_startElement
1193 * Is needed by public method lock.
1195 * Mmethod will called by php xml_parse when a xml start element tag has been detected.
1196 * The xml tree will translated into a flat php array for easier access.
1197 * @param resource parser, string name, string attrs
1198 * @access private
1200 private function _lock_startElement($parser, $name, $attrs) {
1201 // lower XML Names... maybe break a RFC, don't know ...
1202 $propname = strtolower($name);
1203 $this->_xmltree[$parser] .= $propname . '_';
1205 // translate xml tree to a flat array ...
1207 dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_=
1208 dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_=
1209 dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_=
1210 dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_=
1212 switch($this->_xmltree[$parser]) {
1213 case 'dav::prop_dav::lockdiscovery_dav::activelock_':
1214 // new element
1215 $this->_lock_ref =& $this->_lock[$parser][];
1216 break;
1217 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::locktype_dav::write_':
1218 $this->_lock_ref_cdata = &$this->_lock_ref['locktype'];
1219 $this->_lock_cdata = 'write';
1220 $this->_lock_cdata = &$this->_null;
1221 break;
1222 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::lockscope_dav::exclusive_':
1223 $this->_lock_ref_cdata = &$this->_lock_ref['lockscope'];
1224 $this->_lock_ref_cdata = 'exclusive';
1225 $this->_lock_ref_cdata = &$this->_null;
1226 break;
1227 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_':
1228 $this->_lock_ref_cdata = &$this->_lock_ref['depth'];
1229 break;
1230 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_':
1231 $this->_lock_ref_cdata = &$this->_lock_ref['owner'];
1232 break;
1233 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_':
1234 $this->_lock_ref_cdata = &$this->_lock_ref['timeout'];
1235 break;
1236 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_':
1237 $this->_lock_ref_cdata = &$this->_lock_ref['locktoken'];
1238 break;
1239 default:
1240 // handle unknown xml elements...
1241 $this->_lock_cdata = &$this->_lock_ref[$this->_xmltree[$parser]];
1247 * Private method _lock_cData
1249 * Is used by public method lock.
1251 * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
1252 * Stores data found into class var _lock_ref_cdata
1253 * @param resource parser, string cdata
1254 * @access private
1256 private function _lock_cData($parser, $cdata) {
1257 if (trim($cdata) <> '') {
1258 // $this->_error_log(($this->_xmltree[$parser]) . '='. htmlentities($cdata));
1259 $this->_lock_ref_cdata .= $cdata;
1260 } else {
1261 // do nothing
1267 * Private method header_add
1269 * extends class var array _req
1270 * @param string string
1271 * @access private
1273 private function header_add($string) {
1274 $this->_req[] = $string;
1278 * Private method header_unset
1280 * unsets class var array _req
1281 * @access private
1284 private function header_unset() {
1285 unset($this->_req);
1289 * Private method create_basic_request
1291 * creates by using private method header_add an general request header.
1292 * @param string method
1293 * @access private
1295 private function create_basic_request($method) {
1296 $request = '';
1297 $this->header_add(sprintf('%s %s %s', $method, $this->_path, $this->_protocol));
1298 $this->header_add(sprintf('Host: %s:%s', $this->_server, $this->_port));
1299 //$request .= sprintf('Connection: Keep-Alive');
1300 $this->header_add(sprintf('User-Agent: %s', $this->_user_agent));
1301 $this->header_add('Connection: TE');
1302 $this->header_add('TE: Trailers');
1303 if ($this->_auth == 'basic') {
1304 $this->header_add(sprintf('Authorization: Basic %s', base64_encode("$this->_user:$this->_pass")));
1309 * Private method send_request
1311 * Sends a ready formed http/webdav request to webdav server.
1313 * @access private
1315 private function send_request() {
1316 // check if stream is declared to be open
1317 // only logical check we are not sure if socket is really still open ...
1318 if ($this->_connection_closed) {
1319 // reopen it
1320 // be sure to close the open socket.
1321 $this->close();
1322 $this->reopen();
1325 // convert array to string
1326 $buffer = implode("\r\n", $this->_req);
1327 $buffer .= "\r\n\r\n";
1328 $this->_error_log($buffer);
1329 fputs($this->sock, $buffer);
1333 * Private method get_respond
1335 * Reads the reponse from the webdav server.
1337 * Stores data into class vars _header for the header data and
1338 * _body for the rest of the response.
1339 * This routine is the weakest part of this class, because it very depends how php does handle a socket stream.
1340 * If the stream is blocked for some reason php is blocked as well.
1341 * @access private
1343 private function get_respond() {
1344 $this->_error_log('get_respond()');
1345 // init vars (good coding style ;-)
1346 $buffer = '';
1347 $header = '';
1348 // attention: do not make max_chunk_size to big....
1349 $max_chunk_size = 8192;
1350 // be sure we got a open ressource
1351 if (! $this->sock) {
1352 $this->_error_log('socket is not open. Can not process response');
1353 return false;
1356 // following code maybe helps to improve socket behaviour ... more testing needed
1357 // disabled at the moment ...
1358 // socket_set_timeout($this->sock,1 );
1359 // $socket_state = socket_get_status($this->sock);
1361 // read stream one byte by another until http header ends
1362 $i = 0;
1363 $matches = array();
1364 do {
1365 $header.=fread($this->sock, 1);
1366 $i++;
1367 } while (!preg_match('/\\r\\n\\r\\n$/',$header, $matches) && $i < $this->_maxheaderlenth);
1369 $this->_error_log($header);
1371 if (preg_match('/Connection: close\\r\\n/', $header)) {
1372 // This says that the server will close connection at the end of this stream.
1373 // Therefore we need to reopen the socket, before are sending the next request...
1374 $this->_error_log('Connection: close found');
1375 $this->_connection_closed = true;
1377 // check how to get the data on socket stream
1378 // chunked or content-length (HTTP/1.1) or
1379 // one block until feof is received (HTTP/1.0)
1380 switch(true) {
1381 case (preg_match('/Transfer\\-Encoding:\\s+chunked\\r\\n/',$header)):
1382 $this->_error_log('Getting HTTP/1.1 chunked data...');
1383 do {
1384 $byte = '';
1385 $chunk_size='';
1386 do {
1387 $chunk_size.=$byte;
1388 $byte=fread($this->sock,1);
1389 // check what happens while reading, because I do not really understand how php reads the socketstream...
1390 // but so far - it seems to work here - tested with php v4.3.1 on apache 1.3.27 and Debian Linux 3.0 ...
1391 if (strlen($byte) == 0) {
1392 $this->_error_log('get_respond: warning --> read zero bytes');
1394 } while ($byte!="\r" and strlen($byte)>0); // till we match the Carriage Return
1395 fread($this->sock, 1); // also drop off the Line Feed
1396 $chunk_size=hexdec($chunk_size); // convert to a number in decimal system
1397 if ($chunk_size > 0) {
1398 $buffer .= fread($this->sock,$chunk_size);
1400 fread($this->sock, 2); // ditch the CRLF that trails the chunk
1401 } while ($chunk_size); // till we reach the 0 length chunk (end marker)
1402 break;
1404 // check for a specified content-length
1405 case preg_match('/Content\\-Length:\\s+([0-9]*)\\r\\n/',$header,$matches):
1406 $this->_error_log('Getting data using Content-Length '. $matches[1]);
1408 // check if we the content data size is small enough to get it as one block
1409 if ($matches[1] <= $max_chunk_size ) {
1410 // only read something if Content-Length is bigger than 0
1411 if ($matches[1] > 0 ) {
1412 $buffer = fread($this->sock, $matches[1]);
1413 $loadsize = strlen($buffer);
1414 //did we realy get the full length?
1415 if ($loadsize < $matches[1]) {
1416 $max_chunk_size = $loadsize;
1417 do {
1418 $mod = $max_chunk_size % ($matches[1] - strlen($buffer));
1419 $chunk_size = ($mod == $max_chunk_size ? $max_chunk_size : $matches[1] - strlen($buffer));
1420 $buffer .= fread($this->sock, $chunk_size);
1421 $this->_error_log('mod: ' . $mod . ' chunk: ' . $chunk_size . ' total: ' . strlen($buffer));
1422 } while ($mod == $max_chunk_size);
1423 break;
1424 } else {
1425 break;
1427 } else {
1428 $buffer = '';
1429 break;
1433 // data is to big to handle it as one. Get it chunk per chunk...
1434 //trying to get the full length of max_chunk_size
1435 $buffer = fread($this->sock, $max_chunk_size);
1436 $loadsize = strlen($buffer);
1437 if ($loadsize < $max_chunk_size) {
1438 $max_chunk_size = $loadsize;
1440 do {
1441 $mod = $max_chunk_size % ($matches[1] - strlen($buffer));
1442 $chunk_size = ($mod == $max_chunk_size ? $max_chunk_size : $matches[1] - strlen($buffer));
1443 $buffer .= fread($this->sock, $chunk_size);
1444 $this->_error_log('mod: ' . $mod . ' chunk: ' . $chunk_size . ' total: ' . strlen($buffer));
1445 } while ($mod == $max_chunk_size);
1446 $loadsize = strlen($buffer);
1447 if ($loadsize < $matches[1]) {
1448 $buffer .= fread($this->sock, $matches[1] - $loadsize);
1450 break;
1452 // check for 204 No Content
1453 // 204 responds have no body.
1454 // Therefore we do not need to read any data from socket stream.
1455 case preg_match('/HTTP\/1\.1\ 204/',$header):
1456 // nothing to do, just proceed
1457 $this->_error_log('204 No Content found. No further data to read..');
1458 break;
1459 default:
1460 // just get the data until foef appears...
1461 $this->_error_log('reading until feof...' . $header);
1462 socket_set_timeout($this->sock, 0, 0);
1463 while (!feof($this->sock)) {
1464 $buffer .= fread($this->sock, 4096);
1466 // renew the socket timeout...does it do something ???? Is it needed. More debugging needed...
1467 socket_set_timeout($this->sock, $this->_socket_timeout, 0);
1470 $this->_header = $header;
1471 $this->_body = $buffer;
1472 // $this->_buffer = $header . "\r\n\r\n" . $buffer;
1473 $this->_error_log($this->_header);
1474 $this->_error_log($this->_body);
1479 * Private method process_respond
1481 * Processes the webdav server respond and detects its components (header, body).
1482 * and returns data array structure.
1483 * @return array ret_struct
1484 * @access private
1486 private function process_respond() {
1487 $lines = explode("\r\n", $this->_header);
1488 $header_done = false;
1489 // $this->_error_log($this->_buffer);
1490 // First line should be a HTTP status line (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6)
1491 // Format is: HTTP-Version SP Status-Code SP Reason-Phrase CRLF
1492 list($ret_struct['status']['http-version'],
1493 $ret_struct['status']['status-code'],
1494 $ret_struct['status']['reason-phrase']) = explode(' ', $lines[0],3);
1496 // print "HTTP Version: '$http_version' Status-Code: '$status_code' Reason Phrase: '$reason_phrase'<br>";
1497 // get the response header fields
1498 // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6
1499 for($i=1; $i<count($lines); $i++) {
1500 if (rtrim($lines[$i]) == '' && !$header_done) {
1501 $header_done = true;
1502 // print "--- response header end ---<br>";
1505 if (!$header_done ) {
1506 // store all found headers in array ...
1507 list($fieldname, $fieldvalue) = explode(':', $lines[$i]);
1508 // check if this header was allready set (apache 2.0 webdav module does this....).
1509 // If so we add the the value to the end the fieldvalue, separated by comma...
1510 if (empty($ret_struct['header'])) {
1511 $ret_struct['header'] = array();
1513 if (empty($ret_struct['header'][$fieldname])) {
1514 $ret_struct['header'][$fieldname] = trim($fieldvalue);
1515 } else {
1516 $ret_struct['header'][$fieldname] .= ',' . trim($fieldvalue);
1520 // print 'string len of response_body:'. strlen($response_body);
1521 // print '[' . htmlentities($response_body) . ']';
1522 $ret_struct['body'] = $this->_body;
1523 $this->_error_log('process_respond: ' . var_export($ret_struct,true));
1524 return $ret_struct;
1529 * Private method reopen
1531 * Reopens a socket, if 'connection: closed'-header was received from server.
1533 * Uses public method open.
1534 * @access private
1536 private function reopen() {
1537 // let's try to reopen a socket
1538 $this->_error_log('reopen a socket connection');
1539 return $this->open();
1544 * Private method translate_uri
1546 * translates an uri to raw url encoded string.
1547 * Removes any html entity in uri
1548 * @param string uri
1549 * @return string translated_uri
1550 * @access private
1552 private function translate_uri($uri) {
1553 // remove all html entities...
1554 $native_path = html_entity_decode($uri);
1555 $parts = explode('/', $native_path);
1556 for ($i = 0; $i < count($parts); $i++) {
1557 // check if part is allready utf8
1558 if (iconv('UTF-8', 'UTF-8', $parts[$i]) == $parts[$i]) {
1559 $parts[$i] = rawurlencode($parts[$i]);
1560 } else {
1561 $parts[$i] = rawurlencode(utf8_encode($parts[$i]));
1564 return implode('/', $parts);
1568 * Private method utf_decode_path
1570 * decodes a UTF-8 encoded string
1571 * @return string decodedstring
1572 * @access private
1574 private function utf_decode_path($path) {
1575 $fullpath = $path;
1576 if (iconv('UTF-8', 'UTF-8', $fullpath) == $fullpath) {
1577 $this->_error_log("filename is utf-8. Needs conversion...");
1578 $fullpath = utf8_decode($fullpath);
1580 return $fullpath;
1584 * Private method _error_log
1586 * a simple php error_log wrapper.
1587 * @param string err_string
1588 * @access private
1590 private function _error_log($err_string) {
1591 if ($this->_debug) {
1592 error_log($err_string);