Merge branch 'master' of github.com:DAViCal/davical into github
[davical.git] / inc / schedule-functions.php
blobb792b932e4baea2046e6a38b16cac3c229e52128
1 <?php
2 /**
3 * Functions for handling CalDAV Scheduling.
4 *
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 require_once('vCalendar.php');
13 require_once('WritableCollection.php');
14 require_once('RRule-v2.php');
16 /**
17 * Entry point for scheduling on DELETE, for which there are thee outcomes:
18 * - We don't do scheduling (disabled, no organizer, ...)
19 * - We are an ATTENDEE declining the meeting.
20 * - We are the ORGANIZER canceling the meeting.
22 * @param DAVResource $deleted_resource The resource which has already been deleted
24 function do_scheduling_for_delete(DAVResource $deleted_resource ) {
25 // By the time we arrive here the resource *has* actually been deleted from disk
26 // we can only fail to (de-)schedule the activity...
27 global $request, $c;
29 if ( !isset($request) || (isset($c->enable_auto_schedule) && !$c->enable_auto_schedule) ) return true;
30 if ( $deleted_resource->IsInSchedulingCollection() ) return true;
32 $caldav_data = $deleted_resource->GetProperty('dav-data');
33 if ( empty($caldav_data) ) return true;
35 $vcal = new vCalendar($caldav_data);
36 $organizer = $vcal->GetOrganizer();
37 if ( $organizer === false || empty($organizer) ) {
38 dbg_error_log( 'schedule', 'Event has no organizer - no scheduling required.' );
39 return true;
41 if ( $vcal->GetScheduleAgent() != 'SERVER' ) {
42 dbg_error_log( 'schedule', 'SCHEDULE-AGENT=%s - no scheduling required.', $vcal->GetScheduleAgent() );
43 return true;
45 $organizer_email = preg_replace( '/^mailto:/i', '', $organizer->Value() );
47 if ( $request->principal->email() == $organizer_email ) {
48 return doItipOrganizerCancel( $vcal );
50 else {
51 if ( isset($_SERVER['HTTP_SCHEDULE_REPLY']) && $_SERVER['HTTP_SCHEDULE_REPLY'] == 'F') {
52 dbg_error_log( 'schedule', 'Schedule-Reply header set to "F" - no scheduling required.' );
53 return true;
55 return doItipAttendeeReply( $vcal, 'DECLINED', $request->principal->email());
61 /**
62 * Do the scheduling adjustments for a REPLY when an ATTENDEE updates their status.
63 * @param vCalendar $vcal The resource that the ATTENDEE is writing to their calendar
64 * @param string $partstat The participant status being replied
66 //function do_scheduling_reply( vCalendar $vcal, vProperty $organizer ) {
67 function doItipAttendeeReply( vCalendar $resource, $partstat ) {
68 global $request;
70 $organizer = $resource->GetOrganizer();
71 $organizer_email = preg_replace( '/^mailto:/i', '', $organizer->Value() );
72 $organizer_principal = new Principal('email',$organizer_email );
74 if ( !$organizer_principal->Exists() ) {
75 dbg_error_log( 'schedule', 'Unknown ORGANIZER "%s" - unable to notify.', $organizer->Value() );
76 header( "Debug: Could maybe do the iMIP message dance for organizer ". $organizer->Value() );
77 return true;
80 $sql = 'SELECT caldav_data.dav_name, caldav_data.caldav_data FROM caldav_data JOIN calendar_item USING(dav_id) ';
81 $sql .= 'WHERE caldav_data.collection_id IN (SELECT collection_id FROM collection WHERE is_calendar AND user_no =?) ';
82 $sql .= 'AND uid=? LIMIT 1';
83 $uids = $resource->GetPropertiesByPath('/VCALENDAR/*/UID');
84 if ( count($uids) == 0 ) {
85 dbg_error_log( 'schedule', 'No UID in VCALENDAR - giving up on REPLY.' );
86 return true;
88 $uid = $uids[0]->Value();
89 $qry = new AwlQuery($sql, $organizer_principal->user_no(), $uid);
90 if ( !$qry->Exec('schedule',__LINE__,__FILE__) || $qry->rows() < 1 ) {
91 dbg_error_log( 'schedule', 'Could not find original event from organizer - giving up on REPLY.' );
92 return true;
94 $row = $qry->Fetch();
95 $collection_path = preg_replace('{/[^/]+$}', '/', $row->dav_name );
96 $segment_name = str_replace($collection_path, '', $row->dav_name );
97 $vcal = new vCalendar($row->caldav_data);
99 $attendees = $vcal->GetAttendees();
100 foreach( $attendees AS $v ) {
101 $email = preg_replace( '/^mailto:/i', '', $v->Value() );
102 if ( $email == $request->principal->email() ) {
103 $attendee = $v;
104 break;
107 if ( empty($attendee) ) {
108 dbg_error_log( 'schedule', 'Could not find ATTENDEE in VEVENT - giving up on REPLY.' );
109 return true;
112 $attendee->SetParameterValue('PARTSTAT', $partstat);
113 $attendee->SetParameterValue('SCHEDULE-STATUS', '2.0');
114 $vcal->UpdateAttendeeStatus($request->principal->email(), clone($attendee) );
116 $organizer_calendar = new WritableCollection(array('path' => $collection_path));
117 $organizer_inbox = new WritableCollection(array('path' => $organizer_principal->internal_url('schedule-inbox')));
119 $schedule_reply = GetItip(new vCalendar($row->caldav_data),'REPLY',$attendee->Value());
120 $schedule_request = GetItip(new vCalendar($row->caldav_data),'REQUEST',null);
122 dbg_error_log( 'schedule', 'Writing ATTENDEE scheduling REPLY from %s to %s', $request->principal->email(), $organizer_principal->email() );
124 $response = '3.7'; // Organizer was not found on server.
125 if ( !$organizer_calendar->Exists() ) {
126 if ( doImipMessage('REPLY', $organizer_principal->email(), $vcal) ) {
127 $response = '1.1'; // Scheduling whoosit 'Sent'
129 else {
130 dbg_error_log('ERROR','Default calendar at "%s" does not exist for user "%s"',
131 $organizer_calendar->dav_name(), $schedule_target->username());
132 $response = '5.2'; // No scheduling support for user
135 else {
136 if ( ! $organizer_inbox->HavePrivilegeTo('schedule-deliver-reply') ) {
137 $response = '3.8'; // No authority to deliver replies to organizer.
139 $response = '1.2'; // Scheduling reply delivered successfully
140 if ( $organizer_calendar->WriteCalendarMember($vcal, false, false, $segment_name) === false ) {
141 dbg_error_log('ERROR','Could not write updated calendar member to %s', $attendee_calendar->dav_name() );
142 trace_bug('Failed to write scheduling resource.');
144 $organizer_inbox->WriteCalendarMember($schedule_reply, false, false, $request->principal->username().$segment_name);
148 dbg_error_log( 'schedule', 'Status for organizer <%s> set to "%s"', $organizer->Value(), $response );
149 $organizer->SetParameterValue( 'SCHEDULE-STATUS', $response );
150 $resource->UpdateOrganizerStatus($organizer); // Which was passed in by reference, and we're updating it here.
152 // Now we loop through the *other* ATTENDEEs, updating them on the status of the ATTENDEE DECLINE/ACCEPT
153 foreach( $attendees AS $attendee ) {
154 $email = preg_replace( '/^mailto:/i', '', $attendee->Value() );
155 if ( $email == $request->principal->email() || $email == $organizer_principal->email() ) continue;
157 $agent = $attendee->GetParameterValue('SCHEDULE-AGENT');
158 if ( !empty($agent) && $agent != 'SERVER' ) continue;
160 $schedule_target = new Principal('email',$email);
161 if ( $schedule_target->Exists() ) {
162 $attendee_calendar = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-default-calendar')));
163 if ( !$attendee_calendar->Exists() ) {
164 dbg_error_log('ERROR','Default calendar at "%s" does not exist for user "%s"',
165 $attendee_calendar->dav_name(), $schedule_target->username());
166 continue;
168 else {
169 $attendee_inbox = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-inbox')));
170 if ( ! $attendee_inbox->HavePrivilegeTo('schedule-deliver-invite') ) continue;
172 if ( $attendee_calendar->WriteCalendarMember($vcal, false) === false ) {
173 dbg_error_log('ERROR','Could not write updated calendar member to %s', $attendee_calendar->dav_name());
174 trace_bug('Failed to write scheduling resource.');
176 $attendee_inbox->WriteCalendarMember($schedule_request, false);
179 else {
180 header( "Debug: Could maybe do the iMIP message dance for attendee ". $email );
184 return true;
187 function GetItip( VCalendar $vcal, $method, $attendee_value ) {
189 $iTIP = $vcal->GetItip($method, $attendee_value );
190 $iTIP->AddProperty('REQUEST-STATUS','2.0');
191 $components = $iTIP->GetComponents();
192 foreach( $components AS $comp ) {
193 $properties = array();
194 foreach( $comp->GetProperties() AS $k=> $property ) {
195 switch( $property->Name() ) {
196 case 'DTSTART':
197 case 'DTEND':
198 case 'DUE':
199 $when = new RepeatRuleDateTime($property);
200 $properties[] = new vProperty( $property->Name() . ":" . $when->UTC() );
201 break;
202 default:
203 $properties[] = $property;
206 $comp->SetProperties($properties);
209 return $iTIP;
213 * Handles sending the iTIP CANCEL messages to each ATTENDEE by the ORGANIZER.
214 * @param vCalendar $vcal What's being cancelled.
216 function doItipOrganizerCancel( vCalendar $vcal ) {
217 global $request;
219 $attendees = $vcal->GetAttendees();
220 if ( count($attendees) == 0 && count($old_attendees) == 0 ) {
221 dbg_error_log( 'schedule', 'Event has no attendees - no scheduling required.', count($attendees) );
222 return true;
225 dbg_error_log( 'schedule', 'Writing scheduling resources for %d attendees', count($attendees) );
226 $scheduling_actions = false;
228 $iTIP = GetItip($vcal, 'CANCEL', null);
230 foreach( $attendees AS $attendee ) {
231 $email = preg_replace( '/^mailto:/i', '', $attendee->Value() );
232 if ( $email == $request->principal->email() ) {
233 dbg_error_log( 'schedule', "not delivering to owner '%s'", $request->principal->email() );
234 continue;
237 $agent = $attendee->GetParameterValue('SCHEDULE-AGENT');
238 if ( $agent && $agent != 'SERVER' ) {
239 dbg_error_log( 'schedule', "not delivering to %s, schedule agent set to value other than server", $email );
240 continue;
242 $schedule_target = new Principal('email',$email);
243 if ( !$schedule_target->Exists() ) {
244 if ( doImipMessage('CANCEL', $email, $vcal) ) {
245 $response = '1.1'; // Scheduling whoosit 'Sent'
247 else {
248 $response = '3.7';
251 else {
252 $attendee_inbox = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-inbox')));
253 if ( ! $attendee_inbox->HavePrivilegeTo('schedule-deliver-invite') ) {
254 dbg_error_log( 'schedule', "No authority to deliver invite to %s", $schedule_target->internal_url('schedule-inbox') );
255 $response = '3.8';
257 else {
258 $attendee_calendar = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-default-calendar')));
259 $response = processItipCancel( $vcal, $attendee, $attendee_calendar, $schedule_target );
260 deliverItipCancel( $iTIP, $attendee, $attendee_inbox );
263 dbg_error_log( 'schedule', 'Status for attendee <%s> set to "%s"', $attendee->Value(), $response );
264 $attendee->SetParameterValue( 'SCHEDULE-STATUS', $response );
265 $scheduling_actions = true;
268 return true;
272 * Does the actual processing of the iTIP CANCEL message on behalf of an ATTENDEE,
273 * which generally means writing it into the ATTENDEE's default calendar.
275 * @param vCalendar $vcal The message.
276 * @param vProperty $attendee
277 * @param WritableCollection $attendee_calendar
279 function processItipCancel( vCalendar $vcal, vProperty $attendee, WritableCollection $attendee_calendar, Principal $attendee_principal ) {
280 global $request;
282 dbg_error_log( 'schedule', 'Processing iTIP CANCEL to %s', $attendee->Value());
283 header( "Debug: Could maybe do the iMIP message dance for attendee ". $attendee->Value() );
284 if ( !$attendee_calendar->Exists() ) {
285 if ( doImipMessage('CANCEL', $attendee_principal->email(), $vcal) ) {
286 return '1.1'; // Scheduling whoosit 'Sent'
288 else {
289 dbg_error_log('ERROR', 'Default calendar at "%s" does not exist for attendee "%s"',
290 $attendee_calendar->dav_name(), $attendee->Value());
291 return '5.2'; // No scheduling support for user
295 $sql = 'SELECT caldav_data.dav_name FROM caldav_data JOIN calendar_item USING(dav_id) ';
296 $sql .= 'WHERE caldav_data.collection_id IN (SELECT collection_id FROM collection WHERE is_calendar AND user_no =?) ';
297 $sql .= 'AND uid=? LIMIT 1';
298 $uids = $vcal->GetPropertiesByPath('/VCALENDAR/*/UID');
299 if ( count($uids) == 0 ) {
300 dbg_error_log( 'schedule', 'No UID in VCALENDAR - giving up on CANCEL processing.' );
301 return '3.8';
303 $uid = $uids[0]->Value();
304 $qry = new AwlQuery($sql, $attendee_principal->user_no(), $uid);
305 if ( !$qry->Exec('schedule',__LINE__,__FILE__) || $qry->rows() < 1 ) {
306 dbg_error_log( 'schedule', 'Could not find ATTENDEE copy of original event - not trying to DELETE it!' );
307 return '1.2';
309 $row = $qry->Fetch();
311 if ( $attendee_calendar->actualDeleteCalendarMember($row->dav_name) === false ) {
312 dbg_error_log('ERROR', 'Could not delete calendar member %s for %s',
313 $row->dav_name(), $attendee->Value());
314 trace_bug('Failed to write scheduling resource.');
315 return '5.2';
318 return '1.2'; // Scheduling invitation delivered successfully
324 * Delivers the iTIP CANCEL message to an ATTENDEE's Scheduling Inbox Collection.
326 * This is pretty simple at present, but could be extended in the future to do the sending
327 * of e-mail to a remote attendee.
329 * @param vCalendar $iTIP
330 * @param vProperty $attendee
331 * @param WritableCollection $attendee_inbox
333 function deliverItipCancel( vCalendar $iTIP, vProperty $attendee, WritableCollection $attendee_inbox ) {
334 $attendee_inbox->WriteCalendarMember($iTIP, false);
335 header( "Debug: Could maybe do the iMIP message dance canceling for attendee: ".$attendee->Value());
338 require_once('Multipart.php');
341 * Send an iMIP message since they look like a non-local user.
343 * @param string $method The METHOD parameter from the iTIP
344 * @param string $to_email The e-mail address we're going to send to
345 * @param vCalendar $vcal The iTIP part of the message.
347 function doImipMessage($method, $to_email, vCalendar $itip) {
348 global $c, $request;
350 header( 'Debug: Sending iMIP '.$method.' message to '.$to_email);
352 $mime = new MultiPart();
353 $mime->addPart( $itip->Render(), 'text/calendar; charset=UTF-8; method='.$method );
355 $friendly_part = isset($c->iMIP->template[$method]) ? $c->iMIP->template[$method] : <<<EOTEMPLATE
356 This is a meeting ##METHOD## which your e-mail program should be able to
357 import into your calendar. Alternatively you could save the attachment
358 and load that into your calendar instead.
359 EOTEMPLATE;
361 $components = $itip->GetComponents( 'VTIMEZONE',false);
363 $replaceable = array( 'METHOD', 'DTSTART', 'DTEND', 'SUMMARY', 'DESCRIPTION', 'URL' );
364 foreach( $replaceable AS $pname ) {
365 $search = '##'.$pname.'##';
366 if ( strstr($friendly_part,$search) !== false ) {
367 $property = $itip->GetProperty($pname);
368 if ( empty($property) )
369 $property = $components[0]->GetProperty($pname);
371 if ( empty($property) )
372 $replace = '';
373 else {
374 switch( $pname ) {
375 case 'DTSTART':
376 case 'DTEND':
377 $when = new RepeatRuleDateTime($property);
378 $replace = $when->format('c');
379 break;
380 default:
381 $replace = $property->GetValue();
384 $friendly_part = str_replace($search, $replace, $friendly_part);
387 $mime->addPart( $friendly_part, 'text/plain' );
389 $email = new EMail();
390 $email->SetFrom($request->principal->email());
391 $email->AddTo($to_email);
393 $email->SetSubject( $components[0]->GetPValue('SUMMARY') );
394 $email->SetBody($mime->getMimeParts());
396 if ( isset($c->iMIP->pretend_email) ) {
397 $email->Pretend($mime->getMimeHeaders());
399 else if ( !isset($c->iMIP->send_email) || !$c->iMIP->send_email) {
400 $email->PretendLog($mime->getMimeHeaders());
402 else {
403 $email->Send($mime->getMimeHeaders());