3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * A Moodle-modified WebDAV client, based on
20 * webdav_client v0.1.5, a php based webdav client class.
21 * class webdav client. a php based nearly RFC 2518 conforming client.
23 * This class implements methods to get access to an webdav server.
24 * Most of the methods are returning boolean false on error, an integer status (http response status) on success
25 * or an array in case of a multistatus response (207) from the webdav server. Look at the code which keys are used in arrays.
26 * It's your responsibility to handle the webdav server responses in an proper manner.
27 * Please notice that all Filenames coming from or going to the webdav server should be UTF-8 encoded (see RFC 2518).
28 * This class tries to convert all you filenames into utf-8 when it's needed.
30 * Moodle modifications:
31 * * Moodle 3.4: Add support for OAuth 2 bearer token-based authentication
34 * @author Christian Juerges <christian.juerges@xwave.ch>, Xwave GmbH, Josefstr. 92, 8005 Zuerich - Switzerland
35 * @copyright (C) 2003/2004, Christian Juerges
36 * @license http://opensource.org/licenses/lgpl-license.php GNU Lesser General Public License
45 private $_debug = false;
48 private $_protocol = 'HTTP/1.1';
50 private $_socket = '';
52 private $_auth = false;
56 private $_socket_timeout = 5;
59 private $_user_agent = 'Moodle WebDav Client';
60 private $_crlf = "\r\n";
62 private $_resp_status;
67 private $_ls = array();
69 private $_ls_ref_cdata;
70 private $_delete = array();
72 private $_delete_ref_cdata;
73 private $_lock = array();
75 private $_lock_rec_cdata;
76 private $_null = NULL;
79 private $_connection_closed = false;
80 private $_maxheaderlenth = 65536;
81 private $_digestchallenge = null;
82 private $_cnonce = '';
86 * OAuth token used for bearer auth.
94 * Constructor - Initialise class variables
95 * @param string $server Hostname of the server to connect to
96 * @param string $user Username (for basic/digest auth, see $auth)
97 * @param string $pass Password (for basic/digest auth, see $auth)
98 * @param bool $auth Authentication type; one of ['basic', 'digest', 'bearer']
99 * @param string $socket Used protocol for fsockopen, usually: '' (empty) or 'ssl://'
100 * @param string $oauthtoken OAuth 2 bearer token (for bearer auth, see $auth)
102 public function __construct($server = '', $user = '', $pass = '', $auth = false, $socket = '', $oauthtoken = '') {
103 if (!empty($server)) {
104 $this->_server
= $server;
106 if (!empty($user) && !empty($pass)) {
110 $this->_auth
= $auth;
111 $this->_socket
= $socket;
112 if ($auth == 'bearer') {
113 $this->oauthtoken
= $oauthtoken;
116 public function __set($key, $value) {
117 $property = '_' . $key;
118 $this->$property = $value;
122 * Set which HTTP protocol will be used.
123 * Value 1 defines that HTTP/1.1 should be used (Keeps Connection to webdav server alive).
124 * Otherwise HTTP/1.0 will be used.
127 function set_protocol($version) {
129 $this->_protocol
= 'HTTP/1.1';
131 $this->_protocol
= 'HTTP/1.0';
136 * Convert ISO 8601 Date and Time Profile used in RFC 2518 to an unix timestamp.
138 * @param string iso8601
139 * @return unixtimestamp on sucess. Otherwise false.
141 function iso8601totime($iso8601) {
144 date-time = full-date "T" full-time
146 full-date = date-fullyear "-" date-month "-" date-mday
147 full-time = partial-time time-offset
149 date-fullyear = 4DIGIT
150 date-month = 2DIGIT ; 01-12
151 date-mday = 2DIGIT ; 01-28, 01-29, 01-30, 01-31 based on
153 time-hour = 2DIGIT ; 00-23
154 time-minute = 2DIGIT ; 00-59
155 time-second = 2DIGIT ; 00-59, 00-60 based on leap second rules
156 time-secfrac = "." 1*DIGIT
157 time-numoffset = ("+" / "-") time-hour ":" time-minute
158 time-offset = "Z" / time-numoffset
160 partial-time = time-hour ":" time-minute ":" time-second
165 /* [1] [2] [3] [4] [5] [6] */
166 if (preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z$/', $iso8601, $regs)) {
167 return mktime($regs[4],$regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
169 // to be done: regex for partial-time...apache webdav mod never returns partial-time
175 * Open's a socket to a webdav server
176 * @return bool true on success. Otherwise false.
179 // let's try to open a socket
180 $this->_error_log('open a socket connection');
181 $this->sock
= fsockopen($this->_socket
. $this->_server
, $this->_port
, $this->_errno
, $this->_errstr
, $this->_socket_timeout
);
182 core_php_time_limit
::raise(30);
183 if (is_resource($this->sock
)) {
184 socket_set_blocking($this->sock
, true);
185 $this->_connection_closed
= false;
186 $this->_error_log('socket is open: ' . $this->sock
);
189 $this->_error_log("$this->_errstr ($this->_errno)\n");
195 * Closes an open socket.
198 $this->_error_log('closing socket ' . $this->sock
);
199 $this->_connection_closed
= true;
204 * Check's if server is a webdav compliant server.
205 * True if server returns a DAV Element in Header and when
206 * schema 1,2 is supported.
207 * @return bool true if server is webdav server. Otherwise false.
209 function check_webdav() {
210 $resp = $this->options();
214 $this->_error_log($resp['header']['DAV']);
216 if (preg_match('/1,2/', $resp['header']['DAV'])) {
219 // otherwise return false
225 * Get options from webdav server.
226 * @return array with all header fields returned from webdav server. false if server does not speak http.
229 $this->header_unset();
230 $this->create_basic_request('OPTIONS');
231 $this->send_request();
232 $this->get_respond();
233 $response = $this->process_respond();
234 // validate the response ...
235 // check http-version
236 if ($response['status']['http-version'] == 'HTTP/1.1' ||
237 $response['status']['http-version'] == 'HTTP/1.0') {
240 $this->_error_log('Response was not even http');
246 * Public method mkcol
248 * Creates a new collection/directory on a webdav server
250 * @return int status code received as response from webdav server (see rfc 2518)
252 function mkcol($path) {
253 $this->_path
= $this->translate_uri($path);
254 $this->header_unset();
255 $this->create_basic_request('MKCOL');
256 $this->send_request();
257 $this->get_respond();
258 $response = $this->process_respond();
259 // validate the response ...
260 // check http-version
261 $http_version = $response['status']['http-version'];
262 if ($http_version == 'HTTP/1.1' ||
$http_version == 'HTTP/1.0') {
263 /** seems to be http ... proceed
264 * just return what server gave us
266 * 201 (Created) - The collection or structured resource was created in its entirety.
267 * 403 (Forbidden) - This indicates at least one of two conditions:
268 * 1) the server does not allow the creation of collections at the given location in its namespace, or
269 * 2) the parent collection of the Request-URI exists but cannot accept members.
270 * 405 (Method Not Allowed) - MKCOL can only be executed on a deleted/non-existent resource.
271 * 409 (Conflict) - A collection cannot be made at the Request-URI until one or more intermediate
272 * collections have been created.
273 * 415 (Unsupported Media Type)- The server does not support the request type of the body.
274 * 507 (Insufficient Storage) - The resource does not have sufficient space to record the state of the
275 * resource after the execution of this method.
277 return $response['status']['status-code'];
285 * Gets a file from a webdav collection.
286 * @param string $path the path to the file on the webdav server
287 * @param string &$buffer the buffer to store the data in
288 * @param resource $fp optional if included, the data is written directly to this resource and not to the buffer
289 * @return string|bool status code and &$buffer (by reference) with response data from server on success. False on error.
291 function get($path, &$buffer, $fp = null) {
292 $this->_path
= $this->translate_uri($path);
293 $this->header_unset();
294 $this->create_basic_request('GET');
295 $this->send_request();
296 $this->get_respond($fp);
297 $response = $this->process_respond();
299 $http_version = $response['status']['http-version'];
300 // validate the response
301 // check http-version
302 if ($http_version == 'HTTP/1.1' ||
$http_version == 'HTTP/1.0') {
303 // seems to be http ... proceed
304 // We expect a 200 code
305 if ($response['status']['status-code'] == 200 ) {
308 $this->_error_log('file created with ' . $stat['size'] . ' bytes.');
310 $this->_error_log('returning buffer with ' . strlen($response['body']) . ' bytes.');
311 $buffer = $response['body'];
314 return $response['status']['status-code'];
316 // ups: no http status was returned ?
323 * Puts a file into a collection.
324 * Data is putted as one chunk!
325 * @param string path, string data
326 * @return int status-code read from webdavserver. False on error.
328 function put($path, $data ) {
329 $this->_path
= $this->translate_uri($path);
330 $this->header_unset();
331 $this->create_basic_request('PUT');
332 // add more needed header information ...
333 $this->header_add('Content-length: ' . strlen($data));
334 $this->header_add('Content-type: application/octet-stream');
336 $this->send_request();
337 // send the rest (data)
338 fputs($this->sock
, $data);
339 $this->get_respond();
340 $response = $this->process_respond();
342 // validate the response
343 // check http-version
344 if ($response['status']['http-version'] == 'HTTP/1.1' ||
345 $response['status']['http-version'] == 'HTTP/1.0') {
346 // seems to be http ... proceed
347 // We expect a 200 or 204 status code
348 // see rfc 2068 - 9.6 PUT...
349 // print 'http ok<br>';
350 return $response['status']['status-code'];
352 // ups: no http status was returned ?
357 * Public method put_file
359 * Read a file as stream and puts it chunk by chunk into webdav server collection.
361 * Look at php documenation for legal filenames with fopen();
362 * The filename will be translated into utf-8 if not allready in utf-8.
364 * @param string targetpath, string filename
365 * @return int status code. False on error.
367 function put_file($path, $filename) {
368 // try to open the file ...
371 $handle = @fopen
($filename, 'r');
374 // $this->sock = pfsockopen ($this->_server, $this->_port, $this->_errno, $this->_errstr, $this->_socket_timeout);
375 $this->_path
= $this->translate_uri($path);
376 $this->header_unset();
377 $this->create_basic_request('PUT');
378 // add more needed header information ...
379 $this->header_add('Content-length: ' . filesize($filename));
380 $this->header_add('Content-type: application/octet-stream');
382 $this->send_request();
383 while (!feof($handle)) {
384 fputs($this->sock
,fgets($handle,4096));
387 $this->get_respond();
388 $response = $this->process_respond();
390 // validate the response
391 // check http-version
392 if ($response['status']['http-version'] == 'HTTP/1.1' ||
393 $response['status']['http-version'] == 'HTTP/1.0') {
394 // seems to be http ... proceed
395 // We expect a 200 or 204 status code
396 // see rfc 2068 - 9.6 PUT...
397 // print 'http ok<br>';
398 return $response['status']['status-code'];
400 // ups: no http status was returned ?
403 $this->_error_log('put_file: could not open ' . $filename);
410 * Public method get_file
412 * Gets a file from a collection into local filesystem.
415 * @param string $srcpath
416 * @param string $localpath
417 * @return bool true on success. false on error.
419 function get_file($srcpath, $localpath) {
421 $localpath = $this->utf_decode_path($localpath);
423 $handle = fopen($localpath, 'wb');
426 $ret = $this->get($srcpath, $unused, $handle);
436 * Public method copy_file
438 * Copies a file on a webdav server
440 * Duplicates a file on the webdav server (serverside).
441 * All work is done on the webdav server. If you set param overwrite as true,
442 * the target will be overwritten.
444 * @param string src_path, string dest_path, bool overwrite
445 * @return int status code (look at rfc 2518). false on error.
447 function copy_file($src_path, $dst_path, $overwrite) {
448 $this->_path
= $this->translate_uri($src_path);
449 $this->header_unset();
450 $this->create_basic_request('COPY');
451 $this->header_add(sprintf('Destination: http://%s%s', $this->_server
, $this->translate_uri($dst_path)));
453 $this->header_add('Overwrite: T');
455 $this->header_add('Overwrite: F');
457 $this->header_add('');
458 $this->send_request();
459 $this->get_respond();
460 $response = $this->process_respond();
461 // validate the response ...
462 // check http-version
463 if ($response['status']['http-version'] == 'HTTP/1.1' ||
464 $response['status']['http-version'] == 'HTTP/1.0') {
465 /* seems to be http ... proceed
466 just return what server gave us (as defined in rfc 2518) :
467 201 (Created) - The source resource was successfully copied. The copy operation resulted in the creation of a new resource.
468 204 (No Content) - The source resource was successfully copied to a pre-existing destination resource.
469 403 (Forbidden) - The source and destination URIs are the same.
470 409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created.
471 412 (Precondition Failed) - The server was unable to maintain the liveness of the properties listed in the propertybehavior XML element
472 or the Overwrite header is "F" and the state of the destination resource is non-null.
473 423 (Locked) - The destination resource was locked.
474 502 (Bad Gateway) - This may occur when the destination is on another server and the destination server refuses to accept the resource.
475 507 (Insufficient Storage) - The destination resource does not have sufficient space to record the state of the resource after the
476 execution of this method.
478 return $response['status']['status-code'];
484 * Public method copy_coll
486 * Copies a collection on a webdav server
488 * Duplicates a collection on the webdav server (serverside).
489 * All work is done on the webdav server. If you set param overwrite as true,
490 * the target will be overwritten.
492 * @param string src_path, string dest_path, bool overwrite
493 * @return int status code (look at rfc 2518). false on error.
495 function copy_coll($src_path, $dst_path, $overwrite) {
496 $this->_path
= $this->translate_uri($src_path);
497 $this->header_unset();
498 $this->create_basic_request('COPY');
499 $this->header_add(sprintf('Destination: http://%s%s', $this->_server
, $this->translate_uri($dst_path)));
500 $this->header_add('Depth: Infinity');
502 $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n";
503 $xml .= "<d:propertybehavior xmlns:d=\"DAV:\">\r\n";
504 $xml .= " <d:keepalive>*</d:keepalive>\r\n";
505 $xml .= "</d:propertybehavior>\r\n";
507 $this->header_add('Content-length: ' . strlen($xml));
508 $this->header_add('Content-type: application/xml');
509 $this->send_request();
511 fputs($this->sock
, $xml);
512 $this->get_respond();
513 $response = $this->process_respond();
514 // validate the response ...
515 // check http-version
516 if ($response['status']['http-version'] == 'HTTP/1.1' ||
517 $response['status']['http-version'] == 'HTTP/1.0') {
518 /* seems to be http ... proceed
519 just return what server gave us (as defined in rfc 2518) :
520 201 (Created) - The source resource was successfully copied. The copy operation resulted in the creation of a new resource.
521 204 (No Content) - The source resource was successfully copied to a pre-existing destination resource.
522 403 (Forbidden) - The source and destination URIs are the same.
523 409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created.
524 412 (Precondition Failed) - The server was unable to maintain the liveness of the properties listed in the propertybehavior XML element
525 or the Overwrite header is "F" and the state of the destination resource is non-null.
526 423 (Locked) - The destination resource was locked.
527 502 (Bad Gateway) - This may occur when the destination is on another server and the destination server refuses to accept the resource.
528 507 (Insufficient Storage) - The destination resource does not have sufficient space to record the state of the resource after the
529 execution of this method.
531 return $response['status']['status-code'];
539 * Moves a file or collection on webdav server (serverside)
541 * If you set param overwrite as true, the target will be overwritten.
543 * @param string src_path, string dest_path, bool overwrite
544 * @return int status code (look at rfc 2518). false on error.
546 // --------------------------------------------------------------------------
547 // public method move
548 // move/rename a file/collection on webdav server
549 function move($src_path,$dst_path, $overwrite) {
551 $this->_path
= $this->translate_uri($src_path);
552 $this->header_unset();
554 $this->create_basic_request('MOVE');
555 $this->header_add(sprintf('Destination: http://%s%s', $this->_server
, $this->translate_uri($dst_path)));
557 $this->header_add('Overwrite: T');
559 $this->header_add('Overwrite: F');
561 $this->header_add('');
563 $this->send_request();
564 $this->get_respond();
565 $response = $this->process_respond();
566 // validate the response ...
567 // check http-version
568 if ($response['status']['http-version'] == 'HTTP/1.1' ||
569 $response['status']['http-version'] == 'HTTP/1.0') {
570 /* seems to be http ... proceed
571 just return what server gave us (as defined in rfc 2518) :
572 201 (Created) - The source resource was successfully moved, and a new resource was created at the destination.
573 204 (No Content) - The source resource was successfully moved to a pre-existing destination resource.
574 403 (Forbidden) - The source and destination URIs are the same.
575 409 (Conflict) - A resource cannot be created at the destination until one or more intermediate collections have been created.
576 412 (Precondition Failed) - The server was unable to maintain the liveness of the properties listed in the propertybehavior XML element
577 or the Overwrite header is "F" and the state of the destination resource is non-null.
578 423 (Locked) - The source or the destination resource was locked.
579 502 (Bad Gateway) - This may occur when the destination is on another server and the destination server refuses to accept the resource.
581 201 (Created) - The collection or structured resource was created in its entirety.
582 403 (Forbidden) - This indicates at least one of two conditions: 1) the server does not allow the creation of collections at the given
583 location in its namespace, or 2) the parent collection of the Request-URI exists but cannot accept members.
584 405 (Method Not Allowed) - MKCOL can only be executed on a deleted/non-existent resource.
585 409 (Conflict) - A collection cannot be made at the Request-URI until one or more intermediate collections have been created.
586 415 (Unsupported Media Type)- The server does not support the request type of the body.
587 507 (Insufficient Storage) - The resource does not have sufficient space to record the state of the resource after the execution of this method.
589 return $response['status']['status-code'];
597 * Locks a file or collection.
599 * Lock uses this->_user as lock owner.
602 * @return int status code (look at rfc 2518). false on error.
604 function lock($path) {
605 $this->_path
= $this->translate_uri($path);
606 $this->header_unset();
607 $this->create_basic_request('LOCK');
608 $this->header_add('Timeout: Infinite');
609 $this->header_add('Content-type: text/xml');
610 // create the xml request ...
611 $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n";
612 $xml .= "<D:lockinfo xmlns:D='DAV:'\r\n>";
613 $xml .= " <D:lockscope><D:exclusive/></D:lockscope>\r\n";
614 $xml .= " <D:locktype><D:write/></D:locktype>\r\n";
615 $xml .= " <D:owner>\r\n";
616 $xml .= " <D:href>".($this->_user
)."</D:href>\r\n";
617 $xml .= " </D:owner>\r\n";
618 $xml .= "</D:lockinfo>\r\n";
619 $this->header_add('Content-length: ' . strlen($xml));
620 $this->send_request();
622 fputs($this->sock
, $xml);
623 $this->get_respond();
624 $response = $this->process_respond();
625 // validate the response ... (only basic validation)
626 // check http-version
627 if ($response['status']['http-version'] == 'HTTP/1.1' ||
628 $response['status']['http-version'] == 'HTTP/1.0') {
629 /* seems to be http ... proceed
631 200 (OK) - The lock request succeeded and the value of the lockdiscovery property is included in the body.
632 412 (Precondition Failed) - The included lock token was not enforceable on this resource or the server could not satisfy the
633 request in the lockinfo XML element.
634 423 (Locked) - The resource is locked, so the method has been rejected.
637 switch($response['status']['status-code']) {
639 // collection was successfully locked... see xml response to get lock token...
640 if (strcmp($response['header']['Content-Type'], 'text/xml; charset="utf-8"') == 0) {
641 // ok let's get the content of the xml stuff
642 $this->_parser
= xml_parser_create_ns();
643 $this->_parserid
= (int) $this->_parser
;
644 // forget old data...
645 unset($this->_lock
[$this->_parserid
]);
646 unset($this->_xmltree
[$this->_parserid
]);
647 xml_parser_set_option($this->_parser
,XML_OPTION_SKIP_WHITE
,0);
648 xml_parser_set_option($this->_parser
,XML_OPTION_CASE_FOLDING
,0);
649 xml_set_object($this->_parser
, $this);
650 xml_set_element_handler($this->_parser
, "_lock_startElement", "_endElement");
651 xml_set_character_data_handler($this->_parser
, "_lock_cdata");
653 if (!xml_parse($this->_parser
, $response['body'])) {
654 die(sprintf("XML error: %s at line %d",
655 xml_error_string(xml_get_error_code($this->_parser
)),
656 xml_get_current_line_number($this->_parser
)));
660 xml_parser_free($this->_parser
);
661 // add status code to array
662 $this->_lock
[$this->_parserid
]['status'] = 200;
663 return $this->_lock
[$this->_parserid
];
666 print 'Missing Content-Type: text/xml header in response.<br>';
671 // hmm. not what we expected. Just return what we got from webdav server
672 // someone else has to handle it.
673 $this->_lock
['status'] = $response['status']['status-code'];
683 * Public method unlock
685 * Unlocks a file or collection.
687 * @param string path, string locktoken
688 * @return int status code (look at rfc 2518). false on error.
690 function unlock($path, $locktoken) {
691 $this->_path
= $this->translate_uri($path);
692 $this->header_unset();
693 $this->create_basic_request('UNLOCK');
694 $this->header_add(sprintf('Lock-Token: <%s>', $locktoken));
695 $this->send_request();
696 $this->get_respond();
697 $response = $this->process_respond();
698 if ($response['status']['http-version'] == 'HTTP/1.1' ||
699 $response['status']['http-version'] == 'HTTP/1.0') {
700 /* seems to be http ... proceed
702 204 (OK) - The 204 (No Content) status code is used instead of 200 (OK) because there is no response entity body.
704 return $response['status']['status-code'];
710 * Public method delete
712 * deletes a collection/directory on a webdav server
714 * @return int status code (look at rfc 2518). false on error.
716 function delete($path) {
717 $this->_path
= $this->translate_uri($path);
718 $this->header_unset();
719 $this->create_basic_request('DELETE');
720 /* $this->header_add('Content-Length: 0'); */
721 $this->header_add('');
722 $this->send_request();
723 $this->get_respond();
724 $response = $this->process_respond();
726 // validate the response ...
727 // check http-version
728 if ($response['status']['http-version'] == 'HTTP/1.1' ||
729 $response['status']['http-version'] == 'HTTP/1.0') {
730 // seems to be http ... proceed
731 // We expect a 207 Multi-Status status code
732 // print 'http ok<br>';
734 switch ($response['status']['status-code']) {
736 // collection was NOT deleted... see xml response for reason...
737 // next there should be a Content-Type: text/xml; charset="utf-8" header line
738 if (strcmp($response['header']['Content-Type'], 'text/xml; charset="utf-8"') == 0) {
739 // ok let's get the content of the xml stuff
740 $this->_parser
= xml_parser_create_ns();
741 $this->_parserid
= (int) $this->_parser
;
742 // forget old data...
743 unset($this->_delete
[$this->_parserid
]);
744 unset($this->_xmltree
[$this->_parserid
]);
745 xml_parser_set_option($this->_parser
,XML_OPTION_SKIP_WHITE
,0);
746 xml_parser_set_option($this->_parser
,XML_OPTION_CASE_FOLDING
,0);
747 xml_set_object($this->_parser
, $this);
748 xml_set_element_handler($this->_parser
, "_delete_startElement", "_endElement");
749 xml_set_character_data_handler($this->_parser
, "_delete_cdata");
751 if (!xml_parse($this->_parser
, $response['body'])) {
752 die(sprintf("XML error: %s at line %d",
753 xml_error_string(xml_get_error_code($this->_parser
)),
754 xml_get_current_line_number($this->_parser
)));
760 xml_parser_free($this->_parser
);
761 $this->_delete
[$this->_parserid
]['status'] = $response['status']['status-code'];
762 return $this->_delete
[$this->_parserid
];
765 print 'Missing Content-Type: text/xml header in response.<br>';
770 // collection or file was successfully deleted
771 $this->_delete
['status'] = $response['status']['status-code'];
772 return $this->_delete
;
783 * Get's directory information from webdav server into flat a array using PROPFIND
785 * All filenames are UTF-8 encoded.
786 * Have a look at _propfind_startElement what keys are used in array returned.
788 * @return array dirinfo, false on error
792 if (trim($path) == '') {
793 $this->_error_log('Missing a path in method ls');
796 $this->_path
= $this->translate_uri($path);
798 $this->header_unset();
799 $this->create_basic_request('PROPFIND');
800 $this->header_add('Depth: 1');
801 $this->header_add('Content-type: application/xml');
802 // create profind xml request...
804 <?xml version="1.0" encoding="utf-8"?>
805 <propfind xmlns="DAV:"><prop>
806 <getcontentlength xmlns="DAV:"/>
807 <getlastmodified xmlns="DAV:"/>
808 <executable xmlns="http://apache.org/dav/props/"/>
809 <resourcetype xmlns="DAV:"/>
810 <checked-in xmlns="DAV:"/>
811 <checked-out xmlns="DAV:"/>
814 $this->header_add('Content-length: ' . strlen($xml));
815 $this->send_request();
816 $this->_error_log($xml);
817 fputs($this->sock
, $xml);
818 $this->get_respond();
819 $response = $this->process_respond();
820 // validate the response ... (only basic validation)
821 // check http-version
822 if ($response['status']['http-version'] == 'HTTP/1.1' ||
823 $response['status']['http-version'] == 'HTTP/1.0') {
824 // seems to be http ... proceed
825 // We expect a 207 Multi-Status status code
826 // print 'http ok<br>';
827 if (strcmp($response['status']['status-code'],'207') == 0 ) {
829 // next there should be a Content-Type: text/xml; charset="utf-8" header line
830 if (preg_match('#(application|text)/xml;\s?charset=[\'\"]?utf-8[\'\"]?#i', $response['header']['Content-Type'])) {
831 // ok let's get the content of the xml stuff
832 $this->_parser
= xml_parser_create_ns('UTF-8');
833 $this->_parserid
= (int) $this->_parser
;
834 // forget old data...
835 unset($this->_ls
[$this->_parserid
]);
836 unset($this->_xmltree
[$this->_parserid
]);
837 xml_parser_set_option($this->_parser
,XML_OPTION_SKIP_WHITE
,0);
838 xml_parser_set_option($this->_parser
,XML_OPTION_CASE_FOLDING
,0);
839 // xml_parser_set_option($this->_parser,XML_OPTION_TARGET_ENCODING,'UTF-8');
840 xml_set_object($this->_parser
, $this);
841 xml_set_element_handler($this->_parser
, "_propfind_startElement", "_endElement");
842 xml_set_character_data_handler($this->_parser
, "_propfind_cdata");
845 if (!xml_parse($this->_parser
, $response['body'])) {
846 die(sprintf("XML error: %s at line %d",
847 xml_error_string(xml_get_error_code($this->_parser
)),
848 xml_get_current_line_number($this->_parser
)));
852 xml_parser_free($this->_parser
);
853 $arr = $this->_ls
[$this->_parserid
];
856 $this->_error_log('Missing Content-Type: text/xml header in response!!');
860 // return status code ...
861 return $response['status']['status-code'];
865 // response was not http
866 $this->_error_log('Ups in method ls: error in response from server');
874 * Get's path information from webdav server for one element.
877 * @return array dirinfo. false on error
879 function gpi($path) {
881 // split path by last "/"
882 $path = rtrim($path, "/");
883 $item = basename($path);
884 $dir = dirname($path);
886 $list = $this->ls($dir);
888 // be sure it is an array
889 if (is_array($list)) {
890 foreach($list as $e) {
892 $fullpath = urldecode($e['href']);
893 $filename = basename($fullpath);
895 if ($filename == $item && $filename != "" and $fullpath != $dir."/") {
904 * Public method is_file
906 * Gathers whether a path points to a file or not.
909 * @return bool true or false
911 function is_file($path) {
913 $item = $this->gpi($path);
915 if ($item === false) {
918 return ($item['resourcetype'] != 'collection');
923 * Public method is_dir
925 * Gather whether a path points to a directory
927 * return bool true or false
929 function is_dir($path) {
931 // be sure path is utf-8
932 $item = $this->gpi($path);
934 if ($item === false) {
937 return ($item['resourcetype'] == 'collection');
945 * Puts multiple files and/or directories onto a webdav server.
947 * Filenames should be allready UTF-8 encoded.
948 * Param fileList must be in format array("localpath" => "destpath").
950 * @param array filelist
951 * @return bool true on success. otherwise int status code on error
953 function mput($filelist) {
957 foreach ($filelist as $localpath => $destpath) {
959 $localpath = rtrim($localpath, "/");
960 $destpath = rtrim($destpath, "/");
962 // attempt to create target path
963 if (is_dir($localpath)) {
964 $pathparts = explode("/", $destpath."/ "); // add one level, last level will be created as dir
966 $pathparts = explode("/", $destpath);
969 for ($i=1; $i<sizeof($pathparts)-1; $i++
) {
970 $checkpath .= "/" . $pathparts[$i];
971 if (!($this->is_dir($checkpath))) {
973 $result &= ($this->mkcol($checkpath) == 201 );
978 // recurse directories
979 if (is_dir($localpath)) {
980 if (!$dp = opendir($localpath)) {
981 $this->_error_log("Could not open localpath for reading");
985 while($filename = readdir($dp)) {
986 if ((is_file($localpath."/".$filename) ||
is_dir($localpath."/".$filename)) && $filename!="." && $filename != "..") {
987 $fl[$localpath."/".$filename] = $destpath."/".$filename;
990 $result &= $this->mput($fl);
992 $result &= ($this->put_file($destpath, $localpath) == 201);
1000 * Public method mget
1002 * Gets multiple files and directories.
1004 * FileList must be in format array("remotepath" => "localpath").
1005 * Filenames are UTF-8 encoded.
1007 * @param array filelist
1008 * @return bool true on succes, other int status code on error
1010 function mget($filelist) {
1014 foreach ($filelist as $remotepath => $localpath) {
1016 $localpath = rtrim($localpath, "/");
1017 $remotepath = rtrim($remotepath, "/");
1019 // attempt to create local path
1020 if ($this->is_dir($remotepath)) {
1021 $pathparts = explode("/", $localpath."/ "); // add one level, last level will be created as dir
1023 $pathparts = explode("/", $localpath);
1026 for ($i=1; $i<sizeof($pathparts)-1; $i++
) {
1027 $checkpath .= "/" . $pathparts[$i];
1028 if (!is_dir($checkpath)) {
1030 $result &= mkdir($checkpath);
1035 // recurse directories
1036 if ($this->is_dir($remotepath)) {
1037 $list = $this->ls($remotepath);
1040 foreach($list as $e) {
1041 $fullpath = urldecode($e['href']);
1042 $filename = basename($fullpath);
1043 if ($filename != '' and $fullpath != $remotepath . '/') {
1044 $fl[$remotepath."/".$filename] = $localpath."/".$filename;
1047 $result &= $this->mget($fl);
1049 $result &= ($this->get_file($remotepath, $localpath));
1056 // --------------------------------------------------------------------------
1057 // private xml callback and helper functions starting here
1058 // --------------------------------------------------------------------------
1062 * Private method _endelement
1064 * a generic endElement method (used for all xml callbacks).
1066 * @param resource parser, string name
1070 private function _endElement($parser, $name) {
1071 // end tag was found...
1072 $parserid = (int) $parser;
1073 $this->_xmltree
[$parserid] = substr($this->_xmltree
[$parserid],0, strlen($this->_xmltree
[$parserid]) - (strlen($name) +
1));
1077 * Private method _propfind_startElement
1079 * Is needed by public method ls.
1081 * Generic method will called by php xml_parse when a xml start element tag has been detected.
1082 * The xml tree will translated into a flat php array for easier access.
1083 * @param resource parser, string name, string attrs
1086 private function _propfind_startElement($parser, $name, $attrs) {
1087 // lower XML Names... maybe break a RFC, don't know ...
1088 $parserid = (int) $parser;
1090 $propname = strtolower($name);
1091 if (!empty($this->_xmltree
[$parserid])) {
1092 $this->_xmltree
[$parserid] .= $propname . '_';
1094 $this->_xmltree
[$parserid] = $propname . '_';
1097 // translate xml tree to a flat array ...
1098 switch($this->_xmltree
[$parserid]) {
1099 case 'dav::multistatus_dav::response_':
1100 // new element in mu
1101 $this->_ls_ref
=& $this->_ls
[$parserid][];
1103 case 'dav::multistatus_dav::response_dav::href_':
1104 $this->_ls_ref_cdata
= &$this->_ls_ref
['href'];
1106 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::creationdate_':
1107 $this->_ls_ref_cdata
= &$this->_ls_ref
['creationdate'];
1109 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getlastmodified_':
1110 $this->_ls_ref_cdata
= &$this->_ls_ref
['lastmodified'];
1112 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getcontenttype_':
1113 $this->_ls_ref_cdata
= &$this->_ls_ref
['getcontenttype'];
1115 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getcontentlength_':
1116 $this->_ls_ref_cdata
= &$this->_ls_ref
['getcontentlength'];
1118 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_':
1119 $this->_ls_ref_cdata
= &$this->_ls_ref
['activelock_depth'];
1121 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_':
1122 $this->_ls_ref_cdata
= &$this->_ls_ref
['activelock_owner'];
1124 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_':
1125 $this->_ls_ref_cdata
= &$this->_ls_ref
['activelock_owner'];
1127 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_':
1128 $this->_ls_ref_cdata
= &$this->_ls_ref
['activelock_timeout'];
1130 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_':
1131 $this->_ls_ref_cdata
= &$this->_ls_ref
['activelock_token'];
1133 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::lockdiscovery_dav::activelock_dav::locktype_dav::write_':
1134 $this->_ls_ref_cdata
= &$this->_ls_ref
['activelock_type'];
1135 $this->_ls_ref_cdata
= 'write';
1136 $this->_ls_ref_cdata
= &$this->_null
;
1138 case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::resourcetype_dav::collection_':
1139 $this->_ls_ref_cdata
= &$this->_ls_ref
['resourcetype'];
1140 $this->_ls_ref_cdata
= 'collection';
1141 $this->_ls_ref_cdata
= &$this->_null
;
1143 case 'dav::multistatus_dav::response_dav::propstat_dav::status_':
1144 $this->_ls_ref_cdata
= &$this->_ls_ref
['status'];
1148 // handle unknown xml elements...
1149 $this->_ls_ref_cdata
= &$this->_ls_ref
[$this->_xmltree
[$parserid]];
1154 * Private method _propfind_cData
1156 * Is needed by public method ls.
1158 * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
1159 * Stores data found into class var _ls_ref_cdata
1160 * @param resource parser, string cdata
1163 private function _propfind_cData($parser, $cdata) {
1164 if (trim($cdata) <> '') {
1165 // cdata must be appended, because sometimes the php xml parser makes multiple calls
1166 // to _propfind_cData before the xml end tag was reached...
1167 $this->_ls_ref_cdata
.= $cdata;
1174 * Private method _delete_startElement
1176 * Is used by public method delete.
1178 * Will be called by php xml_parse.
1179 * @param resource parser, string name, string attrs)
1182 private function _delete_startElement($parser, $name, $attrs) {
1183 // lower XML Names... maybe break a RFC, don't know ...
1184 $parserid = (int) $parser;
1185 $propname = strtolower($name);
1186 $this->_xmltree
[$parserid] .= $propname . '_';
1188 // translate xml tree to a flat array ...
1189 switch($this->_xmltree
[$parserid]) {
1190 case 'dav::multistatus_dav::response_':
1191 // new element in mu
1192 $this->_delete_ref
=& $this->_delete
[$parserid][];
1194 case 'dav::multistatus_dav::response_dav::href_':
1195 $this->_delete_ref_cdata
= &$this->_ls_ref
['href'];
1199 // handle unknown xml elements...
1200 $this->_delete_cdata
= &$this->_delete_ref
[$this->_xmltree
[$parserid]];
1206 * Private method _delete_cData
1208 * Is used by public method delete.
1210 * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
1211 * Stores data found into class var _delete_ref_cdata
1212 * @param resource parser, string cdata
1215 private function _delete_cData($parser, $cdata) {
1216 if (trim($cdata) <> '') {
1217 $this->_delete_ref_cdata
.= $cdata;
1225 * Private method _lock_startElement
1227 * Is needed by public method lock.
1229 * Mmethod will called by php xml_parse when a xml start element tag has been detected.
1230 * The xml tree will translated into a flat php array for easier access.
1231 * @param resource parser, string name, string attrs
1234 private function _lock_startElement($parser, $name, $attrs) {
1235 // lower XML Names... maybe break a RFC, don't know ...
1236 $parserid = (int) $parser;
1237 $propname = strtolower($name);
1238 $this->_xmltree
[$parserid] .= $propname . '_';
1240 // translate xml tree to a flat array ...
1242 dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_=
1243 dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_=
1244 dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_=
1245 dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_=
1247 switch($this->_xmltree
[$parserid]) {
1248 case 'dav::prop_dav::lockdiscovery_dav::activelock_':
1250 $this->_lock_ref
=& $this->_lock
[$parserid][];
1252 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::locktype_dav::write_':
1253 $this->_lock_ref_cdata
= &$this->_lock_ref
['locktype'];
1254 $this->_lock_cdata
= 'write';
1255 $this->_lock_cdata
= &$this->_null
;
1257 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::lockscope_dav::exclusive_':
1258 $this->_lock_ref_cdata
= &$this->_lock_ref
['lockscope'];
1259 $this->_lock_ref_cdata
= 'exclusive';
1260 $this->_lock_ref_cdata
= &$this->_null
;
1262 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_':
1263 $this->_lock_ref_cdata
= &$this->_lock_ref
['depth'];
1265 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_':
1266 $this->_lock_ref_cdata
= &$this->_lock_ref
['owner'];
1268 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_':
1269 $this->_lock_ref_cdata
= &$this->_lock_ref
['timeout'];
1271 case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_':
1272 $this->_lock_ref_cdata
= &$this->_lock_ref
['locktoken'];
1275 // handle unknown xml elements...
1276 $this->_lock_cdata
= &$this->_lock_ref
[$this->_xmltree
[$parserid]];
1282 * Private method _lock_cData
1284 * Is used by public method lock.
1286 * Will be called by php xml_set_character_data_handler() when xml data has to be handled.
1287 * Stores data found into class var _lock_ref_cdata
1288 * @param resource parser, string cdata
1291 private function _lock_cData($parser, $cdata) {
1292 $parserid = (int) $parser;
1293 if (trim($cdata) <> '') {
1294 // $this->_error_log(($this->_xmltree[$parserid]) . '='. htmlentities($cdata));
1295 $this->_lock_ref_cdata
.= $cdata;
1303 * Private method header_add
1305 * extends class var array _req
1306 * @param string string
1309 private function header_add($string) {
1310 $this->_req
[] = $string;
1314 * Private method header_unset
1316 * unsets class var array _req
1320 private function header_unset() {
1325 * Private method create_basic_request
1327 * creates by using private method header_add an general request header.
1328 * @param string method
1331 private function create_basic_request($method) {
1332 $this->header_add(sprintf('%s %s %s', $method, $this->_path
, $this->_protocol
));
1333 $this->header_add(sprintf('Host: %s:%s', $this->_server
, $this->_port
));
1334 //$request .= sprintf('Connection: Keep-Alive');
1335 $this->header_add(sprintf('User-Agent: %s', $this->_user_agent
));
1336 $this->header_add('Connection: TE');
1337 $this->header_add('TE: Trailers');
1338 if ($this->_auth
== 'basic') {
1339 $this->header_add(sprintf('Authorization: Basic %s', base64_encode("$this->_user:$this->_pass")));
1340 } else if ($this->_auth
== 'digest') {
1341 if ($signature = $this->digest_signature($method)){
1342 $this->header_add($signature);
1344 } else if ($this->_auth
== 'bearer') {
1345 $this->header_add(sprintf('Authorization: Bearer %s', $this->oauthtoken
));
1350 * Reads the header, stores the challenge information
1354 private function digest_auth() {
1357 $headers[] = sprintf('%s %s %s', 'HEAD', $this->_path
, $this->_protocol
);
1358 $headers[] = sprintf('Host: %s:%s', $this->_server
, $this->_port
);
1359 $headers[] = sprintf('User-Agent: %s', $this->_user_agent
);
1360 $headers = implode("\r\n", $headers);
1361 $headers .= "\r\n\r\n";
1362 fputs($this->sock
, $headers);
1364 // Reads the headers.
1368 $header .= fread($this->sock
, 1);
1370 } while (!preg_match('/\\r\\n\\r\\n$/', $header, $matches) && $i < $this->_maxheaderlenth
);
1372 // Analyse the headers.
1374 $splitheaders = explode("\r\n", $header);
1375 foreach ($splitheaders as $line) {
1376 if (!preg_match('/^WWW-Authenticate: Digest/', $line)) {
1379 $line = substr($line, strlen('WWW-Authenticate: Digest '));
1380 $params = explode(',', $line);
1381 foreach ($params as $param) {
1382 list($key, $value) = explode('=', trim($param), 2);
1383 $digest[$key] = trim($value, '"');
1388 $this->_digestchallenge
= $digest;
1392 * Generates the digest signature
1394 * @return string signature to add to the headers
1397 private function digest_signature($method) {
1398 if (!$this->_digestchallenge
) {
1399 $this->digest_auth();
1402 $signature = array();
1403 $signature['username'] = '"' . $this->_user
. '"';
1404 $signature['realm'] = '"' . $this->_digestchallenge
['realm'] . '"';
1405 $signature['nonce'] = '"' . $this->_digestchallenge
['nonce'] . '"';
1406 $signature['uri'] = '"' . $this->_path
. '"';
1408 if (isset($this->_digestchallenge
['algorithm']) && $this->_digestchallenge
['algorithm'] != 'MD5') {
1409 $this->_error_log('Algorithm other than MD5 are not supported');
1413 $a1 = $this->_user
. ':' . $this->_digestchallenge
['realm'] . ':' . $this->_pass
;
1414 $a2 = $method . ':' . $this->_path
;
1416 if (!isset($this->_digestchallenge
['qop'])) {
1417 $signature['response'] = '"' . md5(md5($a1) . ':' . $this->_digestchallenge
['nonce'] . ':' . md5($a2)) . '"';
1419 // Assume QOP is auth
1420 if (empty($this->_cnonce
)) {
1421 $this->_cnonce
= random_string();
1425 $nc = sprintf('%08d', $this->_nc
);
1426 $signature['cnonce'] = '"' . $this->_cnonce
. '"';
1427 $signature['nc'] = '"' . $nc . '"';
1428 $signature['qop'] = '"' . $this->_digestchallenge
['qop'] . '"';
1429 $signature['response'] = '"' . md5(md5($a1) . ':' . $this->_digestchallenge
['nonce'] . ':' .
1430 $nc . ':' . $this->_cnonce
. ':' . $this->_digestchallenge
['qop'] . ':' . md5($a2)) . '"';
1433 $response = array();
1434 foreach ($signature as $key => $value) {
1435 $response[] = "$key=$value";
1437 return 'Authorization: Digest ' . implode(', ', $response);
1441 * Private method send_request
1443 * Sends a ready formed http/webdav request to webdav server.
1447 private function send_request() {
1448 // check if stream is declared to be open
1449 // only logical check we are not sure if socket is really still open ...
1450 if ($this->_connection_closed
) {
1452 // be sure to close the open socket.
1457 // convert array to string
1458 $buffer = implode("\r\n", $this->_req
);
1459 $buffer .= "\r\n\r\n";
1460 $this->_error_log($buffer);
1461 fputs($this->sock
, $buffer);
1465 * Private method get_respond
1467 * Reads the response from the webdav server.
1469 * Stores data into class vars _header for the header data and
1470 * _body for the rest of the response.
1471 * This routine is the weakest part of this class, because it very depends how php does handle a socket stream.
1472 * If the stream is blocked for some reason php is blocked as well.
1474 * @param resource $fp optional the file handle to write the body content to (stored internally in the '_body' if not set)
1476 private function get_respond($fp = null) {
1477 $this->_error_log('get_respond()');
1478 // init vars (good coding style ;-)
1481 // attention: do not make max_chunk_size to big....
1482 $max_chunk_size = 8192;
1483 // be sure we got a open ressource
1484 if (! $this->sock
) {
1485 $this->_error_log('socket is not open. Can not process response');
1489 // following code maybe helps to improve socket behaviour ... more testing needed
1490 // disabled at the moment ...
1491 // socket_set_timeout($this->sock,1 );
1492 // $socket_state = socket_get_status($this->sock);
1494 // read stream one byte by another until http header ends
1498 $header.=fread($this->sock
, 1);
1500 } while (!preg_match('/\\r\\n\\r\\n$/',$header, $matches) && $i < $this->_maxheaderlenth
);
1502 $this->_error_log($header);
1504 if (preg_match('/Connection: close\\r\\n/', $header)) {
1505 // This says that the server will close connection at the end of this stream.
1506 // Therefore we need to reopen the socket, before are sending the next request...
1507 $this->_error_log('Connection: close found');
1508 $this->_connection_closed
= true;
1509 } else if (preg_match('@^HTTP/1\.(1|0) 401 @', $header)) {
1510 $this->_error_log('The server requires an authentication');
1513 // check how to get the data on socket stream
1514 // chunked or content-length (HTTP/1.1) or
1515 // one block until feof is received (HTTP/1.0)
1517 case (preg_match('/Transfer\\-Encoding:\\s+chunked\\r\\n/',$header)):
1518 $this->_error_log('Getting HTTP/1.1 chunked data...');
1524 $byte=fread($this->sock
,1);
1525 // check what happens while reading, because I do not really understand how php reads the socketstream...
1526 // but so far - it seems to work here - tested with php v4.3.1 on apache 1.3.27 and Debian Linux 3.0 ...
1527 if (strlen($byte) == 0) {
1528 $this->_error_log('get_respond: warning --> read zero bytes');
1530 } while ($byte!="\r" and strlen($byte)>0); // till we match the Carriage Return
1531 fread($this->sock
, 1); // also drop off the Line Feed
1532 $chunk_size=hexdec($chunk_size); // convert to a number in decimal system
1533 if ($chunk_size > 0) {
1535 // Reading the chunk in one bite is not secure, we read it byte by byte.
1536 while ($read < $chunk_size) {
1537 $chunk = fread($this->sock
, 1);
1538 self
::update_file_or_buffer($chunk, $fp, $buffer);
1542 fread($this->sock
, 2); // ditch the CRLF that trails the chunk
1543 } while ($chunk_size); // till we reach the 0 length chunk (end marker)
1546 // check for a specified content-length
1547 case preg_match('/Content\\-Length:\\s+([0-9]*)\\r\\n/',$header,$matches):
1548 $this->_error_log('Getting data using Content-Length '. $matches[1]);
1550 // check if we the content data size is small enough to get it as one block
1551 if ($matches[1] <= $max_chunk_size ) {
1552 // only read something if Content-Length is bigger than 0
1553 if ($matches[1] > 0 ) {
1554 $chunk = fread($this->sock
, $matches[1]);
1555 $loadsize = strlen($chunk);
1556 //did we realy get the full length?
1557 if ($loadsize < $matches[1]) {
1558 $max_chunk_size = $loadsize;
1560 $mod = $max_chunk_size %
($matches[1] - strlen($chunk));
1561 $chunk_size = ($mod == $max_chunk_size ?
$max_chunk_size : $matches[1] - strlen($chunk));
1562 $chunk .= fread($this->sock
, $chunk_size);
1563 $this->_error_log('mod: ' . $mod . ' chunk: ' . $chunk_size . ' total: ' . strlen($chunk));
1564 } while ($mod == $max_chunk_size);
1566 self
::update_file_or_buffer($chunk, $fp, $buffer);
1574 // data is to big to handle it as one. Get it chunk per chunk...
1575 //trying to get the full length of max_chunk_size
1576 $chunk = fread($this->sock
, $max_chunk_size);
1577 $loadsize = strlen($chunk);
1578 self
::update_file_or_buffer($chunk, $fp, $buffer);
1579 if ($loadsize < $max_chunk_size) {
1580 $max_chunk_size = $loadsize;
1583 $mod = $max_chunk_size %
($matches[1] - $loadsize);
1584 $chunk_size = ($mod == $max_chunk_size ?
$max_chunk_size : $matches[1] - $loadsize);
1585 $chunk = fread($this->sock
, $chunk_size);
1586 self
::update_file_or_buffer($chunk, $fp, $buffer);
1587 $loadsize +
= strlen($chunk);
1588 $this->_error_log('mod: ' . $mod . ' chunk: ' . $chunk_size . ' total: ' . $loadsize);
1589 } while ($mod == $max_chunk_size);
1590 if ($loadsize < $matches[1]) {
1591 $chunk = fread($this->sock
, $matches[1] - $loadsize);
1592 self
::update_file_or_buffer($chunk, $fp, $buffer);
1596 // check for 204 No Content
1597 // 204 responds have no body.
1598 // Therefore we do not need to read any data from socket stream.
1599 case preg_match('/HTTP\/1\.1\ 204/',$header):
1600 // nothing to do, just proceed
1601 $this->_error_log('204 No Content found. No further data to read..');
1604 // just get the data until foef appears...
1605 $this->_error_log('reading until feof...' . $header);
1606 socket_set_timeout($this->sock
, 0, 0);
1607 while (!feof($this->sock
)) {
1608 $chunk = fread($this->sock
, 4096);
1609 self
::update_file_or_buffer($chunk, $fp, $buffer);
1611 // renew the socket timeout...does it do something ???? Is it needed. More debugging needed...
1612 socket_set_timeout($this->sock
, $this->_socket_timeout
, 0);
1615 $this->_header
= $header;
1616 $this->_body
= $buffer;
1617 // $this->_buffer = $header . "\r\n\r\n" . $buffer;
1618 $this->_error_log($this->_header
);
1619 $this->_error_log($this->_body
);
1624 * Write the chunk to the file if $fp is set, otherwise append the data to the buffer
1625 * @param string $chunk the data to add
1626 * @param resource $fp the file handle to write to (or null)
1627 * @param string &$buffer the buffer to append to (if $fp is null)
1629 static private function update_file_or_buffer($chunk, $fp, &$buffer) {
1631 fwrite($fp, $chunk);
1638 * Private method process_respond
1640 * Processes the webdav server respond and detects its components (header, body).
1641 * and returns data array structure.
1642 * @return array ret_struct
1645 private function process_respond() {
1646 $lines = explode("\r\n", $this->_header
);
1647 $header_done = false;
1648 // $this->_error_log($this->_buffer);
1649 // First line should be a HTTP status line (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6)
1650 // Format is: HTTP-Version SP Status-Code SP Reason-Phrase CRLF
1651 list($ret_struct['status']['http-version'],
1652 $ret_struct['status']['status-code'],
1653 $ret_struct['status']['reason-phrase']) = explode(' ', $lines[0],3);
1655 // print "HTTP Version: '$http_version' Status-Code: '$status_code' Reason Phrase: '$reason_phrase'<br>";
1656 // get the response header fields
1657 // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6
1658 for($i=1; $i<count($lines); $i++
) {
1659 if (rtrim($lines[$i]) == '' && !$header_done) {
1660 $header_done = true;
1661 // print "--- response header end ---<br>";
1664 if (!$header_done ) {
1665 // store all found headers in array ...
1666 list($fieldname, $fieldvalue) = explode(':', $lines[$i]);
1667 // check if this header was allready set (apache 2.0 webdav module does this....).
1668 // If so we add the the value to the end the fieldvalue, separated by comma...
1669 if (empty($ret_struct['header'])) {
1670 $ret_struct['header'] = array();
1672 if (empty($ret_struct['header'][$fieldname])) {
1673 $ret_struct['header'][$fieldname] = trim($fieldvalue);
1675 $ret_struct['header'][$fieldname] .= ',' . trim($fieldvalue);
1679 // print 'string len of response_body:'. strlen($response_body);
1680 // print '[' . htmlentities($response_body) . ']';
1681 $ret_struct['body'] = $this->_body
;
1682 $this->_error_log('process_respond: ' . var_export($ret_struct,true));
1688 * Private method reopen
1690 * Reopens a socket, if 'connection: closed'-header was received from server.
1692 * Uses public method open.
1695 private function reopen() {
1696 // let's try to reopen a socket
1697 $this->_error_log('reopen a socket connection');
1698 return $this->open();
1703 * Private method translate_uri
1705 * translates an uri to raw url encoded string.
1706 * Removes any html entity in uri
1708 * @return string translated_uri
1711 private function translate_uri($uri) {
1712 // remove all html entities...
1713 $native_path = html_entity_decode($uri);
1714 $parts = explode('/', $native_path);
1715 for ($i = 0; $i < count($parts); $i++
) {
1716 // check if part is allready utf8
1717 if (iconv('UTF-8', 'UTF-8', $parts[$i]) == $parts[$i]) {
1718 $parts[$i] = rawurlencode($parts[$i]);
1720 $parts[$i] = rawurlencode(utf8_encode($parts[$i]));
1723 return implode('/', $parts);
1727 * Private method utf_decode_path
1729 * decodes a UTF-8 encoded string
1730 * @return string decodedstring
1733 private function utf_decode_path($path) {
1735 if (iconv('UTF-8', 'UTF-8', $fullpath) == $fullpath) {
1736 $this->_error_log("filename is utf-8. Needs conversion...");
1737 $fullpath = utf8_decode($fullpath);
1743 * Private method _error_log
1745 * a simple php error_log wrapper.
1746 * @param string err_string
1749 private function _error_log($err_string) {
1750 if ($this->_debug
) {
1751 error_log($err_string);