Fixed schedule reply handling for missing organizer
[davical.git] / inc / caldav-PUT-functions.php
blob5be20eb801c42e246bfe9113f50c4a64080fcdd3
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');
23 include_once('RRule-v2.php');
25 $bad_events = null;
27 /**
28 * A regex which will match most reasonable timezones acceptable to PostgreSQL.
30 $tz_regex = ':^(Africa|America|Antarctica|Arctic|Asia|Atlantic|Australia|Brazil|Canada|Chile|Etc|Europe|Indian|Mexico|Mideast|Pacific|US)/[a-z_]+$:i';
32 /**
33 * This function launches an error
34 * @param boolean $caldav_context Whether we are responding via CalDAV or interactively
35 * @param int $user_no the user who will receive this ics file
36 * @param string $path the $path where the PUT failed to store such as /user_foo/home/
37 * @param string $message An optional error message to return to the client
38 * @param int $error_no An optional value for the HTTP error code
40 function rollback_on_error( $caldav_context, $user_no, $path, $message='', $error_no=500 ) {
41 global $c, $bad_events;
42 if ( !$message ) $message = translate('Database error');
43 $qry = new AwlQuery();
44 if ( $qry->TransactionState() != 0 ) $qry->Rollback();
45 if ( $caldav_context ) {
46 if ( isset($bad_events) && isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) {
47 $bad_events[] = $message;
49 else {
50 global $request;
51 $request->DoResponse( $error_no, $message );
53 // and we don't return from that, ever...
56 $c->messages[] = sprintf(translate('Status: %d, Message: %s, User: %d, Path: %s'), $error_no, $message, $user_no, $path);
62 /**
63 * Work out the location we are doing the PUT to, and check that we have the rights to
64 * do the needful.
65 * @param string $username The name of the destination user
66 * @param int $user_no The user making the change
67 * @param string $path The DAV path the resource is bing PUT to
68 * @param boolean $caldav_context Whether we are responding via CalDAV or interactively
69 * @param boolean $public Whether the collection will be public, should we need to create it
71 function controlRequestContainer( $username, $user_no, $path, $caldav_context, $public = null ) {
72 global $c, $request, $bad_events;
74 // 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)
75 if ( preg_match( '#^(.*/)([^/]+)$#', $path, $matches ) ) {//(
76 $request_container = $matches[1]; // get everything up to the last '/'
78 else {
79 // In this case we must have a URL with a trailing '/', so it must be a collection.
80 $request_container = $path;
83 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) {
84 $bad_events = array();
87 /**
88 * Before we write the event, we check the container exists, creating it if it doesn't
90 if ( $request_container == "/$username/" ) {
91 /**
92 * Well, it exists, and we support it, but it is against the CalDAV spec
94 dbg_error_log( 'WARN', ' Storing events directly in user\'s base folders is not recommended!');
96 else {
97 $sql = 'SELECT * FROM collection WHERE dav_name = :dav_name';
98 $qry = new AwlQuery( $sql, array( ':dav_name' => $request_container) );
99 if ( ! $qry->Exec('PUT',__LINE__,__FILE__) ) {
100 rollback_on_error( $caldav_context, $user_no, $path );
102 if ( !isset($c->readonly_webdav_collections) || $c->readonly_webdav_collections == true ) {
103 if ( $qry->rows() == 0 ) {
104 $request->DoResponse( 405 ); // Method not allowed
106 return;
108 if ( $qry->rows() == 0 ) {
109 if ( $public == true ) $public = 't'; else $public = 'f';
110 if ( preg_match( '{^(.*/)([^/]+)/$}', $request_container, $matches ) ) {
111 $parent_container = $matches[1];
112 $displayname = $matches[2];
114 $sql = 'INSERT INTO collection ( user_no, parent_container, dav_name, dav_etag, dav_displayname, is_calendar, created, modified, publicly_readable, resourcetypes )
115 VALUES( :user_no, :parent_container, :dav_name, :dav_etag, :dav_displayname, TRUE, current_timestamp, current_timestamp, :is_public::boolean, :resourcetypes )';
116 $params = array(
117 ':user_no' => $user_no,
118 ':parent_container' => $parent_container,
119 ':dav_name' => $request_container,
120 ':dav_etag' => md5($user_no. $request_container),
121 ':dav_displayname' => $displayname,
122 ':is_public' => $public,
123 ':resourcetypes' => '<DAV::collection/><urn:ietf:params:xml:ns:caldav:calendar/>'
125 $qry->QDo( $sql, $params );
127 else if ( isset($public) ) {
128 $collection = $qry->Fetch();
129 if ( empty($collection->is_public) ) $collection->is_public = 'f';
130 if ( $collection->is_public == ($public?'t':'f') ) {
131 $sql = 'UPDATE collection SET publicly_readable = :is_public::boolean WHERE collection_id = :collection_id';
132 $params = array( ':is_public' => ($public?'t':'f'), ':collection_id' => $collection->collection_id );
133 if ( ! $qry->QDo($sql,$params) ) {
134 rollback_on_error( $caldav_context, $user_no, $path );
144 * Check if this collection should force all events to be PUBLIC.
145 * @param string $user_no the user that owns the collection
146 * @param string $dav_name the collection to check
147 * @return boolean Return true if public events only are allowed.
149 function public_events_only( $user_no, $dav_name ) {
150 global $c;
152 $sql = 'SELECT public_events_only FROM collection WHERE dav_name = :dav_name';
154 $qry = new AwlQuery($sql, array(':dav_name' => $dav_name) );
156 if( $qry->Exec('PUT',__LINE__,__FILE__) && $qry->rows() == 1 ) {
157 $collection = $qry->Fetch();
159 if ($collection->public_events_only == 't') {
160 return true;
164 // Something went wrong, must be false.
165 return false;
169 * Get a TZID string from this VEVENT/VTODO/... component if we can
170 * @param vComponent $comp
171 * @return The TZID value we found, or null
173 function GetTZID( vComponent $comp ) {
174 $p = $comp->GetProperty('DTSTART');
175 if ( !isset($p) && $comp->GetType() == 'VTODO' ) {
176 $p = $comp->GetProperty('DUE');
178 if ( !isset($p) ) return null;
179 return $p->GetParameterValue('TZID');
183 * Deliver scheduling requests to attendees
184 * @param vComponent $ical the VCALENDAR to deliver
186 function handle_schedule_request( $ical ) {
187 global $c, $session, $request;
188 $resources = $ical->GetComponents('VTIMEZONE',false);
189 $ic = $resources[0];
190 $etag = md5 ( $request->raw_post );
191 $reply = new XMLDocument( array("DAV:" => "", "urn:ietf:params:xml:ns:caldav" => "C" ) );
192 $responses = array();
194 $attendees = $ic->GetProperties('ATTENDEE');
195 $wr_attendees = $ic->GetProperties('X-WR-ATTENDEE');
196 if ( count ( $wr_attendees ) > 0 ) {
197 dbg_error_log( "PUT", "Non-compliant iCal request. Using X-WR-ATTENDEE property" );
198 foreach( $wr_attendees AS $k => $v ) {
199 $attendees[] = $v;
202 dbg_error_log( "PUT", "Attempting to deliver scheduling request for %d attendees", count($attendees) );
204 foreach( $attendees AS $k => $attendee ) {
205 $attendee_email = preg_replace( '/^mailto:/', '', $attendee->Value() );
206 if ( $attendee_email == $request->principal->email() ) {
207 dbg_error_log( "PUT", "not delivering to owner" );
208 continue;
210 if ( $attendee->GetParameterValue ( 'PARTSTAT' ) != 'NEEDS-ACTION' || preg_match ( '/^[35]\.[3-9]/', $attendee->GetParameterValue ( 'SCHEDULE-STATUS' ) ) ) {
211 dbg_error_log( "PUT", "attendee %s does not need action", $attendee_email );
212 continue;
215 if ( isset($c->enable_auto_schedule) && !$c->enable_auto_schedule ) {
216 // In this case we're being asked not to do auto-scheduling, so we build
217 // a response back for the client saying we can't...
218 $attendee->SetParameterValue ('SCHEDULE-STATUS','5.3;No scheduling support for user');
219 continue;
222 dbg_error_log( "PUT", "Delivering to %s", $attendee_email );
224 $attendee_principal = new DAVPrincipal ( array ('email'=>$attendee_email, 'options'=> array ( 'allow_by_email' => true ) ) );
225 if ( $attendee_principal == false ){
226 $attendee->SetParameterValue ('SCHEDULE-STATUS','5.3;No scheduling support for user');
227 continue;
229 $deliver_path = $attendee_principal->internal_url('schedule-inbox');
231 $ar = new DAVResource($deliver_path);
232 $priv = $ar->HavePrivilegeTo('schedule-deliver-invite' );
233 if ( ! $ar->HavePrivilegeTo('schedule-deliver-invite' ) ){
234 $reply = new XMLDocument( array('DAV:' => '') );
235 $privnodes = array( $reply->href($attendee_principal->url('schedule_inbox')), new XMLElement( 'privilege' ) );
236 // RFC3744 specifies that we can only respond with one needed privilege, so we pick the first.
237 $reply->NSElement( $privnodes[1], 'schedule-deliver-invite' );
238 $xml = new XMLElement( 'need-privileges', new XMLElement( 'resource', $privnodes) );
239 $xmldoc = $reply->Render('error',$xml);
240 $request->DoResponse( 403, $xmldoc, 'text/xml; charset="utf-8"');
244 $attendee->SetParameterValue ('SCHEDULE-STATUS','1.2;Scheduling message has been delivered');
245 $ncal = new vCalendar( array('METHOD' => 'REQUEST') );
246 $ncal->AddComponent( array_merge( $ical->GetComponents('VEVENT',false), array($ic) ));
247 $content = $ncal->Render();
248 $cid = $ar->GetProperty('collection_id');
249 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 );
250 $item_etag = md5($content);
251 write_resource( new DAVResource($deliver_path . $etag . '.ics'), $content, $ar, $request->user_no, $item_etag,
252 $put_action_type='INSERT', $caldav_context=true, $log_action=true, $etag );
253 $attendee->SetParameterValue ('SCHEDULE-STATUS','1.2;Scheduling message has been delivered');
255 // don't write an entry in the out box, ical doesn't delete it or ever read it again
256 $ncal = new vCalendar(array('METHOD' => 'REQUEST'));
257 $ncal->AddComponent ( array_merge ( $ical->GetComponents('VEVENT',false) , array ($ic) ));
258 $content = $ncal->Render();
259 $deliver_path = $request->principal->internal_url('schedule-inbox');
260 $ar = new DAVResource($deliver_path);
261 $item_etag = md5($content);
262 write_resource( new DAVResource($deliver_path . $etag . '.ics'), $content, $ar, $request->user_no, $item_etag,
263 $put_action_type='INSERT', $caldav_context=true, $log_action=true, $etag );
264 //$etag = md5($content);
265 header('ETag: "'. $etag . '"' );
266 header('Schedule-Tag: "'.$etag . '"' );
267 $request->DoResponse( 201, 'Created' );
271 * Deliver scheduling replies to organizer and other attendees
272 * @param vComponent $ical the VCALENDAR to deliver
273 * @return false on error
275 function handle_schedule_reply ( vCalendar $ical ) {
276 global $c, $session, $request;
277 $resources = $ical->GetComponents('VTIMEZONE',false);
278 $ic = $resources[0];
279 $etag = md5 ( $request->raw_post );
280 $organizer = $ical->GetOrganizer();
281 // for now we treat events with out organizers as an error
282 if ( empty( $organizer ) ) return false;
284 $attendees = array_merge($organizer,$ical->GetAttendees());
285 dbg_error_log( "PUT", "Attempting to deliver scheduling request for %d attendees", count($attendees) );
287 foreach( $attendees AS $k => $attendee ) {
288 $attendee_email = preg_replace( '/^mailto:/i', '', $attendee->Value() );
289 dbg_error_log( "PUT", "Delivering to %s", $attendee_email );
290 $attendee_principal = new DAVPrincipal ( array ('email'=>$attendee_email, 'options'=> array ( 'allow_by_email' => true ) ) );
291 $deliver_path = $attendee_principal->internal_url('schedule_inbox');
292 $attendee_email = preg_replace( '/^mailto:/i', '', $attendee->Value() );
293 if ( $attendee_email == $request->principal->email ) {
294 dbg_error_log( "PUT", "not delivering to owner" );
295 continue;
297 $ar = new DAVResource($deliver_path);
298 if ( ! $ar->HavePrivilegeTo('schedule-deliver-reply' ) ){
299 $reply = new XMLDocument( array('DAV:' => '') );
300 $privnodes = array( $reply->href($attendee_principal->url('schedule_inbox')), new XMLElement( 'privilege' ) );
301 // RFC3744 specifies that we can only respond with one needed privilege, so we pick the first.
302 $reply->NSElement( $privnodes[1], 'schedule-deliver-reply' );
303 $xml = new XMLElement( 'need-privileges', new XMLElement( 'resource', $privnodes) );
304 $xmldoc = $reply->Render('error',$xml);
305 $request->DoResponse( 403, $xmldoc, 'text/xml; charset="utf-8"' );
306 continue;
309 $ncal = new vCalendar( array('METHOD' => 'REPLY') );
310 $ncal->AddComponent ( array_merge ( $ical->GetComponents('VEVENT',false) , array ($ic) ));
311 $content = $ncal->Render();
312 write_resource( new DAVResource($deliver_path . $etag . '.ics'), $content, $ar, $request->user_no, md5($content),
313 $put_action_type='INSERT', $caldav_context=true, $log_action=true, $etag );
315 $request->DoResponse( 201, 'Created' );
320 * Do the scheduling adjustments for a REPLY when an ATTENDEE updates their status.
321 * @param vCalendar $resource The resource that the ATTENDEE is writing to their calendar
322 * @param string $organizer The property which is the event ORGANIZER.
324 function do_scheduling_reply( vCalendar $resource, vProperty $organizer ) {
325 global $request;
326 $organizer_email = preg_replace( '/^mailto:/i', '', $organizer->Value() );
327 $organizer_principal = new Principal('email',$organizer_email );
328 if ( !$organizer_principal->Exists() ) {
329 dbg_error_log( 'PUT', 'Organizer "%s" not found - cannot perform scheduling reply.', $organizer );
330 return false;
332 $sql = 'SELECT caldav_data.dav_name, caldav_data.caldav_data FROM caldav_data JOIN calendar_item USING(dav_id) ';
333 $sql .= 'WHERE caldav_data.collection_id IN (SELECT collection_id FROM collection WHERE is_calendar AND user_no =?) ';
334 $sql .= 'AND uid=? LIMIT 1';
335 $uids = $resource->GetPropertiesByPath('/VCALENDAR/*/UID');
336 if ( count($uids) == 0 ) {
337 dbg_error_log( 'PUT', 'No UID in VCALENDAR - giving up on REPLY.' );
338 return false;
340 $uid = $uids[0]->Value();
341 $qry = new AwlQuery($sql,$organizer_principal->user_no(), $uid);
342 if ( !$qry->Exec('PUT',__LINE__,__FILE__) || $qry->rows() < 1 ) {
343 dbg_error_log( 'PUT', 'Could not find original event from organizer - giving up on REPLY.' );
344 return false;
346 $row = $qry->Fetch();
347 $attendees = $resource->GetAttendees();
348 foreach( $attendees AS $v ) {
349 $email = preg_replace( '/^mailto:/i', '', $v->Value() );
350 if ( $email == $request->principal->email() ) {
351 $attendee = $v;
354 if ( empty($attendee) ) {
355 dbg_error_log( 'PUT', 'Could not find ATTENDEE in VEVENT - giving up on REPLY.' );
356 return false;
358 $schedule_original = new vCalendar($row->caldav_data);
359 $schedule_original->UpdateAttendeeStatus($request->principal->email(), clone($attendee) );
361 $collection_path = preg_replace('{/[^/]+$}', '/', $row->dav_name );
362 $segment_name = str_replace($collection_path, '', $row->dav_name );
363 $organizer_calendar = new WritableCollection(array('path' => $collection_path));
364 $organizer_inbox = new WritableCollection(array('path' => $organizer_principal->internal_url('schedule-inbox')));
366 $schedule_reply = clone($schedule_original);
367 $schedule_reply->AddProperty('METHOD', 'REPLY');
369 dbg_error_log( 'PUT', 'Writing scheduling REPLY from %s to %s', $request->principal->email(), $organizer_principal->email() );
371 $response = '3.7'; // Organizer was not found on server.
372 if ( !$organizer_calendar->Exists() ) {
373 dbg_error_log('ERROR','Default calendar at "%s" does not exist for user "%s"',
374 $organizer_calendar->dav_name(), $schedule_target->username());
375 $response = '5.2'; // No scheduling support for user
377 else {
378 if ( ! $organizer_inbox->HavePrivilegeTo('schedule-deliver-reply') ) {
379 $response = '3.8'; // No authority to deliver replies to organizer.
381 else if ( $organizer_inbox->WriteCalendarMember($schedule_reply, false, false, $request->principal->username().$segment_name) !== false ) {
382 $response = '1.2'; // Scheduling reply delivered successfully
383 if ( $organizer_calendar->WriteCalendarMember($schedule_original, false, false, $segment_name) === false ) {
384 dbg_error_log('ERROR','Could not write updated calendar member to %s',
385 $attendee_calendar->dav_name(), $attendee_calendar->dav_name(), $schedule_target->username());
386 trace_bug('Failed to write scheduling resource.');
391 $schedule_request = clone($schedule_original);
392 $schedule_request->AddProperty('METHOD', 'REQUEST');
394 dbg_error_log( 'PUT', 'Status for organizer <%s> set to "%s"', $organizer->Value(), $response );
395 $organizer->SetParameterValue( 'SCHEDULE-STATUS', $response );
396 $resource->UpdateOrganizerStatus($organizer);
397 $scheduling_actions = true;
399 $calling_attendee = clone($attendee);
400 $attendees = $schedule_original->GetAttendees();
401 foreach( $attendees AS $attendee ) {
402 $email = preg_replace( '/^mailto:/i', '', $attendee->Value() );
403 if ( $email == $request->principal->email() || $email == $organizer_principal->email() ) continue;
405 $agent = $attendee->GetParameterValue('SCHEDULE-AGENT');
406 if ( $agent && $agent != 'SERVER' ) {
407 dbg_error_log( "PUT", "not delivering to %s, schedule agent set to value other than server", $email );
408 continue;
411 // an attendee's reply should modify only the PARTSTAT on other attendees' objects
412 // other properties (that might have been adjusted individually by those other
413 // attendees) should remain unmodified. Therefore, we have to make $schedule_original
414 // and $schedule_request be initialized by each attendee's object here.
415 $attendee_principal = new DAVPrincipal ( array ('email'=>$email, 'options'=> array ( 'allow_by_email' => true ) ) );
416 if ( $attendee_principal == false ){
417 dbg_error_log( 'PUT', 'Could not find attendee %s', $email);
418 continue;
420 $sql = 'SELECT caldav_data.dav_name, caldav_data.caldav_data, caldav_data.collection_id FROM caldav_data JOIN calendar_item USING(dav_id) ';
421 $sql .= 'WHERE caldav_data.collection_id IN (SELECT collection_id FROM collection WHERE is_calendar AND user_no =?) ';
422 $sql .= 'AND uid=? LIMIT 1';
423 $qry = new AwlQuery($sql,$attendee_principal->user_no(), $uid);
424 if ( !$qry->Exec('PUT',__LINE__,__FILE__) || $qry->rows() < 1 ) {
425 dbg_error_log( 'PUT', "Could not find attendee's event %s", $uid );
427 $row = $qry->Fetch();
428 $schedule_original = new vCalendar($row->caldav_data);
429 $schedule_original->UpdateAttendeeStatus($request->principal->email(), clone($calling_attendee) );
430 $schedule_request = clone($schedule_original);
431 $schedule_request->AddProperty('METHOD', 'REQUEST');
433 $schedule_target = new Principal('email',$email);
434 $response = '3.7'; // Attendee was not found on server.
435 if ( $schedule_target->Exists() ) {
436 // Instead of always writing to schedule-default-calendar, we first try to
437 // find a calendar with an existing instance of the event in any calendar of this attendee.
438 $r = new DAVResource($row);
439 $attendee_calendar = new WritableCollection(array('path' => $r->parent_path()));
440 if ($attendee_calendar->IsCalendar()) {
441 dbg_error_log( 'XXX', "found the event in attendee's calendar %s", $attendee_calendar->dav_name() );
442 } else {
443 dbg_error_log( 'XXX', 'could not find the event in any calendar, using schedule-default-calendar');
444 $attendee_calendar = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-default-calendar')));
446 if ( !$attendee_calendar->Exists() ) {
447 dbg_error_log('ERROR','Default calendar at "%s" does not exist for user "%s"',
448 $attendee_calendar->dav_name(), $schedule_target->username());
449 $response = '5.2'; // No scheduling support for user
451 else {
452 $attendee_inbox = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-inbox')));
453 if ( ! $attendee_inbox->HavePrivilegeTo('schedule-deliver-invite') ) {
454 $response = '3.8'; // No authority to deliver invitations to user.
456 else if ( $attendee_inbox->WriteCalendarMember($schedule_request, false) !== false ) {
457 $response = '1.2'; // Scheduling invitation delivered successfully
458 if ( $attendee_calendar->WriteCalendarMember($schedule_original, false) === false ) {
459 dbg_error_log('ERROR','Could not write updated calendar member to %s',
460 $attendee_calendar->dav_name(), $attendee_calendar->dav_name(), $schedule_target->username());
461 trace_bug('Failed to write scheduling resource.');
466 dbg_error_log( 'PUT', 'Status for attendee <%s> set to "%s"', $attendee->Value(), $response );
467 $attendee->SetParameterValue( 'SCHEDULE-STATUS', $response );
468 $scheduling_actions = true;
470 $resource->UpdateAttendeeStatus($email, clone($attendee));
474 return $scheduling_actions;
479 * Create/Update the scheduling requests for this resource. This includes updating
480 * the scheduled user's default calendar.
481 * @param vComponent $resource The VEVENT/VTODO/... resource we are scheduling
482 * @param boolean $create true if the scheduling requests are being created.
483 * @return true If there was any scheduling action
485 function do_scheduling_requests( vCalendar $resource, $create, $old_data = null ) {
486 global $request, $c;
487 if ( !isset($request) || (isset($c->enable_auto_schedule) && !$c->enable_auto_schedule) ) return false;
489 if ( ! is_object($resource) ) {
490 trace_bug( 'do_scheduling_requests called with non-object parameter (%s)', gettype($resource) );
491 return false;
494 $organizer = $resource->GetOrganizer();
495 if ( $organizer === false || empty($organizer) ) {
496 dbg_error_log( 'PUT', 'Event has no organizer - no scheduling required.' );
497 return false;
499 $organizer_email = preg_replace( '/^mailto:/i', '', $organizer->Value() );
501 if ( $request->principal->email() != $organizer_email ) {
502 return do_scheduling_reply($resource,$organizer);
505 $schedule_request = clone($resource);
506 $schedule_request->AddProperty('METHOD', 'REQUEST');
508 $old_attendees = array();
509 if ( !empty($old_data) ) {
510 $old_resource = new vCalendar($old_data);
511 $old_attendees = $old_resource->GetAttendees();
513 $attendees = $resource->GetAttendees();
514 if ( count($attendees) == 0 && count($old_attendees) == 0 ) {
515 dbg_error_log( 'PUT', 'Event has no attendees - no scheduling required.', count($attendees) );
516 return false;
518 $removed_attendees = array();
519 foreach( $old_attendees AS $attendee ) {
520 $email = preg_replace( '/^mailto:/i', '', $attendee->Value() );
521 if ( $email == $request->principal->email() ) continue;
522 $removed_attendees[$email] = $attendee;
525 $uids = $resource->GetPropertiesByPath('/VCALENDAR/*/UID');
526 if ( count($uids) == 0 ) {
527 dbg_error_log( 'PUT', 'No UID in VCALENDAR - giving up on REPLY.' );
528 return false;
530 $uid = $uids[0]->Value();
532 dbg_error_log( 'PUT', 'Writing scheduling resources for %d attendees', count($attendees) );
533 $scheduling_actions = false;
534 foreach( $attendees AS $attendee ) {
535 $email = preg_replace( '/^mailto:/i', '', $attendee->Value() );
536 if ( $email == $request->principal->email() ) {
537 dbg_error_log( "PUT", "not delivering to owner '%s'", $request->principal->email() );
538 continue;
541 if ( $create ) {
542 $attendee_is_new = true;
544 else {
545 $attendee_is_new = !isset($removed_attendees[$email]);
546 if ( !$attendee_is_new ) unset($removed_attendees[$email]);
549 $agent = $attendee->GetParameterValue('SCHEDULE-AGENT');
550 if ( $agent && $agent != 'SERVER' ) {
551 dbg_error_log( "PUT", "not delivering to %s, schedule agent set to value other than server", $email );
552 continue;
554 $schedule_target = new Principal('email',$email);
555 $response = '3.7'; // Attendee was not found on server.
556 dbg_error_log( 'PUT', 'Handling scheduling resources for %s on %s which is %s', $email,
557 ($create?'create':'update'), ($attendee_is_new? 'new' : 'an update') );
558 if ( $schedule_target->Exists() ) {
559 // Instead of always writing to schedule-default-calendar, we first try to
560 // find a calendar with an existing instance of the event.
561 $sql = 'SELECT caldav_data.dav_name, caldav_data.caldav_data, caldav_data.collection_id FROM caldav_data JOIN calendar_item USING(dav_id) ';
562 $sql .= 'WHERE caldav_data.collection_id IN (SELECT collection_id FROM collection WHERE is_calendar AND user_no =?) ';
563 $sql .= 'AND uid=? LIMIT 1';
564 $qry = new AwlQuery($sql,$schedule_target->user_no(), $uid);
565 if ( !$qry->Exec('PUT',__LINE__,__FILE__) || $qry->rows() < 1 ) {
566 dbg_error_log( 'PUT', "Could not find event in attendee's calendars" );
567 $attendee_calendar = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-default-calendar')));
568 } else {
569 $row = $qry->Fetch();
570 $r = new DAVResource($row);
571 $attendee_calendar = new WritableCollection(array('path' => $r->parent_path()));
572 if ($attendee_calendar->IsCalendar()) {
573 dbg_error_log( 'XXX', "found the event in attendee's calendar %s", $attendee_calendar->dav_name() );
574 } else {
575 dbg_error_log( 'XXX', 'could not find the event in any calendar, using schedule-default-calendar');
576 $attendee_calendar = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-default-calendar')));
579 if ( !$attendee_calendar->Exists() ) {
580 dbg_error_log('ERROR','Default calendar at "%s" does not exist for user "%s"',
581 $attendee_calendar->dav_name(), $schedule_target->username());
582 $response = '5.2'; // No scheduling support for user
584 else {
585 $attendee_inbox = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-inbox')));
586 if ( ! $attendee_inbox->HavePrivilegeTo('schedule-deliver-invite') ) {
587 $response = '3.8'; // No authority to deliver invitations to user.
589 else if ( $attendee_inbox->WriteCalendarMember($schedule_request, $attendee_is_new) !== false ) {
590 $response = '1.2'; // Scheduling invitation delivered successfully
591 if ( $attendee_calendar->WriteCalendarMember($resource, $attendee_is_new) === false ) {
592 dbg_error_log('ERROR','Could not write %s calendar member to %s', ($attendee_is_new?'new':'updated'),
593 $attendee_calendar->dav_name(), $attendee_calendar->dav_name(), $schedule_target->username());
594 trace_bug('Failed to write scheduling resource.');
599 else {
600 $remote = new iSchedule ();
601 $answer = $remote->sendRequest ( $email, 'VEVENT/REQUEST', $schedule_request->Render() );
602 if ( $answer === false ) {
603 $response = "3.7;Invalid Calendar User" ;
605 else {
606 foreach ( $answer as $a ) // should only be one element in array
608 if ( $a === false ) {
609 $response = "3.7;Invalid Calendar User" ;
611 elseif ( substr( $a, 0, 1 ) >= 1 ) {
612 $response = $a ;
614 else {
615 $response = "2.0;Success" ;
620 dbg_error_log( 'PUT', 'Status for attendee <%s> set to "%s"', $attendee->Value(), $response );
621 $attendee->SetParameterValue( 'SCHEDULE-STATUS', $response );
622 $scheduling_actions = true;
625 if ( !$create ) {
626 foreach( $removed_attendees AS $attendee ) {
627 $schedule_target = new Principal('email',$email);
628 if ( $schedule_target->Exists() ) {
629 $attendee_calendar = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-default-calendar')));
633 return $scheduling_actions;
638 * This function will import a whole collection
639 * @param string $ics_content the ics file to import
640 * @param int $user_no the user wich will receive this ics file
641 * @param string $path the $path where it will be store such as /user_foo/home/
642 * @param boolean $caldav_context Whether we are responding via CalDAV or interactively
644 * The work is either done by
646 function import_collection( $import_content, $user_no, $path, $caldav_context, $appending = false ) {
647 global $c;
649 if ( ! ini_get('open_basedir') && (isset($c->dbg['ALL']) || isset($c->dbg['put'])) ) {
650 $fh = fopen('/tmp/PUT-2.txt','w');
651 if ( $fh ) {
652 fwrite($fh,$import_content);
653 fclose($fh);
657 if ( preg_match( '{^begin:(vcard|vcalendar)}i', $import_content, $matches) ) {
658 if ( $matches[1] == 'VCARD' )
659 import_addressbook_collection( $import_content, $user_no, $path, $caldav_context, $appending );
660 elseif ( $matches[1] == 'VCALENDAR' )
661 import_calendar_collection( $import_content, $user_no, $path, $caldav_context, $appending );
663 // Uncache anything to do with the collection
664 $cache = getCacheInstance();
665 $cache_ns = 'collection-'.preg_replace( '{/[^/]*$}', '/', $path);
666 $cache->delete( $cache_ns, null );
668 else {
669 dbg_error_log('PUT', 'Can only import files which are VCARD or VCALENDAR');
674 * This function will import a whole calendar
675 * @param string $ics_content the ics file to import
676 * @param int $user_no the user wich will receive this ics file
677 * @param string $path the $path where it will be store such as /user_foo/home/
678 * @param boolean $caldav_context Whether we are responding via CalDAV or interactively
680 * Any VEVENTs with the same UID will be concatenated together
682 function import_addressbook_collection( $vcard_content, $user_no, $path, $caldav_context, $appending = false ) {
683 global $c, $session;
684 // We hack this into an enclosing component because vComponent only expects a single root component
685 $addressbook = new vComponent("BEGIN:ADDRESSES\r\n".$vcard_content."\r\nEND:ADDRESSES\r\n");
687 require_once('vcard.php');
689 $sql = 'SELECT * FROM collection WHERE dav_name = :dav_name';
690 $qry = new AwlQuery( $sql, array( ':dav_name' => $path) );
691 if ( ! $qry->Exec('PUT',__LINE__,__FILE__) ) rollback_on_error( $caldav_context, $user_no, $path );
692 if ( ! $qry->rows() == 1 ) {
693 dbg_error_log( 'ERROR', ' PUT: Collection does not exist at "%s" for user %d', $path, $user_no );
694 rollback_on_error( $caldav_context, $user_no, $path );
696 $collection = $qry->Fetch();
698 if ( !(isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import) ) $qry->Begin();
699 $base_params = array(
700 ':collection_id' => $collection->collection_id,
701 ':session_user' => $session->user_no,
702 ':caldav_type' => 'VCARD'
704 if ( !$appending ) {
705 if ( !$qry->QDo('DELETE FROM caldav_data WHERE collection_id = :collection_id', $base_params) )
706 rollback_on_error( $caldav_context, $user_no, $collection->collection_id );
709 $dav_data_insert = <<<EOSQL
710 INSERT INTO caldav_data ( user_no, dav_name, dav_etag, caldav_data, caldav_type, logged_user, created, modified, collection_id )
711 VALUES( :user_no, :dav_name, :etag, :dav_data, :caldav_type, :session_user, :created, :modified, :collection_id )
712 EOSQL;
715 $resources = $addressbook->GetComponents();
716 foreach( $resources AS $k => $resource ) {
717 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Begin();
719 $vcard = new vCard( $resource->Render() );
721 $uid = $vcard->GetPValue('UID');
722 if ( empty($uid) ) {
723 $uid = uuid();
724 $vcard->AddProperty('UID',$uid);
727 $last_modified = $vcard->GetPValue('REV');
728 if ( empty($last_modified) ) {
729 $last_modified = gmdate( 'Ymd\THis\Z' );
730 $vcard->AddProperty('REV',$last_modified);
733 $created = $vcard->GetPValue('X-CREATED');
734 if ( empty($last_modified) ) {
735 $created = gmdate( 'Ymd\THis\Z' );
736 $vcard->AddProperty('X-CREATED',$created);
739 $rendered_card = $vcard->Render();
741 $dav_data_params = $base_params;
742 $dav_data_params[':user_no'] = $user_no;
743 // We don't allow any of &?\/@%+: in the UID to appear in the path, but anything else is fair game.
744 $dav_data_params[':dav_name'] = sprintf( '%s%s.ics', $path, preg_replace('{[&?\\/@%+:]}','',$uid) );
745 $dav_data_params[':etag'] = md5($rendered_card);
746 $dav_data_params[':dav_data'] = $rendered_card;
747 $dav_data_params[':modified'] = $last_modified;
748 $dav_data_params[':created'] = $created;
750 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Begin();
752 if ( !$qry->QDo($dav_data_insert,$dav_data_params) ) rollback_on_error( $caldav_context, $user_no, $path );
754 $qry->QDo('SELECT dav_id FROM caldav_data WHERE dav_name = :dav_name ', array(':dav_name' => $dav_data_params[':dav_name']));
755 if ( $qry->rows() == 1 && $row = $qry->Fetch() ) {
756 $dav_id = $row->dav_id;
759 $vcard->Write( $row->dav_id, false );
761 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Commit();
764 if ( !(isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import) ) {
765 if ( ! $qry->Commit() ) rollback_on_error( $caldav_context, $user_no, $path);
771 * This function will import a whole calendar
772 * @param string $ics_content the ics file to import
773 * @param int $user_no the user wich will receive this ics file
774 * @param string $path the $path where it will be store such as /user_foo/home/
775 * @param boolean $caldav_context Whether we are responding via CalDAV or interactively
777 * Any VEVENTs with the same UID will be concatenated together
779 function import_calendar_collection( $ics_content, $user_no, $path, $caldav_context, $appending = false ) {
780 global $c, $session, $tz_regex;
781 $calendar = new vComponent($ics_content);
782 $timezones = $calendar->GetComponents('VTIMEZONE',true);
783 $components = $calendar->GetComponents('VTIMEZONE',false);
785 // Add a parameter to calendars on import so it will only load events 'after' @author karora
786 // date, or an RFC5545 duration format offset from the current date.
787 $after = null;
788 if ( isset($_GET['after']) ) {
789 $after = $_GET['after'];
790 if ( strtoupper(substr($after, 0, 1)) == 'P' || strtoupper(substr($after, 0, 1)) == '-P' ) {
791 $duration = new Rfc5545Duration($after);
792 $duration = $duration->asSeconds();
793 $after = time() - (abs($duration));
795 else {
796 $after = new RepeatRuleDateTime($after);
797 $after = $after->epoch();
801 $displayname = $calendar->GetPValue('X-WR-CALNAME');
802 if ( !$appending && isset($displayname) ) {
803 $sql = 'UPDATE collection SET dav_displayname = :displayname WHERE dav_name = :dav_name';
804 $qry = new AwlQuery( $sql, array( ':displayname' => $displayname, ':dav_name' => $path) );
805 if ( ! $qry->Exec('PUT',__LINE__,__FILE__) ) rollback_on_error( $caldav_context, $user_no, $path );
809 $tz_ids = array();
810 foreach( $timezones AS $k => $tz ) {
811 $tz_ids[$tz->GetPValue('TZID')] = $k;
814 /** Build an array of resources. Each resource is an array of vComponent */
815 $resources = array();
816 foreach( $components AS $k => $comp ) {
817 $uid = $comp->GetPValue('UID');
818 if ( $uid == null || $uid == '' ) {
819 $uid = uuid();
820 $comp->AddProperty('UID',$uid);
821 dbg_error_log( 'LOG WARN', ' PUT: New collection resource does not have a UID - we assign one!' );
823 if ( !isset($resources[$uid]) ) $resources[$uid] = array();
824 $resources[$uid][] = $comp;
826 /** Ensure we have the timezone component for this in our array as well */
827 $tzid = GetTZID($comp);
828 if ( !empty($tzid) && !isset($resources[$uid][$tzid]) && isset($tz_ids[$tzid]) ) {
829 $resources[$uid][$tzid] = $timezones[$tz_ids[$tzid]];
834 $sql = 'SELECT * FROM collection WHERE dav_name = :dav_name';
835 $qry = new AwlQuery( $sql, array( ':dav_name' => $path) );
836 if ( ! $qry->Exec('PUT',__LINE__,__FILE__) ) rollback_on_error( $caldav_context, $user_no, $path );
837 if ( ! $qry->rows() == 1 ) {
838 dbg_error_log( 'ERROR', ' PUT: Collection does not exist at "%s" for user %d', $path, $user_no );
839 rollback_on_error( $caldav_context, $user_no, $path );
841 $collection = $qry->Fetch();
842 $collection_id = $collection->collection_id;
844 // Fetch the current collection data
845 $qry->QDo('SELECT dav_name, caldav_data FROM caldav_data WHERE collection_id=:collection_id', array(
846 ':collection_id' => $collection_id
848 $current_data = array();
849 while( $row = $qry->Fetch() )
850 $current_data[$row->dav_name] = $row->caldav_data;
852 if ( !(isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import) ) $qry->Begin();
853 $base_params = array( ':collection_id' => $collection_id );
855 $dav_data_insert = <<<EOSQL
856 INSERT INTO caldav_data ( user_no, dav_name, dav_etag, caldav_data, caldav_type, logged_user, created, modified, collection_id )
857 VALUES( :user_no, :dav_name, :etag, :dav_data, :caldav_type, :session_user, current_timestamp, current_timestamp, :collection_id )
858 EOSQL;
860 $dav_data_update = <<<EOSQL
861 UPDATE caldav_data SET user_no=:user_no, caldav_data=:dav_data, dav_etag=:etag, caldav_type=:caldav_type, logged_user=:session_user,
862 modified=current_timestamp WHERE collection_id=:collection_id AND dav_name=:dav_name
863 EOSQL;
865 $calitem_insert = <<<EOSQL
866 INSERT INTO calendar_item (user_no, dav_name, dav_id, dav_etag, uid, dtstamp, dtstart, dtend, summary, location, class, transp,
867 description, rrule, tz_id, last_modified, url, priority, created, due, percent_complete, status, collection_id )
868 VALUES ( :user_no, :dav_name, currval('dav_id_seq'), :etag, :uid, :dtstamp, :dtstart, ##dtend##, :summary, :location, :class, :transp,
869 :description, :rrule, :tzid, :modified, :url, :priority, :created, :due, :percent_complete, :status, :collection_id)
870 EOSQL;
872 $calitem_update = <<<EOSQL
873 UPDATE calendar_item SET user_no=:user_no, dav_etag=:etag, uid=:uid, dtstamp=:dtstamp,
874 dtstart=:dtstart, dtend=##dtend##, summary=:summary, location=:location,
875 class=:class, transp=:transp, description=:description, rrule=:rrule,
876 tz_id=:tzid, last_modified=:modified, url=:url, priority=:priority,
877 due=:due, percent_complete=:percent_complete, status=:status
878 WHERE collection_id=:collection_id AND dav_name=:dav_name
879 EOSQL;
881 $last_olson = '';
882 if ( count($resources) > 0 )
883 $qry->QDo('SELECT new_sync_token(0,'.$collection_id.')');
885 foreach( $resources AS $uid => $resource ) {
887 /** Construct the VCALENDAR data */
888 $vcal = new vCalendar();
889 $vcal->SetComponents($resource);
890 $icalendar = $vcal->Render();
891 $dav_name = sprintf( '%s%s.ics', $path, preg_replace('{[&?\\/@%+:]}','',$uid) );
893 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Begin();
895 /** As ever, we mostly deal with the first resource component */
896 $first = $resource[0];
898 $dav_data_params = $base_params;
899 $dav_data_params[':user_no'] = $user_no;
900 // We don't allow any of &?\/@%+: in the UID to appear in the path, but anything else is fair game.
901 $dav_data_params[':dav_name'] = $dav_name;
902 $dav_data_params[':etag'] = md5($icalendar);
903 $calitem_params = $dav_data_params;
904 $dav_data_params[':dav_data'] = $icalendar;
905 $dav_data_params[':caldav_type'] = $first->GetType();
906 $dav_data_params[':session_user'] = $session->user_no;
908 $dtstart = $first->GetPValue('DTSTART');
909 $calitem_params[':dtstart'] = $dtstart;
910 if ( (!isset($dtstart) || $dtstart == '') && $first->GetPValue('DUE') != '' ) {
911 $dtstart = $first->GetPValue('DUE');
912 if ( isset($after) ) $dtstart_date = new RepeatRuleDateTime($first->GetProperty('DUE'));
914 else if ( isset($after) ) {
915 $dtstart_date = new RepeatRuleDateTime($first->GetProperty('DTSTART'));
918 $calitem_params[':rrule'] = $first->GetPValue('RRULE');
920 // Skip it if it's after our start date for this import.
921 if ( isset($after) && empty($calitem_params[':rrule']) && $dtstart_date->epoch() < $after ) continue;
923 // Do we actually need to do anything?
924 $inserting = true;
925 if ( isset($current_data[$dav_name]) ) {
926 if ( $icalendar == $current_data[$dav_name] ) {
927 if ( $after == null ) {
928 unset($current_data[$dav_name]);
929 continue;
932 $sync_change = 200;
933 unset($current_data[$dav_name]);
934 $inserting = false;
936 else
937 $sync_change = 201;
939 // Write to the caldav_data table
940 if ( !$qry->QDo( ($inserting ? $dav_data_insert : $dav_data_update), $dav_data_params) )
941 rollback_on_error( $caldav_context, $user_no, $path );
943 // Get the dav_id for this row
944 $qry->QDo('SELECT dav_id FROM caldav_data WHERE dav_name = :dav_name ', array(':dav_name' => $dav_data_params[':dav_name']));
945 if ( $qry->rows() == 1 && $row = $qry->Fetch() ) {
946 $dav_id = $row->dav_id;
949 $dtend = $first->GetPValue('DTEND');
950 if ( isset($dtend) && $dtend != '' ) {
951 dbg_error_log( 'PUT', ' DTEND: "%s", DTSTART: "%s", DURATION: "%s"', $dtend, $dtstart, $first->GetPValue('DURATION') );
952 $calitem_params[':dtend'] = $dtend;
953 $dtend = ':dtend';
955 else {
956 $dtend = 'NULL';
957 if ( $first->GetPValue('DURATION') != '' AND $dtstart != '' ) {
958 $duration = trim(preg_replace( '#[PT]#', ' ', $first->GetPValue('DURATION') ));
959 if ( $duration == '' ) $duration = '0 seconds';
960 $dtend = '(:dtstart::timestamp with time zone + :duration::interval)';
961 $calitem_params[':duration'] = $duration;
963 elseif ( $first->GetType() == 'VEVENT' ) {
965 * From RFC2445 4.6.1:
966 * For cases where a "VEVENT" calendar component specifies a "DTSTART"
967 * property with a DATE data type but no "DTEND" property, the events
968 * non-inclusive end is the end of the calendar date specified by the
969 * "DTSTART" property. For cases where a "VEVENT" calendar component specifies
970 * a "DTSTART" property with a DATE-TIME data type but no "DTEND" property,
971 * the event ends on the same calendar date and time of day specified by the
972 * "DTSTART" property.
974 * So we're looking for 'VALUE=DATE', to identify the duration, effectively.
977 $dtstart_prop = $first->GetProperty('DTSTART');
978 if ( empty($dtstart_prop) ) {
979 dbg_error_log('PUT','Invalid VEVENT without DTSTART, UID="%s" in collection %d', $uid, $collection_id);
980 continue;
982 $value_type = $dtstart_prop->GetParameterValue('VALUE');
983 dbg_error_log('PUT','DTSTART without DTEND. DTSTART value type is %s', $value_type );
984 if ( isset($value_type) && $value_type == 'DATE' )
985 $dtend = '(:dtstart::timestamp with time zone::date + \'1 day\'::interval)';
986 else
987 $dtend = ':dtstart';
991 $last_modified = $first->GetPValue('LAST-MODIFIED');
992 if ( !isset($last_modified) || $last_modified == '' ) $last_modified = gmdate( 'Ymd\THis\Z' );
993 $calitem_params[':modified'] = $last_modified;
995 $dtstamp = $first->GetPValue('DTSTAMP');
996 if ( empty($dtstamp) ) $dtstamp = $last_modified;
997 $calitem_params[':dtstamp'] = $dtstamp;
999 /** RFC2445, 4.8.1.3: Default is PUBLIC, or also if overridden by the collection settings */
1000 $class = ($collection->public_events_only == 't' ? 'PUBLIC' : $first->GetPValue('CLASS') );
1001 if ( !isset($class) || $class == '' ) $class = 'PUBLIC';
1002 $calitem_params[':class'] = $class;
1005 /** Calculate what timezone to set, first, if possible */
1006 $tzid = GetTZID($first);
1007 if ( !empty($tzid) && !empty($resource[$tzid]) ) {
1008 $tz = $resource[$tzid];
1009 $olson = $vcal->GetOlsonName($tz);
1010 dbg_error_log( 'PUT', ' Using TZID[%s] and location of [%s]', $tzid, (isset($olson) ? $olson : '') );
1011 if ( !empty($olson) && ($olson != $last_olson) && preg_match( $tz_regex, $olson ) ) {
1012 dbg_error_log( 'PUT', ' Setting timezone to %s', $olson );
1013 $qry->QDo('SET TIMEZONE TO \''.$olson."'" );
1014 $last_olson = $olson;
1016 $params = array( ':tzid' => $tzid);
1017 $qry = new AwlQuery('SELECT 1 FROM timezones WHERE tzid = :tzid', $params );
1018 if ( $qry->Exec('PUT',__LINE__,__FILE__) && $qry->rows() == 0 ) {
1019 $params[':olson_name'] = $olson;
1020 $params[':vtimezone'] = (isset($tz) ? $tz->Render() : null );
1021 $params[':last_modified'] = (isset($tz) ? $tz->GetPValue('LAST-MODIFIED') : null );
1022 if ( empty($params[':last_modified']) ) {
1023 $params[':last_modified'] = gmdate('Ymd\THis\Z');
1025 $qry->QDo('INSERT INTO timezones (tzid, olson_name, active, vtimezone, last_modified) VALUES(:tzid,:olson_name,false,:vtimezone,:last_modified)', $params );
1028 else {
1029 $tz = $olson = $tzid = null;
1032 $sql = str_replace( '##dtend##', $dtend, ($inserting ? $calitem_insert : $calitem_update) );
1033 $calitem_params[':tzid'] = $tzid;
1034 $calitem_params[':uid'] = $first->GetPValue('UID');
1035 $calitem_params[':summary'] = $first->GetPValue('SUMMARY');
1036 $calitem_params[':location'] = $first->GetPValue('LOCATION');
1037 $calitem_params[':transp'] = $first->GetPValue('TRANSP');
1038 $calitem_params[':description'] = $first->GetPValue('DESCRIPTION');
1039 $calitem_params[':url'] = $first->GetPValue('URL');
1040 $calitem_params[':priority'] = $first->GetPValue('PRIORITY');
1041 $calitem_params[':due'] = $first->GetPValue('DUE');
1042 $calitem_params[':percent_complete'] = $first->GetPValue('PERCENT-COMPLETE');
1043 $calitem_params[':status'] = $first->GetPValue('STATUS');
1045 if ( $inserting ) {
1046 $created = $first->GetPValue('CREATED');
1047 if ( $created == '00001231T000000Z' ) $created = '20001231T000000Z';
1048 $calitem_params[':created'] = $created;
1051 // Write the calendar_item row for this entry
1052 if ( !$qry->QDo($sql,$calitem_params) ) rollback_on_error( $caldav_context, $user_no, $path);
1054 write_alarms($dav_id, $first);
1055 write_attendees($dav_id, $vcal);
1057 $qry->QDo("SELECT write_sync_change( $collection_id, $sync_change, :dav_name)", array(':dav_name' => $dav_name ) );
1059 do_scheduling_requests( $vcal, true );
1060 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Commit();
1063 if ( !$appending && count($current_data) > 0 ) {
1064 $params = array( ':collection_id' => $collection_id );
1065 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Begin();
1066 foreach( $current_data AS $dav_name => $data ) {
1067 $params[':dav_name'] = $dav_name;
1068 $qry->QDo('DELETE FROM caldav_data WHERE collection_id = :collection_id AND dav_name = :dav_name', $params);
1069 $qry->QDo('SELECT write_sync_change(:collection_id, 404, :dav_name)', $params);
1071 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Commit();
1074 if ( !(isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import) ) {
1075 if ( ! $qry->Commit() ) rollback_on_error( $caldav_context, $user_no, $path);
1081 * Given a dav_id and an original vCalendar, pull out each of the VALARMs
1082 * and write the values into the calendar_alarm table.
1084 * @param int $dav_id The dav_id of the caldav_data we're processing
1085 * @param vComponent The VEVENT or VTODO containing the VALARM
1086 * @return null
1088 function write_alarms( $dav_id, vComponent $ical ) {
1089 $qry = new AwlQuery('DELETE FROM calendar_alarm WHERE dav_id = '.$dav_id );
1090 $qry->Exec('PUT',__LINE__,__FILE__);
1092 $alarms = $ical->GetComponents('VALARM');
1093 if ( count($alarms) < 1 ) return;
1095 $qry->SetSql('INSERT INTO calendar_alarm ( dav_id, action, trigger, summary, description, component, next_trigger )
1096 VALUES( '.$dav_id.', :action, :trigger, :summary, :description, :component,
1097 :related::timestamp with time zone + :related_trigger::interval )' );
1098 $qry->Prepare();
1099 foreach( $alarms AS $v ) {
1100 $trigger = array_merge($v->GetProperties('TRIGGER'));
1101 if ( $trigger == null ) continue; // Bogus data.
1102 $trigger = $trigger[0];
1103 $related = null;
1104 $related_trigger = '0M';
1105 $trigger_type = $trigger->GetParameterValue('VALUE');
1106 if ( !isset($trigger_type) || $trigger_type == 'DURATION' ) {
1107 switch ( $trigger->GetParameterValue('RELATED') ) {
1108 case 'DTEND': $related = $ical->GetProperty('DTEND'); break;
1109 case 'DUE': $related = $ical->GetProperty('DUE'); break;
1110 default: $related = $ical->GetProperty('DTSTART');
1112 $duration = $trigger->Value();
1113 if ( !preg_match('{^-?P(:?\d+W)?(:?\d+D)?(:?T(:?\d+H)?(:?\d+M)?(:?\d+S)?)?$}', $duration ) ) continue;
1114 $minus = (substr($duration,0,1) == '-');
1115 $related_trigger = trim(preg_replace( '#[PT-]#', ' ', $duration ));
1116 if ( $minus ) {
1117 $related_trigger = preg_replace( '{(\d+[WDHMS])}', '-$1 ', $related_trigger );
1119 else {
1120 $related_trigger = preg_replace( '{(\d+[WDHMS])}', '$1 ', $related_trigger );
1123 else if ( $trigger_type == 'DATE-TIME' ) {
1124 $related = $trigger;
1126 else {
1127 if ( false === strtotime($trigger->Value()) ) continue; // Invalid date.
1128 $related = $trigger;
1130 $related_date = new RepeatRuleDateTime($related);
1131 $qry->Bind(':action', $v->GetPValue('ACTION'));
1132 $qry->Bind(':trigger', $trigger->Render());
1133 $qry->Bind(':summary', $v->GetPValue('SUMMARY'));
1134 $qry->Bind(':description', $v->GetPValue('DESCRIPTION'));
1135 $qry->Bind(':component', $v->Render());
1136 $qry->Bind(':related', $related_date->UTC() );
1137 $qry->Bind(':related_trigger', $related_trigger );
1138 $qry->Exec('PUT',__LINE__,__FILE__);
1144 * Parse out the attendee property and write a row to the
1145 * calendar_attendee table for each one.
1146 * @param int $dav_id The dav_id of the caldav_data we're processing
1147 * @param vComponent The VEVENT or VTODO containing the ATTENDEEs
1148 * @return null
1150 function write_attendees( $dav_id, vCalendar $ical ) {
1151 $qry = new AwlQuery('DELETE FROM calendar_attendee WHERE dav_id = '.$dav_id );
1152 $qry->Exec('PUT',__LINE__,__FILE__);
1154 $attendees = $ical->GetAttendees();
1155 if ( count($attendees) < 1 ) return;
1157 $qry->SetSql('INSERT INTO calendar_attendee ( dav_id, status, partstat, cn, attendee, role, rsvp, property )
1158 VALUES( '.$dav_id.', :status, :partstat, :cn, :attendee, :role, :rsvp, :property )' );
1159 $qry->Prepare();
1160 $processed = array();
1161 foreach( $attendees AS $v ) {
1162 $attendee = $v->Value();
1163 if ( isset($processed[$attendee]) ) {
1164 dbg_error_log( 'LOG', 'Duplicate attendee "%s" in resource "%d"', $attendee, $dav_id );
1165 dbg_error_log( 'LOG', 'Original: "%s"', $processed[$attendee] );
1166 dbg_error_log( 'LOG', 'Duplicate: "%s"', $v->Render() );
1167 continue; /** @todo work out why we get duplicate ATTENDEE on one VEVENT */
1169 $qry->Bind(':attendee', $attendee );
1170 $qry->Bind(':status', $v->GetParameterValue('STATUS') );
1171 $qry->Bind(':partstat', $v->GetParameterValue('PARTSTAT') );
1172 $qry->Bind(':cn', $v->GetParameterValue('CN') );
1173 $qry->Bind(':role', $v->GetParameterValue('ROLE') );
1174 $qry->Bind(':rsvp', $v->GetParameterValue('RSVP') );
1175 $qry->Bind(':property', $v->Render() );
1176 $qry->Exec('PUT',__LINE__,__FILE__);
1177 $processed[$attendee] = $v->Render();
1183 * Actually write the resource to the database. All checking of whether this is reasonable
1184 * should be done before this is called.
1186 * @param DAVResource $resource The resource being written
1187 * @param string $caldav_data The actual data to be written
1188 * @param DAVResource $collection The collection containing the resource being written
1189 * @param int $author The user_no who wants to put this resource on the server
1190 * @param string $etag An etag unique for this event
1191 * @param string $put_action_type INSERT or UPDATE depending on what we are to do
1192 * @param boolean $caldav_context True, if we are responding via CalDAV, false for other ways of calling this
1193 * @param string Either 'INSERT' or 'UPDATE': the type of action we are doing
1194 * @param boolean $log_action Whether to log the fact that we are writing this into an action log (if configured)
1195 * @param string $weak_etag An etag that is NOT modified on ATTENDEE changes for this event
1197 * @return boolean True for success, false for failure.
1199 function write_resource( DAVResource $resource, $caldav_data, DAVResource $collection, $author, &$etag, $put_action_type, $caldav_context, $log_action=true, $weak_etag=null ) {
1200 global $tz_regex, $session;
1202 $path = $resource->bound_from();
1203 $user_no = $collection->user_no();
1204 $vcal = new vCalendar( $caldav_data );
1205 $resources = $vcal->GetComponents('VTIMEZONE',false); // Not matching VTIMEZONE
1206 if ( !isset($resources[0]) ) {
1207 $resource_type = 'Unknown';
1208 /** @todo Handle writing non-calendar resources, like address book entries or random file data */
1209 rollback_on_error( $caldav_context, $user_no, $path, translate('No calendar content'), 412 );
1210 return false;
1212 else {
1213 $first = $resources[0];
1214 if ( !($first instanceof vComponent) ) {
1215 print $vcal->Render();
1216 fatal('This is not a vComponent!');
1218 $resource_type = $first->GetType();
1221 $collection_id = $collection->collection_id();
1223 $qry = new AwlQuery();
1224 $qry->Begin();
1226 $dav_params = array(
1227 ':etag' => $etag,
1228 ':dav_data' => $caldav_data,
1229 ':caldav_type' => $resource_type,
1230 ':session_user' => $author,
1231 ':weak_etag' => $weak_etag
1234 $calitem_params = array(
1235 ':etag' => $etag
1238 if ( $put_action_type == 'INSERT' ) {
1239 $qry->QDo('SELECT nextval(\'dav_id_seq\') AS dav_id, null AS caldav_data');
1241 else {
1242 $qry->QDo('SELECT dav_id, caldav_data FROM caldav_data WHERE dav_name = :dav_name ', array(':dav_name' => $path));
1244 if ( $qry->rows() != 1 || !($row = $qry->Fetch()) ) {
1245 // No dav_id? => We're toast!
1246 trace_bug( 'No dav_id for "%s" on %s!!!', $path, ($create_resource ? 'create': 'update'));
1247 rollback_on_error( $caldav_context, $user_no, $path);
1248 return false;
1250 $dav_id = $row->dav_id;
1251 $old_dav_data = $row->caldav_data;
1252 $dav_params[':dav_id'] = $dav_id;
1253 $calitem_params[':dav_id'] = $dav_id;
1255 $due = null;
1256 if ( $first->GetType() == 'VTODO' ) $due = $first->GetPValue('DUE');
1257 $calitem_params[':due'] = $due;
1258 $dtstart = $first->GetPValue('DTSTART');
1259 if ( empty($dtstart) ) $dtstart = $due;
1260 $calitem_params[':dtstart'] = $dtstart;
1262 $dtend = $first->GetPValue('DTEND');
1263 if ( isset($dtend) && $dtend != '' ) {
1264 dbg_error_log( 'PUT', ' DTEND: "%s", DTSTART: "%s", DURATION: "%s"', $dtend, $dtstart, $first->GetPValue('DURATION') );
1265 $calitem_params[':dtend'] = $dtend;
1266 $dtend = ':dtend';
1268 else {
1269 // In this case we'll construct the SQL directly as a calculation relative to :dtstart
1270 $dtend = 'NULL';
1271 if ( $first->GetPValue('DURATION') != '' AND $dtstart != '' ) {
1272 $duration = trim(preg_replace( '#[PT]#', ' ', $first->GetPValue('DURATION') ));
1273 if ( $duration == '' ) $duration = '0 seconds';
1274 $dtend = '(:dtstart::timestamp with time zone + :duration::interval)';
1275 $calitem_params[':duration'] = $duration;
1277 elseif ( $first->GetType() == 'VEVENT' ) {
1279 * From RFC2445 4.6.1:
1280 * For cases where a "VEVENT" calendar component specifies a "DTSTART"
1281 * property with a DATE data type but no "DTEND" property, the events
1282 * non-inclusive end is the end of the calendar date specified by the
1283 * "DTSTART" property. For cases where a "VEVENT" calendar component specifies
1284 * a "DTSTART" property with a DATE-TIME data type but no "DTEND" property,
1285 * the event ends on the same calendar date and time of day specified by the
1286 * "DTSTART" property.
1288 * So we're looking for 'VALUE=DATE', to identify the duration, effectively.
1291 $dtstart_prop = $first->GetProperty('DTSTART');
1292 $value_type = $dtstart_prop->GetParameterValue('VALUE');
1293 dbg_error_log('PUT','DTSTART without DTEND. DTSTART value type is %s', $value_type );
1294 if ( isset($value_type) && $value_type == 'DATE' )
1295 $dtend = '(:dtstart::timestamp with time zone::date + \'1 day\'::interval)';
1296 else
1297 $dtend = ':dtstart';
1301 $dtstamp = $first->GetPValue('DTSTAMP');
1302 if ( !isset($dtstamp) || $dtstamp == '' ) {
1303 // Strictly, we're dealing with an out of spec component here, but we'll try and survive
1304 $dtstamp = gmdate( 'Ymd\THis\Z' );
1306 $calitem_params[':dtstamp'] = $dtstamp;
1308 $last_modified = $first->GetPValue('LAST-MODIFIED');
1309 if ( !isset($last_modified) || $last_modified == '' ) $last_modified = $dtstamp;
1310 $dav_params[':modified'] = $last_modified;
1311 $calitem_params[':modified'] = $last_modified;
1313 $created = $first->GetPValue('CREATED');
1314 if ( $created == '00001231T000000Z' ) $created = '20001231T000000Z';
1316 $class = $first->GetPValue('CLASS');
1317 /* Check and see if we should over ride the class. */
1318 /** @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. */
1319 if ( public_events_only($user_no, $path) ) {
1320 $class = 'PUBLIC';
1324 * It seems that some calendar clients don't set a class...
1325 * RFC2445, 4.8.1.3:
1326 * Default is PUBLIC
1328 if ( !isset($class) || $class == '' ) {
1329 $class = 'PUBLIC';
1331 $calitem_params[':class'] = $class;
1333 /** Calculate what timezone to set, first, if possible */
1334 $last_olson = 'Turkmenikikamukau'; // I really hope this location doesn't exist!
1335 $tzid = GetTZID($first);
1336 if ( !empty($tzid) ) {
1337 $timezones = $vcal->GetComponents('VTIMEZONE');
1338 foreach( $timezones AS $k => $tz ) {
1339 if ( $tz->GetPValue('TZID') != $tzid ) {
1341 * We'll skip any tz definitions that are for a TZID other than the DTSTART/DUE on the first VEVENT/VTODO
1343 dbg_error_log( 'ERROR', ' Event uses TZID[%s], skipping included TZID[%s]!', $tz->GetPValue('TZID'), $tzid );
1344 continue;
1346 $olson = olson_from_tzstring($tzid);
1347 if ( empty($olson) ) {
1348 $olson = $tz->GetPValue('X-LIC-LOCATION');
1349 if ( !empty($olson) ) {
1350 $olson = olson_from_tzstring($olson);
1355 dbg_error_log( 'PUT', ' Using TZID[%s] and location of [%s]', $tzid, (isset($olson) ? $olson : '') );
1356 if ( !empty($olson) && ($olson != $last_olson) && preg_match( $tz_regex, $olson ) ) {
1357 dbg_error_log( 'PUT', ' Setting timezone to %s', $olson );
1358 if ( $olson != '' ) {
1359 $qry->QDo('SET TIMEZONE TO \''.$olson."'" );
1361 $last_olson = $olson;
1363 $params = array( ':tzid' => $tzid);
1364 $qry = new AwlQuery('SELECT 1 FROM timezones WHERE tzid = :tzid', $params );
1365 if ( $qry->Exec('PUT',__LINE__,__FILE__) && $qry->rows() == 0 ) {
1366 $params[':olson_name'] = $olson;
1367 $params[':vtimezone'] = (isset($tz) ? $tz->Render() : null );
1368 $qry->QDo('INSERT INTO timezones (tzid, olson_name, active, vtimezone) VALUES(:tzid,:olson_name,false,:vtimezone)', $params );
1370 if ( !isset($olson) || $olson == '' ) $olson = $tzid;
1374 $qry->QDo('SELECT new_sync_token(0,'.$collection_id.')');
1376 $calitem_params[':tzid'] = $tzid;
1377 $calitem_params[':uid'] = $first->GetPValue('UID');
1378 $calitem_params[':summary'] = $first->GetPValue('SUMMARY');
1379 $calitem_params[':location'] = $first->GetPValue('LOCATION');
1380 $calitem_params[':transp'] = $first->GetPValue('TRANSP');
1381 $calitem_params[':description'] = $first->GetPValue('DESCRIPTION');
1382 $calitem_params[':rrule'] = $first->GetPValue('RRULE');
1383 $calitem_params[':url'] = $first->GetPValue('URL');
1384 $calitem_params[':priority'] = $first->GetPValue('PRIORITY');
1385 $calitem_params[':percent_complete'] = $first->GetPValue('PERCENT-COMPLETE');
1386 $calitem_params[':status'] = $first->GetPValue('STATUS');
1388 if ( !$collection->IsSchedulingCollection() ) {
1389 if ( do_scheduling_requests($vcal, ($put_action_type == 'INSERT'), $old_dav_data ) ) {
1390 $dav_params[':dav_data'] = $vcal->Render(null, true);
1391 $etag = null;
1395 if ( !isset($dav_params[':modified']) ) $dav_params[':modified'] = 'now';
1396 if ( $put_action_type == 'INSERT' ) {
1397 $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 )
1398 VALUES( :dav_id, :user_no, :dav_name, :etag, :dav_data, :caldav_type, :session_user, :created, :modified, :collection_id, :weak_etag )';
1399 $dav_params[':collection_id'] = $collection_id;
1400 $dav_params[':user_no'] = $user_no;
1401 $dav_params[':dav_name'] = $path;
1402 $dav_params[':created'] = (isset($created) && $created != '' ? $created : $dtstamp);
1404 else {
1405 $sql = 'UPDATE caldav_data SET caldav_data=:dav_data, dav_etag=:etag, caldav_type=:caldav_type, logged_user=:session_user,
1406 modified=:modified, weak_etag=:weak_etag WHERE dav_id=:dav_id';
1408 $qry = new AwlQuery($sql,$dav_params);
1409 if ( !$qry->Exec('PUT',__LINE__,__FILE__) ) {
1410 fatal('Insert into calendar_item failed...');
1411 rollback_on_error( $caldav_context, $user_no, $path);
1412 return false;
1416 if ( $put_action_type == 'INSERT' ) {
1417 $sql = <<<EOSQL
1418 INSERT INTO calendar_item (user_no, dav_name, dav_id, dav_etag, uid, dtstamp,
1419 dtstart, dtend, summary, location, class, transp,
1420 description, rrule, tz_id, last_modified, url, priority,
1421 created, due, percent_complete, status, collection_id )
1422 VALUES ( :user_no, :dav_name, :dav_id, :etag, :uid, :dtstamp,
1423 :dtstart, $dtend, :summary, :location, :class, :transp,
1424 :description, :rrule, :tzid, :modified, :url, :priority,
1425 :created, :due, :percent_complete, :status, :collection_id )
1426 EOSQL;
1427 $sync_change = 201;
1428 $calitem_params[':collection_id'] = $collection_id;
1429 $calitem_params[':user_no'] = $user_no;
1430 $calitem_params[':dav_name'] = $path;
1431 $calitem_params[':created'] = $dav_params[':created'];
1433 else {
1434 $sql = <<<EOSQL
1435 UPDATE calendar_item SET dav_etag=:etag, uid=:uid, dtstamp=:dtstamp,
1436 dtstart=:dtstart, dtend=$dtend, summary=:summary, location=:location,
1437 class=:class, transp=:transp, description=:description, rrule=:rrule,
1438 tz_id=:tzid, last_modified=:modified, url=:url, priority=:priority,
1439 due=:due, percent_complete=:percent_complete, status=:status
1440 WHERE dav_id=:dav_id
1441 EOSQL;
1442 $sync_change = 200;
1445 write_alarms($dav_id, $first);
1446 write_attendees($dav_id, $vcal);
1448 if ( $log_action && function_exists('log_caldav_action') ) {
1449 log_caldav_action( $put_action_type, $first->GetPValue('UID'), $user_no, $collection_id, $path );
1451 else if ( $log_action ) {
1452 dbg_error_log( 'PUT', 'No log_caldav_action( %s, %s, %s, %s, %s) can be called.',
1453 $put_action_type, $first->GetPValue('UID'), $user_no, $collection_id, $path );
1456 $qry = new AwlQuery( $sql, $calitem_params );
1457 if ( !$qry->Exec('PUT',__LINE__,__FILE__) ) {
1458 rollback_on_error( $caldav_context, $user_no, $path);
1459 return false;
1461 $qry->QDo("SELECT write_sync_change( $collection_id, $sync_change, :dav_name)", array(':dav_name' => $path ) );
1462 $qry->Commit();
1464 if ( function_exists('post_commit_action') ) {
1465 post_commit_action( $put_action_type, $first->GetPValue('UID'), $user_no, $collection_id, $path );
1468 // Uncache anything to do with the collection
1469 $cache = getCacheInstance();
1470 $cache_ns = 'collection-'.preg_replace( '{/[^/]*$}', '/', $path);
1471 $cache->delete( $cache_ns, null );
1473 dbg_error_log( 'PUT', 'User: %d, ETag: %s, Path: %s', $author, $etag, $path);
1475 return true; // Success!
1481 * A slightly simpler version of write_resource which will make more sense for calling from
1482 * an external program. This makes assumptions that the collection and user do exist
1483 * and bypasses all checks for whether it is reasonable to write this here.
1484 * @param string $path The path to the resource being written
1485 * @param string $caldav_data The actual resource to be written
1486 * @param string $put_action_type INSERT or UPDATE depending on what we are to do
1487 * @return boolean True for success, false for failure.
1489 function simple_write_resource( $path, $caldav_data, $put_action_type, $write_action_log = false ) {
1490 global $session;
1493 * We pull the user_no & collection_id out of the collection table, based on the resource path
1495 $dav_resource = new DAVResource($path);
1496 $etag = md5($caldav_data);
1497 $collection_path = preg_replace( '#/[^/]*$#', '/', $path );
1498 $collection = new DAVResource($collection_path);
1499 if ( $collection->IsCollection() || $collection->IsSchedulingCollection() ) {
1500 return write_resource( $dav_resource, $caldav_data, $collection, $session->user_no, $etag, $put_action_type, false, $write_action_log );
1502 return false;