Merge branch 'master' of github.com:DAViCal/davical into github
[davical.git] / inc / caldav-PUT-functions.php
blob09f7c5c43d8884d1ec3d332b129ae2a400677718
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('/var/log/davical/PUT-2.debug','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 /** Do we need to do anything? */
894 $inserting = true;
895 if ( isset($current_data[$dav_name]) ) {
896 if ( $icalendar == $current_data[$dav_name] ) {
897 unset($current_data[$dav_name]);
898 continue;
900 $sync_change = 200;
901 unset($current_data[$dav_name]);
902 $inserting = false;
904 else
905 $sync_change = 201;
907 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Begin();
909 /** As ever, we mostly deal with the first resource component */
910 $first = $resource[0];
912 $dav_data_params = $base_params;
913 $dav_data_params[':user_no'] = $user_no;
914 // We don't allow any of &?\/@%+: in the UID to appear in the path, but anything else is fair game.
915 $dav_data_params[':dav_name'] = $dav_name;
916 $dav_data_params[':etag'] = md5($icalendar);
917 $calitem_params = $dav_data_params;
918 $dav_data_params[':dav_data'] = $icalendar;
919 $dav_data_params[':caldav_type'] = $first->GetType();
920 $dav_data_params[':session_user'] = $session->user_no;
922 $dtstart = $first->GetPValue('DTSTART');
923 $calitem_params[':dtstart'] = $dtstart;
924 if ( (!isset($dtstart) || $dtstart == '') && $first->GetPValue('DUE') != '' ) {
925 $dtstart = $first->GetPValue('DUE');
926 if ( isset($after) ) $dtstart_date = new RepeatRuleDateTime($first->GetProperty('DUE'));
928 else if ( isset($after) ) {
929 $dtstart_date = new RepeatRuleDateTime($first->GetProperty('DTSTART'));
932 $calitem_params[':rrule'] = $first->GetPValue('RRULE');
934 // Skip it if it's after our start date for this import.
935 if ( isset($after) && empty($calitem_params[':rrule']) && $dtstart_date->epoch() < $after ) continue;
937 // Do we actually need to do anything?
938 $inserting = true;
939 if ( isset($current_data[$dav_name]) ) {
940 if ( $icalendar == $current_data[$dav_name] ) {
941 if ( $after == null ) {
942 unset($current_data[$dav_name]);
943 continue;
946 $sync_change = 200;
947 unset($current_data[$dav_name]);
948 $inserting = false;
950 else
951 $sync_change = 201;
953 // Write to the caldav_data table
954 if ( !$qry->QDo( ($inserting ? $dav_data_insert : $dav_data_update), $dav_data_params) )
955 rollback_on_error( $caldav_context, $user_no, $path );
957 // Get the dav_id for this row
958 $qry->QDo('SELECT dav_id FROM caldav_data WHERE dav_name = :dav_name ', array(':dav_name' => $dav_data_params[':dav_name']));
959 if ( $qry->rows() == 1 && $row = $qry->Fetch() ) {
960 $dav_id = $row->dav_id;
963 $dtend = $first->GetPValue('DTEND');
964 if ( isset($dtend) && $dtend != '' ) {
965 dbg_error_log( 'PUT', ' DTEND: "%s", DTSTART: "%s", DURATION: "%s"', $dtend, $dtstart, $first->GetPValue('DURATION') );
966 $calitem_params[':dtend'] = $dtend;
967 $dtend = ':dtend';
969 else {
970 $dtend = 'NULL';
971 if ( $first->GetPValue('DURATION') != '' AND $dtstart != '' ) {
972 $duration = trim(preg_replace( '#[PT]#', ' ', $first->GetPValue('DURATION') ));
973 if ( $duration == '' ) $duration = '0 seconds';
974 $dtend = '(:dtstart::timestamp with time zone + :duration::interval)';
975 $calitem_params[':duration'] = $duration;
977 elseif ( $first->GetType() == 'VEVENT' ) {
979 * From RFC2445 4.6.1:
980 * For cases where a "VEVENT" calendar component specifies a "DTSTART"
981 * property with a DATE data type but no "DTEND" property, the events
982 * non-inclusive end is the end of the calendar date specified by the
983 * "DTSTART" property. For cases where a "VEVENT" calendar component specifies
984 * a "DTSTART" property with a DATE-TIME data type but no "DTEND" property,
985 * the event ends on the same calendar date and time of day specified by the
986 * "DTSTART" property.
988 * So we're looking for 'VALUE=DATE', to identify the duration, effectively.
991 $dtstart_prop = $first->GetProperty('DTSTART');
992 if ( empty($dtstart_prop) ) {
993 dbg_error_log('PUT','Invalid VEVENT without DTSTART, UID="%s" in collection %d', $uid, $collection_id);
994 continue;
996 $value_type = $dtstart_prop->GetParameterValue('VALUE');
997 dbg_error_log('PUT','DTSTART without DTEND. DTSTART value type is %s', $value_type );
998 if ( isset($value_type) && $value_type == 'DATE' )
999 $dtend = '(:dtstart::timestamp with time zone::date + \'1 day\'::interval)';
1000 else
1001 $dtend = ':dtstart';
1005 $last_modified = $first->GetPValue('LAST-MODIFIED');
1006 if ( !isset($last_modified) || $last_modified == '' ) $last_modified = gmdate( 'Ymd\THis\Z' );
1007 $calitem_params[':modified'] = $last_modified;
1009 $dtstamp = $first->GetPValue('DTSTAMP');
1010 if ( empty($dtstamp) ) $dtstamp = $last_modified;
1011 $calitem_params[':dtstamp'] = $dtstamp;
1013 /** RFC2445, 4.8.1.3: Default is PUBLIC, or also if overridden by the collection settings */
1014 $class = ($collection->public_events_only == 't' ? 'PUBLIC' : $first->GetPValue('CLASS') );
1015 if ( !isset($class) || $class == '' ) $class = 'PUBLIC';
1016 $calitem_params[':class'] = $class;
1019 /** Calculate what timezone to set, first, if possible */
1020 $tzid = GetTZID($first);
1021 if ( !empty($tzid) && !empty($resource[$tzid]) ) {
1022 $tz = $resource[$tzid];
1023 $olson = $vcal->GetOlsonName($tz);
1024 dbg_error_log( 'PUT', ' Using TZID[%s] and location of [%s]', $tzid, (isset($olson) ? $olson : '') );
1025 if ( !empty($olson) && ($olson != $last_olson) && preg_match( $tz_regex, $olson ) ) {
1026 dbg_error_log( 'PUT', ' Setting timezone to %s', $olson );
1027 $qry->QDo('SET TIMEZONE TO \''.$olson."'" );
1028 $last_olson = $olson;
1030 $params = array( ':tzid' => $tzid);
1031 $qry = new AwlQuery('SELECT 1 FROM timezones WHERE tzid = :tzid', $params );
1032 if ( $qry->Exec('PUT',__LINE__,__FILE__) && $qry->rows() == 0 ) {
1033 $params[':olson_name'] = $olson;
1034 $params[':vtimezone'] = (isset($tz) ? $tz->Render() : null );
1035 $params[':last_modified'] = (isset($tz) ? $tz->GetPValue('LAST-MODIFIED') : null );
1036 if ( empty($params[':last_modified']) ) {
1037 $params[':last_modified'] = gmdate('Ymd\THis\Z');
1039 $qry->QDo('INSERT INTO timezones (tzid, olson_name, active, vtimezone, last_modified) VALUES(:tzid,:olson_name,false,:vtimezone,:last_modified)', $params );
1042 else {
1043 $tz = $olson = $tzid = null;
1046 $sql = str_replace( '##dtend##', $dtend, ($inserting ? $calitem_insert : $calitem_update) );
1047 $calitem_params[':tzid'] = $tzid;
1048 $calitem_params[':uid'] = $first->GetPValue('UID');
1049 $calitem_params[':summary'] = $first->GetPValue('SUMMARY');
1050 $calitem_params[':location'] = $first->GetPValue('LOCATION');
1051 $calitem_params[':transp'] = $first->GetPValue('TRANSP');
1052 $calitem_params[':description'] = $first->GetPValue('DESCRIPTION');
1053 $calitem_params[':url'] = $first->GetPValue('URL');
1054 $calitem_params[':priority'] = $first->GetPValue('PRIORITY');
1055 $calitem_params[':due'] = $first->GetPValue('DUE');
1056 $calitem_params[':percent_complete'] = $first->GetPValue('PERCENT-COMPLETE');
1057 $calitem_params[':status'] = $first->GetPValue('STATUS');
1059 if ( $inserting ) {
1060 $created = $first->GetPValue('CREATED');
1061 if ( $created == '00001231T000000Z' ) $created = '20001231T000000Z';
1062 $calitem_params[':created'] = $created;
1065 // Write the calendar_item row for this entry
1066 if ( !$qry->QDo($sql,$calitem_params) ) rollback_on_error( $caldav_context, $user_no, $path);
1068 write_alarms($dav_id, $first);
1069 write_attendees($dav_id, $vcal);
1071 $qry->QDo("SELECT write_sync_change( $collection_id, $sync_change, :dav_name)", array(':dav_name' => $dav_name ) );
1073 do_scheduling_requests( $vcal, true );
1074 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Commit();
1077 if ( !$appending && count($current_data) > 0 ) {
1078 $params = array( ':collection_id' => $collection_id );
1079 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Begin();
1080 foreach( $current_data AS $dav_name => $data ) {
1081 $params[':dav_name'] = $dav_name;
1082 $qry->QDo('DELETE FROM caldav_data WHERE collection_id = :collection_id AND dav_name = :dav_name', $params);
1083 $qry->QDo('SELECT write_sync_change(:collection_id, 404, :dav_name)', $params);
1085 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Commit();
1088 if ( !(isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import) ) {
1089 if ( ! $qry->Commit() ) rollback_on_error( $caldav_context, $user_no, $path);
1095 * Given a dav_id and an original vCalendar, pull out each of the VALARMs
1096 * and write the values into the calendar_alarm table.
1098 * @param int $dav_id The dav_id of the caldav_data we're processing
1099 * @param vComponent The VEVENT or VTODO containing the VALARM
1100 * @return null
1102 function write_alarms( $dav_id, vComponent $ical ) {
1103 $qry = new AwlQuery('DELETE FROM calendar_alarm WHERE dav_id = '.$dav_id );
1104 $qry->Exec('PUT',__LINE__,__FILE__);
1106 $alarms = $ical->GetComponents('VALARM');
1107 if ( count($alarms) < 1 ) return;
1109 $qry->SetSql('INSERT INTO calendar_alarm ( dav_id, action, trigger, summary, description, component, next_trigger )
1110 VALUES( '.$dav_id.', :action, :trigger, :summary, :description, :component,
1111 :related::timestamp with time zone + :related_trigger::interval )' );
1112 $qry->Prepare();
1113 foreach( $alarms AS $v ) {
1114 $trigger = array_merge($v->GetProperties('TRIGGER'));
1115 if ( $trigger == null ) continue; // Bogus data.
1116 $trigger = $trigger[0];
1117 $related = null;
1118 $related_trigger = '0M';
1119 $trigger_type = $trigger->GetParameterValue('VALUE');
1120 if ( !isset($trigger_type) || $trigger_type == 'DURATION' ) {
1121 switch ( $trigger->GetParameterValue('RELATED') ) {
1122 case 'DTEND': $related = $ical->GetProperty('DTEND'); break;
1123 case 'DUE': $related = $ical->GetProperty('DUE'); break;
1124 default: $related = $ical->GetProperty('DTSTART');
1126 $duration = $trigger->Value();
1127 if ( !preg_match('{^-?P(:?\d+W)?(:?\d+D)?(:?T(:?\d+H)?(:?\d+M)?(:?\d+S)?)?$}', $duration ) ) continue;
1128 $minus = (substr($duration,0,1) == '-');
1129 $related_trigger = trim(preg_replace( '#[PT-]#', ' ', $duration ));
1130 if ( $minus ) {
1131 $related_trigger = preg_replace( '{(\d+[WDHMS])}', '-$1 ', $related_trigger );
1133 else {
1134 $related_trigger = preg_replace( '{(\d+[WDHMS])}', '$1 ', $related_trigger );
1137 else if ( $trigger_type == 'DATE-TIME' ) {
1138 $related = $trigger;
1140 else {
1141 if ( false === strtotime($trigger->Value()) ) continue; // Invalid date.
1142 $related = $trigger;
1144 $related_date = new RepeatRuleDateTime($related);
1145 $qry->Bind(':action', $v->GetPValue('ACTION'));
1146 $qry->Bind(':trigger', $trigger->Render());
1147 $qry->Bind(':summary', $v->GetPValue('SUMMARY'));
1148 $qry->Bind(':description', $v->GetPValue('DESCRIPTION'));
1149 $qry->Bind(':component', $v->Render());
1150 $qry->Bind(':related', $related_date->UTC() );
1151 $qry->Bind(':related_trigger', $related_trigger );
1152 $qry->Exec('PUT',__LINE__,__FILE__);
1158 * Parse out the attendee property and write a row to the
1159 * calendar_attendee table for each one.
1160 * @param int $dav_id The dav_id of the caldav_data we're processing
1161 * @param vComponent The VEVENT or VTODO containing the ATTENDEEs
1162 * @return null
1164 function write_attendees( $dav_id, vCalendar $ical ) {
1165 $qry = new AwlQuery('DELETE FROM calendar_attendee WHERE dav_id = '.$dav_id );
1166 $qry->Exec('PUT',__LINE__,__FILE__);
1168 $attendees = $ical->GetAttendees();
1169 if ( count($attendees) < 1 ) return;
1171 $qry->SetSql('INSERT INTO calendar_attendee ( dav_id, status, partstat, cn, attendee, role, rsvp, property )
1172 VALUES( '.$dav_id.', :status, :partstat, :cn, :attendee, :role, :rsvp, :property )' );
1173 $qry->Prepare();
1174 $processed = array();
1175 foreach( $attendees AS $v ) {
1176 $attendee = $v->Value();
1177 if ( isset($processed[$attendee]) ) {
1178 dbg_error_log( 'LOG', 'Duplicate attendee "%s" in resource "%d"', $attendee, $dav_id );
1179 dbg_error_log( 'LOG', 'Original: "%s"', $processed[$attendee] );
1180 dbg_error_log( 'LOG', 'Duplicate: "%s"', $v->Render() );
1181 continue; /** @todo work out why we get duplicate ATTENDEE on one VEVENT */
1183 $qry->Bind(':attendee', $attendee );
1184 $qry->Bind(':status', $v->GetParameterValue('STATUS') );
1185 $qry->Bind(':partstat', $v->GetParameterValue('PARTSTAT') );
1186 $qry->Bind(':cn', $v->GetParameterValue('CN') );
1187 $qry->Bind(':role', $v->GetParameterValue('ROLE') );
1188 $qry->Bind(':rsvp', $v->GetParameterValue('RSVP') );
1189 $qry->Bind(':property', $v->Render() );
1190 $qry->Exec('PUT',__LINE__,__FILE__);
1191 $processed[$attendee] = $v->Render();
1197 * Actually write the resource to the database. All checking of whether this is reasonable
1198 * should be done before this is called.
1200 * @param DAVResource $resource The resource being written
1201 * @param string $caldav_data The actual data to be written
1202 * @param DAVResource $collection The collection containing the resource being written
1203 * @param int $author The user_no who wants to put this resource on the server
1204 * @param string $etag An etag unique for this event
1205 * @param string $put_action_type INSERT or UPDATE depending on what we are to do
1206 * @param boolean $caldav_context True, if we are responding via CalDAV, false for other ways of calling this
1207 * @param string Either 'INSERT' or 'UPDATE': the type of action we are doing
1208 * @param boolean $log_action Whether to log the fact that we are writing this into an action log (if configured)
1209 * @param string $weak_etag An etag that is NOT modified on ATTENDEE changes for this event
1211 * @return boolean True for success, false for failure.
1213 function write_resource( DAVResource $resource, $caldav_data, DAVResource $collection, $author, &$etag, $put_action_type, $caldav_context, $log_action=true, $weak_etag=null ) {
1214 global $tz_regex, $session;
1216 $path = $resource->bound_from();
1217 $user_no = $collection->user_no();
1218 $vcal = new vCalendar( $caldav_data );
1219 $resources = $vcal->GetComponents('VTIMEZONE',false); // Not matching VTIMEZONE
1220 if ( !isset($resources[0]) ) {
1221 $resource_type = 'Unknown';
1222 /** @todo Handle writing non-calendar resources, like address book entries or random file data */
1223 rollback_on_error( $caldav_context, $user_no, $path, translate('No calendar content'), 412 );
1224 return false;
1226 else {
1227 $first = $resources[0];
1228 if ( !($first instanceof vComponent) ) {
1229 print $vcal->Render();
1230 fatal('This is not a vComponent!');
1232 $resource_type = $first->GetType();
1235 $collection_id = $collection->collection_id();
1237 $qry = new AwlQuery();
1238 $qry->Begin();
1240 $dav_params = array(
1241 ':etag' => $etag,
1242 ':dav_data' => $caldav_data,
1243 ':caldav_type' => $resource_type,
1244 ':session_user' => $author,
1245 ':weak_etag' => $weak_etag
1248 $calitem_params = array(
1249 ':etag' => $etag
1252 if ( $put_action_type == 'INSERT' ) {
1253 $qry->QDo('SELECT nextval(\'dav_id_seq\') AS dav_id, null AS caldav_data');
1255 else {
1256 $qry->QDo('SELECT dav_id, caldav_data FROM caldav_data WHERE dav_name = :dav_name ', array(':dav_name' => $path));
1258 if ( $qry->rows() != 1 || !($row = $qry->Fetch()) ) {
1259 // No dav_id? => We're toast!
1260 trace_bug( 'No dav_id for "%s" on %s!!!', $path, ($create_resource ? 'create': 'update'));
1261 rollback_on_error( $caldav_context, $user_no, $path);
1262 return false;
1264 $dav_id = $row->dav_id;
1265 $old_dav_data = $row->caldav_data;
1266 $dav_params[':dav_id'] = $dav_id;
1267 $calitem_params[':dav_id'] = $dav_id;
1269 $due = null;
1270 if ( $first->GetType() == 'VTODO' ) $due = $first->GetPValue('DUE');
1271 $calitem_params[':due'] = $due;
1272 $dtstart = $first->GetPValue('DTSTART');
1273 if ( empty($dtstart) ) $dtstart = $due;
1274 $calitem_params[':dtstart'] = $dtstart;
1276 $dtend = $first->GetPValue('DTEND');
1277 if ( isset($dtend) && $dtend != '' ) {
1278 dbg_error_log( 'PUT', ' DTEND: "%s", DTSTART: "%s", DURATION: "%s"', $dtend, $dtstart, $first->GetPValue('DURATION') );
1279 $calitem_params[':dtend'] = $dtend;
1280 $dtend = ':dtend';
1282 else {
1283 // In this case we'll construct the SQL directly as a calculation relative to :dtstart
1284 $dtend = 'NULL';
1285 if ( $first->GetPValue('DURATION') != '' AND $dtstart != '' ) {
1286 $duration = trim(preg_replace( '#[PT]#', ' ', $first->GetPValue('DURATION') ));
1287 if ( $duration == '' ) $duration = '0 seconds';
1288 $dtend = '(:dtstart::timestamp with time zone + :duration::interval)';
1289 $calitem_params[':duration'] = $duration;
1291 elseif ( $first->GetType() == 'VEVENT' ) {
1293 * From RFC2445 4.6.1:
1294 * For cases where a "VEVENT" calendar component specifies a "DTSTART"
1295 * property with a DATE data type but no "DTEND" property, the events
1296 * non-inclusive end is the end of the calendar date specified by the
1297 * "DTSTART" property. For cases where a "VEVENT" calendar component specifies
1298 * a "DTSTART" property with a DATE-TIME data type but no "DTEND" property,
1299 * the event ends on the same calendar date and time of day specified by the
1300 * "DTSTART" property.
1302 * So we're looking for 'VALUE=DATE', to identify the duration, effectively.
1305 $dtstart_prop = $first->GetProperty('DTSTART');
1306 $value_type = $dtstart_prop->GetParameterValue('VALUE');
1307 dbg_error_log('PUT','DTSTART without DTEND. DTSTART value type is %s', $value_type );
1308 if ( isset($value_type) && $value_type == 'DATE' )
1309 $dtend = '(:dtstart::timestamp with time zone::date + \'1 day\'::interval)';
1310 else
1311 $dtend = ':dtstart';
1315 $dtstamp = $first->GetPValue('DTSTAMP');
1316 if ( !isset($dtstamp) || $dtstamp == '' ) {
1317 // Strictly, we're dealing with an out of spec component here, but we'll try and survive
1318 $dtstamp = gmdate( 'Ymd\THis\Z' );
1320 $calitem_params[':dtstamp'] = $dtstamp;
1322 $last_modified = $first->GetPValue('LAST-MODIFIED');
1323 if ( !isset($last_modified) || $last_modified == '' ) $last_modified = $dtstamp;
1324 $dav_params[':modified'] = $last_modified;
1325 $calitem_params[':modified'] = $last_modified;
1327 $created = $first->GetPValue('CREATED');
1328 if ( $created == '00001231T000000Z' ) $created = '20001231T000000Z';
1330 $class = $first->GetPValue('CLASS');
1331 /* Check and see if we should over ride the class. */
1332 /** @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. */
1333 if ( public_events_only($user_no, $path) ) {
1334 $class = 'PUBLIC';
1338 * It seems that some calendar clients don't set a class...
1339 * RFC2445, 4.8.1.3:
1340 * Default is PUBLIC
1342 if ( !isset($class) || $class == '' ) {
1343 $class = 'PUBLIC';
1345 $calitem_params[':class'] = $class;
1347 /** Calculate what timezone to set, first, if possible */
1348 $last_olson = 'Turkmenikikamukau'; // I really hope this location doesn't exist!
1349 $tzid = GetTZID($first);
1350 if ( !empty($tzid) ) {
1351 $timezones = $vcal->GetComponents('VTIMEZONE');
1352 foreach( $timezones AS $k => $tz ) {
1353 if ( $tz->GetPValue('TZID') != $tzid ) {
1355 * We'll skip any tz definitions that are for a TZID other than the DTSTART/DUE on the first VEVENT/VTODO
1357 dbg_error_log( 'ERROR', ' Event uses TZID[%s], skipping included TZID[%s]!', $tz->GetPValue('TZID'), $tzid );
1358 continue;
1360 $olson = olson_from_tzstring($tzid);
1361 if ( empty($olson) ) {
1362 $olson = $tz->GetPValue('X-LIC-LOCATION');
1363 if ( !empty($olson) ) {
1364 $olson = olson_from_tzstring($olson);
1369 dbg_error_log( 'PUT', ' Using TZID[%s] and location of [%s]', $tzid, (isset($olson) ? $olson : '') );
1370 if ( !empty($olson) && ($olson != $last_olson) && preg_match( $tz_regex, $olson ) ) {
1371 dbg_error_log( 'PUT', ' Setting timezone to %s', $olson );
1372 if ( $olson != '' ) {
1373 $qry->QDo('SET TIMEZONE TO \''.$olson."'" );
1375 $last_olson = $olson;
1377 $params = array( ':tzid' => $tzid);
1378 $qry = new AwlQuery('SELECT 1 FROM timezones WHERE tzid = :tzid', $params );
1379 if ( $qry->Exec('PUT',__LINE__,__FILE__) && $qry->rows() == 0 ) {
1380 $params[':olson_name'] = $olson;
1381 $params[':vtimezone'] = (isset($tz) ? $tz->Render() : null );
1382 $qry->QDo('INSERT INTO timezones (tzid, olson_name, active, vtimezone) VALUES(:tzid,:olson_name,false,:vtimezone)', $params );
1384 if ( !isset($olson) || $olson == '' ) $olson = $tzid;
1388 $qry->QDo('SELECT new_sync_token(0,'.$collection_id.')');
1390 $calitem_params[':tzid'] = $tzid;
1391 $calitem_params[':uid'] = $first->GetPValue('UID');
1392 $calitem_params[':summary'] = $first->GetPValue('SUMMARY');
1393 $calitem_params[':location'] = $first->GetPValue('LOCATION');
1394 $calitem_params[':transp'] = $first->GetPValue('TRANSP');
1395 $calitem_params[':description'] = $first->GetPValue('DESCRIPTION');
1396 $calitem_params[':rrule'] = $first->GetPValue('RRULE');
1397 $calitem_params[':url'] = $first->GetPValue('URL');
1398 $calitem_params[':priority'] = $first->GetPValue('PRIORITY');
1399 $calitem_params[':percent_complete'] = $first->GetPValue('PERCENT-COMPLETE');
1400 $calitem_params[':status'] = $first->GetPValue('STATUS');
1402 if ( !$collection->IsSchedulingCollection() ) {
1403 if ( do_scheduling_requests($vcal, ($put_action_type == 'INSERT'), $old_dav_data ) ) {
1404 $dav_params[':dav_data'] = $vcal->Render(null, true);
1405 $etag = null;
1409 if ( !isset($dav_params[':modified']) ) $dav_params[':modified'] = 'now';
1410 if ( $put_action_type == 'INSERT' ) {
1411 $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 )
1412 VALUES( :dav_id, :user_no, :dav_name, :etag, :dav_data, :caldav_type, :session_user, :created, :modified, :collection_id, :weak_etag )';
1413 $dav_params[':collection_id'] = $collection_id;
1414 $dav_params[':user_no'] = $user_no;
1415 $dav_params[':dav_name'] = $path;
1416 $dav_params[':created'] = (isset($created) && $created != '' ? $created : $dtstamp);
1418 else {
1419 $sql = 'UPDATE caldav_data SET caldav_data=:dav_data, dav_etag=:etag, caldav_type=:caldav_type, logged_user=:session_user,
1420 modified=:modified, weak_etag=:weak_etag WHERE dav_id=:dav_id';
1422 $qry = new AwlQuery($sql,$dav_params);
1423 if ( !$qry->Exec('PUT',__LINE__,__FILE__) ) {
1424 fatal('Insert into calendar_item failed...');
1425 rollback_on_error( $caldav_context, $user_no, $path);
1426 return false;
1430 if ( $put_action_type == 'INSERT' ) {
1431 $sql = <<<EOSQL
1432 INSERT INTO calendar_item (user_no, dav_name, dav_id, dav_etag, uid, dtstamp,
1433 dtstart, dtend, summary, location, class, transp,
1434 description, rrule, tz_id, last_modified, url, priority,
1435 created, due, percent_complete, status, collection_id )
1436 VALUES ( :user_no, :dav_name, :dav_id, :etag, :uid, :dtstamp,
1437 :dtstart, $dtend, :summary, :location, :class, :transp,
1438 :description, :rrule, :tzid, :modified, :url, :priority,
1439 :created, :due, :percent_complete, :status, :collection_id )
1440 EOSQL;
1441 $sync_change = 201;
1442 $calitem_params[':collection_id'] = $collection_id;
1443 $calitem_params[':user_no'] = $user_no;
1444 $calitem_params[':dav_name'] = $path;
1445 $calitem_params[':created'] = $dav_params[':created'];
1447 else {
1448 $sql = <<<EOSQL
1449 UPDATE calendar_item SET dav_etag=:etag, uid=:uid, dtstamp=:dtstamp,
1450 dtstart=:dtstart, dtend=$dtend, summary=:summary, location=:location,
1451 class=:class, transp=:transp, description=:description, rrule=:rrule,
1452 tz_id=:tzid, last_modified=:modified, url=:url, priority=:priority,
1453 due=:due, percent_complete=:percent_complete, status=:status
1454 WHERE dav_id=:dav_id
1455 EOSQL;
1456 $sync_change = 200;
1459 write_alarms($dav_id, $first);
1460 write_attendees($dav_id, $vcal);
1462 if ( $log_action && function_exists('log_caldav_action') ) {
1463 log_caldav_action( $put_action_type, $first->GetPValue('UID'), $user_no, $collection_id, $path );
1465 else if ( $log_action ) {
1466 dbg_error_log( 'PUT', 'No log_caldav_action( %s, %s, %s, %s, %s) can be called.',
1467 $put_action_type, $first->GetPValue('UID'), $user_no, $collection_id, $path );
1470 $qry = new AwlQuery( $sql, $calitem_params );
1471 if ( !$qry->Exec('PUT',__LINE__,__FILE__) ) {
1472 rollback_on_error( $caldav_context, $user_no, $path);
1473 return false;
1475 $qry->QDo("SELECT write_sync_change( $collection_id, $sync_change, :dav_name)", array(':dav_name' => $path ) );
1476 $qry->Commit();
1478 if ( function_exists('post_commit_action') ) {
1479 post_commit_action( $put_action_type, $first->GetPValue('UID'), $user_no, $collection_id, $path );
1482 // Uncache anything to do with the collection
1483 $cache = getCacheInstance();
1484 $cache_ns = 'collection-'.preg_replace( '{/[^/]*$}', '/', $path);
1485 $cache->delete( $cache_ns, null );
1487 dbg_error_log( 'PUT', 'User: %d, ETag: %s, Path: %s', $author, $etag, $path);
1489 return true; // Success!
1495 * A slightly simpler version of write_resource which will make more sense for calling from
1496 * an external program. This makes assumptions that the collection and user do exist
1497 * and bypasses all checks for whether it is reasonable to write this here.
1498 * @param string $path The path to the resource being written
1499 * @param string $caldav_data The actual resource to be written
1500 * @param string $put_action_type INSERT or UPDATE depending on what we are to do
1501 * @return boolean True for success, false for failure.
1503 function simple_write_resource( $path, $caldav_data, $put_action_type, $write_action_log = false ) {
1504 global $session;
1507 * We pull the user_no & collection_id out of the collection table, based on the resource path
1509 $dav_resource = new DAVResource($path);
1510 $etag = md5($caldav_data);
1511 $collection_path = preg_replace( '#/[^/]*$#', '/', $path );
1512 $collection = new DAVResource($collection_path);
1513 if ( $collection->IsCollection() || $collection->IsSchedulingCollection() ) {
1514 return write_resource( $dav_resource, $caldav_data, $collection, $session->user_no, $etag, $put_action_type, false, $write_action_log );
1516 return false;