Attendees can only modify own event instance and own PARTSTAT on all attendees' insta...
[davical.git] / inc / caldav-PUT-functions.php
blob9ce52190391b6fc9781020c0ad9f9d8abf82db7c
1 <?php
2 /**
3 * CalDAV Server - handle PUT method
5 * @package davical
6 * @subpackage caldav
7 * @author Andrew McMillan <andrew@morphoss.com>
8 * @copyright Morphoss Ltd - http://www.morphoss.com/
9 * @license http://gnu.org/copyleft/gpl.html GNU GPL v2 or later version
12 /**
13 * Check if the user wants to put just one VEVENT/VTODO or a whole calendar
14 * if the collection = calendar = $request_container doesn't exist then create it
15 * return true if it's a whole calendar
18 require_once('AwlCache.php');
19 require_once('vComponent.php');
20 require_once('vCalendar.php');
21 require_once('WritableCollection.php');
22 include_once('iSchedule.php');
24 $bad_events = null;
26 /**
27 * A regex which will match most reasonable timezones acceptable to PostgreSQL.
29 $tz_regex = ':^(Africa|America|Antarctica|Arctic|Asia|Atlantic|Australia|Brazil|Canada|Chile|Etc|Europe|Indian|Mexico|Mideast|Pacific|US)/[a-z_]+$:i';
31 /**
32 * This function launches an error
33 * @param boolean $caldav_context Whether we are responding via CalDAV or interactively
34 * @param int $user_no the user who will receive this ics file
35 * @param string $path the $path where the PUT failed to store such as /user_foo/home/
36 * @param string $message An optional error message to return to the client
37 * @param int $error_no An optional value for the HTTP error code
39 function rollback_on_error( $caldav_context, $user_no, $path, $message='', $error_no=500 ) {
40 global $c, $bad_events;
41 if ( !$message ) $message = translate('Database error');
42 $qry = new AwlQuery();
43 if ( $qry->TransactionState() != 0 ) $qry->Rollback();
44 if ( $caldav_context ) {
45 if ( isset($bad_events) && isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) {
46 $bad_events[] = $message;
48 else {
49 global $request;
50 $request->DoResponse( $error_no, $message );
52 // and we don't return from that, ever...
55 $c->messages[] = sprintf(translate('Status: %d, Message: %s, User: %d, Path: %s'), $error_no, $message, $user_no, $path);
61 /**
62 * Work out the location we are doing the PUT to, and check that we have the rights to
63 * do the needful.
64 * @param string $username The name of the destination user
65 * @param int $user_no The user making the change
66 * @param string $path The DAV path the resource is bing PUT to
67 * @param boolean $caldav_context Whether we are responding via CalDAV or interactively
68 * @param boolean $public Whether the collection will be public, should we need to create it
70 function controlRequestContainer( $username, $user_no, $path, $caldav_context, $public = null ) {
71 global $c, $request, $bad_events;
73 // Check to see if the path is like /foo /foo/bar or /foo/bar/baz etc. (not ending with a '/', but contains at least one)
74 if ( preg_match( '#^(.*/)([^/]+)$#', $path, $matches ) ) {//(
75 $request_container = $matches[1]; // get everything up to the last '/'
77 else {
78 // In this case we must have a URL with a trailing '/', so it must be a collection.
79 $request_container = $path;
82 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) {
83 $bad_events = array();
86 /**
87 * Before we write the event, we check the container exists, creating it if it doesn't
89 if ( $request_container == "/$username/" ) {
90 /**
91 * Well, it exists, and we support it, but it is against the CalDAV spec
93 dbg_error_log( 'WARN', ' Storing events directly in user\'s base folders is not recommended!');
95 else {
96 $sql = 'SELECT * FROM collection WHERE dav_name = :dav_name';
97 $qry = new AwlQuery( $sql, array( ':dav_name' => $request_container) );
98 if ( ! $qry->Exec('PUT',__LINE__,__FILE__) ) {
99 rollback_on_error( $caldav_context, $user_no, $path );
101 if ( !isset($c->readonly_webdav_collections) || $c->readonly_webdav_collections == true ) {
102 if ( $qry->rows() == 0 ) {
103 $request->DoResponse( 405 ); // Method not allowed
105 return;
107 if ( $qry->rows() == 0 ) {
108 if ( $public == true ) $public = 't'; else $public = 'f';
109 if ( preg_match( '{^(.*/)([^/]+)/$}', $request_container, $matches ) ) {
110 $parent_container = $matches[1];
111 $displayname = $matches[2];
113 $sql = 'INSERT INTO collection ( user_no, parent_container, dav_name, dav_etag, dav_displayname, is_calendar, created, modified, publicly_readable, resourcetypes )
114 VALUES( :user_no, :parent_container, :dav_name, :dav_etag, :dav_displayname, TRUE, current_timestamp, current_timestamp, :is_public::boolean, :resourcetypes )';
115 $params = array(
116 ':user_no' => $user_no,
117 ':parent_container' => $parent_container,
118 ':dav_name' => $request_container,
119 ':dav_etag' => md5($user_no. $request_container),
120 ':dav_displayname' => $displayname,
121 ':is_public' => $public,
122 ':resourcetypes' => '<DAV::collection/><urn:ietf:params:xml:ns:caldav:calendar/>'
124 $qry->QDo( $sql, $params );
126 else if ( isset($public) ) {
127 $collection = $qry->Fetch();
128 if ( empty($collection->is_public) ) $collection->is_public = 'f';
129 if ( $collection->is_public == ($public?'t':'f') ) {
130 $sql = 'UPDATE collection SET publicly_readable = :is_public::boolean WHERE collection_id = :collection_id';
131 $params = array( ':is_public' => ($public?'t':'f'), ':collection_id' => $collection->collection_id );
132 if ( ! $qry->QDo($sql,$params) ) {
133 rollback_on_error( $caldav_context, $user_no, $path );
143 * Check if this collection should force all events to be PUBLIC.
144 * @param string $user_no the user that owns the collection
145 * @param string $dav_name the collection to check
146 * @return boolean Return true if public events only are allowed.
148 function public_events_only( $user_no, $dav_name ) {
149 global $c;
151 $sql = 'SELECT public_events_only FROM collection WHERE dav_name = :dav_name';
153 $qry = new AwlQuery($sql, array(':dav_name' => $dav_name) );
155 if( $qry->Exec('PUT',__LINE__,__FILE__) && $qry->rows() == 1 ) {
156 $collection = $qry->Fetch();
158 if ($collection->public_events_only == 't') {
159 return true;
163 // Something went wrong, must be false.
164 return false;
168 * Get a TZID string from this VEVENT/VTODO/... component if we can
169 * @param vComponent $comp
170 * @return The TZID value we found, or null
172 function GetTZID( vComponent $comp ) {
173 $p = $comp->GetProperty('DTSTART');
174 if ( !isset($p) && $comp->GetType() == 'VTODO' ) {
175 $p = $comp->GetProperty('DUE');
177 if ( !isset($p) ) return null;
178 return $p->GetParameterValue('TZID');
182 * Deliver scheduling requests to attendees
183 * @param vComponent $ical the VCALENDAR to deliver
185 function handle_schedule_request( $ical ) {
186 global $c, $session, $request;
187 $resources = $ical->GetComponents('VTIMEZONE',false);
188 $ic = $resources[0];
189 $etag = md5 ( $request->raw_post );
190 $reply = new XMLDocument( array("DAV:" => "", "urn:ietf:params:xml:ns:caldav" => "C" ) );
191 $responses = array();
193 $attendees = $ic->GetProperties('ATTENDEE');
194 $wr_attendees = $ic->GetProperties('X-WR-ATTENDEE');
195 if ( count ( $wr_attendees ) > 0 ) {
196 dbg_error_log( "PUT", "Non-compliant iCal request. Using X-WR-ATTENDEE property" );
197 foreach( $wr_attendees AS $k => $v ) {
198 $attendees[] = $v;
201 dbg_error_log( "PUT", "Attempting to deliver scheduling request for %d attendees", count($attendees) );
203 foreach( $attendees AS $k => $attendee ) {
204 $attendee_email = preg_replace( '/^mailto:/', '', $attendee->Value() );
205 if ( $attendee_email == $request->principal->email() ) {
206 dbg_error_log( "PUT", "not delivering to owner" );
207 continue;
209 if ( $attendee->GetParameterValue ( 'PARTSTAT' ) != 'NEEDS-ACTION' || preg_match ( '/^[35]\.[3-9]/', $attendee->GetParameterValue ( 'SCHEDULE-STATUS' ) ) ) {
210 dbg_error_log( "PUT", "attendee %s does not need action", $attendee_email );
211 continue;
214 if ( isset($c->enable_auto_schedule) && !$c->enable_auto_schedule ) {
215 // In this case we're being asked not to do auto-scheduling, so we build
216 // a response back for the client saying we can't...
217 $attendee->SetParameterValue ('SCHEDULE-STATUS','5.3;No scheduling support for user');
218 continue;
221 dbg_error_log( "PUT", "Delivering to %s", $attendee_email );
223 $attendee_principal = new DAVPrincipal ( array ('email'=>$attendee_email, 'options'=> array ( 'allow_by_email' => true ) ) );
224 if ( $attendee_principal == false ){
225 $attendee->SetParameterValue ('SCHEDULE-STATUS','5.3;No scheduling support for user');
226 continue;
228 $deliver_path = $attendee_principal->internal_url('schedule-inbox');
230 $ar = new DAVResource($deliver_path);
231 $priv = $ar->HavePrivilegeTo('schedule-deliver-invite' );
232 if ( ! $ar->HavePrivilegeTo('schedule-deliver-invite' ) ){
233 $reply = new XMLDocument( array('DAV:' => '') );
234 $privnodes = array( $reply->href($attendee_principal->url('schedule_inbox')), new XMLElement( 'privilege' ) );
235 // RFC3744 specifies that we can only respond with one needed privilege, so we pick the first.
236 $reply->NSElement( $privnodes[1], 'schedule-deliver-invite' );
237 $xml = new XMLElement( 'need-privileges', new XMLElement( 'resource', $privnodes) );
238 $xmldoc = $reply->Render('error',$xml);
239 $request->DoResponse( 403, $xmldoc, 'text/xml; charset="utf-8"');
243 $attendee->SetParameterValue ('SCHEDULE-STATUS','1.2;Scheduling message has been delivered');
244 $ncal = new vCalendar( array('METHOD' => 'REQUEST') );
245 $ncal->AddComponent( array_merge( $ical->GetComponents('VEVENT',false), array($ic) ));
246 $content = $ncal->Render();
247 $cid = $ar->GetProperty('collection_id');
248 dbg_error_log('DELIVER', 'to user: %s, to path: %s, collection: %s, from user: %s, caldata %s', $attendee_principal->user_no(), $deliver_path, $cid, $request->user_no, $content );
249 $item_etag = md5($content);
250 write_resource( new DAVResource($deliver_path . $etag . '.ics'), $content, $ar, $request->user_no, $item_etag,
251 $put_action_type='INSERT', $caldav_context=true, $log_action=true, $etag );
252 $attendee->SetParameterValue ('SCHEDULE-STATUS','1.2;Scheduling message has been delivered');
254 // don't write an entry in the out box, ical doesn't delete it or ever read it again
255 $ncal = new vCalendar(array('METHOD' => 'REQUEST'));
256 $ncal->AddComponent ( array_merge ( $ical->GetComponents('VEVENT',false) , array ($ic) ));
257 $content = $ncal->Render();
258 $deliver_path = $request->principal->internal_url('schedule-inbox');
259 $ar = new DAVResource($deliver_path);
260 $item_etag = md5($content);
261 write_resource( new DAVResource($deliver_path . $etag . '.ics'), $content, $ar, $request->user_no, $item_etag,
262 $put_action_type='INSERT', $caldav_context=true, $log_action=true, $etag );
263 //$etag = md5($content);
264 header('ETag: "'. $etag . '"' );
265 header('Schedule-Tag: "'.$etag . '"' );
266 $request->DoResponse( 201, 'Created' );
270 * Deliver scheduling replies to organizer and other attendees
271 * @param vComponent $ical the VCALENDAR to deliver
272 * @return false on error
274 function handle_schedule_reply ( vCalendar $ical ) {
275 global $c, $session, $request;
276 $resources = $ical->GetComponents('VTIMEZONE',false);
277 $ic = $resources[0];
278 $etag = md5 ( $request->raw_post );
279 $organizer = $ical->GetOrganizer();
280 // for now we treat events with out organizers as an error
281 if ( count ( $organizer ) < 1 ) return false;
283 $attendees = array_merge($organizer,$ical->GetAttendees());
284 dbg_error_log( "PUT", "Attempting to deliver scheduling request for %d attendees", count($attendees) );
286 foreach( $attendees AS $k => $attendee ) {
287 $attendee_email = preg_replace( '/^mailto:/i', '', $attendee->Value() );
288 dbg_error_log( "PUT", "Delivering to %s", $attendee_email );
289 $attendee_principal = new DAVPrincipal ( array ('email'=>$attendee_email, 'options'=> array ( 'allow_by_email' => true ) ) );
290 $deliver_path = $attendee_principal->internal_url('schedule_inbox');
291 $attendee_email = preg_replace( '/^mailto:/i', '', $attendee->Value() );
292 if ( $attendee_email == $request->principal->email ) {
293 dbg_error_log( "PUT", "not delivering to owner" );
294 continue;
296 $ar = new DAVResource($deliver_path);
297 if ( ! $ar->HavePrivilegeTo('schedule-deliver-reply' ) ){
298 $reply = new XMLDocument( array('DAV:' => '') );
299 $privnodes = array( $reply->href($attendee_principal->url('schedule_inbox')), new XMLElement( 'privilege' ) );
300 // RFC3744 specifies that we can only respond with one needed privilege, so we pick the first.
301 $reply->NSElement( $privnodes[1], 'schedule-deliver-reply' );
302 $xml = new XMLElement( 'need-privileges', new XMLElement( 'resource', $privnodes) );
303 $xmldoc = $reply->Render('error',$xml);
304 $request->DoResponse( 403, $xmldoc, 'text/xml; charset="utf-8"' );
305 continue;
308 $ncal = new vCalendar( array('METHOD' => 'REPLY') );
309 $ncal->AddComponent ( array_merge ( $ical->GetComponents('VEVENT',false) , array ($ic) ));
310 $content = $ncal->Render();
311 write_resource( new DAVResource($deliver_path . $etag . '.ics'), $content, $ar, $request->user_no, md5($content),
312 $put_action_type='INSERT', $caldav_context=true, $log_action=true, $etag );
314 $request->DoResponse( 201, 'Created' );
319 * Do the scheduling adjustments for a REPLY when an ATTENDEE updates their status.
320 * @param vCalendar $resource The resource that the ATTENDEE is writing to their calendar
321 * @param string $organizer The property which is the event ORGANIZER.
323 function do_scheduling_reply( vCalendar $resource, vProperty $organizer ) {
324 global $request;
325 $organizer_email = preg_replace( '/^mailto:/i', '', $organizer->Value() );
326 $organizer_principal = new Principal('email',$organizer_email );
327 if ( !$organizer_principal->Exists() ) {
328 dbg_error_log( 'PUT', 'Organizer "%s" not found - cannot perform scheduling reply.', $organizer );
329 return false;
331 $sql = 'SELECT caldav_data.dav_name, caldav_data.caldav_data FROM caldav_data JOIN calendar_item USING(dav_id) ';
332 $sql .= 'WHERE caldav_data.collection_id IN (SELECT collection_id FROM collection WHERE is_calendar AND user_no =?) ';
333 $sql .= 'AND uid=? LIMIT 1';
334 $uids = $resource->GetPropertiesByPath('/VCALENDAR/*/UID');
335 if ( count($uids) == 0 ) {
336 dbg_error_log( 'PUT', 'No UID in VCALENDAR - giving up on REPLY.' );
337 return false;
339 $uid = $uids[0]->Value();
340 $qry = new AwlQuery($sql,$organizer_principal->user_no(), $uid);
341 if ( !$qry->Exec('PUT',__LINE__,__FILE__) || $qry->rows() < 1 ) {
342 dbg_error_log( 'PUT', 'Could not find original event from organizer - giving up on REPLY.' );
343 return false;
345 $row = $qry->Fetch();
346 $attendees = $resource->GetAttendees();
347 foreach( $attendees AS $v ) {
348 $email = preg_replace( '/^mailto:/i', '', $v->Value() );
349 if ( $email == $request->principal->email() ) {
350 $attendee = $v;
353 if ( empty($attendee) ) {
354 dbg_error_log( 'PUT', 'Could not find ATTENDEE in VEVENT - giving up on REPLY.' );
355 return false;
357 $schedule_original = new vCalendar($row->caldav_data);
358 $schedule_original->UpdateAttendeeStatus($request->principal->email(), clone($attendee) );
360 $collection_path = preg_replace('{/[^/]+$}', '/', $row->dav_name );
361 $segment_name = str_replace($collection_path, '', $row->dav_name );
362 $organizer_calendar = new WritableCollection(array('path' => $collection_path));
363 $organizer_inbox = new WritableCollection(array('path' => $organizer_principal->internal_url('schedule-inbox')));
365 $schedule_reply = clone($schedule_original);
366 $schedule_reply->AddProperty('METHOD', 'REPLY');
368 dbg_error_log( 'PUT', 'Writing scheduling REPLY from %s to %s', $request->principal->email(), $organizer_principal->email() );
370 $response = '3.7'; // Organizer was not found on server.
371 if ( !$organizer_calendar->Exists() ) {
372 dbg_error_log('ERROR','Default calendar at "%s" does not exist for user "%s"',
373 $organizer_calendar->dav_name(), $schedule_target->username());
374 $response = '5.2'; // No scheduling support for user
376 else {
377 if ( ! $organizer_inbox->HavePrivilegeTo('schedule-deliver-reply') ) {
378 $response = '3.8'; // No authority to deliver replies to organizer.
380 else if ( $organizer_inbox->WriteCalendarMember($schedule_reply, false, false, $request->principal->username().$segment_name) !== false ) {
381 $response = '1.2'; // Scheduling reply delivered successfully
382 if ( $organizer_calendar->WriteCalendarMember($schedule_original, false, false, $segment_name) === false ) {
383 dbg_error_log('ERROR','Could not write updated calendar member to %s',
384 $attendee_calendar->dav_name(), $attendee_calendar->dav_name(), $schedule_target->username());
385 trace_bug('Failed to write scheduling resource.');
390 $schedule_request = clone($schedule_original);
391 $schedule_request->AddProperty('METHOD', 'REQUEST');
393 dbg_error_log( 'PUT', 'Status for organizer <%s> set to "%s"', $organizer->Value(), $response );
394 $organizer->SetParameterValue( 'SCHEDULE-STATUS', $response );
395 $resource->UpdateOrganizerStatus($organizer);
396 $scheduling_actions = true;
398 $calling_attendee = clone($attendee);
399 $attendees = $schedule_original->GetAttendees();
400 foreach( $attendees AS $attendee ) {
401 $email = preg_replace( '/^mailto:/i', '', $attendee->Value() );
402 if ( $email == $request->principal->email() || $email == $organizer_principal->email() ) continue;
404 $agent = $attendee->GetParameterValue('SCHEDULE-AGENT');
405 if ( $agent && $agent != 'SERVER' ) {
406 dbg_error_log( "PUT", "not delivering to %s, schedule agent set to value other than server", $email );
407 continue;
410 // an attendee's reply should modify only the PARTSTAT on other attendees' objects
411 // other properties (that might have been adjusted individually by those other
412 // attendees) should remain unmodified. Therefore, we have to make $schedule_original
413 // and $schedule_request be initialized by each attendee's object here.
414 $attendee_principal = new DAVPrincipal ( array ('email'=>$email, 'options'=> array ( 'allow_by_email' => true ) ) );
415 if ( $attendee_principal == false ){
416 dbg_error_log( 'PUT', 'Could not find attendee %s', $email);
417 continue;
419 $sql = 'SELECT caldav_data.dav_name, caldav_data.caldav_data, caldav_data.collection_id FROM caldav_data JOIN calendar_item USING(dav_id) ';
420 $sql .= 'WHERE caldav_data.collection_id IN (SELECT collection_id FROM collection WHERE is_calendar AND user_no =?) ';
421 $sql .= 'AND uid=? LIMIT 1';
422 $qry = new AwlQuery($sql,$attendee_principal->user_no(), $uid);
423 if ( !$qry->Exec('PUT',__LINE__,__FILE__) || $qry->rows() < 1 ) {
424 dbg_error_log( 'PUT', "Could not find attendee's event %s", $uid );
426 $row = $qry->Fetch();
427 $schedule_original = new vCalendar($row->caldav_data);
428 $schedule_original->UpdateAttendeeStatus($request->principal->email(), clone($calling_attendee) );
429 $schedule_request = clone($schedule_original);
430 $schedule_request->AddProperty('METHOD', 'REQUEST');
432 $schedule_target = new Principal('email',$email);
433 $response = '3.7'; // Attendee was not found on server.
434 if ( $schedule_target->Exists() ) {
435 // Instead of always writing to schedule-default-calendar, we first try to
436 // find a calendar with an existing instance of the event in any calendar of this attendee.
437 $r = new DAVResource($row);
438 $attendee_calendar = new WritableCollection(array('path' => $r->parent_path()));
439 if ($attendee_calendar->IsCalendar()) {
440 dbg_error_log( 'XXX', "found the event in attendee's calendar %s", $attendee_calendar->dav_name() );
441 } else {
442 dbg_error_log( 'XXX', 'could not find the event in any calendar, using schedule-default-calendar');
443 $attendee_calendar = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-default-calendar')));
445 if ( !$attendee_calendar->Exists() ) {
446 dbg_error_log('ERROR','Default calendar at "%s" does not exist for user "%s"',
447 $attendee_calendar->dav_name(), $schedule_target->username());
448 $response = '5.2'; // No scheduling support for user
450 else {
451 $attendee_inbox = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-inbox')));
452 if ( ! $attendee_inbox->HavePrivilegeTo('schedule-deliver-invite') ) {
453 $response = '3.8'; // No authority to deliver invitations to user.
455 else if ( $attendee_inbox->WriteCalendarMember($schedule_request, false) !== false ) {
456 $response = '1.2'; // Scheduling invitation delivered successfully
457 if ( $attendee_calendar->WriteCalendarMember($schedule_original, false) === false ) {
458 dbg_error_log('ERROR','Could not write updated calendar member to %s',
459 $attendee_calendar->dav_name(), $attendee_calendar->dav_name(), $schedule_target->username());
460 trace_bug('Failed to write scheduling resource.');
465 dbg_error_log( 'PUT', 'Status for attendee <%s> set to "%s"', $attendee->Value(), $response );
466 $attendee->SetParameterValue( 'SCHEDULE-STATUS', $response );
467 $scheduling_actions = true;
469 $resource->UpdateAttendeeStatus($email, clone($attendee));
473 return $scheduling_actions;
478 * Create/Update the scheduling requests for this resource. This includes updating
479 * the scheduled user's default calendar.
480 * @param vComponent $resource The VEVENT/VTODO/... resource we are scheduling
481 * @param boolean $create true if the scheduling requests are being created.
482 * @return true If there was any scheduling action
484 function do_scheduling_requests( vCalendar $resource, $create, $old_data = null ) {
485 global $request, $c;
486 if ( !isset($request) || (isset($c->enable_auto_schedule) && !$c->enable_auto_schedule) ) return false;
488 if ( ! is_object($resource) ) {
489 trace_bug( 'do_scheduling_requests called with non-object parameter (%s)', gettype($resource) );
490 return false;
493 $organizer = $resource->GetOrganizer();
494 if ( $organizer === false || empty($organizer) ) {
495 dbg_error_log( 'PUT', 'Event has no organizer - no scheduling required.' );
496 return false;
498 $organizer_email = preg_replace( '/^mailto:/i', '', $organizer->Value() );
500 if ( $request->principal->email() != $organizer_email ) {
501 return do_scheduling_reply($resource,$organizer);
504 $schedule_request = clone($resource);
505 $schedule_request->AddProperty('METHOD', 'REQUEST');
507 $old_attendees = array();
508 if ( !empty($old_data) ) {
509 $old_resource = new vCalendar($old_data);
510 $old_attendees = $old_resource->GetAttendees();
512 $attendees = $resource->GetAttendees();
513 if ( count($attendees) == 0 && count($old_attendees) == 0 ) {
514 dbg_error_log( 'PUT', 'Event has no attendees - no scheduling required.', count($attendees) );
515 return false;
517 $removed_attendees = array();
518 foreach( $old_attendees AS $attendee ) {
519 $email = preg_replace( '/^mailto:/i', '', $attendee->Value() );
520 if ( $email == $request->principal->email() ) continue;
521 $removed_attendees[$email] = $attendee;
524 $uids = $resource->GetPropertiesByPath('/VCALENDAR/*/UID');
525 if ( count($uids) == 0 ) {
526 dbg_error_log( 'PUT', 'No UID in VCALENDAR - giving up on REPLY.' );
527 return false;
529 $uid = $uids[0]->Value();
531 dbg_error_log( 'PUT', 'Writing scheduling resources for %d attendees', count($attendees) );
532 $scheduling_actions = false;
533 foreach( $attendees AS $attendee ) {
534 $email = preg_replace( '/^mailto:/i', '', $attendee->Value() );
535 if ( $email == $request->principal->email() ) {
536 dbg_error_log( "PUT", "not delivering to owner '%s'", $request->principal->email() );
537 continue;
540 if ( $create ) {
541 $attendee_is_new = true;
543 else {
544 $attendee_is_new = !isset($removed_attendees[$email]);
545 if ( !$attendee_is_new ) unset($removed_attendees[$email]);
548 $agent = $attendee->GetParameterValue('SCHEDULE-AGENT');
549 if ( $agent && $agent != 'SERVER' ) {
550 dbg_error_log( "PUT", "not delivering to %s, schedule agent set to value other than server", $email );
551 continue;
553 $schedule_target = new Principal('email',$email);
554 $response = '3.7'; // Attendee was not found on server.
555 dbg_error_log( 'PUT', 'Handling scheduling resources for %s on %s which is %s', $email,
556 ($create?'create':'update'), ($attendee_is_new? 'new' : 'an update') );
557 if ( $schedule_target->Exists() ) {
558 // Instead of always writing to schedule-default-calendar, we first try to
559 // find a calendar with an existing instance of the event.
560 $sql = 'SELECT caldav_data.dav_name, caldav_data.caldav_data, caldav_data.collection_id FROM caldav_data JOIN calendar_item USING(dav_id) ';
561 $sql .= 'WHERE caldav_data.collection_id IN (SELECT collection_id FROM collection WHERE is_calendar AND user_no =?) ';
562 $sql .= 'AND uid=? LIMIT 1';
563 $qry = new AwlQuery($sql,$schedule_target->user_no(), $uid);
564 if ( !$qry->Exec('PUT',__LINE__,__FILE__) || $qry->rows() < 1 ) {
565 dbg_error_log( 'PUT', "Could not find event in attendee's calendars" );
566 $attendee_calendar = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-default-calendar')));
567 } else {
568 $row = $qry->Fetch();
569 $r = new DAVResource($row);
570 $attendee_calendar = new WritableCollection(array('path' => $r->parent_path()));
571 if ($attendee_calendar->IsCalendar()) {
572 dbg_error_log( 'XXX', "found the event in attendee's calendar %s", $attendee_calendar->dav_name() );
573 } else {
574 dbg_error_log( 'XXX', 'could not find the event in any calendar, using schedule-default-calendar');
575 $attendee_calendar = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-default-calendar')));
578 if ( !$attendee_calendar->Exists() ) {
579 dbg_error_log('ERROR','Default calendar at "%s" does not exist for user "%s"',
580 $attendee_calendar->dav_name(), $schedule_target->username());
581 $response = '5.2'; // No scheduling support for user
583 else {
584 $attendee_inbox = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-inbox')));
585 if ( ! $attendee_inbox->HavePrivilegeTo('schedule-deliver-invite') ) {
586 $response = '3.8'; // No authority to deliver invitations to user.
588 else if ( $attendee_inbox->WriteCalendarMember($schedule_request, $attendee_is_new) !== false ) {
589 $response = '1.2'; // Scheduling invitation delivered successfully
590 if ( $attendee_calendar->WriteCalendarMember($resource, $attendee_is_new) === false ) {
591 dbg_error_log('ERROR','Could not write %s calendar member to %s', ($attendee_is_new?'new':'updated'),
592 $attendee_calendar->dav_name(), $attendee_calendar->dav_name(), $schedule_target->username());
593 trace_bug('Failed to write scheduling resource.');
598 else {
599 $remote = new iSchedule ();
600 $answer = $remote->sendRequest ( $email, 'VEVENT/REQUEST', $schedule_request->Render() );
601 if ( $answer === false ) {
602 $response = "3.7;Invalid Calendar User" ;
604 else {
605 foreach ( $answer as $a ) // should only be one element in array
607 if ( $a === false ) {
608 $response = "3.7;Invalid Calendar User" ;
610 elseif ( substr( $a, 0, 1 ) >= 1 ) {
611 $response = $a ;
613 else {
614 $response = "2.0;Success" ;
619 dbg_error_log( 'PUT', 'Status for attendee <%s> set to "%s"', $attendee->Value(), $response );
620 $attendee->SetParameterValue( 'SCHEDULE-STATUS', $response );
621 $scheduling_actions = true;
624 if ( !$create ) {
625 foreach( $removed_attendees AS $attendee ) {
626 $schedule_target = new Principal('email',$email);
627 if ( $schedule_target->Exists() ) {
628 $attendee_calendar = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-default-calendar')));
632 return $scheduling_actions;
637 * This function will import a whole collection
638 * @param string $ics_content the ics file to import
639 * @param int $user_no the user wich will receive this ics file
640 * @param string $path the $path where it will be store such as /user_foo/home/
641 * @param boolean $caldav_context Whether we are responding via CalDAV or interactively
643 * The work is either done by
645 function import_collection( $import_content, $user_no, $path, $caldav_context, $appending = false ) {
646 global $c;
648 if ( ! ini_get('open_basedir') && (isset($c->dbg['ALL']) || isset($c->dbg['put'])) ) {
649 $fh = fopen('/tmp/PUT-2.txt','w');
650 if ( $fh ) {
651 fwrite($fh,$import_content);
652 fclose($fh);
656 if ( preg_match( '{^begin:(vcard|vcalendar)}i', $import_content, $matches) ) {
657 if ( $matches[1] == 'VCARD' )
658 import_addressbook_collection( $import_content, $user_no, $path, $caldav_context, $appending );
659 elseif ( $matches[1] == 'VCALENDAR' )
660 import_calendar_collection( $import_content, $user_no, $path, $caldav_context, $appending );
662 // Uncache anything to do with the collection
663 $cache = getCacheInstance();
664 $cache_ns = 'collection-'.preg_replace( '{/[^/]*$}', '/', $path);
665 $cache->delete( $cache_ns, null );
667 else {
668 dbg_error_log('PUT', 'Can only import files which are VCARD or VCALENDAR');
673 * This function will import a whole calendar
674 * @param string $ics_content the ics file to import
675 * @param int $user_no the user wich will receive this ics file
676 * @param string $path the $path where it will be store such as /user_foo/home/
677 * @param boolean $caldav_context Whether we are responding via CalDAV or interactively
679 * Any VEVENTs with the same UID will be concatenated together
681 function import_addressbook_collection( $vcard_content, $user_no, $path, $caldav_context, $appending = false ) {
682 global $c, $session;
683 // We hack this into an enclosing component because vComponent only expects a single root component
684 $addressbook = new vComponent("BEGIN:ADDRESSES\r\n".$vcard_content."\r\nEND:ADDRESSES\r\n");
686 require_once('vcard.php');
688 $sql = 'SELECT * FROM collection WHERE dav_name = :dav_name';
689 $qry = new AwlQuery( $sql, array( ':dav_name' => $path) );
690 if ( ! $qry->Exec('PUT',__LINE__,__FILE__) ) rollback_on_error( $caldav_context, $user_no, $path );
691 if ( ! $qry->rows() == 1 ) {
692 dbg_error_log( 'ERROR', ' PUT: Collection does not exist at "%s" for user %d', $path, $user_no );
693 rollback_on_error( $caldav_context, $user_no, $path );
695 $collection = $qry->Fetch();
697 if ( !(isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import) ) $qry->Begin();
698 $base_params = array(
699 ':collection_id' => $collection->collection_id,
700 ':session_user' => $session->user_no,
701 ':caldav_type' => 'VCARD'
703 if ( !$appending ) {
704 if ( !$qry->QDo('DELETE FROM caldav_data WHERE collection_id = :collection_id', $base_params) )
705 rollback_on_error( $caldav_context, $user_no, $collection->collection_id );
708 $dav_data_insert = <<<EOSQL
709 INSERT INTO caldav_data ( user_no, dav_name, dav_etag, caldav_data, caldav_type, logged_user, created, modified, collection_id )
710 VALUES( :user_no, :dav_name, :etag, :dav_data, :caldav_type, :session_user, :created, :modified, :collection_id )
711 EOSQL;
714 $resources = $addressbook->GetComponents();
715 foreach( $resources AS $k => $resource ) {
716 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Begin();
718 $vcard = new vCard( $resource->Render() );
720 $uid = $vcard->GetPValue('UID');
721 if ( empty($uid) ) {
722 $uid = uuid();
723 $vcard->AddProperty('UID',$uid);
726 $last_modified = $vcard->GetPValue('REV');
727 if ( empty($last_modified) ) {
728 $last_modified = gmdate( 'Ymd\THis\Z' );
729 $vcard->AddProperty('REV',$last_modified);
732 $created = $vcard->GetPValue('X-CREATED');
733 if ( empty($last_modified) ) {
734 $created = gmdate( 'Ymd\THis\Z' );
735 $vcard->AddProperty('X-CREATED',$created);
738 $rendered_card = $vcard->Render();
740 $dav_data_params = $base_params;
741 $dav_data_params[':user_no'] = $user_no;
742 // We don't allow any of &?\/@%+: in the UID to appear in the path, but anything else is fair game.
743 $dav_data_params[':dav_name'] = sprintf( '%s%s.ics', $path, preg_replace('{[&?\\/@%+:]}','',$uid) );
744 $dav_data_params[':etag'] = md5($rendered_card);
745 $dav_data_params[':dav_data'] = $rendered_card;
746 $dav_data_params[':modified'] = $last_modified;
747 $dav_data_params[':created'] = $created;
749 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Begin();
751 if ( !$qry->QDo($dav_data_insert,$dav_data_params) ) rollback_on_error( $caldav_context, $user_no, $path );
753 $qry->QDo('SELECT dav_id FROM caldav_data WHERE dav_name = :dav_name ', array(':dav_name' => $dav_data_params[':dav_name']));
754 if ( $qry->rows() == 1 && $row = $qry->Fetch() ) {
755 $dav_id = $row->dav_id;
758 $vcard->Write( $row->dav_id, false );
760 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Commit();
763 if ( !(isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import) ) {
764 if ( ! $qry->Commit() ) rollback_on_error( $caldav_context, $user_no, $path);
770 * This function will import a whole calendar
771 * @param string $ics_content the ics file to import
772 * @param int $user_no the user wich will receive this ics file
773 * @param string $path the $path where it will be store such as /user_foo/home/
774 * @param boolean $caldav_context Whether we are responding via CalDAV or interactively
776 * Any VEVENTs with the same UID will be concatenated together
778 function import_calendar_collection( $ics_content, $user_no, $path, $caldav_context, $appending = false ) {
779 global $c, $session, $tz_regex;
780 $calendar = new vComponent($ics_content);
781 $timezones = $calendar->GetComponents('VTIMEZONE',true);
782 $components = $calendar->GetComponents('VTIMEZONE',false);
784 $displayname = $calendar->GetPValue('X-WR-CALNAME');
785 if ( !$appending && isset($displayname) ) {
786 $sql = 'UPDATE collection SET dav_displayname = :displayname WHERE dav_name = :dav_name';
787 $qry = new AwlQuery( $sql, array( ':displayname' => $displayname, ':dav_name' => $path) );
788 if ( ! $qry->Exec('PUT',__LINE__,__FILE__) ) rollback_on_error( $caldav_context, $user_no, $path );
792 $tz_ids = array();
793 foreach( $timezones AS $k => $tz ) {
794 $tz_ids[$tz->GetPValue('TZID')] = $k;
797 /** Build an array of resources. Each resource is an array of vComponent */
798 $resources = array();
799 foreach( $components AS $k => $comp ) {
800 $uid = $comp->GetPValue('UID');
801 if ( $uid == null || $uid == '' ) {
802 $uid = uuid();
803 $comp->AddProperty('UID',$uid);
804 dbg_error_log( 'LOG WARN', ' PUT: New collection resource does not have a UID - we assign one!' );
806 if ( !isset($resources[$uid]) ) $resources[$uid] = array();
807 $resources[$uid][] = $comp;
809 /** Ensure we have the timezone component for this in our array as well */
810 $tzid = GetTZID($comp);
811 if ( !empty($tzid) && !isset($resources[$uid][$tzid]) && isset($tz_ids[$tzid]) ) {
812 $resources[$uid][$tzid] = $timezones[$tz_ids[$tzid]];
817 $sql = 'SELECT * FROM collection WHERE dav_name = :dav_name';
818 $qry = new AwlQuery( $sql, array( ':dav_name' => $path) );
819 if ( ! $qry->Exec('PUT',__LINE__,__FILE__) ) rollback_on_error( $caldav_context, $user_no, $path );
820 if ( ! $qry->rows() == 1 ) {
821 dbg_error_log( 'ERROR', ' PUT: Collection does not exist at "%s" for user %d', $path, $user_no );
822 rollback_on_error( $caldav_context, $user_no, $path );
824 $collection = $qry->Fetch();
825 $collection_id = $collection->collection_id;
827 // Fetch the current collection data
828 $qry->QDo('SELECT dav_name, caldav_data FROM caldav_data WHERE collection_id=:collection_id', array(
829 ':collection_id' => $collection_id
831 $current_data = array();
832 while( $row = $qry->Fetch() )
833 $current_data[$row->dav_name] = $row->caldav_data;
835 if ( !(isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import) ) $qry->Begin();
836 $base_params = array( ':collection_id' => $collection_id );
838 $dav_data_insert = <<<EOSQL
839 INSERT INTO caldav_data ( user_no, dav_name, dav_etag, caldav_data, caldav_type, logged_user, created, modified, collection_id )
840 VALUES( :user_no, :dav_name, :etag, :dav_data, :caldav_type, :session_user, current_timestamp, current_timestamp, :collection_id )
841 EOSQL;
843 $dav_data_update = <<<EOSQL
844 UPDATE caldav_data SET user_no=:user_no, caldav_data=:dav_data, dav_etag=:etag, caldav_type=:caldav_type, logged_user=:session_user,
845 modified=current_timestamp WHERE collection_id=:collection_id AND dav_name=:dav_name
846 EOSQL;
848 $calitem_insert = <<<EOSQL
849 INSERT INTO calendar_item (user_no, dav_name, dav_id, dav_etag, uid, dtstamp, dtstart, dtend, summary, location, class, transp,
850 description, rrule, tz_id, last_modified, url, priority, created, due, percent_complete, status, collection_id )
851 VALUES ( :user_no, :dav_name, currval('dav_id_seq'), :etag, :uid, :dtstamp, :dtstart, ##dtend##, :summary, :location, :class, :transp,
852 :description, :rrule, :tzid, :modified, :url, :priority, :created, :due, :percent_complete, :status, :collection_id)
853 EOSQL;
855 $calitem_update = <<<EOSQL
856 UPDATE calendar_item SET user_no=:user_no, dav_etag=:etag, uid=:uid, dtstamp=:dtstamp,
857 dtstart=:dtstart, dtend=##dtend##, summary=:summary, location=:location,
858 class=:class, transp=:transp, description=:description, rrule=:rrule,
859 tz_id=:tzid, last_modified=:modified, url=:url, priority=:priority,
860 due=:due, percent_complete=:percent_complete, status=:status
861 WHERE collection_id=:collection_id AND dav_name=:dav_name
862 EOSQL;
864 $last_olson = '';
865 if ( count($resources) > 0 )
866 $qry->QDo('SELECT new_sync_token(0,'.$collection_id.')');
868 foreach( $resources AS $uid => $resource ) {
870 /** Construct the VCALENDAR data */
871 $vcal = new vCalendar();
872 $vcal->SetComponents($resource);
873 $icalendar = $vcal->Render();
874 $dav_name = sprintf( '%s%s.ics', $path, preg_replace('{[&?\\/@%+:]}','',$uid) );
876 /** Do we need to do anything? */
877 $inserting = true;
878 if ( isset($current_data[$dav_name]) ) {
879 if ( $icalendar == $current_data[$dav_name] ) {
880 unset($current_data[$dav_name]);
881 continue;
883 $sync_change = 200;
884 unset($current_data[$dav_name]);
885 $inserting = false;
887 else
888 $sync_change = 201;
890 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Begin();
892 /** As ever, we mostly deal with the first resource component */
893 $first = $resource[0];
895 $dav_data_params = $base_params;
896 $dav_data_params[':user_no'] = $user_no;
897 // We don't allow any of &?\/@%+: in the UID to appear in the path, but anything else is fair game.
898 $dav_data_params[':dav_name'] = $dav_name;
899 $dav_data_params[':etag'] = md5($icalendar);
900 $calitem_params = $dav_data_params;
901 $dav_data_params[':dav_data'] = $icalendar;
902 $dav_data_params[':caldav_type'] = $first->GetType();
903 $dav_data_params[':session_user'] = $session->user_no;
904 if ( !$qry->QDo( ($inserting ? $dav_data_insert : $dav_data_update), $dav_data_params) )
905 rollback_on_error( $caldav_context, $user_no, $path );
907 $qry->QDo('SELECT dav_id FROM caldav_data WHERE dav_name = :dav_name ', array(':dav_name' => $dav_data_params[':dav_name']));
908 if ( $qry->rows() == 1 && $row = $qry->Fetch() ) {
909 $dav_id = $row->dav_id;
912 $dtstart = $first->GetPValue('DTSTART');
913 $calitem_params[':dtstart'] = $dtstart;
914 if ( (!isset($dtstart) || $dtstart == '') && $first->GetPValue('DUE') != '' ) {
915 $dtstart = $first->GetPValue('DUE');
918 $dtend = $first->GetPValue('DTEND');
919 if ( isset($dtend) && $dtend != '' ) {
920 dbg_error_log( 'PUT', ' DTEND: "%s", DTSTART: "%s", DURATION: "%s"', $dtend, $dtstart, $first->GetPValue('DURATION') );
921 $calitem_params[':dtend'] = $dtend;
922 $dtend = ':dtend';
924 else {
925 $dtend = 'NULL';
926 if ( $first->GetPValue('DURATION') != '' AND $dtstart != '' ) {
927 $duration = trim(preg_replace( '#[PT]#', ' ', $first->GetPValue('DURATION') ));
928 if ( $duration == '' ) $duration = '0 seconds';
929 $dtend = '(:dtstart::timestamp with time zone + :duration::interval)';
930 $calitem_params[':duration'] = $duration;
932 elseif ( $first->GetType() == 'VEVENT' ) {
934 * From RFC2445 4.6.1:
935 * For cases where a "VEVENT" calendar component specifies a "DTSTART"
936 * property with a DATE data type but no "DTEND" property, the events
937 * non-inclusive end is the end of the calendar date specified by the
938 * "DTSTART" property. For cases where a "VEVENT" calendar component specifies
939 * a "DTSTART" property with a DATE-TIME data type but no "DTEND" property,
940 * the event ends on the same calendar date and time of day specified by the
941 * "DTSTART" property.
943 * So we're looking for 'VALUE=DATE', to identify the duration, effectively.
946 $dtstart_prop = $first->GetProperty('DTSTART');
947 $value_type = $dtstart_prop->GetParameterValue('VALUE');
948 dbg_error_log('PUT','DTSTART without DTEND. DTSTART value type is %s', $value_type );
949 if ( isset($value_type) && $value_type == 'DATE' )
950 $dtend = '(:dtstart::timestamp with time zone::date + \'1 day\'::interval)';
951 else
952 $dtend = ':dtstart';
956 $last_modified = $first->GetPValue('LAST-MODIFIED');
957 if ( !isset($last_modified) || $last_modified == '' ) $last_modified = gmdate( 'Ymd\THis\Z' );
958 $calitem_params[':modified'] = $last_modified;
960 $dtstamp = $first->GetPValue('DTSTAMP');
961 if ( empty($dtstamp) ) $dtstamp = $last_modified;
962 $calitem_params[':dtstamp'] = $dtstamp;
964 /** RFC2445, 4.8.1.3: Default is PUBLIC, or also if overridden by the collection settings */
965 $class = ($collection->public_events_only == 't' ? 'PUBLIC' : $first->GetPValue('CLASS') );
966 if ( !isset($class) || $class == '' ) $class = 'PUBLIC';
967 $calitem_params[':class'] = $class;
970 /** Calculate what timezone to set, first, if possible */
971 $tzid = GetTZID($first);
972 if ( !empty($tzid) && !empty($resource[$tzid]) ) {
973 $tz = $resource[$tzid];
974 $olson = $vcal->GetOlsonName($tz);
975 dbg_error_log( 'PUT', ' Using TZID[%s] and location of [%s]', $tzid, (isset($olson) ? $olson : '') );
976 if ( !empty($olson) && ($olson != $last_olson) && preg_match( $tz_regex, $olson ) ) {
977 dbg_error_log( 'PUT', ' Setting timezone to %s', $olson );
978 $qry->QDo('SET TIMEZONE TO \''.$olson."'" );
979 $last_olson = $olson;
981 $params = array( ':tzid' => $tzid);
982 $qry = new AwlQuery('SELECT 1 FROM timezones WHERE tzid = :tzid', $params );
983 if ( $qry->Exec('PUT',__LINE__,__FILE__) && $qry->rows() == 0 ) {
984 $params[':olson_name'] = $olson;
985 $params[':vtimezone'] = (isset($tz) ? $tz->Render() : null );
986 $params[':last_modified'] = (isset($tz) ? $tz->GetPValue('LAST-MODIFIED') : null );
987 if ( empty($params[':last_modified']) ) {
988 $params[':last_modified'] = gmdate('Ymd\THis\Z');
990 $qry->QDo('INSERT INTO timezones (tzid, olson_name, active, vtimezone, last_modified) VALUES(:tzid,:olson_name,false,:vtimezone,:last_modified)', $params );
993 else {
994 $tz = $olson = $tzid = null;
997 $sql = str_replace( '##dtend##', $dtend, ($inserting ? $calitem_insert : $calitem_update) );
998 $calitem_params[':tzid'] = $tzid;
999 $calitem_params[':uid'] = $first->GetPValue('UID');
1000 $calitem_params[':summary'] = $first->GetPValue('SUMMARY');
1001 $calitem_params[':location'] = $first->GetPValue('LOCATION');
1002 $calitem_params[':transp'] = $first->GetPValue('TRANSP');
1003 $calitem_params[':description'] = $first->GetPValue('DESCRIPTION');
1004 $calitem_params[':rrule'] = $first->GetPValue('RRULE');
1005 $calitem_params[':url'] = $first->GetPValue('URL');
1006 $calitem_params[':priority'] = $first->GetPValue('PRIORITY');
1007 $calitem_params[':due'] = $first->GetPValue('DUE');
1008 $calitem_params[':percent_complete'] = $first->GetPValue('PERCENT-COMPLETE');
1009 $calitem_params[':status'] = $first->GetPValue('STATUS');
1011 if ( $inserting ) {
1012 $created = $first->GetPValue('CREATED');
1013 if ( $created == '00001231T000000Z' ) $created = '20001231T000000Z';
1014 $calitem_params[':created'] = $created;
1017 if ( !$qry->QDo($sql,$calitem_params) ) rollback_on_error( $caldav_context, $user_no, $path);
1019 write_alarms($dav_id, $first);
1020 write_attendees($dav_id, $vcal);
1022 $qry->QDo("SELECT write_sync_change( $collection_id, $sync_change, :dav_name)", array(':dav_name' => $dav_name ) );
1024 do_scheduling_requests( $vcal, true );
1025 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Commit();
1028 if ( !$appending && count($current_data) > 0 ) {
1029 $params = array( ':collection_id' => $collection_id );
1030 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Begin();
1031 foreach( $current_data AS $dav_name => $data ) {
1032 $params[':dav_name'] = $dav_name;
1033 $qry->QDo('DELETE FROM caldav_data WHERE collection_id = :collection_id AND dav_name = :dav_name', $params);
1034 $qry->QDo('SELECT write_sync_change(:collection_id, 404, :dav_name)', $params);
1036 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Commit();
1039 if ( !(isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import) ) {
1040 if ( ! $qry->Commit() ) rollback_on_error( $caldav_context, $user_no, $path);
1046 * Given a dav_id and an original vCalendar, pull out each of the VALARMs
1047 * and write the values into the calendar_alarm table.
1049 * @param int $dav_id The dav_id of the caldav_data we're processing
1050 * @param vComponent The VEVENT or VTODO containing the VALARM
1051 * @return null
1053 function write_alarms( $dav_id, vComponent $ical ) {
1054 $qry = new AwlQuery('DELETE FROM calendar_alarm WHERE dav_id = '.$dav_id );
1055 $qry->Exec('PUT',__LINE__,__FILE__);
1057 $alarms = $ical->GetComponents('VALARM');
1058 if ( count($alarms) < 1 ) return;
1060 $qry->SetSql('INSERT INTO calendar_alarm ( dav_id, action, trigger, summary, description, component, next_trigger )
1061 VALUES( '.$dav_id.', :action, :trigger, :summary, :description, :component,
1062 :related::timestamp with time zone + :related_trigger::interval )' );
1063 $qry->Prepare();
1064 foreach( $alarms AS $v ) {
1065 $trigger = array_merge($v->GetProperties('TRIGGER'));
1066 if ( $trigger == null ) continue; // Bogus data.
1067 $trigger = $trigger[0];
1068 $related = null;
1069 $related_trigger = '0M';
1070 $trigger_type = $trigger->GetParameterValue('VALUE');
1071 if ( !isset($trigger_type) || $trigger_type == 'DURATION' ) {
1072 switch ( $trigger->GetParameterValue('RELATED') ) {
1073 case 'DTEND': $related = $ical->GetPValue('DTEND'); break;
1074 case 'DUE': $related = $ical->GetPValue('DUE'); break;
1075 default: $related = $ical->GetPValue('DTSTART');
1077 $duration = $trigger->Value();
1078 if ( !preg_match('{^-?P(:?\d+W)?(:?\d+D)?(:?T(:?\d+H)?(:?\d+M)?(:?\d+S)?)?$}', $duration ) ) continue;
1079 $minus = (substr($duration,0,1) == '-');
1080 $related_trigger = trim(preg_replace( '#[PT-]#', ' ', $duration ));
1081 if ( $minus ) {
1082 $related_trigger = preg_replace( '{(\d+[WDHMS])}', '-$1 ', $related_trigger );
1084 else {
1085 $related_trigger = preg_replace( '{(\d+[WDHMS])}', '$1 ', $related_trigger );
1088 else {
1089 if ( false === strtotime($trigger->Value()) ) continue; // Invalid date.
1091 $qry->Bind(':action', $v->GetPValue('ACTION'));
1092 $qry->Bind(':trigger', $trigger->Render());
1093 $qry->Bind(':summary', $v->GetPValue('SUMMARY'));
1094 $qry->Bind(':description', $v->GetPValue('DESCRIPTION'));
1095 $qry->Bind(':component', $v->Render());
1096 $qry->Bind(':related', $related );
1097 $qry->Bind(':related_trigger', $related_trigger );
1098 $qry->Exec('PUT',__LINE__,__FILE__);
1104 * Parse out the attendee property and write a row to the
1105 * calendar_attendee table for each one.
1106 * @param int $dav_id The dav_id of the caldav_data we're processing
1107 * @param vComponent The VEVENT or VTODO containing the ATTENDEEs
1108 * @return null
1110 function write_attendees( $dav_id, vCalendar $ical ) {
1111 $qry = new AwlQuery('DELETE FROM calendar_attendee WHERE dav_id = '.$dav_id );
1112 $qry->Exec('PUT',__LINE__,__FILE__);
1114 $attendees = $ical->GetAttendees();
1115 if ( count($attendees) < 1 ) return;
1117 $qry->SetSql('INSERT INTO calendar_attendee ( dav_id, status, partstat, cn, attendee, role, rsvp, property )
1118 VALUES( '.$dav_id.', :status, :partstat, :cn, :attendee, :role, :rsvp, :property )' );
1119 $qry->Prepare();
1120 $processed = array();
1121 foreach( $attendees AS $v ) {
1122 $attendee = $v->Value();
1123 if ( isset($processed[$attendee]) ) {
1124 dbg_error_log( 'LOG', 'Duplicate attendee "%s" in resource "%d"', $attendee, $dav_id );
1125 dbg_error_log( 'LOG', 'Original: "%s"', $processed[$attendee] );
1126 dbg_error_log( 'LOG', 'Duplicate: "%s"', $v->Render() );
1127 continue; /** @todo work out why we get duplicate ATTENDEE on one VEVENT */
1129 $qry->Bind(':attendee', $attendee );
1130 $qry->Bind(':status', $v->GetParameterValue('STATUS') );
1131 $qry->Bind(':partstat', $v->GetParameterValue('PARTSTAT') );
1132 $qry->Bind(':cn', $v->GetParameterValue('CN') );
1133 $qry->Bind(':role', $v->GetParameterValue('ROLE') );
1134 $qry->Bind(':rsvp', $v->GetParameterValue('RSVP') );
1135 $qry->Bind(':property', $v->Render() );
1136 $qry->Exec('PUT',__LINE__,__FILE__);
1137 $processed[$attendee] = $v->Render();
1143 * Actually write the resource to the database. All checking of whether this is reasonable
1144 * should be done before this is called.
1146 * @param DAVResource $resource The resource being written
1147 * @param string $caldav_data The actual data to be written
1148 * @param DAVResource $collection The collection containing the resource being written
1149 * @param int $author The user_no who wants to put this resource on the server
1150 * @param string $etag An etag unique for this event
1151 * @param string $put_action_type INSERT or UPDATE depending on what we are to do
1152 * @param boolean $caldav_context True, if we are responding via CalDAV, false for other ways of calling this
1153 * @param string Either 'INSERT' or 'UPDATE': the type of action we are doing
1154 * @param boolean $log_action Whether to log the fact that we are writing this into an action log (if configured)
1155 * @param string $weak_etag An etag that is NOT modified on ATTENDEE changes for this event
1157 * @return boolean True for success, false for failure.
1159 function write_resource( DAVResource $resource, $caldav_data, DAVResource $collection, $author, &$etag, $put_action_type, $caldav_context, $log_action=true, $weak_etag=null ) {
1160 global $tz_regex, $session;
1162 $path = $resource->bound_from();
1163 $user_no = $collection->user_no();
1164 $vcal = new vCalendar( $caldav_data );
1165 $resources = $vcal->GetComponents('VTIMEZONE',false); // Not matching VTIMEZONE
1166 if ( !isset($resources[0]) ) {
1167 $resource_type = 'Unknown';
1168 /** @todo Handle writing non-calendar resources, like address book entries or random file data */
1169 rollback_on_error( $caldav_context, $user_no, $path, translate('No calendar content'), 412 );
1170 return false;
1172 else {
1173 $first = $resources[0];
1174 if ( !($first instanceof vComponent) ) {
1175 print $vcal->Render();
1176 fatal('This is not a vComponent!');
1178 $resource_type = $first->GetType();
1181 $collection_id = $collection->collection_id();
1183 $qry = new AwlQuery();
1184 $qry->Begin();
1186 $dav_params = array(
1187 ':etag' => $etag,
1188 ':dav_data' => $caldav_data,
1189 ':caldav_type' => $resource_type,
1190 ':session_user' => $author,
1191 ':weak_etag' => $weak_etag
1194 $calitem_params = array(
1195 ':etag' => $etag
1198 if ( $put_action_type == 'INSERT' ) {
1199 $qry->QDo('SELECT nextval(\'dav_id_seq\') AS dav_id, null AS caldav_data');
1201 else {
1202 $qry->QDo('SELECT dav_id, caldav_data FROM caldav_data WHERE dav_name = :dav_name ', array(':dav_name' => $path));
1204 if ( $qry->rows() != 1 || !($row = $qry->Fetch()) ) {
1205 // No dav_id? => We're toast!
1206 trace_bug( 'No dav_id for "%s" on %s!!!', $path, ($create_resource ? 'create': 'update'));
1207 rollback_on_error( $caldav_context, $user_no, $path);
1208 return false;
1210 $dav_id = $row->dav_id;
1211 $old_dav_data = $row->caldav_data;
1212 $dav_params[':dav_id'] = $dav_id;
1213 $calitem_params[':dav_id'] = $dav_id;
1215 $due = null;
1216 if ( $first->GetType() == 'VTODO' ) $due = $first->GetPValue('DUE');
1217 $calitem_params[':due'] = $due;
1218 $dtstart = $first->GetPValue('DTSTART');
1219 if ( empty($dtstart) ) $dtstart = $due;
1220 $calitem_params[':dtstart'] = $dtstart;
1222 $dtend = $first->GetPValue('DTEND');
1223 if ( isset($dtend) && $dtend != '' ) {
1224 dbg_error_log( 'PUT', ' DTEND: "%s", DTSTART: "%s", DURATION: "%s"', $dtend, $dtstart, $first->GetPValue('DURATION') );
1225 $calitem_params[':dtend'] = $dtend;
1226 $dtend = ':dtend';
1228 else {
1229 // In this case we'll construct the SQL directly as a calculation relative to :dtstart
1230 $dtend = 'NULL';
1231 if ( $first->GetPValue('DURATION') != '' AND $dtstart != '' ) {
1232 $duration = trim(preg_replace( '#[PT]#', ' ', $first->GetPValue('DURATION') ));
1233 if ( $duration == '' ) $duration = '0 seconds';
1234 $dtend = '(:dtstart::timestamp with time zone + :duration::interval)';
1235 $calitem_params[':duration'] = $duration;
1237 elseif ( $first->GetType() == 'VEVENT' ) {
1239 * From RFC2445 4.6.1:
1240 * For cases where a "VEVENT" calendar component specifies a "DTSTART"
1241 * property with a DATE data type but no "DTEND" property, the events
1242 * non-inclusive end is the end of the calendar date specified by the
1243 * "DTSTART" property. For cases where a "VEVENT" calendar component specifies
1244 * a "DTSTART" property with a DATE-TIME data type but no "DTEND" property,
1245 * the event ends on the same calendar date and time of day specified by the
1246 * "DTSTART" property.
1248 * So we're looking for 'VALUE=DATE', to identify the duration, effectively.
1251 $dtstart_prop = $first->GetProperty('DTSTART');
1252 $value_type = $dtstart_prop->GetParameterValue('VALUE');
1253 dbg_error_log('PUT','DTSTART without DTEND. DTSTART value type is %s', $value_type );
1254 if ( isset($value_type) && $value_type == 'DATE' )
1255 $dtend = '(:dtstart::timestamp with time zone::date + \'1 day\'::interval)';
1256 else
1257 $dtend = ':dtstart';
1261 $dtstamp = $first->GetPValue('DTSTAMP');
1262 if ( !isset($dtstamp) || $dtstamp == '' ) {
1263 // Strictly, we're dealing with an out of spec component here, but we'll try and survive
1264 $dtstamp = gmdate( 'Ymd\THis\Z' );
1266 $calitem_params[':dtstamp'] = $dtstamp;
1268 $last_modified = $first->GetPValue('LAST-MODIFIED');
1269 if ( !isset($last_modified) || $last_modified == '' ) $last_modified = $dtstamp;
1270 $dav_params[':modified'] = $last_modified;
1271 $calitem_params[':modified'] = $last_modified;
1273 $created = $first->GetPValue('CREATED');
1274 if ( $created == '00001231T000000Z' ) $created = '20001231T000000Z';
1276 $class = $first->GetPValue('CLASS');
1277 /* Check and see if we should over ride the class. */
1278 /** @todo is there some way we can move this out of this function? Or at least get rid of the need for the SQL query here. */
1279 if ( public_events_only($user_no, $path) ) {
1280 $class = 'PUBLIC';
1284 * It seems that some calendar clients don't set a class...
1285 * RFC2445, 4.8.1.3:
1286 * Default is PUBLIC
1288 if ( !isset($class) || $class == '' ) {
1289 $class = 'PUBLIC';
1291 $calitem_params[':class'] = $class;
1293 /** Calculate what timezone to set, first, if possible */
1294 $last_olson = 'Turkmenikikamukau'; // I really hope this location doesn't exist!
1295 $tzid = GetTZID($first);
1296 if ( !empty($tzid) ) {
1297 $timezones = $vcal->GetComponents('VTIMEZONE');
1298 foreach( $timezones AS $k => $tz ) {
1299 if ( $tz->GetPValue('TZID') != $tzid ) {
1301 * We'll skip any tz definitions that are for a TZID other than the DTSTART/DUE on the first VEVENT/VTODO
1303 dbg_error_log( 'ERROR', ' Event uses TZID[%s], skipping included TZID[%s]!', $tz->GetPValue('TZID'), $tzid );
1304 continue;
1306 $olson = olson_from_tzstring($tzid);
1307 if ( empty($olson) ) {
1308 $olson = $tz->GetPValue('X-LIC-LOCATION');
1309 if ( !empty($olson) ) {
1310 $olson = olson_from_tzstring($olson);
1315 dbg_error_log( 'PUT', ' Using TZID[%s] and location of [%s]', $tzid, (isset($olson) ? $olson : '') );
1316 if ( !empty($olson) && ($olson != $last_olson) && preg_match( $tz_regex, $olson ) ) {
1317 dbg_error_log( 'PUT', ' Setting timezone to %s', $olson );
1318 if ( $olson != '' ) {
1319 $qry->QDo('SET TIMEZONE TO \''.$olson."'" );
1321 $last_olson = $olson;
1323 $params = array( ':tzid' => $tzid);
1324 $qry = new AwlQuery('SELECT 1 FROM timezones WHERE tzid = :tzid', $params );
1325 if ( $qry->Exec('PUT',__LINE__,__FILE__) && $qry->rows() == 0 ) {
1326 $params[':olson_name'] = $olson;
1327 $params[':vtimezone'] = (isset($tz) ? $tz->Render() : null );
1328 $qry->QDo('INSERT INTO timezones (tzid, olson_name, active, vtimezone) VALUES(:tzid,:olson_name,false,:vtimezone)', $params );
1330 if ( !isset($olson) || $olson == '' ) $olson = $tzid;
1334 $qry->QDo('SELECT new_sync_token(0,'.$collection_id.')');
1336 $calitem_params[':tzid'] = $tzid;
1337 $calitem_params[':uid'] = $first->GetPValue('UID');
1338 $calitem_params[':summary'] = $first->GetPValue('SUMMARY');
1339 $calitem_params[':location'] = $first->GetPValue('LOCATION');
1340 $calitem_params[':transp'] = $first->GetPValue('TRANSP');
1341 $calitem_params[':description'] = $first->GetPValue('DESCRIPTION');
1342 $calitem_params[':rrule'] = $first->GetPValue('RRULE');
1343 $calitem_params[':url'] = $first->GetPValue('URL');
1344 $calitem_params[':priority'] = $first->GetPValue('PRIORITY');
1345 $calitem_params[':percent_complete'] = $first->GetPValue('PERCENT-COMPLETE');
1346 $calitem_params[':status'] = $first->GetPValue('STATUS');
1348 if ( !$collection->IsSchedulingCollection() ) {
1349 if ( do_scheduling_requests($vcal, ($put_action_type == 'INSERT'), $old_dav_data ) ) {
1350 $dav_params[':dav_data'] = $vcal->Render(null, true);
1351 $etag = null;
1355 if ( !isset($dav_params[':modified']) ) $dav_params[':modified'] = 'now';
1356 if ( $put_action_type == 'INSERT' ) {
1357 $sql = 'INSERT INTO caldav_data ( dav_id, user_no, dav_name, dav_etag, caldav_data, caldav_type, logged_user, created, modified, collection_id, weak_etag )
1358 VALUES( :dav_id, :user_no, :dav_name, :etag, :dav_data, :caldav_type, :session_user, :created, :modified, :collection_id, :weak_etag )';
1359 $dav_params[':collection_id'] = $collection_id;
1360 $dav_params[':user_no'] = $user_no;
1361 $dav_params[':dav_name'] = $path;
1362 $dav_params[':created'] = (isset($created) && $created != '' ? $created : $dtstamp);
1364 else {
1365 $sql = 'UPDATE caldav_data SET caldav_data=:dav_data, dav_etag=:etag, caldav_type=:caldav_type, logged_user=:session_user,
1366 modified=:modified, weak_etag=:weak_etag WHERE dav_id=:dav_id';
1368 $qry = new AwlQuery($sql,$dav_params);
1369 if ( !$qry->Exec('PUT',__LINE__,__FILE__) ) {
1370 fatal('Insert into calendar_item failed...');
1371 rollback_on_error( $caldav_context, $user_no, $path);
1372 return false;
1376 if ( $put_action_type == 'INSERT' ) {
1377 $sql = <<<EOSQL
1378 INSERT INTO calendar_item (user_no, dav_name, dav_id, dav_etag, uid, dtstamp,
1379 dtstart, dtend, summary, location, class, transp,
1380 description, rrule, tz_id, last_modified, url, priority,
1381 created, due, percent_complete, status, collection_id )
1382 VALUES ( :user_no, :dav_name, :dav_id, :etag, :uid, :dtstamp,
1383 :dtstart, $dtend, :summary, :location, :class, :transp,
1384 :description, :rrule, :tzid, :modified, :url, :priority,
1385 :created, :due, :percent_complete, :status, :collection_id )
1386 EOSQL;
1387 $sync_change = 201;
1388 $calitem_params[':collection_id'] = $collection_id;
1389 $calitem_params[':user_no'] = $user_no;
1390 $calitem_params[':dav_name'] = $path;
1391 $calitem_params[':created'] = $dav_params[':created'];
1393 else {
1394 $sql = <<<EOSQL
1395 UPDATE calendar_item SET dav_etag=:etag, uid=:uid, dtstamp=:dtstamp,
1396 dtstart=:dtstart, dtend=$dtend, summary=:summary, location=:location,
1397 class=:class, transp=:transp, description=:description, rrule=:rrule,
1398 tz_id=:tzid, last_modified=:modified, url=:url, priority=:priority,
1399 due=:due, percent_complete=:percent_complete, status=:status
1400 WHERE dav_id=:dav_id
1401 EOSQL;
1402 $sync_change = 200;
1405 write_alarms($dav_id, $first);
1406 write_attendees($dav_id, $vcal);
1408 if ( $log_action && function_exists('log_caldav_action') ) {
1409 log_caldav_action( $put_action_type, $first->GetPValue('UID'), $user_no, $collection_id, $path );
1411 else if ( $log_action ) {
1412 dbg_error_log( 'PUT', 'No log_caldav_action( %s, %s, %s, %s, %s) can be called.',
1413 $put_action_type, $first->GetPValue('UID'), $user_no, $collection_id, $path );
1416 $qry = new AwlQuery( $sql, $calitem_params );
1417 if ( !$qry->Exec('PUT',__LINE__,__FILE__) ) {
1418 rollback_on_error( $caldav_context, $user_no, $path);
1419 return false;
1421 $qry->QDo("SELECT write_sync_change( $collection_id, $sync_change, :dav_name)", array(':dav_name' => $path ) );
1422 $qry->Commit();
1424 if ( function_exists('post_commit_action') ) {
1425 post_commit_action( $put_action_type, $first->GetPValue('UID'), $user_no, $collection_id, $path );
1428 // Uncache anything to do with the collection
1429 $cache = getCacheInstance();
1430 $cache_ns = 'collection-'.preg_replace( '{/[^/]*$}', '/', $path);
1431 $cache->delete( $cache_ns, null );
1433 dbg_error_log( 'PUT', 'User: %d, ETag: %s, Path: %s', $author, $etag, $path);
1435 return true; // Success!
1441 * A slightly simpler version of write_resource which will make more sense for calling from
1442 * an external program. This makes assumptions that the collection and user do exist
1443 * and bypasses all checks for whether it is reasonable to write this here.
1444 * @param string $path The path to the resource being written
1445 * @param string $caldav_data The actual resource to be written
1446 * @param string $put_action_type INSERT or UPDATE depending on what we are to do
1447 * @return boolean True for success, false for failure.
1449 function simple_write_resource( $path, $caldav_data, $put_action_type, $write_action_log = false ) {
1450 global $session;
1453 * We pull the user_no & collection_id out of the collection table, based on the resource path
1455 $dav_resource = new DAVResource($path);
1456 $etag = md5($caldav_data);
1457 $collection_path = preg_replace( '#/[^/]*$#', '/', $path );
1458 $collection = new DAVResource($collection_path);
1459 if ( $collection->IsCollection() || $collection->IsSchedulingCollection() ) {
1460 return write_resource( $dav_resource, $caldav_data, $collection, $session->user_no, $etag, $put_action_type, false, $write_action_log );
1462 return false;