]>
git.datanom.net - webcal.git/blob - caldav/caldav-client.php
3 * A Class for connecting to a caldav server
6 * removed curl - now using fsockopen
7 * changed 2009 by Andres Obrero - Switzerland andres@obrero.ch
10 * @author Andrew McMillan <debian@mcmillan.net.nz>
11 * @copyright Andrew McMillan
12 * @license http://gnu.org/copyleft/gpl.html GNU GPL v2
17 * A class for accessing DAViCal via CalDAV, as a client
23 * Server, username, password, calendar
27 var $base_url, $user, $pass, $calendar, $entry, $protocol, $server, $port;
30 * The useragent which is send to the caldav server
34 var $user_agent = 'DAViCalClient';
36 var $headers = array();
38 var $requestMethod = "GET";
39 var $httpRequest = ""; // for debugging http headers sent
40 var $xmlRequest = ""; // for debugging xml sent
41 var $httpResponse = ""; // for debugging http headers received
42 var $xmlResponse = ""; // for debugging xml received
45 * Constructor, initialises the class
47 * @param string $base_url The URL for the calendar server
48 * @param string $user The name of the user logging in
49 * @param string $pass The password for that user
50 * @param string $calendar The name of the calendar (not currently used)
52 function CalDAVClient( $base_url, $user, $pass, $calendar ) {
55 $this->calendar
= $calendar;
56 $this->headers
= array();
58 if ( preg_match( '#^(https?)://([a-z0-9.-]+)(:([0-9]+))?(/.*)$#', $base_url, $matches ) ) {
59 $this->server
= $matches[2];
60 $this->base_url
= $matches[5];
61 if ( $matches[1] == 'https' ) {
62 $this->protocol
= 'ssl';
66 $this->protocol
= 'tcp';
69 if ( $matches[4] != '' ) {
70 $this->port
= intval($matches[4]);
74 trigger_error("Invalid URL: '".$base_url."'", E_USER_ERROR
);
79 * Adds an If-Match or If-None-Match header
81 * @param bool $match to Match or Not to Match, that is the question!
82 * @param string $etag The etag to match / not match against.
84 function SetMatch( $match, $etag = '*' ) {
85 $this->headers
[] = sprintf( "%s-Match: \"%s\"", ($match ?
"If" : "If-None"), $etag);
89 * Add a Depth: header. Valid values are 1 or infinity
91 * @param int $depth The depth, default to infinity
93 function SetDepth( $depth = 'infinity' ) {
94 $this->headers
[] = "Depth: ". ($depth == 1 ?
"1" : "infinity" );
98 * Add a Depth: header. Valid values are 1 or infinity
100 * @param int $depth The depth, default to infinity
102 function SetUserAgent( $user_agent = null ) {
103 if ( !isset($user_agent) ) $user_agent = $this->user_agent
;
104 $this->user_agent
= $user_agent;
108 * Add a Content-type: header.
110 * @param int $type The content type
112 function SetContentType( $type ) {
113 $this->headers
[] = "Content-type: $type";
117 * Split response into httpResponse and xmlResponse
119 * @param string Response from server
121 function ParseResponse( $response ) {
122 $pos = strpos($response, '<?xml');
124 $this->httpResponse
= trim($response);
127 $this->httpResponse
= trim(substr($response, 0, $pos));
128 $this->xmlResponse
= trim(substr($response, $pos));
133 * Output http request headers
135 * @return HTTP headers
137 function GetHttpRequest() {
138 return $this->httpRequest
;
141 * Output http response headers
143 * @return HTTP headers
145 function GetHttpResponse() {
146 return $this->httpResponse
;
153 function GetXmlRequest() {
154 return $this->xmlRequest
;
157 * Output xml response
161 function GetXmlResponse() {
162 return $this->xmlResponse
;
166 * Send a request to the server
168 * @param string $relative_url The URL to make the request to, relative to $base_url
170 * @return string The content of the response from the server
172 function DoRequest( $relative_url = "" ) {
173 if(!defined("_FSOCK_TIMEOUT")){ define("_FSOCK_TIMEOUT", 10); }
176 $headers[] = $this->requestMethod
." ". $this->base_url
. $relative_url . " HTTP/1.1";
177 $headers[] = "Authorization: Basic ".base64_encode($this->user
.":". $this->pass
);
178 $headers[] = "Host: ".$this->server
.":".$this->port
;
180 foreach( $this->headers
as $ii => $head ) {
183 $headers[] = "Content-Length: " . strlen($this->body
);
184 $headers[] = "User-Agent: " . $this->user_agent
;
185 $headers[] = 'Connection: close';
186 $this->httpRequest
= join("\r\n",$headers);
187 $this->xmlRequest
= $this->body
;
189 $fip = fsockopen( $this->protocol
. '://' . $this->server
, $this->port
, $errno, $errstr, _FSOCK_TIMEOUT
); //error handling?
190 if ( !(get_resource_type($fip) == 'stream') ) return false;
191 if ( !fwrite($fip, $this->httpRequest
."\r\n\r\n".$this->body
) ) { fclose($fip); return false; }
193 while( !feof($fip) ) { $rsp .= fgets($fip,8192); }
196 $this->headers
= array(); // reset the headers array for our next request
197 $this->ParseResponse($rsp);
203 * Send an OPTIONS request to the server
205 * @param string $relative_url The URL to make the request to, relative to $base_url
207 * @return array The allowed options
209 function DoOptionsRequest( $relative_url = "" ) {
210 $this->requestMethod
= "OPTIONS";
212 $headers = $this->DoRequest($relative_url);
213 $options_header = preg_replace( '/^.*Allow: ([a-z, ]+)\r?\n.*/is', '$1', $headers );
214 $options = array_flip( preg_split( '/[, ]+/', $options_header ));
221 * Send an XML request to the server (e.g. PROPFIND, REPORT, MKCALENDAR)
223 * @param string $method The method (PROPFIND, REPORT, etc) to use with the request
224 * @param string $xml The XML to send along with the request
225 * @param string $relative_url The URL to make the request to, relative to $base_url
227 * @return array An array of the allowed methods
229 function DoXMLRequest( $request_method, $xml, $relative_url = '' ) {
231 $this->requestMethod
= $request_method;
232 $this->SetContentType("text/xml");
233 return $this->DoRequest($relative_url);
239 * Get a single item from the server.
241 * @param string $relative_url The part of the URL after the calendar
243 function DoGETRequest( $relative_url ) {
245 $this->requestMethod
= "GET";
246 return $this->DoRequest( $relative_url );
250 * PUT a text/icalendar resource, returning the etag
252 * @param string $relative_url The URL to make the request to, relative to $base_url
253 * @param string $icalendar The iCalendar resource to send to the server
254 * @param string $etag The etag of an existing resource to be overwritten, or '*' for a new resource.
256 * @return string The content of the response from the server
258 function DoPUTRequest( $relative_url, $icalendar, $etag = null ) {
259 $this->body
= $icalendar;
261 $this->requestMethod
= "PUT";
262 if ( $etag != null ) {
263 $this->SetMatch( ($etag != '*'), $etag );
265 $this->SetContentType("text/calendar");
266 $headers = $this->DoRequest($relative_url);
269 * RSCDS will always return the real etag on PUT. Other CalDAV servers may need
270 * more work, but we are assuming we are running against RSCDS in this case.
272 preg_match('/^HTTP\/1\.[01]+\s+(\d+)\s+/i', $headers, $match);
274 //print htmlentities($this->GetXmlResponse())."<br/>";
275 $xml = simplexml_load_string($this->GetXmlResponse());
276 $xml->registerXPathNamespace('e', 'DAV:');
277 $elems = $xml->xpath('//e:error');
281 //echo "$error<br/>";
282 preg_match('/^"?[^"]+"+([0-9a-zA-Z]+)"+.*"+([0-9a-zA-Z]+)"+/', $error, $m);
285 if (strcasecmp($m[1], $m[2]) !== 0) {
286 $error = "Remote changes discovered.\n";
287 $error .= "Enter changes again after reload\n";
290 $etag = array($match[1] => "$error");
297 $etag = preg_replace( '/^.*Etag: "?([^"\r\n]+)"?\r?\n.*/is', '$1', $headers );
303 * DELETE a text/icalendar resource
305 * @param string $relative_url The URL to make the request to, relative to $base_url
306 * @param string $etag The etag of an existing resource to be deleted, or '*' for any resource at that URL.
308 * @return int The HTTP Result Code for the DELETE
310 function DoDELETERequest( $relative_url, $etag = null ) {
313 $this->requestMethod
= "DELETE";
314 if ( $etag != null ) {
315 $this->SetMatch( true, $etag );
317 $this->DoRequest($relative_url);
318 return $this->resultcode
;
323 * Given XML for a calendar query, return an array of the events (/todos) in the
324 * response. Each event in the array will have a 'href', 'etag' and '$response_type'
325 * part, where the 'href' is relative to the calendar and the '$response_type' contains the
326 * definition of the calendar data in iCalendar format.
328 * @param string $filter XML fragment which is the <filter> element of a calendar-query
329 * @param string $relative_url The URL relative to the base_url specified when the calendar was opened. Default ''.
330 * @param string $report_type Used as a name for the array element containing the calendar data. @deprecated
332 * @return array An array of the relative URLs, etags, and events from the server. Each element of the array will
333 * be an array with 'href', 'etag' and 'data' elements, corresponding to the URL, the server-supplied
334 * etag (which only varies when the data changes) and the calendar data in iCalendar format.
336 function DoCalendarQuery( $filter, $relative_url = '' ) {
339 <?xml version="1.0" encoding="utf-8" ?>
340 <C:calendar-query xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">
349 $this->DoXMLRequest( 'REPORT', $xml, $relative_url );
350 $xml_parser = xml_parser_create_ns('UTF-8');
351 $this->xml_tags
= array();
352 xml_parser_set_option ( $xml_parser, XML_OPTION_SKIP_WHITE
, 1 );
353 xml_parse_into_struct( $xml_parser, $this->xmlResponse
, $this->xml_tags
);
354 xml_parser_free($xml_parser);
357 foreach( $this->xml_tags
as $k => $v ) {
358 switch( $v['tag'] ) {
359 case 'DAV::RESPONSE':
360 if ( $v['type'] == 'open' ) {
363 elseif ( $v['type'] == 'close' ) {
364 $report[] = $response;
368 $response['href'] = basename( $v['value'] );
371 $response['etag'] = preg_replace('/^"?([^"]+)"?/', '$1', $v['value']);
373 case 'URN:IETF:PARAMS:XML:NS:CALDAV:CALENDAR-DATA':
374 $response['data'] = $v['value'];
383 * Get the events in a range from $start to $finish. The dates should be in the
384 * format yyyymmddThhmmssZ and should be in GMT. The events are returned as an
385 * array of event arrays. Each event array will have a 'href', 'etag' and 'event'
386 * part, where the 'href' is relative to the calendar and the event contains the
387 * definition of the event in iCalendar format.
389 * @param timestamp $start The start time for the period
390 * @param timestamp $finish The finish time for the period
391 * @param string $relative_url The URL relative to the base_url specified when the calendar was opened. Default ''.
393 * @return array An array of the relative URLs, etags, and events, returned from DoCalendarQuery() @see DoCalendarQuery()
395 function GetEvents( $start = null, $finish = null, $relative_url = '' ) {
397 if ( isset($start) && isset($finish) )
398 $range = "<C:time-range start=\"$start\" end=\"$finish\"/>";
402 $filter = <<<EOFILTER
404 <C:comp-filter name="VCALENDAR">
405 <C:comp-filter name="VEVENT">
412 return $this->DoCalendarQuery($filter, $relative_url);
417 * Get the todo's in a range from $start to $finish. The dates should be in the
418 * format yyyymmddThhmmssZ and should be in GMT. The events are returned as an
419 * array of event arrays. Each event array will have a 'href', 'etag' and 'event'
420 * part, where the 'href' is relative to the calendar and the event contains the
421 * definition of the event in iCalendar format.
423 * @param timestamp $start The start time for the period
424 * @param timestamp $finish The finish time for the period
425 * @param boolean $completed Whether to include completed tasks
426 * @param boolean $cancelled Whether to include cancelled tasks
427 * @param string $relative_url The URL relative to the base_url specified when the calendar was opened. Default ''.
429 * @return array An array of the relative URLs, etags, and events, returned from DoCalendarQuery() @see DoCalendarQuery()
431 function GetTodos( $start, $finish, $completed = false, $cancelled = false, $relative_url = "" ) {
433 if ( $start && $finish ) {
434 $time_range = <<<EOTIME
435 <C:time-range start="$start" end="$finish"/>
439 // Warning! May contain traces of double negatives...
440 $neg_cancelled = ( $cancelled === true ?
"no" : "yes" );
441 $neg_completed = ( $cancelled === true ?
"no" : "yes" );
443 $filter = <<<EOFILTER
445 <C:comp-filter name="VCALENDAR">
446 <C:comp-filter name="VTODO">
447 <C:prop-filter name="STATUS">
448 <C:text-match negate-condition="$neg_completed">COMPLETED</C:text-match>
450 <C:prop-filter name="STATUS">
451 <C:text-match negate-condition="$neg_cancelled">CANCELLED</C:text-match>
452 </C:prop-filter>$time_range
458 return $this->DoCalendarQuery($filter, $relative_url);
463 * Get the calendar entry by UID
466 * @param string $relative_url The URL relative to the base_url specified when the calendar was opened. Default ''.
468 * @return array An array of the relative URL, etag, and calendar data returned from DoCalendarQuery() @see DoCalendarQuery()
470 function GetEntryByUid( $uid, $relative_url = '' ) {
473 $filter = <<<EOFILTER
475 <C:comp-filter name="VCALENDAR">
476 <C:comp-filter name="VEVENT">
477 <C:prop-filter name="UID">
478 <C:text-match icollation="i;octet">$uid</C:text-match>
486 return $this->DoCalendarQuery($filter, $relative_url);
491 * Get the calendar entry by HREF
493 * @param string $href The href from a call to GetEvents or GetTodos etc.
494 * @param string $relative_url The URL relative to the base_url specified when the calendar was opened. Default ''.
496 * @return string The iCalendar of the calendar entry
498 function GetEntryByHref( $href, $relative_url = '' ) {
499 return $this->DoGETRequest( $relative_url . $href );
504 //$cal = new CalDAVClient( "https://www.google.com/calendar/dav/[mail id]/events/", "uid", "pwd", "calendar" );
505 //$cal = new CalDAVClient( "http://calendar.datanom.net/caldav.php/[uid]/home", "uid", "pwd", "calendar" );
507 /*$folder_xml = $cal->DoXMLRequest("PROPFIND",
508 '<?xml version="1.0" encoding="utf-8" ?>
509 <propfind xmlns="DAV:">
517 //print_r($folder_xml);
520 /*$events = $cal->GetEvents("20100616T000000Z", "20100616T235959Z");
521 foreach ( $events AS $k => $event ) {
522 print_r( $event['data'] );
527 print "Debug information\n";
528 print "Headers sent:\n".$cal->GetHttpRequest()."\n".
529 "XML sent:\n".$cal->GetXmlRequest()."\n".
530 "Headers received:\n".$cal->GetHttpResponse()."\n".
531 "XML received:\n".$cal->GetXmlResponse()."\n";
This page took 0.139854 seconds and 6 git commands to generate.