MDL-34338 mod_folder: delete unused $browser var.
[moodle.git] / lib / webdavlib.php
blobd36095e25ed434e3884439e7915a5f0f28005d34
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 $_socket = '';
48 private $_path ='/';
49 private $_auth = false;
50 private $_user;
51 private $_pass;
53 private $_socket_timeout = 5;
54 private $_errno;
55 private $_errstr;
56 private $_user_agent = 'Moodle WebDav Client';
57 private $_crlf = "\r\n";
58 private $_req;
59 private $_resp_status;
60 private $_parser;
61 private $_parserid;
62 private $_xmltree;
63 private $_tree;
64 private $_ls = array();
65 private $_ls_ref;
66 private $_ls_ref_cdata;
67 private $_delete = array();
68 private $_delete_ref;
69 private $_delete_ref_cdata;
70 private $_lock = array();
71 private $_lock_ref;
72 private $_lock_rec_cdata;
73 private $_null = NULL;
74 private $_header='';
75 private $_body='';
76 private $_connection_closed = false;
77 private $_maxheaderlenth = 1000;
78 private $_digestchallenge = null;
79 private $_cnonce = '';
80 private $_nc = 0;
82 /**#@-*/
84 /**
85 * Constructor - Initialise class variables
87 function __construct($server = '', $user = '', $pass = '', $auth = false, $socket = '') {
88 if (!empty($server)) {
89 $this->_server = $server;
91 if (!empty($user) && !empty($pass)) {
92 $this->user = $user;
93 $this->pass = $pass;
95 $this->_auth = $auth;
96 $this->_socket = $socket;
98 public function __set($key, $value) {
99 $property = '_' . $key;
100 $this->$property = $value;
104 * Set which HTTP protocol will be used.
105 * Value 1 defines that HTTP/1.1 should be used (Keeps Connection to webdav server alive).
106 * Otherwise HTTP/1.0 will be used.
107 * @param int version
109 function set_protocol($version) {
110 if ($version == 1) {
111 $this->_protocol = 'HTTP/1.1';
112 } else {
113 $this->_protocol = 'HTTP/1.0';
118 * Convert ISO 8601 Date and Time Profile used in RFC 2518 to an unix timestamp.
119 * @access private
120 * @param string iso8601
121 * @return unixtimestamp on sucess. Otherwise false.
123 function iso8601totime($iso8601) {
126 date-time = full-date "T" full-time
128 full-date = date-fullyear "-" date-month "-" date-mday
129 full-time = partial-time time-offset
131 date-fullyear = 4DIGIT
132 date-month = 2DIGIT ; 01-12
133 date-mday = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on
134 month/year
135 time-hour = 2DIGIT ; 00-23
136 time-minute = 2DIGIT ; 00-59
137 time-second = 2DIGIT ; 00-59, 00-60 based on leap second rules
138 time-secfrac = "." 1*DIGIT
139 time-numoffset = ("+" / "-") time-hour ":" time-minute
140 time-offset = "Z" / time-numoffset
142 partial-time = time-hour ":" time-minute ":" time-second
143 [time-secfrac]
146 $regs = array();
147 /* [1] [2] [3] [4] [5] [6] */
148 if (preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z$/', $iso8601, $regs)) {
149 return mktime($regs[4],$regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
151 // to be done: regex for partial-time...apache webdav mod never returns partial-time
153 return false;
157 * Open's a socket to a webdav server
158 * @return bool true on success. Otherwise false.
160 function open() {
161 // let's try to open a socket
162 $this->_error_log('open a socket connection');
163 $this->sock = fsockopen($this->_socket . $this->_server, $this->_port, $this->_errno, $this->_errstr, $this->_socket_timeout);
164 set_time_limit(30);
165 if (is_resource($this->sock)) {
166 socket_set_blocking($this->sock, true);
167 $this->_connection_closed = false;
168 $this->_error_log('socket is open: ' . $this->sock);
169 return true;
170 } else {
171 $this->_error_log("$this->_errstr ($this->_errno)\n");
172 return false;
177 * Closes an open socket.
179 function close() {
180 $this->_error_log('closing socket ' . $this->sock);
181 $this->_connection_closed = true;
182 fclose($this->sock);
186 * Check's if server is a webdav compliant server.
187 * True if server returns a DAV Element in Header and when
188 * schema 1,2 is supported.
189 * @return bool true if server is webdav server. Otherwise false.
191 function check_webdav() {
192 $resp = $this->options();
193 if (!$resp) {
194 return false;
196 $this->_error_log($resp['header']['DAV']);
197 // check schema
198 if (preg_match('/1,2/', $resp['header']['DAV'])) {
199 return true;
201 // otherwise return false
202 return false;
207 * Get options from webdav server.
208 * @return array with all header fields returned from webdav server. false if server does not speak http.
210 function options() {
211 $this->header_unset();
212 $this->create_basic_request('OPTIONS');
213 $this->send_request();
214 $this->get_respond();
215 $response = $this->process_respond();
216 // validate the response ...
217 // check http-version
218 if ($response['status']['http-version'] == 'HTTP/1.1' ||
219 $response['status']['http-version'] == 'HTTP/1.0') {
220 return $response;
222 $this->_error_log('Response was not even http');
223 return false;
228 * Public method mkcol
230 * Creates a new collection/directory on a webdav server
231 * @param string path
232 * @return int status code received as reponse from webdav server (see rfc 2518)
234 function mkcol($path) {
235 $this->_path = $this->translate_uri($path);
236 $this->header_unset();
237 $this->create_basic_request('MKCOL');
238 $this->send_request();
239 $this->get_respond();
240 $response = $this->process_respond();
241 // validate the response ...
242 // check http-version
243 $http_version = $response['status']['http-version'];
244 if ($http_version == 'HTTP/1.1' || $http_version == 'HTTP/1.0') {
245 /** seems to be http ... proceed
246 * just return what server gave us
247 * rfc 2518 says:
248 * 201 (Created) - The collection or structured resource was created in its entirety.
249 * 403 (Forbidden) - This indicates at least one of two conditions:
250 * 1) the server does not allow the creation of collections at the given location in its namespace, or
251 * 2) the parent collection of the Request-URI exists but cannot accept members.
252 * 405 (Method Not Allowed) - MKCOL can only be executed on a deleted/non-existent resource.
253 * 409 (Conflict) - A collection cannot be made at the Request-URI until one or more intermediate
254 * collections have been created.
255 * 415 (Unsupported Media Type)- The server does not support the request type of the body.
256 * 507 (Insufficient Storage) - The resource does not have sufficient space to record the state of the
257 * resource after the execution of this method.
259 return $response['status']['status-code'];
265 * Public method get
267 * Gets a file from a webdav collection.
268 * @param string path, string &buffer
269 * @return status code and &$buffer (by reference) with response data from server on success. False on error.
271 function get($path, &$buffer) {
272 $this->_path = $this->translate_uri($path);
273 $this->header_unset();
274 $this->create_basic_request('GET');
275 $this->send_request();
276 $this->get_respond();
277 $response = $this->process_respond();
279 $http_version = $response['status']['http-version'];
280 // validate the response
281 // check http-version
282 if ($http_version == 'HTTP/1.1' || $http_version == 'HTTP/1.0') {
283 // seems to be http ... proceed
284 // We expect a 200 code
285 if ($response['status']['status-code'] == 200 ) {
286 $this->_error_log('returning buffer with ' . strlen($response['body']) . ' bytes.');
287 $buffer = $response['body'];
289 return $response['status']['status-code'];
291 // ups: no http status was returned ?
292 return false;
296 * Public method put
298 * Puts a file into a collection.
299 * Data is putted as one chunk!
300 * @param string path, string data
301 * @return int status-code read from webdavserver. False on error.
303 function put($path, $data ) {
304 $this->_path = $this->translate_uri($path);
305 $this->header_unset();
306 $this->create_basic_request('PUT');
307 // add more needed header information ...
308 $this->header_add('Content-length: ' . strlen($data));
309 $this->header_add('Content-type: application/octet-stream');
310 // send header
311 $this->send_request();
312 // send the rest (data)
313 fputs($this->sock, $data);
314 $this->get_respond();
315 $response = $this->process_respond();
317 // validate the response
318 // check http-version
319 if ($response['status']['http-version'] == 'HTTP/1.1' ||
320 $response['status']['http-version'] == 'HTTP/1.0') {
321 // seems to be http ... proceed
322 // We expect a 200 or 204 status code
323 // see rfc 2068 - 9.6 PUT...
324 // print 'http ok<br>';
325 return $response['status']['status-code'];
327 // ups: no http status was returned ?
328 return false;
332 * Public method put_file
334 * Read a file as stream and puts it chunk by chunk into webdav server collection.
336 * Look at php documenation for legal filenames with fopen();
337 * The filename will be translated into utf-8 if not allready in utf-8.
339 * @param string targetpath, string filename
340 * @return int status code. False on error.
342 function put_file($path, $filename) {
343 // try to open the file ...
346 $handle = @fopen ($filename, 'r');
348 if ($handle) {
349 // $this->sock = pfsockopen ($this->_server, $this->_port, $this->_errno, $this->_errstr, $this->_socket_timeout);
350 $this->_path = $this->translate_uri($path);
351 $this->header_unset();
352 $this->create_basic_request('PUT');
353 // add more needed header information ...
354 $this->header_add('Content-length: ' . filesize($filename));
355 $this->header_add('Content-type: application/octet-stream');
356 // send header
357 $this->send_request();
358 while (!feof($handle)) {
359 fputs($this->sock,fgets($handle,4096));
361 fclose($handle);
362 $this->get_respond();
363 $response = $this->process_respond();
365 // validate the response
366 // check http-version
367 if ($response['status']['http-version'] == 'HTTP/1.1' ||
368 $response['status']['http-version'] == 'HTTP/1.0') {
369 // seems to be http ... proceed
370 // We expect a 200 or 204 status code
371 // see rfc 2068 - 9.6 PUT...
372 // print 'http ok<br>';
373 return $response['status']['status-code'];
375 // ups: no http status was returned ?
376 return false;
377 } else {
378 $this->_error_log('put_file: could not open ' . $filename);
379 return false;
385 * Public method get_file
387 * Gets a file from a collection into local filesystem.
389 * fopen() is used.
390 * @param string srcpath, string localpath
391 * @return true on success. false on error.
393 function get_file($srcpath, $localpath) {
395 if ($this->get($srcpath, $buffer)) {
396 // convert utf-8 filename to iso-8859-1
398 $localpath = $this->utf_decode_path($localpath);
400 $handle = fopen ($localpath, 'w');
401 if ($handle) {
402 fwrite($handle, $buffer);
403 fclose($handle);
404 return true;
405 } else {
406 return false;
408 } else {
409 return false;
414 * Public method copy_file
416 * Copies a file on a webdav server
418 * Duplicates a file on the webdav server (serverside).
419 * All work is done on the webdav server. If you set param overwrite as true,
420 * the target will be overwritten.
422 * @param string src_path, string dest_path, bool overwrite
423 * @return int status code (look at rfc 2518). false on error.
425 function copy_file($src_path, $dst_path, $overwrite) {
426 $this->_path = $this->translate_uri($src_path);
427 $this->header_unset();
428 $this->create_basic_request('COPY');
429 $this->header_add(sprintf('Destination: http://%s%s', $this->_server, $this->translate_uri($dst_path)));
430 if ($overwrite) {
431 $this->header_add('Overwrite: T');
432 } else {
433 $this->header_add('Overwrite: F');
435 $this->header_add('');
436 $this->send_request();
437 $this->get_respond();
438 $response = $this->process_respond();
439 // validate the response ...
440 // check http-version
441 if ($response['status']['http-version'] == 'HTTP/1.1' ||
442 $response['status']['http-version'] == 'HTTP/1.0') {
443 /* seems to be http ... proceed
444 just return what server gave us (as defined in rfc 2518) :
445 201 (Created) - The source resource was successfully copied. The copy operation resulted in the creation of a new resource.
446 204 (No Content) - The source resource was successfully copied to a pre-existing destination resource.
447 403 (Forbidden) - The source and destination URIs are the same.
448 409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created.
449 412 (Precondition Failed) - The server was unable to maintain the liveness of the properties listed in the propertybehavior XML element
450 or the Overwrite header is "F" and the state of the destination resource is non-null.
451 423 (Locked) - The destination resource was locked.
452 502 (Bad Gateway) - This may occur when the destination is on another server and the destination server refuses to accept the resource.
453 507 (Insufficient Storage) - The destination resource does not have sufficient space to record the state of the resource after the
454 execution of this method.
456 return $response['status']['status-code'];
458 return false;
462 * Public method copy_coll
464 * Copies a collection on a webdav server
466 * Duplicates a collection on the webdav server (serverside).
467 * All work is done on the webdav server. If you set param overwrite as true,
468 * the target will be overwritten.
470 * @param string src_path, string dest_path, bool overwrite
471 * @return int status code (look at rfc 2518). false on error.
473 function copy_coll($src_path, $dst_path, $overwrite) {
474 $this->_path = $this->translate_uri($src_path);
475 $this->header_unset();
476 $this->create_basic_request('COPY');
477 $this->header_add(sprintf('Destination: http://%s%s', $this->_server, $this->translate_uri($dst_path)));
478 $this->header_add('Depth: Infinity');
480 $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n";
481 $xml .= "<d:propertybehavior xmlns:d=\"DAV:\">\r\n";
482 $xml .= " <d:keepalive>*</d:keepalive>\r\n";
483 $xml .= "</d:propertybehavior>\r\n";
485 $this->header_add('Content-length: ' . strlen($xml));
486 $this->header_add('Content-type: application/xml');
487 $this->send_request();
488 // send also xml
489 fputs($this->sock, $xml);
490 $this->get_respond();
491 $response = $this->process_respond();
492 // validate the response ...
493 // check http-version
494 if ($response['status']['http-version'] == 'HTTP/1.1' ||
495 $response['status']['http-version'] == 'HTTP/1.0') {
496 /* seems to be http ... proceed
497 just return what server gave us (as defined in rfc 2518) :
498 201 (Created) - The source resource was successfully copied. The copy operation resulted in the creation of a new resource.
499 204 (No Content) - The source resource was successfully copied to a pre-existing destination resource.
500 403 (Forbidden) - The source and destination URIs are the same.
501 409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created.
502 412 (Precondition Failed) - The server was unable to maintain the liveness of the properties listed in the propertybehavior XML element
503 or the Overwrite header is "F" and the state of the destination resource is non-null.
504 423 (Locked) - The destination resource was locked.
505 502 (Bad Gateway) - This may occur when the destination is on another server and the destination server refuses to accept the resource.
506 507 (Insufficient Storage) - The destination resource does not have sufficient space to record the state of the resource after the
507 execution of this method.
509 return $response['status']['status-code'];
511 return false;
515 * Public method move
517 * Moves a file or collection on webdav server (serverside)
519 * If you set param overwrite as true, the target will be overwritten.
521 * @param string src_path, string dest_path, bool overwrite
522 * @return int status code (look at rfc 2518). false on error.
524 // --------------------------------------------------------------------------
525 // public method move
526 // move/rename a file/collection on webdav server
527 function move($src_path,$dst_path, $overwrite) {
529 $this->_path = $this->translate_uri($src_path);
530 $this->header_unset();
532 $this->create_basic_request('MOVE');
533 $this->header_add(sprintf('Destination: http://%s%s', $this->_server, $this->translate_uri($dst_path)));
534 if ($overwrite) {
535 $this->header_add('Overwrite: T');
536 } else {
537 $this->header_add('Overwrite: F');
539 $this->header_add('');
541 $this->send_request();
542 $this->get_respond();
543 $response = $this->process_respond();
544 // validate the response ...
545 // check http-version
546 if ($response['status']['http-version'] == 'HTTP/1.1' ||
547 $response['status']['http-version'] == 'HTTP/1.0') {
548 /* seems to be http ... proceed
549 just return what server gave us (as defined in rfc 2518) :
550 201 (Created) - The source resource was successfully moved, and a new resource was created at the destination.
551 204 (No Content) - The source resource was successfully moved to a pre-existing destination resource.
552 403 (Forbidden) - The source and destination URIs are the same.
553 409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created.
554 412 (Precondition Failed) - The server was unable to maintain the liveness of the properties listed in the propertybehavior XML element
555 or the Overwrite header is "F" and the state of the destination resource is non-null.
556 423 (Locked) - The source or the destination resource was locked.
557 502 (Bad Gateway) - This may occur when the destination is on another server and the destination server refuses to accept the resource.
559 201 (Created) - The collection or structured resource was created in its entirety.
560 403 (Forbidden) - This indicates at least one of two conditions: 1) the server does not allow the creation of collections at the given
561 location in its namespace, or 2) the parent collection of the Request-URI exists but cannot accept members.
562 405 (Method Not Allowed) - MKCOL can only be executed on a deleted/non-existent resource.
563 409 (Conflict) - A collection cannot be made at the Request-URI until one or more intermediate collections have been created.
564 415 (Unsupported Media Type)- The server does not support the request type of the body.
565 507 (Insufficient Storage) - The resource does not have sufficient space to record the state of the resource after the execution of this method.
567 return $response['status']['status-code'];
569 return false;
573 * Public method lock
575 * Locks a file or collection.
577 * Lock uses this->_user as lock owner.
579 * @param string path
580 * @return int status code (look at rfc 2518). false on error.
582 function lock($path) {
583 $this->_path = $this->translate_uri($path);
584 $this->header_unset();
585 $this->create_basic_request('LOCK');
586 $this->header_add('Timeout: Infinite');
587 $this->header_add('Content-type: text/xml');
588 // create the xml request ...
589 $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n";
590 $xml .= "<D:lockinfo xmlns:D='DAV:'\r\n>";
591 $xml .= " <D:lockscope><D:exclusive/></D:lockscope>\r\n";
592 $xml .= " <D:locktype><D:write/></D:locktype>\r\n";
593 $xml .= " <D:owner>\r\n";
594 $xml .= " <D:href>".($this->_user)."</D:href>\r\n";
595 $xml .= " </D:owner>\r\n";
596 $xml .= "</D:lockinfo>\r\n";
597 $this->header_add('Content-length: ' . strlen($xml));
598 $this->send_request();
599 // send also xml
600 fputs($this->sock, $xml);
601 $this->get_respond();
602 $response = $this->process_respond();
603 // validate the response ... (only basic validation)
604 // check http-version
605 if ($response['status']['http-version'] == 'HTTP/1.1' ||
606 $response['status']['http-version'] == 'HTTP/1.0') {
607 /* seems to be http ... proceed
608 rfc 2518 says:
609 200 (OK) - The lock request succeeded and the value of the lockdiscovery property is included in the body.
610 412 (Precondition Failed) - The included lock token was not enforceable on this resource or the server could not satisfy the
611 request in the lockinfo XML element.
612 423 (Locked) - The resource is locked, so the method has been rejected.
615 switch($response['status']['status-code']) {
616 case 200:
617 // collection was successfully locked... see xml response to get lock token...
618 if (strcmp($response['header']['Content-Type'], 'text/xml; charset="utf-8"') == 0) {
619 // ok let's get the content of the xml stuff
620 $this->_parser = xml_parser_create_ns();
621 $this->_parserid = (int) $this->_parser;
622 // forget old data...
623 unset($this->_lock[$this->_parserid]);
624 unset($this->_xmltree[$this->_parserid]);
625 xml_parser_set_option($this->_parser,XML_OPTION_SKIP_WHITE,0);
626 xml_parser_set_option($this->_parser,XML_OPTION_CASE_FOLDING,0);
627 xml_set_object($this->_parser, $this);
628 xml_set_element_handler($this->_parser, "_lock_startElement", "_endElement");
629 xml_set_character_data_handler($this->_parser, "_lock_cdata");
631 if (!xml_parse($this->_parser, $response['body'])) {
632 die(sprintf("XML error: %s at line %d",
633 xml_error_string(xml_get_error_code($this->_parser)),
634 xml_get_current_line_number($this->_parser)));
637 // Free resources
638 xml_parser_free($this->_parser);
639 // add status code to array
640 $this->_lock[$this->_parserid]['status'] = 200;
641 return $this->_lock[$this->_parserid];
643 } else {
644 print 'Missing Content-Type: text/xml header in response.<br>';
646 return false;
648 default:
649 // hmm. not what we expected. Just return what we got from webdav server
650 // someone else has to handle it.
651 $this->_lock['status'] = $response['status']['status-code'];
652 return $this->_lock;
661 * Public method unlock
663 * Unlocks a file or collection.
665 * @param string path, string locktoken
666 * @return int status code (look at rfc 2518). false on error.
668 function unlock($path, $locktoken) {
669 $this->_path = $this->translate_uri($path);
670 $this->header_unset();
671 $this->create_basic_request('UNLOCK');
672 $this->header_add(sprintf('Lock-Token: <%s>', $locktoken));
673 $this->send_request();
674 $this->get_respond();
675 $response = $this->process_respond();
676 if ($response['status']['http-version'] == 'HTTP/1.1' ||
677 $response['status']['http-version'] == 'HTTP/1.0') {
678 /* seems to be http ... proceed
679 rfc 2518 says:
680 204 (OK) - The 204 (No Content) status code is used instead of 200 (OK) because there is no response entity body.
682 return $response['status']['status-code'];
684 return false;
688 * Public method delete
690 * deletes a collection/directory on a webdav server
691 * @param string path
692 * @return int status code (look at rfc 2518). false on error.
694 function delete($path) {
695 $this->_path = $this->translate_uri($path);
696 $this->header_unset();
697 $this->create_basic_request('DELETE');
698 /* $this->header_add('Content-Length: 0'); */
699 $this->header_add('');
700 $this->send_request();
701 $this->get_respond();
702 $response = $this->process_respond();
704 // validate the response ...
705 // check http-version
706 if ($response['status']['http-version'] == 'HTTP/1.1' ||
707 $response['status']['http-version'] == 'HTTP/1.0') {
708 // seems to be http ... proceed
709 // We expect a 207 Multi-Status status code
710 // print 'http ok<br>';
712 switch ($response['status']['status-code']) {
713 case 207:
714 // collection was NOT deleted... see xml response for reason...
715 // next there should be a Content-Type: text/xml; charset="utf-8" header line
716 if (strcmp($response['header']['Content-Type'], 'text/xml; charset="utf-8"') == 0) {
717 // ok let's get the content of the xml stuff
718 $this->_parser = xml_parser_create_ns();
719 $this->_parserid = (int) $this->_parser;
720 // forget old data...
721 unset($this->_delete[$this->_parserid]);
722 unset($this->_xmltree[$this->_parserid]);
723 xml_parser_set_option($this->_parser,XML_OPTION_SKIP_WHITE,0);
724 xml_parser_set_option($this->_parser,XML_OPTION_CASE_FOLDING,0);
725 xml_set_object($this->_parser, $this);
726 xml_set_element_handler($this->_parser, "_delete_startElement", "_endElement");
727 xml_set_character_data_handler($this->_parser, "_delete_cdata");
729 if (!xml_parse($this->_parser, $response['body'])) {
730 die(sprintf("XML error: %s at line %d",
731 xml_error_string(xml_get_error_code($this->_parser)),
732 xml_get_current_line_number($this->_parser)));
735 print "<br>";
737 // Free resources
738 xml_parser_free($this->_parser);
739 $this->_delete[$this->_parserid]['status'] = $response['status']['status-code'];
740 return $this->_delete[$this->_parserid];
742 } else {
743 print 'Missing Content-Type: text/xml header in response.<br>';
745 return false;
747 default:
748 // collection or file was successfully deleted
749 $this->_delete['status'] = $response['status']['status-code'];
750 return $this->_delete;
759 * Public method ls
761 * Get's directory information from webdav server into flat a array using PROPFIND
763 * All filenames are UTF-8 encoded.
764 * Have a look at _propfind_startElement what keys are used in array returned.
765 * @param string path
766 * @return array dirinfo, false on error
768 function ls($path) {
770 if (trim($path) == '') {
771 $this->_error_log('Missing a path in method ls');
772 return false;
774 $this->_path = $this->translate_uri($path);
776 $this->header_unset();
777 $this->create_basic_request('PROPFIND');
778 $this->header_add('Depth: 1');
779 $this->header_add('Content-type: application/xml');
780 // create profind xml request...
781 $xml = <<<EOD
782 <?xml version="1.0" encoding="utf-8"?>
783 <propfind xmlns="DAV:"><prop>
784 <getcontentlength xmlns="DAV:"/>
785 <getlastmodified xmlns="DAV:"/>
786 <executable xmlns="http://apache.org/dav/props/"/>
787 <resourcetype xmlns="DAV:"/>
788 <checked-in xmlns="DAV:"/>
789 <checked-out xmlns="DAV:"/>
790 </prop></propfind>
791 EOD;
792 $this->header_add('Content-length: ' . strlen($xml));
793 $this->send_request();
794 $this->_error_log($xml);
795 fputs($this->sock, $xml);
796 $this->get_respond();
797 $response = $this->process_respond();
798 // validate the response ... (only basic validation)
799 // check http-version
800 if ($response['status']['http-version'] == 'HTTP/1.1' ||
801 $response['status']['http-version'] == 'HTTP/1.0') {
802 // seems to be http ... proceed
803 // We expect a 207 Multi-Status status code
804 // print 'http ok<br>';
805 if (strcmp($response['status']['status-code'],'207') == 0 ) {
806 // ok so far
807 // next there should be a Content-Type: text/xml; charset="utf-8" header line
808 if (preg_match('#(application|text)/xml;\s?charset=[\'\"]?utf-8[\'\"]?#i', $response['header']['Content-Type'])) {
809 // ok let's get the content of the xml stuff
810 $this->_parser = xml_parser_create_ns('UTF-8');
811 $this->_parserid = (int) $this->_parser;
812 // forget old data...
813 unset($this->_ls[$this->_parserid]);
814 unset($this->_xmltree[$this->_parserid]);
815 xml_parser_set_option($this->_parser,XML_OPTION_SKIP_WHITE,0);
816 xml_parser_set_option($this->_parser,XML_OPTION_CASE_FOLDING,0);
817 // xml_parser_set_option($this->_parser,XML_OPTION_TARGET_ENCODING,'UTF-8');
818 xml_set_object($this->_parser, $this);
819 xml_set_element_handler($this->_parser, "_propfind_startElement", "_endElement");
820 xml_set_character_data_handler($this->_parser, "_propfind_cdata");
823 if (!xml_parse($this->_parser, $response['body'])) {
824 die(sprintf("XML error: %s at line %d",
825 xml_error_string(xml_get_error_code($this->_parser)),
826 xml_get_current_line_number($this->_parser)));
829 // Free resources
830 xml_parser_free($this->_parser);
831 $arr = $this->_ls[$this->_parserid];
832 return $arr;
833 } else {
834 $this->_error_log('Missing Content-Type: text/xml header in response!!');
835 return false;
837 } else {
838 // return status code ...
839 return $response['status']['status-code'];
843 // response was not http
844 $this->_error_log('Ups in method ls: error in response from server');
845 return false;
850 * Public method gpi
852 * Get's path information from webdav server for one element.
854 * @param string path
855 * @return array dirinfo. false on error
857 function gpi($path) {
859 // split path by last "/"
860 $path = rtrim($path, "/");
861 $item = basename($path);
862 $dir = dirname($path);
864 $list = $this->ls($dir);
866 // be sure it is an array
867 if (is_array($list)) {
868 foreach($list as $e) {
870 $fullpath = urldecode($e['href']);
871 $filename = basename($fullpath);
873 if ($filename == $item && $filename != "" and $fullpath != $dir."/") {
874 return $e;
878 return false;
882 * Public method is_file
884 * Gathers whether a path points to a file or not.
886 * @param string path
887 * @return bool true or false
889 function is_file($path) {
891 $item = $this->gpi($path);
893 if ($item === false) {
894 return false;
895 } else {
896 return ($item['resourcetype'] != 'collection');
901 * Public method is_dir
903 * Gather whether a path points to a directory
904 * @param string path
905 * return bool true or false
907 function is_dir($path) {
909 // be sure path is utf-8
910 $item = $this->gpi($path);
912 if ($item === false) {
913 return false;
914 } else {
915 return ($item['resourcetype'] == 'collection');
921 * Public method mput
923 * Puts multiple files and/or directories onto a webdav server.
925 * Filenames should be allready UTF-8 encoded.
926 * Param fileList must be in format array("localpath" => "destpath").
928 * @param array filelist
929 * @return bool true on success. otherwise int status code on error
931 function mput($filelist) {
933 $result = true;
935 while (list($localpath, $destpath) = each($filelist)) {
937 $localpath = rtrim($localpath, "/");
938 $destpath = rtrim($destpath, "/");
940 // attempt to create target path
941 if (is_dir($localpath)) {
942 $pathparts = explode("/", $destpath."/ "); // add one level, last level will be created as dir
943 } else {
944 $pathparts = explode("/", $destpath);
946 $checkpath = "";
947 for ($i=1; $i<sizeof($pathparts)-1; $i++) {
948 $checkpath .= "/" . $pathparts[$i];
949 if (!($this->is_dir($checkpath))) {
951 $result &= ($this->mkcol($checkpath) == 201 );
955 if ($result) {
956 // recurse directories
957 if (is_dir($localpath)) {
958 if (!$dp = opendir($localpath)) {
959 $this->_error_log("Could not open localpath for reading");
960 return false;
962 $fl = array();
963 while($filename = readdir($dp)) {
964 if ((is_file($localpath."/".$filename) || is_dir($localpath."/".$filename)) && $filename!="." && $filename != "..") {
965 $fl[$localpath."/".$filename] = $destpath."/".$filename;
968 $result &= $this->mput($fl);
969 } else {
970 $result &= ($this->put_file($destpath, $localpath) == 201);
974 return $result;
978 * Public method mget
980 * Gets multiple files and directories.
982 * FileList must be in format array("remotepath" => "localpath").
983 * Filenames are UTF-8 encoded.
985 * @param array filelist
986 * @return bool true on succes, other int status code on error
988 function mget($filelist) {
990 $result = true;
992 while (list($remotepath, $localpath) = each($filelist)) {
994 $localpath = rtrim($localpath, "/");
995 $remotepath = rtrim($remotepath, "/");
997 // attempt to create local path
998 if ($this->is_dir($remotepath)) {
999 $pathparts = explode("/", $localpath."/ "); // add one level, last level will be created as dir
1000 } else {
1001 $pathparts = explode("/", $localpath);
1003 $checkpath = "";
1004 for ($i=1; $i<sizeof($pathparts)-1; $i++) {
1005 $checkpath .= "/" . $pathparts[$i];
1006 if (!is_dir($checkpath)) {
1008 $result &= mkdir($checkpath);
1012 if ($result) {
1013 // recurse directories
1014 if ($this->is_dir($remotepath)) {
1015 $list = $this->ls($remotepath);
1017 $fl = array();
1018 foreach($list as $e) {
1019 $fullpath = urldecode($e['href']);
1020 $filename = basename($fullpath);
1021 if ($filename != '' and $fullpath != $remotepath . '/') {
1022 $fl[$remotepath."/".$filename] = $localpath."/".$filename;
1025 $result &= $this->mget($fl);
1026 } else {
1027 $result &= ($this->get_file($remotepath, $localpath));
1031 return $result;
1034 // --------------------------------------------------------------------------
1035 // private xml callback and helper functions starting here
1036 // --------------------------------------------------------------------------
1040 * Private method _endelement
1042 * a generic endElement method (used for all xml callbacks).
1044 * @param resource parser, string name
1045 * @access private
1048 private function _endElement($parser, $name) {
1049 // end tag was found...
1050 $parserid = (int) $parser;
1051 $this->_xmltree[$parserid] = substr($this->_xmltree[$parserid],0, strlen($this->_xmltree[$parserid]) - (strlen($name) + 1));
1055 * Private method _propfind_startElement
1057 * Is needed by public method ls.
1059 * Generic method will called by php xml_parse when a xml start element tag has been detected.
1060 * The xml tree will translated into a flat php array for easier access.
1061 * @param resource parser, string name, string attrs
1062 * @access private
1064 private function _propfind_startElement($parser, $name, $attrs) {
1065 // lower XML Names... maybe break a RFC, don't know ...
1066 $parserid = (int) $parser;
1068 $propname = strtolower($name);
1069 if (!empty($this->_xmltree[$parserid])) {
1070 $this->_xmltree[$parserid] .= $propname . '_';
1071 } else {
1072 $this->_xmltree[$parserid] = $propname . '_';
1075 // translate xml tree to a flat array ...
1076 switch($this->_xmltree[$parserid]) {
1077 case 'dav::multistatus_dav::response_':
1078 // new element in mu
1079 $this->_ls_ref =& $this->_ls[$parserid][];
1080 break;
1081 case 'dav::multistatus_dav::response_dav::href_':
1082 $this->_ls_ref_cdata = &$this->_ls_ref['href'];
1083 break;
1084 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::creationdate_':
1085 $this->_ls_ref_cdata = &$this->_ls_ref['creationdate'];
1086 break;
1087 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getlastmodified_':
1088 $this->_ls_ref_cdata = &$this->_ls_ref['lastmodified'];
1089 break;
1090 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getcontenttype_':
1091 $this->_ls_ref_cdata = &$this->_ls_ref['getcontenttype'];
1092 break;
1093 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getcontentlength_':
1094 $this->_ls_ref_cdata = &$this->_ls_ref['getcontentlength'];
1095 break;
1096 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_':
1097 $this->_ls_ref_cdata = &$this->_ls_ref['activelock_depth'];
1098 break;
1099 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_':
1100 $this->_ls_ref_cdata = &$this->_ls_ref['activelock_owner'];
1101 break;
1102 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_':
1103 $this->_ls_ref_cdata = &$this->_ls_ref['activelock_owner'];
1104 break;
1105 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_':
1106 $this->_ls_ref_cdata = &$this->_ls_ref['activelock_timeout'];
1107 break;
1108 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_':
1109 $this->_ls_ref_cdata = &$this->_ls_ref['activelock_token'];
1110 break;
1111 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::locktype_dav::write_':
1112 $this->_ls_ref_cdata = &$this->_ls_ref['activelock_type'];
1113 $this->_ls_ref_cdata = 'write';
1114 $this->_ls_ref_cdata = &$this->_null;
1115 break;
1116 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::resourcetype_dav::collection_':
1117 $this->_ls_ref_cdata = &$this->_ls_ref['resourcetype'];
1118 $this->_ls_ref_cdata = 'collection';
1119 $this->_ls_ref_cdata = &$this->_null;
1120 break;
1121 case 'dav::multistatus_dav::response_dav::propstat_dav::status_':
1122 $this->_ls_ref_cdata = &$this->_ls_ref['status'];
1123 break;
1125 default:
1126 // handle unknown xml elements...
1127 $this->_ls_ref_cdata = &$this->_ls_ref[$this->_xmltree[$parserid]];
1132 * Private method _propfind_cData
1134 * Is needed by public method ls.
1136 * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
1137 * Stores data found into class var _ls_ref_cdata
1138 * @param resource parser, string cdata
1139 * @access private
1141 private function _propfind_cData($parser, $cdata) {
1142 if (trim($cdata) <> '') {
1143 // cdata must be appended, because sometimes the php xml parser makes multiple calls
1144 // to _propfind_cData before the xml end tag was reached...
1145 $this->_ls_ref_cdata .= $cdata;
1146 } else {
1147 // do nothing
1152 * Private method _delete_startElement
1154 * Is used by public method delete.
1156 * Will be called by php xml_parse.
1157 * @param resource parser, string name, string attrs)
1158 * @access private
1160 private function _delete_startElement($parser, $name, $attrs) {
1161 // lower XML Names... maybe break a RFC, don't know ...
1162 $parserid = (int) $parser;
1163 $propname = strtolower($name);
1164 $this->_xmltree[$parserid] .= $propname . '_';
1166 // translate xml tree to a flat array ...
1167 switch($this->_xmltree[$parserid]) {
1168 case 'dav::multistatus_dav::response_':
1169 // new element in mu
1170 $this->_delete_ref =& $this->_delete[$parserid][];
1171 break;
1172 case 'dav::multistatus_dav::response_dav::href_':
1173 $this->_delete_ref_cdata = &$this->_ls_ref['href'];
1174 break;
1176 default:
1177 // handle unknown xml elements...
1178 $this->_delete_cdata = &$this->_delete_ref[$this->_xmltree[$parserid]];
1184 * Private method _delete_cData
1186 * Is used by public method delete.
1188 * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
1189 * Stores data found into class var _delete_ref_cdata
1190 * @param resource parser, string cdata
1191 * @access private
1193 private function _delete_cData($parser, $cdata) {
1194 if (trim($cdata) <> '') {
1195 $this->_delete_ref_cdata .= $cdata;
1196 } else {
1197 // do nothing
1203 * Private method _lock_startElement
1205 * Is needed by public method lock.
1207 * Mmethod will called by php xml_parse when a xml start element tag has been detected.
1208 * The xml tree will translated into a flat php array for easier access.
1209 * @param resource parser, string name, string attrs
1210 * @access private
1212 private function _lock_startElement($parser, $name, $attrs) {
1213 // lower XML Names... maybe break a RFC, don't know ...
1214 $parserid = (int) $parser;
1215 $propname = strtolower($name);
1216 $this->_xmltree[$parserid] .= $propname . '_';
1218 // translate xml tree to a flat array ...
1220 dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_=
1221 dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_=
1222 dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_=
1223 dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_=
1225 switch($this->_xmltree[$parserid]) {
1226 case 'dav::prop_dav::lockdiscovery_dav::activelock_':
1227 // new element
1228 $this->_lock_ref =& $this->_lock[$parserid][];
1229 break;
1230 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::locktype_dav::write_':
1231 $this->_lock_ref_cdata = &$this->_lock_ref['locktype'];
1232 $this->_lock_cdata = 'write';
1233 $this->_lock_cdata = &$this->_null;
1234 break;
1235 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::lockscope_dav::exclusive_':
1236 $this->_lock_ref_cdata = &$this->_lock_ref['lockscope'];
1237 $this->_lock_ref_cdata = 'exclusive';
1238 $this->_lock_ref_cdata = &$this->_null;
1239 break;
1240 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_':
1241 $this->_lock_ref_cdata = &$this->_lock_ref['depth'];
1242 break;
1243 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_':
1244 $this->_lock_ref_cdata = &$this->_lock_ref['owner'];
1245 break;
1246 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_':
1247 $this->_lock_ref_cdata = &$this->_lock_ref['timeout'];
1248 break;
1249 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_':
1250 $this->_lock_ref_cdata = &$this->_lock_ref['locktoken'];
1251 break;
1252 default:
1253 // handle unknown xml elements...
1254 $this->_lock_cdata = &$this->_lock_ref[$this->_xmltree[$parserid]];
1260 * Private method _lock_cData
1262 * Is used by public method lock.
1264 * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
1265 * Stores data found into class var _lock_ref_cdata
1266 * @param resource parser, string cdata
1267 * @access private
1269 private function _lock_cData($parser, $cdata) {
1270 $parserid = (int) $parser;
1271 if (trim($cdata) <> '') {
1272 // $this->_error_log(($this->_xmltree[$parserid]) . '='. htmlentities($cdata));
1273 $this->_lock_ref_cdata .= $cdata;
1274 } else {
1275 // do nothing
1281 * Private method header_add
1283 * extends class var array _req
1284 * @param string string
1285 * @access private
1287 private function header_add($string) {
1288 $this->_req[] = $string;
1292 * Private method header_unset
1294 * unsets class var array _req
1295 * @access private
1298 private function header_unset() {
1299 unset($this->_req);
1303 * Private method create_basic_request
1305 * creates by using private method header_add an general request header.
1306 * @param string method
1307 * @access private
1309 private function create_basic_request($method) {
1310 $this->header_add(sprintf('%s %s %s', $method, $this->_path, $this->_protocol));
1311 $this->header_add(sprintf('Host: %s:%s', $this->_server, $this->_port));
1312 //$request .= sprintf('Connection: Keep-Alive');
1313 $this->header_add(sprintf('User-Agent: %s', $this->_user_agent));
1314 $this->header_add('Connection: TE');
1315 $this->header_add('TE: Trailers');
1316 if ($this->_auth == 'basic') {
1317 $this->header_add(sprintf('Authorization: Basic %s', base64_encode("$this->_user:$this->_pass")));
1318 } else if ($this->_auth == 'digest') {
1319 if ($signature = $this->digest_signature($method)){
1320 $this->header_add($signature);
1326 * Reads the header, stores the challenge information
1328 * @return void
1330 private function digest_auth() {
1332 $headers = array();
1333 $headers[] = sprintf('%s %s %s', 'HEAD', $this->_path, $this->_protocol);
1334 $headers[] = sprintf('Host: %s:%s', $this->_server, $this->_port);
1335 $headers[] = sprintf('User-Agent: %s', $this->_user_agent);
1336 $headers = implode("\r\n", $headers);
1337 $headers .= "\r\n\r\n";
1338 fputs($this->sock, $headers);
1340 // Reads the headers.
1341 $i = 0;
1342 $header = '';
1343 do {
1344 $header .= fread($this->sock, 1);
1345 $i++;
1346 } while (!preg_match('/\\r\\n\\r\\n$/', $header, $matches) && $i < $this->_maxheaderlenth);
1348 // Analyse the headers.
1349 $digest = array();
1350 $splitheaders = explode("\r\n", $header);
1351 foreach ($splitheaders as $line) {
1352 if (!preg_match('/^WWW-Authenticate: Digest/', $line)) {
1353 continue;
1355 $line = substr($line, strlen('WWW-Authenticate: Digest '));
1356 $params = explode(',', $line);
1357 foreach ($params as $param) {
1358 list($key, $value) = explode('=', trim($param), 2);
1359 $digest[$key] = trim($value, '"');
1361 break;
1364 $this->_digestchallenge = $digest;
1368 * Generates the digest signature
1370 * @return string signature to add to the headers
1371 * @access private
1373 private function digest_signature($method) {
1374 if (!$this->_digestchallenge) {
1375 $this->digest_auth();
1378 $signature = array();
1379 $signature['username'] = '"' . $this->_user . '"';
1380 $signature['realm'] = '"' . $this->_digestchallenge['realm'] . '"';
1381 $signature['nonce'] = '"' . $this->_digestchallenge['nonce'] . '"';
1382 $signature['uri'] = '"' . $this->_path . '"';
1384 if (isset($this->_digestchallenge['algorithm']) && $this->_digestchallenge['algorithm'] != 'MD5') {
1385 $this->_error_log('Algorithm other than MD5 are not supported');
1386 return false;
1389 $a1 = $this->_user . ':' . $this->_digestchallenge['realm'] . ':' . $this->_pass;
1390 $a2 = $method . ':' . $this->_path;
1392 if (!isset($this->_digestchallenge['qop'])) {
1393 $signature['response'] = '"' . md5(md5($a1) . ':' . $this->_digestchallenge['nonce'] . ':' . md5($a2)) . '"';
1394 } else {
1395 // Assume QOP is auth
1396 if (empty($this->_cnonce)) {
1397 $this->_cnonce = random_string();
1398 $this->_nc = 0;
1400 $this->_nc++;
1401 $nc = sprintf('%08d', $this->_nc);
1402 $signature['cnonce'] = '"' . $this->_cnonce . '"';
1403 $signature['nc'] = '"' . $nc . '"';
1404 $signature['qop'] = '"' . $this->_digestchallenge['qop'] . '"';
1405 $signature['response'] = '"' . md5(md5($a1) . ':' . $this->_digestchallenge['nonce'] . ':' .
1406 $nc . ':' . $this->_cnonce . ':' . $this->_digestchallenge['qop'] . ':' . md5($a2)) . '"';
1409 $response = array();
1410 foreach ($signature as $key => $value) {
1411 $response[] = "$key=$value";
1413 return 'Authorization: Digest ' . implode(', ', $response);
1417 * Private method send_request
1419 * Sends a ready formed http/webdav request to webdav server.
1421 * @access private
1423 private function send_request() {
1424 // check if stream is declared to be open
1425 // only logical check we are not sure if socket is really still open ...
1426 if ($this->_connection_closed) {
1427 // reopen it
1428 // be sure to close the open socket.
1429 $this->close();
1430 $this->reopen();
1433 // convert array to string
1434 $buffer = implode("\r\n", $this->_req);
1435 $buffer .= "\r\n\r\n";
1436 $this->_error_log($buffer);
1437 fputs($this->sock, $buffer);
1441 * Private method get_respond
1443 * Reads the reponse from the webdav server.
1445 * Stores data into class vars _header for the header data and
1446 * _body for the rest of the response.
1447 * This routine is the weakest part of this class, because it very depends how php does handle a socket stream.
1448 * If the stream is blocked for some reason php is blocked as well.
1449 * @access private
1451 private function get_respond() {
1452 $this->_error_log('get_respond()');
1453 // init vars (good coding style ;-)
1454 $buffer = '';
1455 $header = '';
1456 // attention: do not make max_chunk_size to big....
1457 $max_chunk_size = 8192;
1458 // be sure we got a open ressource
1459 if (! $this->sock) {
1460 $this->_error_log('socket is not open. Can not process response');
1461 return false;
1464 // following code maybe helps to improve socket behaviour ... more testing needed
1465 // disabled at the moment ...
1466 // socket_set_timeout($this->sock,1 );
1467 // $socket_state = socket_get_status($this->sock);
1469 // read stream one byte by another until http header ends
1470 $i = 0;
1471 $matches = array();
1472 do {
1473 $header.=fread($this->sock, 1);
1474 $i++;
1475 } while (!preg_match('/\\r\\n\\r\\n$/',$header, $matches) && $i < $this->_maxheaderlenth);
1477 $this->_error_log($header);
1479 if (preg_match('/Connection: close\\r\\n/', $header)) {
1480 // This says that the server will close connection at the end of this stream.
1481 // Therefore we need to reopen the socket, before are sending the next request...
1482 $this->_error_log('Connection: close found');
1483 $this->_connection_closed = true;
1484 } else if (preg_match('@^HTTP/1\.(1|0) 401 @', $header)) {
1485 $this->_error_log('The server requires an authentication');
1488 // check how to get the data on socket stream
1489 // chunked or content-length (HTTP/1.1) or
1490 // one block until feof is received (HTTP/1.0)
1491 switch(true) {
1492 case (preg_match('/Transfer\\-Encoding:\\s+chunked\\r\\n/',$header)):
1493 $this->_error_log('Getting HTTP/1.1 chunked data...');
1494 do {
1495 $byte = '';
1496 $chunk_size='';
1497 do {
1498 $chunk_size.=$byte;
1499 $byte=fread($this->sock,1);
1500 // check what happens while reading, because I do not really understand how php reads the socketstream...
1501 // but so far - it seems to work here - tested with php v4.3.1 on apache 1.3.27 and Debian Linux 3.0 ...
1502 if (strlen($byte) == 0) {
1503 $this->_error_log('get_respond: warning --> read zero bytes');
1505 } while ($byte!="\r" and strlen($byte)>0); // till we match the Carriage Return
1506 fread($this->sock, 1); // also drop off the Line Feed
1507 $chunk_size=hexdec($chunk_size); // convert to a number in decimal system
1508 if ($chunk_size > 0) {
1509 $read = 0;
1510 // Reading the chunk in one bite is not secure, we read it byte by byte.
1511 while ($read < $chunk_size) {
1512 $buffer .= fread($this->sock, 1);
1513 $read++;
1516 fread($this->sock, 2); // ditch the CRLF that trails the chunk
1517 } while ($chunk_size); // till we reach the 0 length chunk (end marker)
1518 break;
1520 // check for a specified content-length
1521 case preg_match('/Content\\-Length:\\s+([0-9]*)\\r\\n/',$header,$matches):
1522 $this->_error_log('Getting data using Content-Length '. $matches[1]);
1524 // check if we the content data size is small enough to get it as one block
1525 if ($matches[1] <= $max_chunk_size ) {
1526 // only read something if Content-Length is bigger than 0
1527 if ($matches[1] > 0 ) {
1528 $buffer = fread($this->sock, $matches[1]);
1529 $loadsize = strlen($buffer);
1530 //did we realy get the full length?
1531 if ($loadsize < $matches[1]) {
1532 $max_chunk_size = $loadsize;
1533 do {
1534 $mod = $max_chunk_size % ($matches[1] - strlen($buffer));
1535 $chunk_size = ($mod == $max_chunk_size ? $max_chunk_size : $matches[1] - strlen($buffer));
1536 $buffer .= fread($this->sock, $chunk_size);
1537 $this->_error_log('mod: ' . $mod . ' chunk: ' . $chunk_size . ' total: ' . strlen($buffer));
1538 } while ($mod == $max_chunk_size);
1539 break;
1540 } else {
1541 break;
1543 } else {
1544 $buffer = '';
1545 break;
1549 // data is to big to handle it as one. Get it chunk per chunk...
1550 //trying to get the full length of max_chunk_size
1551 $buffer = fread($this->sock, $max_chunk_size);
1552 $loadsize = strlen($buffer);
1553 if ($loadsize < $max_chunk_size) {
1554 $max_chunk_size = $loadsize;
1556 do {
1557 $mod = $max_chunk_size % ($matches[1] - strlen($buffer));
1558 $chunk_size = ($mod == $max_chunk_size ? $max_chunk_size : $matches[1] - strlen($buffer));
1559 $buffer .= fread($this->sock, $chunk_size);
1560 $this->_error_log('mod: ' . $mod . ' chunk: ' . $chunk_size . ' total: ' . strlen($buffer));
1561 } while ($mod == $max_chunk_size);
1562 $loadsize = strlen($buffer);
1563 if ($loadsize < $matches[1]) {
1564 $buffer .= fread($this->sock, $matches[1] - $loadsize);
1566 break;
1568 // check for 204 No Content
1569 // 204 responds have no body.
1570 // Therefore we do not need to read any data from socket stream.
1571 case preg_match('/HTTP\/1\.1\ 204/',$header):
1572 // nothing to do, just proceed
1573 $this->_error_log('204 No Content found. No further data to read..');
1574 break;
1575 default:
1576 // just get the data until foef appears...
1577 $this->_error_log('reading until feof...' . $header);
1578 socket_set_timeout($this->sock, 0, 0);
1579 while (!feof($this->sock)) {
1580 $buffer .= fread($this->sock, 4096);
1582 // renew the socket timeout...does it do something ???? Is it needed. More debugging needed...
1583 socket_set_timeout($this->sock, $this->_socket_timeout, 0);
1586 $this->_header = $header;
1587 $this->_body = $buffer;
1588 // $this->_buffer = $header . "\r\n\r\n" . $buffer;
1589 $this->_error_log($this->_header);
1590 $this->_error_log($this->_body);
1596 * Private method process_respond
1598 * Processes the webdav server respond and detects its components (header, body).
1599 * and returns data array structure.
1600 * @return array ret_struct
1601 * @access private
1603 private function process_respond() {
1604 $lines = explode("\r\n", $this->_header);
1605 $header_done = false;
1606 // $this->_error_log($this->_buffer);
1607 // First line should be a HTTP status line (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6)
1608 // Format is: HTTP-Version SP Status-Code SP Reason-Phrase CRLF
1609 list($ret_struct['status']['http-version'],
1610 $ret_struct['status']['status-code'],
1611 $ret_struct['status']['reason-phrase']) = explode(' ', $lines[0],3);
1613 // print "HTTP Version: '$http_version' Status-Code: '$status_code' Reason Phrase: '$reason_phrase'<br>";
1614 // get the response header fields
1615 // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6
1616 for($i=1; $i<count($lines); $i++) {
1617 if (rtrim($lines[$i]) == '' && !$header_done) {
1618 $header_done = true;
1619 // print "--- response header end ---<br>";
1622 if (!$header_done ) {
1623 // store all found headers in array ...
1624 list($fieldname, $fieldvalue) = explode(':', $lines[$i]);
1625 // check if this header was allready set (apache 2.0 webdav module does this....).
1626 // If so we add the the value to the end the fieldvalue, separated by comma...
1627 if (empty($ret_struct['header'])) {
1628 $ret_struct['header'] = array();
1630 if (empty($ret_struct['header'][$fieldname])) {
1631 $ret_struct['header'][$fieldname] = trim($fieldvalue);
1632 } else {
1633 $ret_struct['header'][$fieldname] .= ',' . trim($fieldvalue);
1637 // print 'string len of response_body:'. strlen($response_body);
1638 // print '[' . htmlentities($response_body) . ']';
1639 $ret_struct['body'] = $this->_body;
1640 $this->_error_log('process_respond: ' . var_export($ret_struct,true));
1641 return $ret_struct;
1646 * Private method reopen
1648 * Reopens a socket, if 'connection: closed'-header was received from server.
1650 * Uses public method open.
1651 * @access private
1653 private function reopen() {
1654 // let's try to reopen a socket
1655 $this->_error_log('reopen a socket connection');
1656 return $this->open();
1661 * Private method translate_uri
1663 * translates an uri to raw url encoded string.
1664 * Removes any html entity in uri
1665 * @param string uri
1666 * @return string translated_uri
1667 * @access private
1669 private function translate_uri($uri) {
1670 // remove all html entities...
1671 $native_path = html_entity_decode($uri);
1672 $parts = explode('/', $native_path);
1673 for ($i = 0; $i < count($parts); $i++) {
1674 // check if part is allready utf8
1675 if (iconv('UTF-8', 'UTF-8', $parts[$i]) == $parts[$i]) {
1676 $parts[$i] = rawurlencode($parts[$i]);
1677 } else {
1678 $parts[$i] = rawurlencode(utf8_encode($parts[$i]));
1681 return implode('/', $parts);
1685 * Private method utf_decode_path
1687 * decodes a UTF-8 encoded string
1688 * @return string decodedstring
1689 * @access private
1691 private function utf_decode_path($path) {
1692 $fullpath = $path;
1693 if (iconv('UTF-8', 'UTF-8', $fullpath) == $fullpath) {
1694 $this->_error_log("filename is utf-8. Needs conversion...");
1695 $fullpath = utf8_decode($fullpath);
1697 return $fullpath;
1701 * Private method _error_log
1703 * a simple php error_log wrapper.
1704 * @param string err_string
1705 * @access private
1707 private function _error_log($err_string) {
1708 if ($this->_debug) {
1709 error_log($err_string);