Handle HTTP date formatting for non-english locales (force English names).
[davical.git] / inc / caldav-PUT-functions.php
blobaaef0a850dd4f750286a6dd7d3e2a3fe785d08e6
1 <?php
2 /**
3 * CalDAV Server - handle PUT method
5 * @package davical
6 * @subpackage caldav
7 * @author Andrew McMillan <andrew@morphoss.com>
8 * @copyright Morphoss Ltd - http://www.morphoss.com/
9 * @license http://gnu.org/copyleft/gpl.html GNU GPL v2 or later version
12 /**
13 * Check if the user wants to put just one VEVENT/VTODO or a whole calendar
14 * if the collection = calendar = $request_container doesn't exist then create it
15 * return true if it's a whole calendar
18 require_once('AwlCache.php');
19 require_once('vComponent.php');
20 require_once('vCalendar.php');
21 require_once('WritableCollection.php');
22 include_once('iSchedule.php');
24 $bad_events = null;
26 /**
27 * A regex which will match most reasonable timezones acceptable to PostgreSQL.
29 $tz_regex = ':^(Africa|America|Antarctica|Arctic|Asia|Atlantic|Australia|Brazil|Canada|Chile|Etc|Europe|Indian|Mexico|Mideast|Pacific|US)/[a-z_]+$:i';
31 /**
32 * This function launches an error
33 * @param boolean $caldav_context Whether we are responding via CalDAV or interactively
34 * @param int $user_no the user who will receive this ics file
35 * @param string $path the $path where the PUT failed to store such as /user_foo/home/
36 * @param string $message An optional error message to return to the client
37 * @param int $error_no An optional value for the HTTP error code
39 function rollback_on_error( $caldav_context, $user_no, $path, $message='', $error_no=500 ) {
40 global $c, $bad_events;
41 if ( !$message ) $message = translate('Database error');
42 $qry = new AwlQuery();
43 if ( $qry->TransactionState() != 0 ) $qry->Rollback();
44 if ( $caldav_context ) {
45 if ( isset($bad_events) && isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) {
46 $bad_events[] = $message;
48 else {
49 global $request;
50 $request->DoResponse( $error_no, $message );
52 // and we don't return from that, ever...
55 $c->messages[] = sprintf(translate('Status: %d, Message: %s, User: %d, Path: %s'), $error_no, $message, $user_no, $path);
61 /**
62 * Work out the location we are doing the PUT to, and check that we have the rights to
63 * do the needful.
64 * @param string $username The name of the destination user
65 * @param int $user_no The user making the change
66 * @param string $path The DAV path the resource is bing PUT to
67 * @param boolean $caldav_context Whether we are responding via CalDAV or interactively
68 * @param boolean $public Whether the collection will be public, should we need to create it
70 function controlRequestContainer( $username, $user_no, $path, $caldav_context, $public = null ) {
71 global $c, $request, $bad_events;
73 // Check to see if the path is like /foo /foo/bar or /foo/bar/baz etc. (not ending with a '/', but contains at least one)
74 if ( preg_match( '#^(.*/)([^/]+)$#', $path, $matches ) ) {//(
75 $request_container = $matches[1]; // get everything up to the last '/'
77 else {
78 // In this case we must have a URL with a trailing '/', so it must be a collection.
79 $request_container = $path;
82 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) {
83 $bad_events = array();
86 /**
87 * Before we write the event, we check the container exists, creating it if it doesn't
89 if ( $request_container == "/$username/" ) {
90 /**
91 * Well, it exists, and we support it, but it is against the CalDAV spec
93 dbg_error_log( 'WARN', ' Storing events directly in user\'s base folders is not recommended!');
95 else {
96 $sql = 'SELECT * FROM collection WHERE dav_name = :dav_name';
97 $qry = new AwlQuery( $sql, array( ':dav_name' => $request_container) );
98 if ( ! $qry->Exec('PUT',__LINE__,__FILE__) ) {
99 rollback_on_error( $caldav_context, $user_no, $path );
101 if ( !isset($c->readonly_webdav_collections) || $c->readonly_webdav_collections == true ) {
102 if ( $qry->rows() == 0 ) {
103 $request->DoResponse( 405 ); // Method not allowed
105 return;
107 if ( $qry->rows() == 0 ) {
108 if ( $public == true ) $public = 't'; else $public = 'f';
109 if ( preg_match( '{^(.*/)([^/]+)/$}', $request_container, $matches ) ) {
110 $parent_container = $matches[1];
111 $displayname = $matches[2];
113 $sql = 'INSERT INTO collection ( user_no, parent_container, dav_name, dav_etag, dav_displayname, is_calendar, created, modified, publicly_readable, resourcetypes )
114 VALUES( :user_no, :parent_container, :dav_name, :dav_etag, :dav_displayname, TRUE, current_timestamp, current_timestamp, :is_public::boolean, :resourcetypes )';
115 $params = array(
116 ':user_no' => $user_no,
117 ':parent_container' => $parent_container,
118 ':dav_name' => $request_container,
119 ':dav_etag' => md5($user_no. $request_container),
120 ':dav_displayname' => $displayname,
121 ':is_public' => $public,
122 ':resourcetypes' => '<DAV::collection/><urn:ietf:params:xml:ns:caldav:calendar/>'
124 $qry->QDo( $sql, $params );
126 else if ( isset($public) ) {
127 $collection = $qry->Fetch();
128 if ( empty($collection->is_public) ) $collection->is_public = 'f';
129 if ( $collection->is_public == ($public?'t':'f') ) {
130 $sql = 'UPDATE collection SET publicly_readable = :is_public::boolean WHERE collection_id = :collection_id';
131 $params = array( ':is_public' => ($public?'t':'f'), ':collection_id' => $collection->collection_id );
132 if ( ! $qry->QDo($sql,$params) ) {
133 rollback_on_error( $caldav_context, $user_no, $path );
143 * Check if this collection should force all events to be PUBLIC.
144 * @param string $user_no the user that owns the collection
145 * @param string $dav_name the collection to check
146 * @return boolean Return true if public events only are allowed.
148 function public_events_only( $user_no, $dav_name ) {
149 global $c;
151 $sql = 'SELECT public_events_only FROM collection WHERE dav_name = :dav_name';
153 $qry = new AwlQuery($sql, array(':dav_name' => $dav_name) );
155 if( $qry->Exec('PUT',__LINE__,__FILE__) && $qry->rows() == 1 ) {
156 $collection = $qry->Fetch();
158 if ($collection->public_events_only == 't') {
159 return true;
163 // Something went wrong, must be false.
164 return false;
168 * Get a TZID string from this VEVENT/VTODO/... component if we can
169 * @param vComponent $comp
170 * @return The TZID value we found, or null
172 function GetTZID( vComponent $comp ) {
173 $p = $comp->GetProperty('DTSTART');
174 if ( !isset($p) && $comp->GetType() == 'VTODO' ) {
175 $p = $comp->GetProperty('DUE');
177 if ( !isset($p) ) return null;
178 return $p->GetParameterValue('TZID');
182 * Deliver scheduling requests to attendees
183 * @param vComponent $ical the VCALENDAR to deliver
185 function handle_schedule_request( $ical ) {
186 global $c, $session, $request;
187 $resources = $ical->GetComponents('VTIMEZONE',false);
188 $ic = $resources[0];
189 $etag = md5 ( $request->raw_post );
190 $reply = new XMLDocument( array("DAV:" => "", "urn:ietf:params:xml:ns:caldav" => "C" ) );
191 $responses = array();
193 $attendees = $ic->GetProperties('ATTENDEE');
194 $wr_attendees = $ic->GetProperties('X-WR-ATTENDEE');
195 if ( count ( $wr_attendees ) > 0 ) {
196 dbg_error_log( "PUT", "Non-compliant iCal request. Using X-WR-ATTENDEE property" );
197 foreach( $wr_attendees AS $k => $v ) {
198 $attendees[] = $v;
201 dbg_error_log( "PUT", "Attempting to deliver scheduling request for %d attendees", count($attendees) );
203 foreach( $attendees AS $k => $attendee ) {
204 $attendee_email = preg_replace( '/^mailto:/', '', $attendee->Value() );
205 if ( $attendee_email == $request->principal->email() ) {
206 dbg_error_log( "PUT", "not delivering to owner" );
207 continue;
209 if ( $attendee->GetParameterValue ( 'PARTSTAT' ) != 'NEEDS-ACTION' || preg_match ( '/^[35]\.[3-9]/', $attendee->GetParameterValue ( 'SCHEDULE-STATUS' ) ) ) {
210 dbg_error_log( "PUT", "attendee %s does not need action", $attendee_email );
211 continue;
214 if ( isset($c->enable_auto_schedule) && !$c->enable_auto_schedule ) {
215 // In this case we're being asked not to do auto-scheduling, so we build
216 // a response back for the client saying we can't...
217 $attendee->SetParameterValue ('SCHEDULE-STATUS','5.3;No scheduling support for user');
218 continue;
221 dbg_error_log( "PUT", "Delivering to %s", $attendee_email );
223 $attendee_principal = new DAVPrincipal ( array ('email'=>$attendee_email, 'options'=> array ( 'allow_by_email' => true ) ) );
224 if ( $attendee_principal == false ){
225 $attendee->SetParameterValue ('SCHEDULE-STATUS','5.3;No scheduling support for user');
226 continue;
228 $deliver_path = $attendee_principal->internal_url('schedule-inbox');
230 $ar = new DAVResource($deliver_path);
231 $priv = $ar->HavePrivilegeTo('schedule-deliver-invite' );
232 if ( ! $ar->HavePrivilegeTo('schedule-deliver-invite' ) ){
233 $reply = new XMLDocument( array('DAV:' => '') );
234 $privnodes = array( $reply->href($attendee_principal->url('schedule_inbox')), new XMLElement( 'privilege' ) );
235 // RFC3744 specifies that we can only respond with one needed privilege, so we pick the first.
236 $reply->NSElement( $privnodes[1], 'schedule-deliver-invite' );
237 $xml = new XMLElement( 'need-privileges', new XMLElement( 'resource', $privnodes) );
238 $xmldoc = $reply->Render('error',$xml);
239 $request->DoResponse( 403, $xmldoc, 'text/xml; charset="utf-8"');
243 $attendee->SetParameterValue ('SCHEDULE-STATUS','1.2;Scheduling message has been delivered');
244 $ncal = new vCalendar( array('METHOD' => 'REQUEST') );
245 $ncal->AddComponent( array_merge( $ical->GetComponents('VEVENT',false), array($ic) ));
246 $content = $ncal->Render();
247 $cid = $ar->GetProperty('collection_id');
248 dbg_error_log('DELIVER', 'to user: %s, to path: %s, collection: %s, from user: %s, caldata %s', $attendee_principal->user_no(), $deliver_path, $cid, $request->user_no, $content );
249 $item_etag = md5($content);
250 write_resource( new DAVResource($deliver_path . $etag . '.ics'), $content, $ar, $request->user_no, $item_etag,
251 $put_action_type='INSERT', $caldav_context=true, $log_action=true, $etag );
252 $attendee->SetParameterValue ('SCHEDULE-STATUS','1.2;Scheduling message has been delivered');
254 // don't write an entry in the out box, ical doesn't delete it or ever read it again
255 $ncal = new vCalendar(array('METHOD' => 'REQUEST'));
256 $ncal->AddComponent ( array_merge ( $ical->GetComponents('VEVENT',false) , array ($ic) ));
257 $content = $ncal->Render();
258 $deliver_path = $request->principal->internal_url('schedule-inbox');
259 $ar = new DAVResource($deliver_path);
260 $item_etag = md5($content);
261 write_resource( new DAVResource($deliver_path . $etag . '.ics'), $content, $ar, $request->user_no, $item_etag,
262 $put_action_type='INSERT', $caldav_context=true, $log_action=true, $etag );
263 //$etag = md5($content);
264 header('ETag: "'. $etag . '"' );
265 header('Schedule-Tag: "'.$etag . '"' );
266 $request->DoResponse( 201, 'Created' );
270 * Deliver scheduling replies to organizer and other attendees
271 * @param vComponent $ical the VCALENDAR to deliver
272 * @return false on error
274 function handle_schedule_reply ( vCalendar $ical ) {
275 global $c, $session, $request;
276 $resources = $ical->GetComponents('VTIMEZONE',false);
277 $ic = $resources[0];
278 $etag = md5 ( $request->raw_post );
279 $organizer = $ical->GetOrganizer();
280 // for now we treat events with out organizers as an error
281 if ( count ( $organizer ) < 1 ) return false;
283 $attendees = array_merge($organizer,$ical->GetAttendees());
284 dbg_error_log( "PUT", "Attempting to deliver scheduling request for %d attendees", count($attendees) );
286 foreach( $attendees AS $k => $attendee ) {
287 $attendee_email = preg_replace( '/^mailto:/i', '', $attendee->Value() );
288 dbg_error_log( "PUT", "Delivering to %s", $attendee_email );
289 $attendee_principal = new DAVPrincipal ( array ('email'=>$attendee_email, 'options'=> array ( 'allow_by_email' => true ) ) );
290 $deliver_path = $attendee_principal->internal_url('schedule_inbox');
291 $attendee_email = preg_replace( '/^mailto:/i', '', $attendee->Value() );
292 if ( $attendee_email == $request->principal->email ) {
293 dbg_error_log( "PUT", "not delivering to owner" );
294 continue;
296 $ar = new DAVResource($deliver_path);
297 if ( ! $ar->HavePrivilegeTo('schedule-deliver-reply' ) ){
298 $reply = new XMLDocument( array('DAV:' => '') );
299 $privnodes = array( $reply->href($attendee_principal->url('schedule_inbox')), new XMLElement( 'privilege' ) );
300 // RFC3744 specifies that we can only respond with one needed privilege, so we pick the first.
301 $reply->NSElement( $privnodes[1], 'schedule-deliver-reply' );
302 $xml = new XMLElement( 'need-privileges', new XMLElement( 'resource', $privnodes) );
303 $xmldoc = $reply->Render('error',$xml);
304 $request->DoResponse( 403, $xmldoc, 'text/xml; charset="utf-8"' );
305 continue;
308 $ncal = new vCalendar( array('METHOD' => 'REPLY') );
309 $ncal->AddComponent ( array_merge ( $ical->GetComponents('VEVENT',false) , array ($ic) ));
310 $content = $ncal->Render();
311 write_resource( new DAVResource($deliver_path . $etag . '.ics'), $content, $ar, $request->user_no, md5($content),
312 $put_action_type='INSERT', $caldav_context=true, $log_action=true, $etag );
314 $request->DoResponse( 201, 'Created' );
319 * Do the scheduling adjustments for a REPLY when an ATTENDEE updates their status.
320 * @param vCalendar $resource The resource that the ATTENDEE is writing to their calendar
321 * @param string $organizer The property which is the event ORGANIZER.
323 function do_scheduling_reply( vCalendar $resource, vProperty $organizer ) {
324 global $request;
325 $organizer_email = preg_replace( '/^mailto:/i', '', $organizer->Value() );
326 $organizer_principal = new Principal('email',$organizer_email );
327 if ( !$organizer_principal->Exists() ) {
328 dbg_error_log( 'PUT', 'Organizer "%s" not found - cannot perform scheduling reply.', $organizer );
329 return false;
331 $sql = 'SELECT caldav_data.dav_name, caldav_data.caldav_data FROM caldav_data JOIN calendar_item USING(dav_id) ';
332 $sql .= 'WHERE caldav_data.collection_id IN (SELECT collection_id FROM collection WHERE is_calendar AND user_no =?) ';
333 $sql .= 'AND uid=? LIMIT 1';
334 $uids = $resource->GetPropertiesByPath('/VCALENDAR/*/UID');
335 if ( count($uids) == 0 ) {
336 dbg_error_log( 'PUT', 'No UID in VCALENDAR - giving up on REPLY.' );
337 return false;
339 $uid = $uids[0]->Value();
340 $qry = new AwlQuery($sql,$organizer_principal->user_no(), $uid);
341 if ( !$qry->Exec('PUT',__LINE__,__FILE__) || $qry->rows() < 1 ) {
342 dbg_error_log( 'PUT', 'Could not find original event from organizer - giving up on REPLY.' );
343 return false;
345 $row = $qry->Fetch();
346 $attendees = $resource->GetAttendees();
347 foreach( $attendees AS $v ) {
348 $email = preg_replace( '/^mailto:/i', '', $v->Value() );
349 if ( $email == $request->principal->email() ) {
350 $attendee = $v;
353 if ( empty($attendee) ) {
354 dbg_error_log( 'PUT', 'Could not find ATTENDEE in VEVENT - giving up on REPLY.' );
355 return false;
357 $schedule_original = new vCalendar($row->caldav_data);
358 $schedule_original->UpdateAttendeeStatus($request->principal->email(), clone($attendee) );
360 $collection_path = preg_replace('{/[^/]+$}', '/', $row->dav_name );
361 $segment_name = str_replace($collection_path, '', $row->dav_name );
362 $organizer_calendar = new WritableCollection(array('path' => $collection_path));
363 $organizer_inbox = new WritableCollection(array('path' => $organizer_principal->internal_url('schedule-inbox')));
365 $schedule_reply = clone($schedule_original);
366 $schedule_reply->AddProperty('METHOD', 'REPLY');
368 dbg_error_log( 'PUT', 'Writing scheduling REPLY from %s to %s', $request->principal->email(), $organizer_principal->email() );
370 $response = '3.7'; // Organizer was not found on server.
371 if ( !$organizer_calendar->Exists() ) {
372 dbg_error_log('ERROR','Default calendar at "%s" does not exist for user "%s"',
373 $organizer_calendar->dav_name(), $schedule_target->username());
374 $response = '5.2'; // No scheduling support for user
376 else {
377 if ( ! $organizer_inbox->HavePrivilegeTo('schedule-deliver-reply') ) {
378 $response = '3.8'; // No authority to deliver replies to organizer.
380 else if ( $organizer_inbox->WriteCalendarMember($schedule_reply, false, false, $request->principal->username().$segment_name) !== false ) {
381 $response = '1.2'; // Scheduling reply delivered successfully
382 if ( $organizer_calendar->WriteCalendarMember($schedule_original, false, false, $segment_name) === false ) {
383 dbg_error_log('ERROR','Could not write updated calendar member to %s',
384 $attendee_calendar->dav_name(), $attendee_calendar->dav_name(), $schedule_target->username());
385 trace_bug('Failed to write scheduling resource.');
390 $schedule_request = clone($schedule_original);
391 $schedule_request->AddProperty('METHOD', 'REQUEST');
393 dbg_error_log( 'PUT', 'Status for organizer <%s> set to "%s"', $organizer->Value(), $response );
394 $organizer->SetParameterValue( 'SCHEDULE-STATUS', $response );
395 $resource->UpdateOrganizerStatus($organizer);
396 $scheduling_actions = true;
398 $attendees = $schedule_original->GetAttendees();
399 foreach( $attendees AS $attendee ) {
400 $email = preg_replace( '/^mailto:/i', '', $attendee->Value() );
401 if ( $email == $request->principal->email() || $email == $organizer_principal->email() ) continue;
403 $agent = $attendee->GetParameterValue('SCHEDULE-AGENT');
404 if ( $agent && $agent != 'SERVER' ) {
405 dbg_error_log( "PUT", "not delivering to %s, schedule agent set to value other than server", $email );
406 continue;
408 $schedule_target = new Principal('email',$email);
409 $response = '3.7'; // Attendee was not found on server.
410 if ( $schedule_target->Exists() ) {
411 $attendee_calendar = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-default-calendar')));
412 if ( !$attendee_calendar->Exists() ) {
413 dbg_error_log('ERROR','Default calendar at "%s" does not exist for user "%s"',
414 $attendee_calendar->dav_name(), $schedule_target->username());
415 $response = '5.2'; // No scheduling support for user
417 else {
418 $attendee_inbox = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-inbox')));
419 if ( ! $attendee_inbox->HavePrivilegeTo('schedule-deliver-invite') ) {
420 $response = '3.8'; // No authority to deliver invitations to user.
422 else if ( $attendee_inbox->WriteCalendarMember($schedule_request, false) !== false ) {
423 $response = '1.2'; // Scheduling invitation delivered successfully
424 if ( $attendee_calendar->WriteCalendarMember($schedule_original, false) === false ) {
425 dbg_error_log('ERROR','Could not write updated calendar member to %s',
426 $attendee_calendar->dav_name(), $attendee_calendar->dav_name(), $schedule_target->username());
427 trace_bug('Failed to write scheduling resource.');
432 dbg_error_log( 'PUT', 'Status for attendee <%s> set to "%s"', $attendee->Value(), $response );
433 $attendee->SetParameterValue( 'SCHEDULE-STATUS', $response );
434 $scheduling_actions = true;
436 $resource->UpdateAttendeeStatus($email, clone($attendee));
440 return $scheduling_actions;
445 * Create/Update the scheduling requests for this resource. This includes updating
446 * the scheduled user's default calendar.
447 * @param vComponent $resource The VEVENT/VTODO/... resource we are scheduling
448 * @param boolean $create true if the scheduling requests are being created.
449 * @return true If there was any scheduling action
451 function do_scheduling_requests( vCalendar $resource, $create, $old_data = null ) {
452 global $request, $c;
453 if ( !isset($request) || (isset($c->enable_auto_schedule) && !$c->enable_auto_schedule) ) return false;
455 if ( ! is_object($resource) ) {
456 trace_bug( 'do_scheduling_requests called with non-object parameter (%s)', gettype($resource) );
457 return false;
460 $organizer = $resource->GetOrganizer();
461 if ( $organizer === false || empty($organizer) ) {
462 dbg_error_log( 'PUT', 'Event has no organizer - no scheduling required.' );
463 return false;
465 $organizer_email = preg_replace( '/^mailto:/i', '', $organizer->Value() );
467 if ( $request->principal->email() != $organizer_email ) {
468 return do_scheduling_reply($resource,$organizer);
471 $schedule_request = clone($resource);
472 $schedule_request->AddProperty('METHOD', 'REQUEST');
474 $old_attendees = array();
475 if ( !empty($old_data) ) {
476 $old_resource = new vCalendar($old_data);
477 $old_attendees = $old_resource->GetAttendees();
479 $attendees = $resource->GetAttendees();
480 if ( count($attendees) == 0 && count($old_attendees) == 0 ) {
481 dbg_error_log( 'PUT', 'Event has no attendees - no scheduling required.', count($attendees) );
482 return false;
484 $removed_attendees = array();
485 foreach( $old_attendees AS $attendee ) {
486 $email = preg_replace( '/^mailto:/i', '', $attendee->Value() );
487 if ( $email == $request->principal->email() ) continue;
488 $removed_attendees[$email] = $attendee;
491 dbg_error_log( 'PUT', 'Writing scheduling resources for %d attendees', count($attendees) );
492 $scheduling_actions = false;
493 foreach( $attendees AS $attendee ) {
494 $email = preg_replace( '/^mailto:/i', '', $attendee->Value() );
495 if ( $email == $request->principal->email() ) {
496 dbg_error_log( "PUT", "not delivering to owner '%s'", $request->principal->email() );
497 continue;
500 if ( $create ) {
501 $attendee_is_new = true;
503 else {
504 $attendee_is_new = !isset($removed_attendees[$email]);
505 if ( !$attendee_is_new ) unset($removed_attendees[$email]);
508 $agent = $attendee->GetParameterValue('SCHEDULE-AGENT');
509 if ( $agent && $agent != 'SERVER' ) {
510 dbg_error_log( "PUT", "not delivering to %s, schedule agent set to value other than server", $email );
511 continue;
513 $schedule_target = new Principal('email',$email);
514 $response = '3.7'; // Attendee was not found on server.
515 dbg_error_log( 'PUT', 'Handling scheduling resources for %s on %s which is %s', $email,
516 ($create?'create':'update'), ($attendee_is_new? 'new' : 'an update') );
517 if ( $schedule_target->Exists() ) {
518 $attendee_calendar = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-default-calendar')));
519 if ( !$attendee_calendar->Exists() ) {
520 dbg_error_log('ERROR','Default calendar at "%s" does not exist for user "%s"',
521 $attendee_calendar->dav_name(), $schedule_target->username());
522 $response = '5.2'; // No scheduling support for user
524 else {
525 $attendee_inbox = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-inbox')));
526 if ( ! $attendee_inbox->HavePrivilegeTo('schedule-deliver-invite') ) {
527 $response = '3.8'; // No authority to deliver invitations to user.
529 else if ( $attendee_inbox->WriteCalendarMember($schedule_request, $attendee_is_new) !== false ) {
530 $response = '1.2'; // Scheduling invitation delivered successfully
531 if ( $attendee_calendar->WriteCalendarMember($resource, $attendee_is_new) === false ) {
532 dbg_error_log('ERROR','Could not write %s calendar member to %s', ($attendee_is_new?'new':'updated'),
533 $attendee_calendar->dav_name(), $attendee_calendar->dav_name(), $schedule_target->username());
534 trace_bug('Failed to write scheduling resource.');
539 else {
540 $remote = new iSchedule ();
541 $answer = $remote->sendRequest ( $email, 'VEVENT/REQUEST', $schedule_request->Render() );
542 if ( $answer === false ) {
543 $response = "3.7;Invalid Calendar User" ;
545 else {
546 foreach ( $answer as $a ) // should only be one element in array
548 if ( $a === false ) {
549 $response = "3.7;Invalid Calendar User" ;
551 elseif ( substr( $a, 0, 1 ) >= 1 ) {
552 $response = $a ;
554 else {
555 $response = "2.0;Success" ;
560 dbg_error_log( 'PUT', 'Status for attendee <%s> set to "%s"', $attendee->Value(), $response );
561 $attendee->SetParameterValue( 'SCHEDULE-STATUS', $response );
562 $scheduling_actions = true;
565 if ( !$create ) {
566 foreach( $removed_attendees AS $attendee ) {
567 $schedule_target = new Principal('email',$email);
568 if ( $schedule_target->Exists() ) {
569 $attendee_calendar = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-default-calendar')));
573 return $scheduling_actions;
578 * This function will import a whole collection
579 * @param string $ics_content the ics file to import
580 * @param int $user_no the user wich will receive this ics file
581 * @param string $path the $path where it will be store such as /user_foo/home/
582 * @param boolean $caldav_context Whether we are responding via CalDAV or interactively
584 * The work is either done by
586 function import_collection( $import_content, $user_no, $path, $caldav_context, $appending = false ) {
587 global $c;
589 if ( ! ini_get('open_basedir') && (isset($c->dbg['ALL']) || isset($c->dbg['put'])) ) {
590 $fh = fopen('/tmp/PUT-2.txt','w');
591 if ( $fh ) {
592 fwrite($fh,$import_content);
593 fclose($fh);
597 if ( preg_match( '{^begin:(vcard|vcalendar)}i', $import_content, $matches) ) {
598 if ( $matches[1] == 'VCARD' )
599 import_addressbook_collection( $import_content, $user_no, $path, $caldav_context, $appending );
600 elseif ( $matches[1] == 'VCALENDAR' )
601 import_calendar_collection( $import_content, $user_no, $path, $caldav_context, $appending );
603 // Uncache anything to do with the collection
604 $cache = getCacheInstance();
605 $cache_ns = 'collection-'.preg_replace( '{/[^/]*$}', '/', $path);
606 $cache->delete( $cache_ns, null );
608 else {
609 dbg_error_log('PUT', 'Can only import files which are VCARD or VCALENDAR');
614 * This function will import a whole calendar
615 * @param string $ics_content the ics file to import
616 * @param int $user_no the user wich will receive this ics file
617 * @param string $path the $path where it will be store such as /user_foo/home/
618 * @param boolean $caldav_context Whether we are responding via CalDAV or interactively
620 * Any VEVENTs with the same UID will be concatenated together
622 function import_addressbook_collection( $vcard_content, $user_no, $path, $caldav_context, $appending = false ) {
623 global $c, $session;
624 // We hack this into an enclosing component because vComponent only expects a single root component
625 $addressbook = new vComponent("BEGIN:ADDRESSES\r\n".$vcard_content."\r\nEND:ADDRESSES\r\n");
627 require_once('vcard.php');
629 $sql = 'SELECT * FROM collection WHERE dav_name = :dav_name';
630 $qry = new AwlQuery( $sql, array( ':dav_name' => $path) );
631 if ( ! $qry->Exec('PUT',__LINE__,__FILE__) ) rollback_on_error( $caldav_context, $user_no, $path );
632 if ( ! $qry->rows() == 1 ) {
633 dbg_error_log( 'ERROR', ' PUT: Collection does not exist at "%s" for user %d', $path, $user_no );
634 rollback_on_error( $caldav_context, $user_no, $path );
636 $collection = $qry->Fetch();
638 if ( !(isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import) ) $qry->Begin();
639 $base_params = array(
640 ':collection_id' => $collection->collection_id,
641 ':session_user' => $session->user_no,
642 ':caldav_type' => 'VCARD'
644 if ( !$appending ) {
645 if ( !$qry->QDo('DELETE FROM caldav_data WHERE collection_id = :collection_id', $base_params) )
646 rollback_on_error( $caldav_context, $user_no, $collection->collection_id );
649 $dav_data_insert = <<<EOSQL
650 INSERT INTO caldav_data ( user_no, dav_name, dav_etag, caldav_data, caldav_type, logged_user, created, modified, collection_id )
651 VALUES( :user_no, :dav_name, :etag, :dav_data, :caldav_type, :session_user, :created, :modified, :collection_id )
652 EOSQL;
655 $resources = $addressbook->GetComponents();
656 foreach( $resources AS $k => $resource ) {
657 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Begin();
659 $vcard = new vCard( $resource->Render() );
661 $uid = $vcard->GetPValue('UID');
662 if ( empty($uid) ) {
663 $uid = uuid();
664 $vcard->AddProperty('UID',$uid);
667 $last_modified = $vcard->GetPValue('REV');
668 if ( empty($last_modified) ) {
669 $last_modified = gmdate( 'Ymd\THis\Z' );
670 $vcard->AddProperty('REV',$last_modified);
673 $created = $vcard->GetPValue('X-CREATED');
674 if ( empty($last_modified) ) {
675 $created = gmdate( 'Ymd\THis\Z' );
676 $vcard->AddProperty('X-CREATED',$created);
679 $rendered_card = $vcard->Render();
681 $dav_data_params = $base_params;
682 $dav_data_params[':user_no'] = $user_no;
683 // We don't allow any of &?\/@%+: in the UID to appear in the path, but anything else is fair game.
684 $dav_data_params[':dav_name'] = sprintf( '%s%s.ics', $path, preg_replace('{[&?\\/@%+:]}','',$uid) );
685 $dav_data_params[':etag'] = md5($rendered_card);
686 $dav_data_params[':dav_data'] = $rendered_card;
687 $dav_data_params[':modified'] = $last_modified;
688 $dav_data_params[':created'] = $created;
690 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Begin();
692 if ( !$qry->QDo($dav_data_insert,$dav_data_params) ) rollback_on_error( $caldav_context, $user_no, $path );
694 $qry->QDo('SELECT dav_id FROM caldav_data WHERE dav_name = :dav_name ', array(':dav_name' => $dav_data_params[':dav_name']));
695 if ( $qry->rows() == 1 && $row = $qry->Fetch() ) {
696 $dav_id = $row->dav_id;
699 $vcard->Write( $row->dav_id, false );
701 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Commit();
704 if ( !(isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import) ) {
705 if ( ! $qry->Commit() ) rollback_on_error( $caldav_context, $user_no, $path);
711 * This function will import a whole calendar
712 * @param string $ics_content the ics file to import
713 * @param int $user_no the user wich will receive this ics file
714 * @param string $path the $path where it will be store such as /user_foo/home/
715 * @param boolean $caldav_context Whether we are responding via CalDAV or interactively
717 * Any VEVENTs with the same UID will be concatenated together
719 function import_calendar_collection( $ics_content, $user_no, $path, $caldav_context, $appending = false ) {
720 global $c, $session, $tz_regex;
721 $calendar = new vComponent($ics_content);
722 $timezones = $calendar->GetComponents('VTIMEZONE',true);
723 $components = $calendar->GetComponents('VTIMEZONE',false);
725 $displayname = $calendar->GetPValue('X-WR-CALNAME');
726 if ( !$appending && isset($displayname) ) {
727 $sql = 'UPDATE collection SET dav_displayname = :displayname WHERE dav_name = :dav_name';
728 $qry = new AwlQuery( $sql, array( ':displayname' => $displayname, ':dav_name' => $path) );
729 if ( ! $qry->Exec('PUT',__LINE__,__FILE__) ) rollback_on_error( $caldav_context, $user_no, $path );
732 $tz_ids = array();
733 foreach( $timezones AS $k => $tz ) {
734 $tz_ids[$tz->GetPValue('TZID')] = $k;
737 /** Build an array of resources. Each resource is an array of vComponent */
738 $resources = array();
739 foreach( $components AS $k => $comp ) {
740 $uid = $comp->GetPValue('UID');
741 if ( $uid == null || $uid == '' ) {
742 $uid = uuid();
743 $comp->AddProperty('UID',$uid);
744 dbg_error_log( 'LOG WARN', ' PUT: New collection resource does not have a UID - we assign one!' );
746 if ( !isset($resources[$uid]) ) $resources[$uid] = array();
747 $resources[$uid][] = $comp;
749 /** Ensure we have the timezone component for this in our array as well */
750 $tzid = GetTZID($comp);
751 if ( !empty($tzid) && !isset($resources[$uid][$tzid]) && isset($tz_ids[$tzid]) ) {
752 $resources[$uid][$tzid] = $timezones[$tz_ids[$tzid]];
757 $sql = 'SELECT * FROM collection WHERE dav_name = :dav_name';
758 $qry = new AwlQuery( $sql, array( ':dav_name' => $path) );
759 if ( ! $qry->Exec('PUT',__LINE__,__FILE__) ) rollback_on_error( $caldav_context, $user_no, $path );
760 if ( ! $qry->rows() == 1 ) {
761 dbg_error_log( 'ERROR', ' PUT: Collection does not exist at "%s" for user %d', $path, $user_no );
762 rollback_on_error( $caldav_context, $user_no, $path );
764 $collection = $qry->Fetch();
766 if ( !(isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import) ) $qry->Begin();
767 $base_params = array( ':collection_id' => $collection->collection_id );
768 if ( !$appending ) {
769 if ( !$qry->QDo('DELETE FROM calendar_item WHERE collection_id = :collection_id', $base_params)
770 || !$qry->QDo('DELETE FROM caldav_data WHERE collection_id = :collection_id', $base_params) )
771 rollback_on_error( $caldav_context, $user_no, $collection->collection_id );
774 $dav_data_insert = <<<EOSQL
775 INSERT INTO caldav_data ( user_no, dav_name, dav_etag, caldav_data, caldav_type, logged_user, created, modified, collection_id )
776 VALUES( :user_no, :dav_name, :etag, :dav_data, :caldav_type, :session_user, current_timestamp, current_timestamp, :collection_id )
777 EOSQL;
779 $calitem_insert = <<<EOSQL
780 INSERT INTO calendar_item (user_no, dav_name, dav_id, dav_etag, uid, dtstamp, dtstart, dtend, summary, location, class, transp,
781 description, rrule, tz_id, last_modified, url, priority, created, due, percent_complete, status, collection_id )
782 VALUES ( :user_no, :dav_name, currval('dav_id_seq'), :etag, :uid, :dtstamp, :dtstart, ##dtend##, :summary, :location, :class, :transp,
783 :description, :rrule, :tzid, :modified, :url, :priority, :created, :due, :percent_complete, :status, :collection_id)
784 EOSQL;
786 $last_olson = '';
787 foreach( $resources AS $uid => $resource ) {
788 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Begin();
790 /** Construct the VCALENDAR data */
791 $vcal = new vCalendar();
792 $vcal->SetComponents($resource);
793 $icalendar = $vcal->Render();
795 /** As ever, we mostly deal with the first resource component */
796 $first = $resource[0];
798 $dav_data_params = $base_params;
799 $dav_data_params[':user_no'] = $user_no;
800 // We don't allow any of &?\/@%+: in the UID to appear in the path, but anything else is fair game.
801 $dav_data_params[':dav_name'] = sprintf( '%s%s.ics', $path, preg_replace('{[&?\\/@%+:]}','',$uid) );
802 $dav_data_params[':etag'] = md5($icalendar);
803 $calitem_params = $dav_data_params;
804 $dav_data_params[':dav_data'] = $icalendar;
805 $dav_data_params[':caldav_type'] = $first->GetType();
806 $dav_data_params[':session_user'] = $session->user_no;
807 if ( !$qry->QDo($dav_data_insert,$dav_data_params) ) rollback_on_error( $caldav_context, $user_no, $path );
809 $qry->QDo('SELECT dav_id FROM caldav_data WHERE dav_name = :dav_name ', array(':dav_name' => $dav_data_params[':dav_name']));
810 if ( $qry->rows() == 1 && $row = $qry->Fetch() ) {
811 $dav_id = $row->dav_id;
814 $dtstart = $first->GetPValue('DTSTART');
815 $calitem_params[':dtstart'] = $dtstart;
816 if ( (!isset($dtstart) || $dtstart == '') && $first->GetPValue('DUE') != '' ) {
817 $dtstart = $first->GetPValue('DUE');
820 $dtend = $first->GetPValue('DTEND');
821 if ( isset($dtend) && $dtend != '' ) {
822 dbg_error_log( 'PUT', ' DTEND: "%s", DTSTART: "%s", DURATION: "%s"', $dtend, $dtstart, $first->GetPValue('DURATION') );
823 $calitem_params[':dtend'] = $dtend;
824 $dtend = ':dtend';
826 else {
827 $dtend = 'NULL';
828 if ( $first->GetPValue('DURATION') != '' AND $dtstart != '' ) {
829 $duration = trim(preg_replace( '#[PT]#', ' ', $first->GetPValue('DURATION') ));
830 if ( $duration == '' ) $duration = '0 seconds';
831 $dtend = '(:dtstart::timestamp with time zone + :duration::interval)';
832 $calitem_params[':duration'] = $duration;
834 elseif ( $first->GetType() == 'VEVENT' ) {
836 * From RFC2445 4.6.1:
837 * For cases where a "VEVENT" calendar component specifies a "DTSTART"
838 * property with a DATE data type but no "DTEND" property, the events
839 * non-inclusive end is the end of the calendar date specified by the
840 * "DTSTART" property. For cases where a "VEVENT" calendar component specifies
841 * a "DTSTART" property with a DATE-TIME data type but no "DTEND" property,
842 * the event ends on the same calendar date and time of day specified by the
843 * "DTSTART" property.
845 * So we're looking for 'VALUE=DATE', to identify the duration, effectively.
848 $dtstart_prop = $first->GetProperty('DTSTART');
849 $value_type = $dtstart_prop->GetParameterValue('VALUE');
850 dbg_error_log('PUT','DTSTART without DTEND. DTSTART value type is %s', $value_type );
851 if ( isset($value_type) && $value_type == 'DATE' )
852 $dtend = '(:dtstart::timestamp with time zone::date + \'1 day\'::interval)';
853 else
854 $dtend = ':dtstart';
858 $last_modified = $first->GetPValue('LAST-MODIFIED');
859 if ( !isset($last_modified) || $last_modified == '' ) $last_modified = gmdate( 'Ymd\THis\Z' );
860 $calitem_params[':modified'] = $last_modified;
862 $dtstamp = $first->GetPValue('DTSTAMP');
863 if ( empty($dtstamp) ) $dtstamp = $last_modified;
864 $calitem_params[':dtstamp'] = $dtstamp;
866 /** RFC2445, 4.8.1.3: Default is PUBLIC, or also if overridden by the collection settings */
867 $class = ($collection->public_events_only == 't' ? 'PUBLIC' : $first->GetPValue('CLASS') );
868 if ( !isset($class) || $class == '' ) $class = 'PUBLIC';
869 $calitem_params[':class'] = $class;
872 /** Calculate what timezone to set, first, if possible */
873 $tzid = GetTZID($first);
874 if ( !empty($tzid) && !empty($resource[$tzid]) ) {
875 $tz = $resource[$tzid];
876 $olson = $vcal->GetOlsonName($tz);
877 dbg_error_log( 'PUT', ' Using TZID[%s] and location of [%s]', $tzid, (isset($olson) ? $olson : '') );
878 if ( !empty($olson) && ($olson != $last_olson) && preg_match( $tz_regex, $olson ) ) {
879 dbg_error_log( 'PUT', ' Setting timezone to %s', $olson );
880 $qry->QDo('SET TIMEZONE TO \''.$olson."'" );
881 $last_olson = $olson;
883 $params = array( ':tzid' => $tzid);
884 $qry = new AwlQuery('SELECT 1 FROM timezones WHERE tzid = :tzid', $params );
885 if ( $qry->Exec('PUT',__LINE__,__FILE__) && $qry->rows() == 0 ) {
886 $params[':olson_name'] = $olson;
887 $params[':vtimezone'] = (isset($tz) ? $tz->Render() : null );
888 $params[':last_modified'] = (isset($tz) ? $tz->GetPValue('LAST-MODIFIED') : null );
889 if ( empty($params[':last_modified']) ) {
890 $params[':last_modified'] = gmdate('Ymd\THis\Z');
892 $qry->QDo('INSERT INTO timezones (tzid, olson_name, active, vtimezone, last_modified) VALUES(:tzid,:olson_name,false,:vtimezone,:last_modified)', $params );
895 else {
896 $tz = $olson = $tzid = null;
899 $sql = str_replace( '##dtend##', $dtend, $calitem_insert );
900 $calitem_params[':tzid'] = $tzid;
901 $calitem_params[':uid'] = $first->GetPValue('UID');
902 $calitem_params[':summary'] = $first->GetPValue('SUMMARY');
903 $calitem_params[':location'] = $first->GetPValue('LOCATION');
904 $calitem_params[':transp'] = $first->GetPValue('TRANSP');
905 $calitem_params[':description'] = $first->GetPValue('DESCRIPTION');
906 $calitem_params[':rrule'] = $first->GetPValue('RRULE');
907 $calitem_params[':url'] = $first->GetPValue('URL');
908 $calitem_params[':priority'] = $first->GetPValue('PRIORITY');
909 $calitem_params[':due'] = $first->GetPValue('DUE');
910 $calitem_params[':percent_complete'] = $first->GetPValue('PERCENT-COMPLETE');
911 $calitem_params[':status'] = $first->GetPValue('STATUS');
913 $created = $first->GetPValue('CREATED');
914 if ( $created == '00001231T000000Z' ) $created = '20001231T000000Z';
915 $calitem_params[':created'] = $created;
917 if ( !$qry->QDo($sql,$calitem_params) ) rollback_on_error( $caldav_context, $user_no, $path);
919 write_alarms($dav_id, $first);
920 write_attendees($dav_id, $vcal);
922 do_scheduling_requests( $vcal, true );
923 if ( isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import ) $qry->Commit();
926 if ( !(isset($c->skip_bad_event_on_import) && $c->skip_bad_event_on_import) ) {
927 if ( ! $qry->Commit() ) rollback_on_error( $caldav_context, $user_no, $path);
933 * Given a dav_id and an original vCalendar, pull out each of the VALARMs
934 * and write the values into the calendar_alarm table.
936 * @param int $dav_id The dav_id of the caldav_data we're processing
937 * @param vComponent The VEVENT or VTODO containing the VALARM
938 * @return null
940 function write_alarms( $dav_id, vComponent $ical ) {
941 $qry = new AwlQuery('DELETE FROM calendar_alarm WHERE dav_id = '.$dav_id );
942 $qry->Exec('PUT',__LINE__,__FILE__);
944 $alarms = $ical->GetComponents('VALARM');
945 if ( count($alarms) < 1 ) return;
947 $qry->SetSql('INSERT INTO calendar_alarm ( dav_id, action, trigger, summary, description, component, next_trigger )
948 VALUES( '.$dav_id.', :action, :trigger, :summary, :description, :component,
949 :related::timestamp with time zone + :related_trigger::interval )' );
950 $qry->Prepare();
951 foreach( $alarms AS $v ) {
952 $trigger = array_merge($v->GetProperties('TRIGGER'));
953 if ( $trigger == null ) continue; // Bogus data.
954 $trigger = $trigger[0];
955 $related = null;
956 $related_trigger = '0M';
957 $trigger_type = $trigger->GetParameterValue('VALUE');
958 if ( !isset($trigger_type) || $trigger_type == 'DURATION' ) {
959 switch ( $trigger->GetParameterValue('RELATED') ) {
960 case 'DTEND': $related = $ical->GetPValue('DTEND'); break;
961 case 'DUE': $related = $ical->GetPValue('DUE'); break;
962 default: $related = $ical->GetPValue('DTSTART');
964 $duration = $trigger->Value();
965 if ( !preg_match('{^-?P(:?\d+W)?(:?\d+D)?(:?T(:?\d+H)?(:?\d+M)?(:?\d+S)?)?$}', $duration ) ) continue;
966 $minus = (substr($duration,0,1) == '-');
967 $related_trigger = trim(preg_replace( '#[PT-]#', ' ', $duration ));
968 if ( $minus ) {
969 $related_trigger = preg_replace( '{(\d+[WDHMS])}', '-$1 ', $related_trigger );
971 else {
972 $related_trigger = preg_replace( '{(\d+[WDHMS])}', '$1 ', $related_trigger );
975 else {
976 if ( false === strtotime($trigger->Value()) ) continue; // Invalid date.
978 $qry->Bind(':action', $v->GetPValue('ACTION'));
979 $qry->Bind(':trigger', $trigger->Render());
980 $qry->Bind(':summary', $v->GetPValue('SUMMARY'));
981 $qry->Bind(':description', $v->GetPValue('DESCRIPTION'));
982 $qry->Bind(':component', $v->Render());
983 $qry->Bind(':related', $related );
984 $qry->Bind(':related_trigger', $related_trigger );
985 $qry->Exec('PUT',__LINE__,__FILE__);
991 * Parse out the attendee property and write a row to the
992 * calendar_attendee table for each one.
993 * @param int $dav_id The dav_id of the caldav_data we're processing
994 * @param vComponent The VEVENT or VTODO containing the ATTENDEEs
995 * @return null
997 function write_attendees( $dav_id, vCalendar $ical ) {
998 $qry = new AwlQuery('DELETE FROM calendar_attendee WHERE dav_id = '.$dav_id );
999 $qry->Exec('PUT',__LINE__,__FILE__);
1001 $attendees = $ical->GetAttendees();
1002 if ( count($attendees) < 1 ) return;
1004 $qry->SetSql('INSERT INTO calendar_attendee ( dav_id, status, partstat, cn, attendee, role, rsvp, property )
1005 VALUES( '.$dav_id.', :status, :partstat, :cn, :attendee, :role, :rsvp, :property )' );
1006 $qry->Prepare();
1007 $processed = array();
1008 foreach( $attendees AS $v ) {
1009 $attendee = $v->Value();
1010 if ( isset($processed[$attendee]) ) {
1011 dbg_error_log( 'LOG', 'Duplicate attendee "%s" in resource "%d"', $attendee, $dav_id );
1012 dbg_error_log( 'LOG', 'Original: "%s"', $processed[$attendee] );
1013 dbg_error_log( 'LOG', 'Duplicate: "%s"', $v->Render() );
1014 continue; /** @todo work out why we get duplicate ATTENDEE on one VEVENT */
1016 $qry->Bind(':attendee', $attendee );
1017 $qry->Bind(':status', $v->GetParameterValue('STATUS') );
1018 $qry->Bind(':partstat', $v->GetParameterValue('PARTSTAT') );
1019 $qry->Bind(':cn', $v->GetParameterValue('CN') );
1020 $qry->Bind(':role', $v->GetParameterValue('ROLE') );
1021 $qry->Bind(':rsvp', $v->GetParameterValue('RSVP') );
1022 $qry->Bind(':property', $v->Render() );
1023 $qry->Exec('PUT',__LINE__,__FILE__);
1024 $processed[$attendee] = $v->Render();
1030 * Actually write the resource to the database. All checking of whether this is reasonable
1031 * should be done before this is called.
1033 * @param DAVResource $resource The resource being written
1034 * @param string $caldav_data The actual data to be written
1035 * @param DAVResource $collection The collection containing the resource being written
1036 * @param int $author The user_no who wants to put this resource on the server
1037 * @param string $etag An etag unique for this event
1038 * @param string $put_action_type INSERT or UPDATE depending on what we are to do
1039 * @param boolean $caldav_context True, if we are responding via CalDAV, false for other ways of calling this
1040 * @param string Either 'INSERT' or 'UPDATE': the type of action we are doing
1041 * @param boolean $log_action Whether to log the fact that we are writing this into an action log (if configured)
1042 * @param string $weak_etag An etag that is NOT modified on ATTENDEE changes for this event
1044 * @return boolean True for success, false for failure.
1046 function write_resource( DAVResource $resource, $caldav_data, DAVResource $collection, $author, &$etag, $put_action_type, $caldav_context, $log_action=true, $weak_etag=null ) {
1047 global $tz_regex, $session;
1049 $path = $resource->bound_from();
1050 $user_no = $collection->user_no();
1051 $vcal = new vCalendar( $caldav_data );
1052 $resources = $vcal->GetComponents('VTIMEZONE',false); // Not matching VTIMEZONE
1053 if ( !isset($resources[0]) ) {
1054 $resource_type = 'Unknown';
1055 /** @todo Handle writing non-calendar resources, like address book entries or random file data */
1056 rollback_on_error( $caldav_context, $user_no, $path, translate('No calendar content'), 412 );
1057 return false;
1059 else {
1060 $first = $resources[0];
1061 if ( !($first instanceof vComponent) ) {
1062 print $vcal->Render();
1063 fatal('This is not a vComponent!');
1065 $resource_type = $first->GetType();
1068 $collection_id = $collection->collection_id();
1070 $qry = new AwlQuery();
1071 $qry->Begin();
1073 $dav_params = array(
1074 ':etag' => $etag,
1075 ':dav_data' => $caldav_data,
1076 ':caldav_type' => $resource_type,
1077 ':session_user' => $author,
1078 ':weak_etag' => $weak_etag
1081 $calitem_params = array(
1082 ':etag' => $etag
1085 if ( $put_action_type == 'INSERT' ) {
1086 $qry->QDo('SELECT nextval(\'dav_id_seq\') AS dav_id, null AS caldav_data');
1088 else {
1089 $qry->QDo('SELECT dav_id, caldav_data FROM caldav_data WHERE dav_name = :dav_name ', array(':dav_name' => $path));
1091 if ( $qry->rows() != 1 || !($row = $qry->Fetch()) ) {
1092 // No dav_id? => We're toast!
1093 trace_bug( 'No dav_id for "%s" on %s!!!', $path, ($create_resource ? 'create': 'update'));
1094 rollback_on_error( $caldav_context, $user_no, $path);
1095 return false;
1097 $dav_id = $row->dav_id;
1098 $old_dav_data = $row->caldav_data;
1099 $dav_params[':dav_id'] = $dav_id;
1100 $calitem_params[':dav_id'] = $dav_id;
1102 $due = null;
1103 if ( $first->GetType() == 'VTODO' ) $due = $first->GetPValue('DUE');
1104 $calitem_params[':due'] = $due;
1105 $dtstart = $first->GetPValue('DTSTART');
1106 if ( empty($dtstart) ) $dtstart = $due;
1107 $calitem_params[':dtstart'] = $dtstart;
1109 $dtend = $first->GetPValue('DTEND');
1110 if ( isset($dtend) && $dtend != '' ) {
1111 dbg_error_log( 'PUT', ' DTEND: "%s", DTSTART: "%s", DURATION: "%s"', $dtend, $dtstart, $first->GetPValue('DURATION') );
1112 $calitem_params[':dtend'] = $dtend;
1113 $dtend = ':dtend';
1115 else {
1116 // In this case we'll construct the SQL directly as a calculation relative to :dtstart
1117 $dtend = 'NULL';
1118 if ( $first->GetPValue('DURATION') != '' AND $dtstart != '' ) {
1119 $duration = trim(preg_replace( '#[PT]#', ' ', $first->GetPValue('DURATION') ));
1120 if ( $duration == '' ) $duration = '0 seconds';
1121 $dtend = '(:dtstart::timestamp with time zone + :duration::interval)';
1122 $calitem_params[':duration'] = $duration;
1124 elseif ( $first->GetType() == 'VEVENT' ) {
1126 * From RFC2445 4.6.1:
1127 * For cases where a "VEVENT" calendar component specifies a "DTSTART"
1128 * property with a DATE data type but no "DTEND" property, the events
1129 * non-inclusive end is the end of the calendar date specified by the
1130 * "DTSTART" property. For cases where a "VEVENT" calendar component specifies
1131 * a "DTSTART" property with a DATE-TIME data type but no "DTEND" property,
1132 * the event ends on the same calendar date and time of day specified by the
1133 * "DTSTART" property.
1135 * So we're looking for 'VALUE=DATE', to identify the duration, effectively.
1138 $dtstart_prop = $first->GetProperty('DTSTART');
1139 $value_type = $dtstart_prop->GetParameterValue('VALUE');
1140 dbg_error_log('PUT','DTSTART without DTEND. DTSTART value type is %s', $value_type );
1141 if ( isset($value_type) && $value_type == 'DATE' )
1142 $dtend = '(:dtstart::timestamp with time zone::date + \'1 day\'::interval)';
1143 else
1144 $dtend = ':dtstart';
1148 $dtstamp = $first->GetPValue('DTSTAMP');
1149 if ( !isset($dtstamp) || $dtstamp == '' ) {
1150 // Strictly, we're dealing with an out of spec component here, but we'll try and survive
1151 $dtstamp = gmdate( 'Ymd\THis\Z' );
1153 $calitem_params[':dtstamp'] = $dtstamp;
1155 $last_modified = $first->GetPValue('LAST-MODIFIED');
1156 if ( !isset($last_modified) || $last_modified == '' ) $last_modified = $dtstamp;
1157 $dav_params[':modified'] = $last_modified;
1158 $calitem_params[':modified'] = $last_modified;
1160 $created = $first->GetPValue('CREATED');
1161 if ( $created == '00001231T000000Z' ) $created = '20001231T000000Z';
1163 $class = $first->GetPValue('CLASS');
1164 /* Check and see if we should over ride the class. */
1165 /** @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. */
1166 if ( public_events_only($user_no, $path) ) {
1167 $class = 'PUBLIC';
1171 * It seems that some calendar clients don't set a class...
1172 * RFC2445, 4.8.1.3:
1173 * Default is PUBLIC
1175 if ( !isset($class) || $class == '' ) {
1176 $class = 'PUBLIC';
1178 $calitem_params[':class'] = $class;
1180 /** Calculate what timezone to set, first, if possible */
1181 $last_olson = 'Turkmenikikamukau'; // I really hope this location doesn't exist!
1182 $tzid = GetTZID($first);
1183 if ( !empty($tzid) ) {
1184 $timezones = $vcal->GetComponents('VTIMEZONE');
1185 foreach( $timezones AS $k => $tz ) {
1186 if ( $tz->GetPValue('TZID') != $tzid ) {
1188 * We'll skip any tz definitions that are for a TZID other than the DTSTART/DUE on the first VEVENT/VTODO
1190 dbg_error_log( 'ERROR', ' Event uses TZID[%s], skipping included TZID[%s]!', $tz->GetPValue('TZID'), $tzid );
1191 continue;
1193 $olson = olson_from_tzstring($tzid);
1194 if ( empty($olson) ) {
1195 $olson = $tz->GetPValue('X-LIC-LOCATION');
1196 if ( !empty($olson) ) {
1197 $olson = olson_from_tzstring($olson);
1202 dbg_error_log( 'PUT', ' Using TZID[%s] and location of [%s]', $tzid, (isset($olson) ? $olson : '') );
1203 if ( !empty($olson) && ($olson != $last_olson) && preg_match( $tz_regex, $olson ) ) {
1204 dbg_error_log( 'PUT', ' Setting timezone to %s', $olson );
1205 if ( $olson != '' ) {
1206 $qry->QDo('SET TIMEZONE TO \''.$olson."'" );
1208 $last_olson = $olson;
1210 $params = array( ':tzid' => $tzid);
1211 $qry = new AwlQuery('SELECT 1 FROM timezones WHERE tzid = :tzid', $params );
1212 if ( $qry->Exec('PUT',__LINE__,__FILE__) && $qry->rows() == 0 ) {
1213 $params[':olson_name'] = $olson;
1214 $params[':vtimezone'] = (isset($tz) ? $tz->Render() : null );
1215 $qry->QDo('INSERT INTO timezones (tzid, olson_name, active, vtimezone) VALUES(:tzid,:olson_name,false,:vtimezone)', $params );
1217 if ( !isset($olson) || $olson == '' ) $olson = $tzid;
1222 $calitem_params[':tzid'] = $tzid;
1223 $calitem_params[':uid'] = $first->GetPValue('UID');
1224 $calitem_params[':summary'] = $first->GetPValue('SUMMARY');
1225 $calitem_params[':location'] = $first->GetPValue('LOCATION');
1226 $calitem_params[':transp'] = $first->GetPValue('TRANSP');
1227 $calitem_params[':description'] = $first->GetPValue('DESCRIPTION');
1228 $calitem_params[':rrule'] = $first->GetPValue('RRULE');
1229 $calitem_params[':url'] = $first->GetPValue('URL');
1230 $calitem_params[':priority'] = $first->GetPValue('PRIORITY');
1231 $calitem_params[':percent_complete'] = $first->GetPValue('PERCENT-COMPLETE');
1232 $calitem_params[':status'] = $first->GetPValue('STATUS');
1234 if ( !$collection->IsSchedulingCollection() ) {
1235 if ( do_scheduling_requests($vcal, ($put_action_type == 'INSERT'), $old_dav_data ) ) {
1236 $dav_params[':dav_data'] = $vcal->Render(null, true);
1237 $etag = null;
1241 if ( !isset($dav_params[':modified']) ) $dav_params[':modified'] = 'now';
1242 if ( $put_action_type == 'INSERT' ) {
1243 $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 )
1244 VALUES( :dav_id, :user_no, :dav_name, :etag, :dav_data, :caldav_type, :session_user, :created, :modified, :collection_id, :weak_etag )';
1245 $dav_params[':collection_id'] = $collection_id;
1246 $dav_params[':user_no'] = $user_no;
1247 $dav_params[':dav_name'] = $path;
1248 $dav_params[':created'] = (isset($created) && $created != '' ? $created : $dtstamp);
1250 else {
1251 $sql = 'UPDATE caldav_data SET caldav_data=:dav_data, dav_etag=:etag, caldav_type=:caldav_type, logged_user=:session_user,
1252 modified=:modified, weak_etag=:weak_etag WHERE dav_id=:dav_id';
1254 $qry = new AwlQuery($sql,$dav_params);
1255 if ( !$qry->Exec('PUT',__LINE__,__FILE__) ) {
1256 fatal('Insert into calendar_item failed...');
1257 rollback_on_error( $caldav_context, $user_no, $path);
1258 return false;
1262 if ( $put_action_type == 'INSERT' ) {
1263 $sql = <<<EOSQL
1264 INSERT INTO calendar_item (user_no, dav_name, dav_id, dav_etag, uid, dtstamp,
1265 dtstart, dtend, summary, location, class, transp,
1266 description, rrule, tz_id, last_modified, url, priority,
1267 created, due, percent_complete, status, collection_id )
1268 VALUES ( :user_no, :dav_name, :dav_id, :etag, :uid, :dtstamp,
1269 :dtstart, $dtend, :summary, :location, :class, :transp,
1270 :description, :rrule, :tzid, :modified, :url, :priority,
1271 :created, :due, :percent_complete, :status, :collection_id )
1272 EOSQL;
1273 $sync_change = 201;
1274 $calitem_params[':collection_id'] = $collection_id;
1275 $calitem_params[':user_no'] = $user_no;
1276 $calitem_params[':dav_name'] = $path;
1277 $calitem_params[':created'] = $dav_params[':created'];
1279 else {
1280 $sql = <<<EOSQL
1281 UPDATE calendar_item SET dav_etag=:etag, uid=:uid, dtstamp=:dtstamp,
1282 dtstart=:dtstart, dtend=$dtend, summary=:summary, location=:location,
1283 class=:class, transp=:transp, description=:description, rrule=:rrule,
1284 tz_id=:tzid, last_modified=:modified, url=:url, priority=:priority,
1285 due=:due, percent_complete=:percent_complete, status=:status
1286 WHERE dav_id=:dav_id
1287 EOSQL;
1288 $sync_change = 200;
1291 write_alarms($dav_id, $first);
1292 write_attendees($dav_id, $vcal);
1294 if ( $log_action && function_exists('log_caldav_action') ) {
1295 log_caldav_action( $put_action_type, $first->GetPValue('UID'), $user_no, $collection_id, $path );
1297 else if ( $log_action ) {
1298 dbg_error_log( 'PUT', 'No log_caldav_action( %s, %s, %s, %s, %s) can be called.',
1299 $put_action_type, $first->GetPValue('UID'), $user_no, $collection_id, $path );
1302 $qry = new AwlQuery( $sql, $calitem_params );
1303 if ( !$qry->Exec('PUT',__LINE__,__FILE__) ) {
1304 rollback_on_error( $caldav_context, $user_no, $path);
1305 return false;
1307 $qry->QDo("SELECT write_sync_change( $collection_id, $sync_change, :dav_name)", array(':dav_name' => $path ) );
1308 $qry->Commit();
1310 // Uncache anything to do with the collection
1311 $cache = getCacheInstance();
1312 $cache_ns = 'collection-'.preg_replace( '{/[^/]*$}', '/', $path);
1313 $cache->delete( $cache_ns, null );
1315 dbg_error_log( 'PUT', 'User: %d, ETag: %s, Path: %s', $author, $etag, $path);
1317 return true; // Success!
1323 * A slightly simpler version of write_resource which will make more sense for calling from
1324 * an external program. This makes assumptions that the collection and user do exist
1325 * and bypasses all checks for whether it is reasonable to write this here.
1326 * @param string $path The path to the resource being written
1327 * @param string $caldav_data The actual resource to be written
1328 * @param string $put_action_type INSERT or UPDATE depending on what we are to do
1329 * @return boolean True for success, false for failure.
1331 function simple_write_resource( $path, $caldav_data, $put_action_type, $write_action_log = false ) {
1332 global $session;
1335 * We pull the user_no & collection_id out of the collection table, based on the resource path
1337 $dav_resource = new DAVResource($path);
1338 $etag = md5($caldav_data);
1339 $collection_path = preg_replace( '#/[^/]*$#', '/', $path );
1340 $collection = new DAVResource($collection_path);
1341 if ( $collection->IsCollection() || $collection->IsSchedulingCollection() ) {
1342 return write_resource( $dav_resource, $caldav_data, $collection, $session->user_no, $etag, $put_action_type, false, $write_action_log );
1344 return false;