Fixed CalDAV/GroupDAV to include all exceptions of a series in the

resource of the series master. Now the status of single recurrences of a
serie are send to the clients as (virtual) exceptions as Jaytrax&Joerg
implemented it already for SyncML.
The implementation is unfortunately a little different, as CalDAV
differs from SyncML and I dont know the SyncML part that well. Maybe we
can re-unify the code again together.
Tested so far with Tb3/Lightning1.0b and a little with iPhone.
Please let me know, if you run into problems with other clients.
This commit is contained in:
Ralf Becker 2009-12-27 04:21:33 +00:00
parent fdf4dcb9b9
commit dd0a5c1b13
3 changed files with 266 additions and 52 deletions

View File

@ -35,6 +35,22 @@ class calendar_groupdav extends groupdav_handler
//'EXDATE' //'EXDATE'
//'RECURRENCE-ID' //'RECURRENCE-ID'
); );
/**
* Does client understand exceptions to be included in VCALENDAR component of series master sharing its UID
*
* That also means no EXDATE for these exceptions!
*
* Setting it to false, should give the old behavior used in 1.6 (hopefully) no client needs that.
*
* @var boolean
*/
var $client_shared_uid_exceptions = true;
/**
* Are we using id or uid for the path/url
*/
const PATH_ATTRIBUTE = 'id';
/** /**
* Constructor * Constructor
@ -50,8 +66,6 @@ class calendar_groupdav extends groupdav_handler
$this->bo = new calendar_boupdate(); $this->bo = new calendar_boupdate();
} }
const PATH_ATTRIBUTE = 'id';
/** /**
* Create the path for an event * Create the path for an event
* *
@ -96,13 +110,17 @@ class calendar_groupdav extends groupdav_handler
'daywise' => false, 'daywise' => false,
'date_format' => 'server', 'date_format' => 'server',
); );
if ($this->debug > 1) error_log(__METHOD__."($path,,,$user,$id) cal_filters=".array2string($cal_filters)); if ($this->client_shared_uid_exceptions)
//error_log(__METHOD__."($path,,,$user,$id) cal_filters=".array2string($cal_filters)); {
$cal_filters['query']['cal_reference'] = 0;
}
// process REPORT filters or multiget href's // process REPORT filters or multiget href's
if (($id || $options['root']['name'] != 'propfind') && !$this->_report_filters($options,$cal_filters,$id)) if (($id || $options['root']['name'] != 'propfind') && !$this->_report_filters($options,$cal_filters,$id))
{ {
return false; return false;
} }
if ($this->debug > 1) error_log(__METHOD__."($path,,,$user,$id) cal_filters=".array2string($cal_filters));
// check if we have to return the full calendar data or just the etag's // check if we have to return the full calendar data or just the etag's
if (!($calendar_data = $options['props'] == 'all' && $options['root']['ns'] == groupdav::CALDAV) && is_array($options['props'])) if (!($calendar_data = $options['props'] == 'all' && $options['root']['ns'] == groupdav::CALDAV) && is_array($options['props']))
{ {
@ -115,10 +133,19 @@ class calendar_groupdav extends groupdav_handler
} }
} }
} }
if (($events =& $this->bo->search($cal_filters))) $events =& $this->bo->search($cal_filters);
if ($events)
{ {
// get all max user modified times at once
foreach($events as &$event) foreach($events as &$event)
{ {
$ids[] = $event['id'];
}
$max_user_modified = $this->bo->so->max_user_modified($ids);
foreach($events as &$event)
{
$event['max_user_modified'] = $max_user_modified[$event['id']];
//header('X-EGROUPWARE-EVENT-'.$event['id'].': '.$event['title'].': '.date('Y-m-d H:i:s',$event['start']).' - '.date('Y-m-d H:i:s',$event['end'])); //header('X-EGROUPWARE-EVENT-'.$event['id'].': '.$event['title'].': '.date('Y-m-d H:i:s',$event['start']).' - '.date('Y-m-d H:i:s',$event['end']));
$props = array( $props = array(
HTTP_WebDAV_Server::mkprop('getetag',$this->get_etag($event)), HTTP_WebDAV_Server::mkprop('getetag',$this->get_etag($event)),
@ -131,8 +158,7 @@ class calendar_groupdav extends groupdav_handler
//error_log(__FILE__ . __METHOD__ . "Calendar Data : $calendar_data"); //error_log(__FILE__ . __METHOD__ . "Calendar Data : $calendar_data");
if ($calendar_data) if ($calendar_data)
{ {
if (is_null($handler)) $handler = $this->_get_handler(); $content = $this->iCal($event);
$content = $handler->exportVCal(array($event),'2.0','PUBLISH');
$props[] = HTTP_WebDAV_Server::mkprop('getcontentlength',bytes($content)); $props[] = HTTP_WebDAV_Server::mkprop('getcontentlength',bytes($content));
$props[] = HTTP_WebDAV_Server::mkprop(groupdav::CALDAV,'calendar-data',$content); $props[] = HTTP_WebDAV_Server::mkprop(groupdav::CALDAV,'calendar-data',$content);
} }
@ -172,29 +198,29 @@ class calendar_groupdav extends groupdav_handler
switch($filter['name']) switch($filter['name'])
{ {
case 'comp-filter': case 'comp-filter':
if ($this->debug > 1) error_log(__METHOD__."($path,...) comp-filter='{$filter['attrs']['name']}'"); if ($this->debug > 1) error_log(__METHOD__."($options[path],...) comp-filter='{$filter['attrs']['name']}'");
switch($filter['attrs']['name']) switch($filter['attrs']['name'])
{ {
case 'VTODO': case 'VTODO':
return false; // return nothing for now, todo: check if we can pass it on to the infolog handler return false; // return nothing for now, todo: check if we can pass it on to the infolog handler
// todos are handled by the infolog handler // todos are handled by the infolog handler
$infolog_handler = new groupdav_infolog(); //$infolog_handler = new groupdav_infolog();
return $infolog_handler->propfind($path,$options,$files,$user,$method); //return $infolog_handler->propfind($path,$options,$files,$user,$method);
case 'VCALENDAR': case 'VCALENDAR':
case 'VEVENT': case 'VEVENT':
break; // that's our default anyway break; // that's our default anyway
} }
break; break;
case 'prop-filter': case 'prop-filter':
if ($this->debug > 1) error_log(__METHOD__."($path,...) prop-filter='{$filter['attrs']['name']}'"); if ($this->debug > 1) error_log(__METHOD__."($options[path],...) prop-filter='{$filter['attrs']['name']}'");
$prop_filter = $filter['attrs']['name']; $prop_filter = $filter['attrs']['name'];
break; break;
case 'text-match': case 'text-match':
if ($this->debug > 1) error_log(__METHOD__."($path,...) text-match: $prop_filter='{$filter['data']}'"); if ($this->debug > 1) error_log(__METHOD__."($options[path],...) text-match: $prop_filter='{$filter['data']}'");
if (!isset($this->filter_prop2cal[strtoupper($prop_filter)])) if (!isset($this->filter_prop2cal[strtoupper($prop_filter)]))
{ {
if ($this->debug) error_log(__METHOD__."($path,".array2string($options).",,$user) unknown property '$prop_filter' --> ignored"); if ($this->debug) error_log(__METHOD__."($options[path],".array2string($options).",...) unknown property '$prop_filter' --> ignored");
} }
else else
{ {
@ -203,15 +229,15 @@ class calendar_groupdav extends groupdav_handler
unset($prop_filter); unset($prop_filter);
break; break;
case 'param-filter': case 'param-filter':
if ($this->debug) error_log(__METHOD__."($path,...) param-filter='{$filter['attrs']['name']}' not (yet) implemented!"); if ($this->debug) error_log(__METHOD__."($options[path],...) param-filter='{$filter['attrs']['name']}' not (yet) implemented!");
break; break;
case 'time-range': case 'time-range':
if ($this->debug > 1) error_log(__FILE__ . __METHOD__."($path,...) time-range={$filter['attrs']['start']}-{$filter['attrs']['end']}"); if ($this->debug > 1) error_log(__FILE__ . __METHOD__."($options[path],...) time-range={$filter['attrs']['start']}-{$filter['attrs']['end']}");
$cal_filters['start'] = $filter['attrs']['start']; $cal_filters['start'] = $filter['attrs']['start'];
$cal_filters['end'] = $filter['attrs']['end']; $cal_filters['end'] = $filter['attrs']['end'];
break; break;
default: default:
if ($this->debug) error_log(__METHOD__."($path,".array2string($options).",,$user) unknown filter --> ignored"); if ($this->debug) error_log(__METHOD__."($options[path],".array2string($options).",...) unknown filter --> ignored");
break; break;
} }
} }
@ -261,7 +287,7 @@ class calendar_groupdav extends groupdav_handler
$cal_filters['query'][] = 'egw_cal.cal_id IN ('.implode(',',array_map(create_function('$n','return (int)$n;'),$ids)).')'; $cal_filters['query'][] = 'egw_cal.cal_id IN ('.implode(',',array_map(create_function('$n','return (int)$n;'),$ids)).')';
} }
if ($this->debug > 1) error_log(__FILE__ . __METHOD__ ."($path,,,$user,$id) calendar-multiget: ids=".implode(',',$ids)); if ($this->debug > 1) error_log(__FILE__ . __METHOD__ ."($options[path],...,$id) calendar-multiget: ids=".implode(',',$ids));
} }
return true; return true;
} }
@ -279,13 +305,96 @@ class calendar_groupdav extends groupdav_handler
{ {
return $event; return $event;
} }
$handler = $this->_get_handler(); $options['data'] = $this->iCal($event);
$options['data'] = $handler->exportVCal(array($event),'2.0','PUBLISH');
$options['mimetype'] = 'text/calendar; charset=utf-8'; $options['mimetype'] = 'text/calendar; charset=utf-8';
header('Content-Encoding: identity'); header('Content-Encoding: identity');
header('ETag: '.$this->get_etag($event)); header('ETag: '.$this->get_etag($event));
return true; return true;
} }
/**
* Generate an iCal for the given event
*
* Taking into account virtual an real exceptions for recuring events
*
* @param array $event
* @return string
*/
private function iCal(array $event)
{
static $handler = null;
if (is_null($handler)) $handler = $this->_get_handler();
$events = array($event);
// for recuring events we have to add the exceptions
if ($this->client_shared_uid_exceptions && $event['recur_type'] && !empty($event['uid']))
{
$events =& self::get_series($event['uid'],$this->bo);
}
elseif(!$this->client_shared_uid_exceptions && $event['reference'])
{
$events[0]['uid'] .= '-'.$event['id']; // force a different uid
}
return $handler->exportVCal($events,'2.0','PUBLISH');
}
/**
* Get array with events of a series identified by its UID (master and all exceptions)
*
* Maybe that should be part of calendar_bo
*
* @param string $uid UID
* @param calendar_bo $bo=null calendar_bo object to reuse for search call
* @return array
*/
private static function &get_series($uid,calendar_bo $bo=null)
{
if (is_null($bo)) $bo = new calendar_bo();
$events =& $bo->search(array(
'query' => array('cal_uid' => $uid),
'daywise' => false,
'date_format' => 'server',
));
$master = null;
foreach($events as $k => &$recurrence)
{
if (!isset($master)) // first event is allways the series master
{
$master =& $events[$k];
//error_log('master: '.array2string($master));
continue; // nothing to change
}
if ($recurrence['id'] != $master['id']) // real exception
{
//error_log('real exception: '.array2string($recurrence));
// remove from masters recur_exception, as exception is include
// at least Lightning "understands" EXDATE as exception from what's included
// in the whole resource / VCALENDAR component
// not removing it causes Lightning to remove the exception itself
if (($k = array_search($recurrence['recurrence'],$master['recur_exception'])) !== false)
{
unset($master['recur_exception'][$k]);
}
continue; // nothing to change
}
// now we need to check if this recurrence is an exception
if ($master['participants'] == $recurrence['participants'])
{
//error_log('NO exception: '.array2string($recurrence));
unset($events[$k]); // no exception --> remove it
continue;
}
// this is a virtual excetion now (no extra event/cal_id in DB)
//error_log('virtual exception: '.array2string($recurrence));
$recurrence['recurrence'] = $recurrence['start'];
$recurrence['reference'] = $master['id'];
$recurrence['recur_type'] = MCAL_RECUR_NONE; // is set, as this is a copy of the master
// not for included exceptions (Lightning): $master['recur_exception'][] = $recurrence['start'];
}
return $events;
}
/** /**
* Handle put request for an event * Handle put request for an event
@ -303,8 +412,7 @@ class calendar_groupdav extends groupdav_handler
if (!is_null($event) && !is_array($event)) if (!is_null($event) && !is_array($event))
{ {
if($this->debug) error_log(__METHOD__.print_r($event,true).function_backtrace());
if($this->debug) error_log(__METHOD__.print_r($event,true).function_backtrace());
return $event; return $event;
} }
$handler = $this->_get_handler(); $handler = $this->_get_handler();
@ -324,12 +432,78 @@ class calendar_groupdav extends groupdav_handler
} }
return true; return true;
} }
/**
* Fix event series with exceptions, called by calendar_ical::importVCal():
* a) only series master = first event got cal_id from URL
* b) exceptions need to be checked if they are already in DB or new
* c) recurrence-id of (real not virtual) exceptions need to be re-added to master
*
* @param array &$events
*/
static function fix_series(array &$events)
{
foreach($events as $n => $event) error_log(__METHOD__." $n before: ".array2string($event));
$master =& $events[0];
$bo = new calendar_boupdate();
// get array with orginal recurrences indexed by recurrence-id
$org_recurrences = array();
foreach(self::get_series($master['uid'],$bo) as $event)
{
if ($event['recurrence'])
{
$org_recurrences[$event['recurrence']] = $event;
}
}
// assign cal_id's to already existing recurrences and evtl. re-add recur_exception to master
foreach($events as &$recurrence)
{
if ($recurrence['id'] || !$recurrence['recurrence']) continue; // master
// from now on we deal with exceptions
$org_recurrence = $org_recurrences[$recurrence['recurrence']];
if (isset($org_recurrence)) // already existing recurrence
{
error_log(__METHOD__.'() setting id #'.$org_recurrence['id']).' for '.$recurrence['recurrence'].' = '.date('Y-m-d H:i:s',$recurrence['recurrence']);
$recurrence['id'] = $org_recurrence['id'];
// re-add (non-virtual) exceptions to master's recur_exception
if ($recurrence['id'] != $master['id'])
{
error_log(__METHOD__.'() re-adding recur_exception '.$recurrence['recurrence'].' = '.date('Y-m-d H:i:s',$recurrence['recurrence']));
$master['recur_exception'][] = $recurrence['recurrence'];
}
// remove recurrence to be able to detect deleted exceptions
unset($org_recurrences[$recurrence['recurrence']]);
}
}
// delete not longer existing recurrences
foreach($org_recurrences as $org_recurrence)
{
if ($org_recurrence['id'] != $master['id']) // non-virtual recurrence
{
error_log(__METHOD__.'() deleting #'.$org_recurrence['id']);
$bo->delete($org_recurrence['id']); // might fail because of permissions
}
else // virtual recurrence
{
error_log(__METHOD__.'() ToDO: delete virtual exception '.$org_recurrence['recurrence'].' = '.date('Y-m-d H:i:s',$org_recurrence['recurrence']));
// todo: reset status and participants to master default
}
}
foreach($events as $n => $event) error_log(__METHOD__." $n after: ".array2string($event));
}
/** /**
* Handle delete request for an event * Handle delete request for an event
* *
* If current user has no right to delete the event, but is an attendee, we reject the event for him. * If current user has no right to delete the event, but is an attendee, we reject the event for him.
* *
* @todo remove (non-virtual) exceptions, if series master gets deleted
* @param array &$options * @param array &$options
* @param int $id * @param int $id
* @return mixed boolean true on success, false on failure or string with http status (eg. '404 Not Found') * @return mixed boolean true on success, false on failure or string with http status (eg. '404 Not Found')
@ -372,20 +546,41 @@ class calendar_groupdav extends groupdav_handler
*/ */
function get_etag($entry) function get_etag($entry)
{ {
$e_in = $entry;
if (!is_array($entry)) if (!is_array($entry))
{ {
$entry = $this->read($entry); $entry = $this->read($entry);
} }
if (!$entry['id'] || !isset($entry['etag']) || !isset($entry['participants'])) {
if ($this->debug > 1) error_log(__FILE__ . __METHOD__."($e_in): id=$entry[id], etag=$entry[etag], isset(participants)=".(int)isset($entry['participants']).", title=$entry[title]: id, etag or participants not set!!!");
}
$etag = $entry['id'].':'.$entry['etag']; $etag = $entry['id'].':'.$entry['etag'];
// add a hash over the participants and their stati
ksort($entry['participants']); // create a defined order // use new MAX(modification date) of egw_cal_user table (deals with virtual exceptions too)
$etag .= ':'.md5(serialize($entry['participants'])); if (isset($entry['max_user_modified']))
//error_log(__FILE__ .__METHOD__ . "($entry[id] ($entry[etag]): $entry[title] --> etag=$etag"); {
return $etag; $etag .= ':'.$entry['max_user_modified'];
}
else
{
$etag .= ':'.$this->bo->so->max_user_modified($entry['id']);
}
// include exception etags into our own etag, if exceptions are included
if ($this->client_shared_uid_exceptions && !empty($entry['uid']) &&
$entry['recur_type'] != MCAL_RECUR_NONE && $entry['recur_exception'])
{
$events =& $this->bo->search(array(
'query' => array('cal_uid' => $entry['uid']),
'daywise' => false,
'enum_recuring' => false,
'date_format' => 'server',
));
foreach($events as $k => &$recurrence)
{
if ($recurrence['reference']) // ignore series master
{
$etag .= ':'.substr($this->get_etag($recurrence),1,-1);
}
}
}
//error_log(__METHOD__ . "($entry[id] ($entry[etag]): $entry[title] --> etag=$etag");
return '"'.$etag.'"';
} }
/** /**

View File

@ -747,6 +747,16 @@ class calendar_ical extends calendar_boupdate
if (!is_array($this->supportedFields)) $this->setSupportedFields(); if (!is_array($this->supportedFields)) $this->setSupportedFields();
// check if we are importing an event series with exceptions in CalDAV
// only first event / series master get's cal_id from URL
// other events are exceptions and need to be checked if they are new
// and for real (not status only) exceptions their recurrence-id need
// to be included as recur_exception to the master
if ($cal_id > 0 && count($events) > 1 && !$events[1]['id'] &&
$events[0]['recur_type'] != MCAL_RECUR_NONE)
{
calendar_groupdav::fix_series($events);
}
foreach ($events as $event) foreach ($events as $event)
{ {
$updated_id = false; $updated_id = false;
@ -1408,7 +1418,7 @@ class calendar_ical extends calendar_boupdate
{ {
if (is_a($component, 'Horde_iCalendar_vevent')) if (is_a($component, 'Horde_iCalendar_vevent'))
{ {
if ($event = $this->vevent2egw($component, $version, $this->supportedFields, $cal_id)) if (($event = $this->vevent2egw($component, $version, $this->supportedFields, $cal_id)))
{ {
//common adjustments //common adjustments
if ($this->productManufacturer == '' && $this->productName == '' if ($this->productManufacturer == '' && $this->productName == ''
@ -1444,23 +1454,12 @@ class calendar_ical extends calendar_boupdate
date_default_timezone_set($GLOBALS['egw_info']['server']['server_timezone']); date_default_timezone_set($GLOBALS['egw_info']['server']['server_timezone']);
} }
// decide what to return // if cal_id, etag or recur_date is given, use/set it for 1. event
if (count($events) == 1) if ($cal_id > 0) $events[0]['id'] = $cal_id;
{ if (!is_null($etag)) $events[0]['etag'] = $etag;
$event = array_shift($events); if ($recur_date) $events[0]['recurrence'] = $recur_date;
if ($cal_id > 0) $event['id'] = $cal_id;
if (!is_null($etag)) $event['etag'] = $etag;
if ($recur_date) $event['recurrence'] = $recur_date;
return array($event); return $events;
}
elseif (count($events) == 0 || $cal_id > 0 || !is_null($etag) || $recur_date)
{
// no events to return
// or not allowed N:1 relation with params just meant for a single event
return false;
}
else return $events;
} }
/** /**

View File

@ -238,6 +238,26 @@ class calendar_so
//echo "<p>socal::read(".print_r($ids,true).")=<pre>".print_r($events,true)."</pre>\n"; //echo "<p>socal::read(".print_r($ids,true).")=<pre>".print_r($events,true)."</pre>\n";
return $events; return $events;
} }
/**
* Get maximum modification time of participant data of given event(s)
*
* This includes ALL recurences of an event series
*
* @param int|array $ids one or multiple cal_id's
* @return int|array (array of) modification timestamp(s)
*/
function max_user_modified($ids)
{
foreach($this->db->select($this->user_table,'cal_id,MAX(cal_user_modified) AS user_etag',array(
'cal_id' => $ids,
),__LINE__,__FILE__,false,'GROUP BY cal_id','calendar') as $row)
{
$etags[$row['cal_id']] = $this->db->from_timestamp($row['user_etag']);
}
//echo "<p>".__METHOD__.'('.array2string($ids).') = '.array2string($etags)."</p>\n";
return is_array($ids) ? $etags : $etags[$ids];
}
/** /**
* generate SQL to filter after a given category (evtl. incl. subcategories) * generate SQL to filter after a given category (evtl. incl. subcategories)
@ -300,10 +320,6 @@ class calendar_so
$cols = !is_null($_cols) ? $_cols : "$this->repeats_table.*,$this->cal_table.*,cal_start,cal_end,cal_recur_date"; $cols = !is_null($_cols) ? $_cols : "$this->repeats_table.*,$this->cal_table.*,cal_start,cal_end,cal_recur_date";
$where = array(); $where = array();
if (!empty($sql_filter) && is_string($sql_filter))
{
$where[] = $sql_filter;
}
if (is_array($query)) if (is_array($query))
{ {
$where = $query; $where = $query;
@ -316,6 +332,10 @@ class calendar_so
} }
$where[] = '('.implode(' OR ',$to_or).')'; $where[] = '('.implode(' OR ',$to_or).')';
} }
if (!empty($sql_filter) && is_string($sql_filter))
{
$where[] = $sql_filter;
}
if ($users) if ($users)
{ {
$users_by_type = array(); $users_by_type = array();
@ -371,7 +391,7 @@ class calendar_so
if ($start) $where[] = (int)$start.' < cal_end'; if ($start) $where[] = (int)$start.' < cal_end';
if ($end) $where[] = 'cal_start < '.(int)$end; if ($end) $where[] = 'cal_start < '.(int)$end;
if (!preg_match('/^[a-z_ ,]+$/i',$order)) $order = 'cal_start'; // gard against SQL injunktion if (!preg_match('/^[a-z_ ,]+$/i',$order)) $order = 'cal_start'; // gard against SQL injection
if ($this->db->capabilities['distinct_on_text'] && $this->db->capabilities['union']) if ($this->db->capabilities['distinct_on_text'] && $this->db->capabilities['union'])
{ {