1<?php
2
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.
14//
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/>.
17
18/**
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.
22 *
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.
29 *
30 * Moodle modifications:
31 * * Moodle 3.4: Add support for OAuth 2 bearer token-based authentication
32 *
33 * @package moodlecore
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
37 */
38
39class webdav_client {
40
41    /**#@+
42     * @access private
43     * @var string
44     */
45    private $_debug = false;
46    private $sock;
47    private $_server;
48    private $_protocol = 'HTTP/1.1';
49    private $_port = 80;
50    private $_socket = '';
51    private $_path ='/';
52    private $_auth = false;
53    private $_user;
54    private $_pass;
55
56    private $_socket_timeout = 5;
57    private $_errno;
58    private $_errstr;
59    private $_user_agent = 'Moodle WebDav Client';
60    private $_crlf = "\r\n";
61    private $_req;
62    private $_resp_status;
63    private $_parser;
64    private $_parserid;
65    private $_xmltree;
66    private $_tree;
67    private $_ls = array();
68    private $_ls_ref;
69    private $_ls_ref_cdata;
70    private $_delete = array();
71    private $_delete_ref;
72    private $_delete_ref_cdata;
73    private $_lock = array();
74    private $_lock_ref;
75    private $_lock_rec_cdata;
76    private $_null = NULL;
77    private $_header='';
78    private $_body='';
79    private $_connection_closed = false;
80    private $_maxheaderlenth = 65536;
81    private $_digestchallenge = null;
82    private $_cnonce = '';
83    private $_nc = 0;
84
85    /**
86     * OAuth token used for bearer auth.
87     * @var string
88     */
89    private $oauthtoken;
90
91    /**#@-*/
92
93    /**
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)
101     */
102    public function __construct($server = '', $user = '', $pass = '', $auth = false, $socket = '', $oauthtoken = '') {
103        if (!empty($server)) {
104            $this->_server = $server;
105        }
106        if (!empty($user) && !empty($pass)) {
107            $this->user = $user;
108            $this->pass = $pass;
109        }
110        $this->_auth = $auth;
111        $this->_socket = $socket;
112        if ($auth == 'bearer') {
113            $this->oauthtoken = $oauthtoken;
114        }
115    }
116    public function __set($key, $value) {
117        $property = '_' . $key;
118        $this->$property = $value;
119    }
120
121    /**
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.
125     * @param int version
126     */
127    function set_protocol($version) {
128        if ($version == 1) {
129            $this->_protocol = 'HTTP/1.1';
130        } else {
131            $this->_protocol = 'HTTP/1.0';
132        }
133    }
134
135    /**
136     * Convert ISO 8601 Date and Time Profile used in RFC 2518 to an unix timestamp.
137     * @access private
138     * @param string iso8601
139     * @return unixtimestamp on sucess. Otherwise false.
140     */
141    function iso8601totime($iso8601) {
142        /*
143
144         date-time       = full-date "T" full-time
145
146         full-date       = date-fullyear "-" date-month "-" date-mday
147         full-time       = partial-time time-offset
148
149         date-fullyear   = 4DIGIT
150         date-month      = 2DIGIT  ; 01-12
151         date-mday       = 2DIGIT  ; 01-28, 01-29, 01-30, 01-31 based on
152         month/year
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
159
160         partial-time    = time-hour ":" time-minute ":" time-second
161                                            [time-secfrac]
162         */
163
164        $regs = array();
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]);
168        }
169        // to be done: regex for partial-time...apache webdav mod never returns partial-time
170
171        return false;
172    }
173
174    /**
175     * Open's a socket to a webdav server
176     * @return bool true on success. Otherwise false.
177     */
178    function open() {
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);
187            return true;
188        } else {
189            $this->_error_log("$this->_errstr ($this->_errno)\n");
190            return false;
191        }
192    }
193
194    /**
195     * Closes an open socket.
196     */
197    function close() {
198        $this->_error_log('closing socket ' . $this->sock);
199        $this->_connection_closed = true;
200        fclose($this->sock);
201    }
202
203    /**
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.
208     */
209    function check_webdav() {
210        $resp = $this->options();
211        if (!$resp) {
212            return false;
213        }
214        $this->_error_log($resp['header']['DAV']);
215        // check schema
216        if (preg_match('/1,2/', $resp['header']['DAV'])) {
217            return true;
218        }
219        // otherwise return false
220        return false;
221    }
222
223
224    /**
225     * Get options from webdav server.
226     * @return array with all header fields returned from webdav server. false if server does not speak http.
227     */
228    function options() {
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') {
238                return $response;
239            }
240        $this->_error_log('Response was not even http');
241        return false;
242
243    }
244
245    /**
246     * Public method mkcol
247     *
248     * Creates a new collection/directory on a webdav server
249     * @param string path
250     * @return int status code received as response from webdav server (see rfc 2518)
251     */
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
265             * rfc 2518 says:
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.
276             */
277            return $response['status']['status-code'];
278        }
279
280    }
281
282    /**
283     * Public method get
284     *
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.
290     */
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();
298
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 ) {
306                    if (!is_null($fp)) {
307                        $stat = fstat($fp);
308                        $this->_error_log('file created with ' . $stat['size'] . ' bytes.');
309                    } else {
310                        $this->_error_log('returning buffer with ' . strlen($response['body']) . ' bytes.');
311                        $buffer = $response['body'];
312                    }
313                }
314                return $response['status']['status-code'];
315            }
316        // ups: no http status was returned ?
317        return false;
318    }
319
320    /**
321     * Public method put
322     *
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.
327     */
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');
335        // send header
336        $this->send_request();
337        // send the rest (data)
338        fputs($this->sock, $data);
339        $this->get_respond();
340        $response = $this->process_respond();
341
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'];
351            }
352        // ups: no http status was returned ?
353        return false;
354    }
355
356    /**
357     * Public method put_file
358     *
359     * Read a file as stream and puts it chunk by chunk into webdav server collection.
360     *
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.
363     *
364     * @param string targetpath, string filename
365     * @return int status code. False on error.
366     */
367    function put_file($path, $filename) {
368        // try to open the file ...
369
370
371        $handle = @fopen ($filename, 'r');
372
373        if ($handle) {
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');
381            // send header
382            $this->send_request();
383            while (!feof($handle)) {
384                fputs($this->sock,fgets($handle,4096));
385            }
386            fclose($handle);
387            $this->get_respond();
388            $response = $this->process_respond();
389
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'];
399                }
400            // ups: no http status was returned ?
401            return false;
402        } else {
403            $this->_error_log('put_file: could not open ' . $filename);
404            return false;
405        }
406
407    }
408
409    /**
410     * Public method get_file
411     *
412     * Gets a file from a collection into local filesystem.
413     *
414     * fopen() is used.
415     * @param string $srcpath
416     * @param string $localpath
417     * @return bool true on success. false on error.
418     */
419    function get_file($srcpath, $localpath) {
420
421        $localpath = $this->utf_decode_path($localpath);
422
423        $handle = fopen($localpath, 'wb');
424        if ($handle) {
425            $unused = '';
426            $ret = $this->get($srcpath, $unused, $handle);
427            fclose($handle);
428            if ($ret) {
429                return true;
430            }
431        }
432        return false;
433    }
434
435    /**
436     * Public method copy_file
437     *
438     * Copies a file on a webdav server
439     *
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.
443     *
444     * @param string src_path, string dest_path, bool overwrite
445     * @return int status code (look at rfc 2518). false on error.
446     */
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)));
452        if ($overwrite) {
453            $this->header_add('Overwrite: T');
454        } else {
455            $this->header_add('Overwrite: F');
456        }
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.
477          */
478                return $response['status']['status-code'];
479            }
480        return false;
481    }
482
483    /**
484     * Public method copy_coll
485     *
486     * Copies a collection on a webdav server
487     *
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.
491     *
492     * @param string src_path, string dest_path, bool overwrite
493     * @return int status code (look at rfc 2518). false on error.
494     */
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');
501
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";
506
507        $this->header_add('Content-length: ' . strlen($xml));
508        $this->header_add('Content-type: application/xml');
509        $this->send_request();
510        // send also xml
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.
530          */
531                return $response['status']['status-code'];
532            }
533        return false;
534    }
535
536    /**
537     * Public method move
538     *
539     * Moves a file or collection on webdav server (serverside)
540     *
541     * If you set param overwrite as true, the target will be overwritten.
542     *
543     * @param string src_path, string dest_path, bool overwrite
544     * @return int status code (look at rfc 2518). false on error.
545     */
546    // --------------------------------------------------------------------------
547    // public method move
548    // move/rename a file/collection on webdav server
549    function move($src_path,$dst_path, $overwrite) {
550
551        $this->_path = $this->translate_uri($src_path);
552        $this->header_unset();
553
554        $this->create_basic_request('MOVE');
555        $this->header_add(sprintf('Destination: http://%s%s', $this->_server, $this->translate_uri($dst_path)));
556        if ($overwrite) {
557            $this->header_add('Overwrite: T');
558        } else {
559            $this->header_add('Overwrite: F');
560        }
561        $this->header_add('');
562
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.
580
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.
588             */
589                return $response['status']['status-code'];
590            }
591        return false;
592    }
593
594    /**
595     * Public method lock
596     *
597     * Locks a file or collection.
598     *
599     * Lock uses this->_user as lock owner.
600     *
601     * @param string path
602     * @return int status code (look at rfc 2518). false on error.
603     */
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();
621        // send also xml
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
630            rfc 2518 says:
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.
635             */
636
637                switch($response['status']['status-code']) {
638                case 200:
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");
652
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)));
657                        }
658
659                        // Free resources
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];
664
665                    } else {
666                        print 'Missing Content-Type: text/xml header in response.<br>';
667                    }
668                    return false;
669
670                default:
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'];
674                    return $this->_lock;
675                }
676            }
677
678
679    }
680
681
682    /**
683     * Public method unlock
684     *
685     * Unlocks a file or collection.
686     *
687     * @param string path, string locktoken
688     * @return int status code (look at rfc 2518). false on error.
689     */
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
701            rfc 2518 says:
702            204 (OK) - The 204 (No Content) status code is used instead of 200 (OK) because there is no response entity body.
703             */
704                return $response['status']['status-code'];
705            }
706        return false;
707    }
708
709    /**
710     * Public method delete
711     *
712     * deletes a collection/directory on a webdav server
713     * @param string path
714     * @return int status code (look at rfc 2518). false on error.
715     */
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();
725
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>';
733
734                switch ($response['status']['status-code']) {
735                case 207:
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");
750
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)));
755                        }
756
757                        print "<br>";
758
759                        // Free resources
760                        xml_parser_free($this->_parser);
761                        $this->_delete[$this->_parserid]['status'] = $response['status']['status-code'];
762                        return $this->_delete[$this->_parserid];
763
764                    } else {
765                        print 'Missing Content-Type: text/xml header in response.<br>';
766                    }
767                    return false;
768
769                default:
770                    // collection or file was successfully deleted
771                    $this->_delete['status'] = $response['status']['status-code'];
772                    return $this->_delete;
773
774
775                }
776            }
777
778    }
779
780    /**
781     * Public method ls
782     *
783     * Get's directory information from webdav server into flat a array using PROPFIND
784     *
785     * All filenames are UTF-8 encoded.
786     * Have a look at _propfind_startElement what keys are used in array returned.
787     * @param string path
788     * @return array dirinfo, false on error
789     */
790    function ls($path) {
791
792        if (trim($path) == '') {
793            $this->_error_log('Missing a path in method ls');
794            return false;
795        }
796        $this->_path = $this->translate_uri($path);
797
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...
803        $xml  = <<<EOD
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:"/>
812</prop></propfind>
813EOD;
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 ) {
828                    // ok so far
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");
843
844
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)));
849                        }
850
851                        // Free resources
852                        xml_parser_free($this->_parser);
853                        $arr = $this->_ls[$this->_parserid];
854                        return $arr;
855                    } else {
856                        $this->_error_log('Missing Content-Type: text/xml header in response!!');
857                        return false;
858                    }
859                } else {
860                    // return status code ...
861                    return $response['status']['status-code'];
862                }
863            }
864
865        // response was not http
866        $this->_error_log('Ups in method ls: error in response from server');
867        return false;
868    }
869
870
871    /**
872     * Public method gpi
873     *
874     * Get's path information from webdav server for one element.
875     *
876     * @param string path
877     * @return array dirinfo. false on error
878     */
879    function gpi($path) {
880
881        // split path by last "/"
882        $path = rtrim($path, "/");
883        $item = basename($path);
884        $dir  = dirname($path);
885
886        $list = $this->ls($dir);
887
888        // be sure it is an array
889        if (is_array($list)) {
890            foreach($list as $e) {
891
892                $fullpath = urldecode($e['href']);
893                $filename = basename($fullpath);
894
895                if ($filename == $item && $filename != "" and $fullpath != $dir."/") {
896                    return $e;
897                }
898            }
899        }
900        return false;
901    }
902
903    /**
904     * Public method is_file
905     *
906     * Gathers whether a path points to a file or not.
907     *
908     * @param string path
909     * @return bool true or false
910     */
911    function is_file($path) {
912
913        $item = $this->gpi($path);
914
915        if ($item === false) {
916            return false;
917        } else {
918            return ($item['resourcetype'] != 'collection');
919        }
920    }
921
922    /**
923     * Public method is_dir
924     *
925     * Gather whether a path points to a directory
926     * @param string path
927     * return bool true or false
928     */
929    function is_dir($path) {
930
931        // be sure path is utf-8
932        $item = $this->gpi($path);
933
934        if ($item === false) {
935            return false;
936        } else {
937            return ($item['resourcetype'] == 'collection');
938        }
939    }
940
941
942    /**
943     * Public method mput
944     *
945     * Puts multiple files and/or directories onto a webdav server.
946     *
947     * Filenames should be allready UTF-8 encoded.
948     * Param fileList must be in format array("localpath" => "destpath").
949     *
950     * @param array filelist
951     * @return bool true on success. otherwise int status code on error
952     */
953    function mput($filelist) {
954
955        $result = true;
956
957        foreach ($filelist as $localpath => $destpath) {
958
959            $localpath = rtrim($localpath, "/");
960            $destpath  = rtrim($destpath, "/");
961
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
965            } else {
966                $pathparts = explode("/", $destpath);
967            }
968            $checkpath = "";
969            for ($i=1; $i<sizeof($pathparts)-1; $i++) {
970                $checkpath .= "/" . $pathparts[$i];
971                if (!($this->is_dir($checkpath))) {
972
973                    $result &= ($this->mkcol($checkpath) == 201 );
974                }
975            }
976
977            if ($result) {
978                // recurse directories
979                if (is_dir($localpath)) {
980                    if (!$dp = opendir($localpath)) {
981                        $this->_error_log("Could not open localpath for reading");
982                        return false;
983                    }
984                    $fl = array();
985                    while($filename = readdir($dp)) {
986                        if ((is_file($localpath."/".$filename) || is_dir($localpath."/".$filename)) && $filename!="." && $filename != "..") {
987                            $fl[$localpath."/".$filename] = $destpath."/".$filename;
988                        }
989                    }
990                    $result &= $this->mput($fl);
991                } else {
992                    $result &= ($this->put_file($destpath, $localpath) == 201);
993                }
994            }
995        }
996        return $result;
997    }
998
999    /**
1000     * Public method mget
1001     *
1002     * Gets multiple files and directories.
1003     *
1004     * FileList must be in format array("remotepath" => "localpath").
1005     * Filenames are UTF-8 encoded.
1006     *
1007     * @param array filelist
1008     * @return bool true on succes, other int status code on error
1009     */
1010    function mget($filelist) {
1011
1012        $result = true;
1013
1014        foreach ($filelist as $remotepath => $localpath) {
1015
1016            $localpath   = rtrim($localpath, "/");
1017            $remotepath  = rtrim($remotepath, "/");
1018
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
1022            } else {
1023                $pathparts = explode("/", $localpath);
1024            }
1025            $checkpath = "";
1026            for ($i=1; $i<sizeof($pathparts)-1; $i++) {
1027                $checkpath .= "/" . $pathparts[$i];
1028                if (!is_dir($checkpath)) {
1029
1030                    $result &= mkdir($checkpath);
1031                }
1032            }
1033
1034            if ($result) {
1035                // recurse directories
1036                if ($this->is_dir($remotepath)) {
1037                    $list = $this->ls($remotepath);
1038
1039                    $fl = array();
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;
1045                        }
1046                    }
1047                    $result &= $this->mget($fl);
1048                } else {
1049                    $result &= ($this->get_file($remotepath, $localpath));
1050                }
1051            }
1052        }
1053        return $result;
1054    }
1055
1056    // --------------------------------------------------------------------------
1057    // private xml callback and helper functions starting here
1058    // --------------------------------------------------------------------------
1059
1060
1061    /**
1062     * Private method _endelement
1063     *
1064     * a generic endElement method  (used for all xml callbacks).
1065     *
1066     * @param resource parser, string name
1067     * @access private
1068     */
1069
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));
1074    }
1075
1076    /**
1077     * Private method _propfind_startElement
1078     *
1079     * Is needed by public method ls.
1080     *
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
1084     * @access private
1085     */
1086    private function _propfind_startElement($parser, $name, $attrs) {
1087        // lower XML Names... maybe break a RFC, don't know ...
1088        $parserid = (int) $parser;
1089
1090        $propname = strtolower($name);
1091        if (!empty($this->_xmltree[$parserid])) {
1092            $this->_xmltree[$parserid] .= $propname . '_';
1093        } else {
1094            $this->_xmltree[$parserid] = $propname . '_';
1095        }
1096
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][];
1102            break;
1103        case 'dav::multistatus_dav::response_dav::href_':
1104            $this->_ls_ref_cdata = &$this->_ls_ref['href'];
1105            break;
1106        case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::creationdate_':
1107            $this->_ls_ref_cdata = &$this->_ls_ref['creationdate'];
1108            break;
1109        case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getlastmodified_':
1110            $this->_ls_ref_cdata = &$this->_ls_ref['lastmodified'];
1111            break;
1112        case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getcontenttype_':
1113            $this->_ls_ref_cdata = &$this->_ls_ref['getcontenttype'];
1114            break;
1115        case 'dav::multistatus_dav::response_dav::propstat_dav::prop_dav::getcontentlength_':
1116            $this->_ls_ref_cdata = &$this->_ls_ref['getcontentlength'];
1117            break;
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'];
1120            break;
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'];
1123            break;
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'];
1126            break;
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'];
1129            break;
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'];
1132            break;
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;
1137            break;
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;
1142            break;
1143        case 'dav::multistatus_dav::response_dav::propstat_dav::status_':
1144            $this->_ls_ref_cdata = &$this->_ls_ref['status'];
1145            break;
1146
1147        default:
1148            // handle unknown xml elements...
1149            $this->_ls_ref_cdata = &$this->_ls_ref[$this->_xmltree[$parserid]];
1150        }
1151    }
1152
1153    /**
1154     * Private method _propfind_cData
1155     *
1156     * Is needed by public method ls.
1157     *
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
1161     * @access private
1162     */
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;
1168        } else {
1169            // do nothing
1170        }
1171    }
1172
1173    /**
1174     * Private method _delete_startElement
1175     *
1176     * Is used by public method delete.
1177     *
1178     * Will be called by php xml_parse.
1179     * @param resource parser, string name, string attrs)
1180     * @access private
1181     */
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 . '_';
1187
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][];
1193            break;
1194        case 'dav::multistatus_dav::response_dav::href_':
1195            $this->_delete_ref_cdata = &$this->_ls_ref['href'];
1196            break;
1197
1198        default:
1199            // handle unknown xml elements...
1200            $this->_delete_cdata = &$this->_delete_ref[$this->_xmltree[$parserid]];
1201        }
1202    }
1203
1204
1205    /**
1206     * Private method _delete_cData
1207     *
1208     * Is used by public method delete.
1209     *
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
1213     * @access private
1214     */
1215    private function _delete_cData($parser, $cdata) {
1216        if (trim($cdata) <> '') {
1217            $this->_delete_ref_cdata .= $cdata;
1218        } else {
1219            // do nothing
1220        }
1221    }
1222
1223
1224    /**
1225     * Private method _lock_startElement
1226     *
1227     * Is needed by public method lock.
1228     *
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
1232     * @access private
1233     */
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 . '_';
1239
1240        // translate xml tree to a flat array ...
1241        /*
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_=
1246         */
1247        switch($this->_xmltree[$parserid]) {
1248        case 'dav::prop_dav::lockdiscovery_dav::activelock_':
1249            // new element
1250            $this->_lock_ref =& $this->_lock[$parserid][];
1251            break;
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;
1256            break;
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;
1261            break;
1262        case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::depth_':
1263            $this->_lock_ref_cdata = &$this->_lock_ref['depth'];
1264            break;
1265        case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::owner_dav::href_':
1266            $this->_lock_ref_cdata = &$this->_lock_ref['owner'];
1267            break;
1268        case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::timeout_':
1269            $this->_lock_ref_cdata = &$this->_lock_ref['timeout'];
1270            break;
1271        case 'dav::prop_dav::lockdiscovery_dav::activelock_dav::locktoken_dav::href_':
1272            $this->_lock_ref_cdata = &$this->_lock_ref['locktoken'];
1273            break;
1274        default:
1275            // handle unknown xml elements...
1276            $this->_lock_cdata = &$this->_lock_ref[$this->_xmltree[$parserid]];
1277
1278        }
1279    }
1280
1281    /**
1282     * Private method _lock_cData
1283     *
1284     * Is used by public method lock.
1285     *
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
1289     * @access private
1290     */
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;
1296        } else {
1297            // do nothing
1298        }
1299    }
1300
1301
1302    /**
1303     * Private method header_add
1304     *
1305     * extends class var array _req
1306     * @param string string
1307     * @access private
1308     */
1309    private function header_add($string) {
1310        $this->_req[] = $string;
1311    }
1312
1313    /**
1314     * Private method header_unset
1315     *
1316     * unsets class var array _req
1317     * @access private
1318     */
1319
1320    private function header_unset() {
1321        unset($this->_req);
1322    }
1323
1324    /**
1325     * Private method create_basic_request
1326     *
1327     * creates by using private method header_add an general request header.
1328     * @param string method
1329     * @access private
1330     */
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);
1343            }
1344        } else if ($this->_auth == 'bearer') {
1345            $this->header_add(sprintf('Authorization: Bearer %s', $this->oauthtoken));
1346        }
1347    }
1348
1349    /**
1350     * Reads the header, stores the challenge information
1351     *
1352     * @return void
1353     */
1354    private function digest_auth() {
1355
1356        $headers = array();
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);
1363
1364        // Reads the headers.
1365        $i = 0;
1366        $header = '';
1367        do {
1368            $header .= fread($this->sock, 1);
1369            $i++;
1370        } while (!preg_match('/\\r\\n\\r\\n$/', $header, $matches) && $i < $this->_maxheaderlenth);
1371
1372        // Analyse the headers.
1373        $digest = array();
1374        $splitheaders = explode("\r\n", $header);
1375        foreach ($splitheaders as $line) {
1376            if (!preg_match('/^WWW-Authenticate: Digest/', $line)) {
1377                continue;
1378            }
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, '"');
1384            }
1385            break;
1386        }
1387
1388        $this->_digestchallenge = $digest;
1389    }
1390
1391    /**
1392     * Generates the digest signature
1393     *
1394     * @return string signature to add to the headers
1395     * @access private
1396     */
1397    private function digest_signature($method) {
1398        if (!$this->_digestchallenge) {
1399            $this->digest_auth();
1400        }
1401
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 . '"';
1407
1408        if (isset($this->_digestchallenge['algorithm']) && $this->_digestchallenge['algorithm'] != 'MD5') {
1409            $this->_error_log('Algorithm other than MD5 are not supported');
1410            return false;
1411        }
1412
1413        $a1 = $this->_user . ':' . $this->_digestchallenge['realm'] . ':' . $this->_pass;
1414        $a2 = $method . ':' . $this->_path;
1415
1416        if (!isset($this->_digestchallenge['qop'])) {
1417            $signature['response'] = '"' . md5(md5($a1) . ':' . $this->_digestchallenge['nonce'] . ':' . md5($a2)) . '"';
1418        } else {
1419            // Assume QOP is auth
1420            if (empty($this->_cnonce)) {
1421                $this->_cnonce = random_string();
1422                $this->_nc = 0;
1423            }
1424            $this->_nc++;
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)) . '"';
1431        }
1432
1433        $response = array();
1434        foreach ($signature as $key => $value) {
1435            $response[] = "$key=$value";
1436        }
1437        return 'Authorization: Digest ' . implode(', ', $response);
1438    }
1439
1440    /**
1441     * Private method send_request
1442     *
1443     * Sends a ready formed http/webdav request to webdav server.
1444     *
1445     * @access private
1446     */
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) {
1451            // reopen it
1452            // be sure to close the open socket.
1453            $this->close();
1454            $this->reopen();
1455        }
1456
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);
1462    }
1463
1464    /**
1465     * Private method get_respond
1466     *
1467     * Reads the response from the webdav server.
1468     *
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.
1473     * @access private
1474     * @param resource $fp optional the file handle to write the body content to (stored internally in the '_body' if not set)
1475     */
1476    private function get_respond($fp = null) {
1477        $this->_error_log('get_respond()');
1478        // init vars (good coding style ;-)
1479        $buffer = '';
1480        $header = '';
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');
1486            return false;
1487        }
1488
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);
1493
1494        // read stream one byte by another until http header ends
1495        $i = 0;
1496        $matches = array();
1497        do {
1498            $header.=fread($this->sock, 1);
1499            $i++;
1500        } while (!preg_match('/\\r\\n\\r\\n$/',$header, $matches) && $i < $this->_maxheaderlenth);
1501
1502        $this->_error_log($header);
1503
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');
1511        }
1512
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)
1516        switch(true) {
1517        case (preg_match('/Transfer\\-Encoding:\\s+chunked\\r\\n/',$header)):
1518            $this->_error_log('Getting HTTP/1.1 chunked data...');
1519            do {
1520                $byte = '';
1521                $chunk_size='';
1522                do {
1523                    $chunk_size.=$byte;
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');
1529                    }
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) {
1534                    $read = 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);
1539                        $read++;
1540                    }
1541                }
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)
1544            break;
1545
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]);
1549
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;
1559                        do {
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);
1565                    }
1566                    self::update_file_or_buffer($chunk, $fp, $buffer);
1567                    break;
1568                } else {
1569                    $buffer = '';
1570                    break;
1571                }
1572            }
1573
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;
1581            }
1582            do {
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);
1593            }
1594            break;
1595
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..');
1602            break;
1603        default:
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);
1610            }
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);
1613        }
1614
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);
1620
1621    }
1622
1623    /**
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)
1628     */
1629    static private function update_file_or_buffer($chunk, $fp, &$buffer) {
1630        if ($fp) {
1631            fwrite($fp, $chunk);
1632        } else {
1633            $buffer .= $chunk;
1634        }
1635    }
1636
1637    /**
1638     * Private method process_respond
1639     *
1640     * Processes the webdav server respond and detects its components (header, body).
1641     * and returns data array structure.
1642     * @return array ret_struct
1643     * @access private
1644     */
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);
1654
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>";
1662
1663            }
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();
1671                }
1672                if (empty($ret_struct['header'][$fieldname])) {
1673                    $ret_struct['header'][$fieldname] = trim($fieldvalue);
1674                } else {
1675                    $ret_struct['header'][$fieldname] .= ',' . trim($fieldvalue);
1676                }
1677            }
1678        }
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));
1683        return $ret_struct;
1684
1685    }
1686
1687    /**
1688     * Private method reopen
1689     *
1690     * Reopens a socket, if 'connection: closed'-header was received from server.
1691     *
1692     * Uses public method open.
1693     * @access private
1694     */
1695    private function reopen() {
1696        // let's try to reopen a socket
1697        $this->_error_log('reopen a socket connection');
1698        return $this->open();
1699    }
1700
1701
1702    /**
1703     * Private method translate_uri
1704     *
1705     * translates an uri to raw url encoded string.
1706     * Removes any html entity in uri
1707     * @param string uri
1708     * @return string translated_uri
1709     * @access private
1710     */
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]);
1719            } else {
1720                $parts[$i] = rawurlencode(utf8_encode($parts[$i]));
1721            }
1722        }
1723        return implode('/', $parts);
1724    }
1725
1726    /**
1727     * Private method utf_decode_path
1728     *
1729     * decodes a UTF-8 encoded string
1730     * @return string decodedstring
1731     * @access private
1732     */
1733    private function utf_decode_path($path) {
1734        $fullpath = $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);
1738        }
1739        return $fullpath;
1740    }
1741
1742    /**
1743     * Private method _error_log
1744     *
1745     * a simple php error_log wrapper.
1746     * @param string err_string
1747     * @access private
1748     */
1749    private function _error_log($err_string) {
1750        if ($this->_debug) {
1751            error_log($err_string);
1752        }
1753    }
1754}
1755