Page MenuHomePhorge

No OneTemporary

This file is larger than 256 KB, so syntax highlighting was skipped.
diff --git a/plugins/calendar/composer.json b/plugins/calendar/composer.json
index c1bfe40e..019d17e1 100644
--- a/plugins/calendar/composer.json
+++ b/plugins/calendar/composer.json
@@ -1,38 +1,38 @@
{
"name": "kolab/calendar",
"type": "roundcube-plugin",
"description": "Calendar plugin",
"homepage": "https://git.kolab.org/diffusion/RPK/",
"license": "AGPLv3",
"version": "3.5.11",
"authors": [
{
"name": "Thomas Bruederli",
"email": "bruederli@kolabsys.com",
"role": "Lead"
},
{
"name": "Aleksander Machniak",
"email": "machniak@kolabsys.com",
"role": "Developer"
}
],
"repositories": [
{
"type": "composer",
"url": "https://plugins.roundcube.net"
}
],
"require": {
- "php": ">=7.4.0",
+ "php": ">=7.2.0",
"roundcube/plugin-installer": ">=0.1.3",
"kolab/libcalendaring": ">=3.4.0",
"kolab/libkolab": ">=3.4.0"
},
"extra": {
"roundcube": {
"min-version": "1.4.0",
"sql-dir": "drivers/database/SQL"
}
}
}
diff --git a/plugins/calendar/drivers/caldav/caldav_calendar.php b/plugins/calendar/drivers/caldav/caldav_calendar.php
index 40648922..742e9dac 100644
--- a/plugins/calendar/drivers/caldav/caldav_calendar.php
+++ b/plugins/calendar/drivers/caldav/caldav_calendar.php
@@ -1,899 +1,899 @@
<?php
/**
* CalDAV calendar storage class
*
* @author Aleksander Machniak <machniak@apheleia-it.ch>
*
* Copyright (C) 2012-2022, Apheleia IT AG <contact@apheleia-it.ch>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class caldav_calendar extends kolab_storage_dav_folder
{
public $ready = false;
public $rights = 'lrs';
public $editable = false;
public $attachments = false; // TODO
public $alarms = false;
public $history = false;
public $subscriptions = false;
public $categories = [];
public $storage;
public $type = 'event';
protected $cal;
protected $events = [];
protected $search_fields = ['title', 'description', 'location', 'attendees', 'categories'];
/**
* Factory method to instantiate a caldav_calendar object
*
* @param string $id Calendar ID (encoded IMAP folder name)
* @param object $calendar Calendar plugin object
*
* @return caldav_calendar Self instance
*/
public static function factory($id, $calendar)
{
return new caldav_calendar($id, $calendar);
}
/**
* Default constructor
*/
public function __construct($folder_or_id, $calendar)
{
if ($folder_or_id instanceof kolab_storage_dav_folder) {
$this->storage = $folder_or_id;
}
else {
// $this->storage = kolab_storage_dav::get_folder($folder_or_id, 'event');
}
$this->cal = $calendar;
$this->id = $this->storage->id;
$this->attributes = $this->storage->attributes;
$this->ready = true;
$this->alarms = !isset($this->storage->attributes['alarms']) || $this->storage->attributes['alarms'];
// Set writeable and alarms flags according to folder permissions
if ($this->ready) {
if ($this->storage->get_namespace() == 'personal') {
$this->editable = true;
$this->rights = 'lrswikxteav';
}
else {
$rights = $this->storage->get_myrights();
if ($rights) {
$this->rights = $rights;
if (strpos($rights, 't') !== false || strpos($rights, 'd') !== false) {
$this->editable = strpos($rights, 'i');;
}
}
}
}
$this->default = $this->storage->default;
$this->subtype = $this->storage->subtype;
}
/**
* Getter for the folder name
*
* @return string Name of the folder
*/
public function get_realname()
{
return $this->get_name();
}
/**
* Return color to display this calendar
*/
public function get_color($default = null)
{
if ($color = $this->storage->get_color()) {
return $color;
}
return $default ?: 'cc0000';
}
/**
* Compose an URL for CalDAV access to this calendar (if configured)
*/
public function get_caldav_url()
{
/*
if ($template = $this->cal->rc->config->get('calendar_caldav_url', null)) {
return strtr($template, [
'%h' => $_SERVER['HTTP_HOST'],
'%u' => urlencode($this->cal->rc->get_user_name()),
'%i' => urlencode($this->storage->get_uid()),
'%n' => urlencode($this->name),
]);
}
*/
return false;
}
/**
* Update properties of this calendar folder
*
* @see caldav_driver::edit_calendar()
*/
public function update(&$prop)
{
return false; // NOP
}
/**
* Getter for a single event object
*/
public function get_event($id)
{
// remove our occurrence identifier if it's there
$master_id = preg_replace('/-\d{8}(T\d{6})?$/', '', $id);
// directly access storage object
if (empty($this->events[$id]) && $master_id == $id && ($record = $this->storage->get_object($id))) {
$this->events[$id] = $record = $this->_to_driver_event($record, true);
}
// maybe a recurring instance is requested
if (empty($this->events[$id]) && $master_id != $id) {
$instance_id = substr($id, strlen($master_id) + 1);
if ($record = $this->storage->get_object($master_id)) {
$master = $record = $this->_to_driver_event($record);
}
if (!empty($master)) {
// check for match in top-level exceptions (aka loose single occurrences)
if (!empty($master['_formatobj']) && ($instance = $master['_formatobj']->get_instance($instance_id))) {
$this->events[$id] = $this->_to_driver_event($instance, false, true, $master);
}
// check for match on the first instance already
else if (!empty($master['_instance']) && $master['_instance'] == $instance_id) {
$this->events[$id] = $master;
}
else if (!empty($master['recurrence'])) {
$start_date = $master['start'];
// For performance reasons we'll get only the specific instance
if (($date = substr($id, strlen($master_id) + 1, 8)) && strlen($date) == 8 && is_numeric($date)) {
$start_date = new DateTime($date . 'T000000', $master['start']->getTimezone());
}
$this->get_recurring_events($record, $start_date, null, $id, 1);
}
}
}
return $this->events[$id];
}
/**
* Get attachment body
* @see calendar_driver::get_attachment_body()
*/
public function get_attachment_body($id, $event)
{
if (!$this->ready) {
return false;
}
$data = $this->storage->get_attachment($event['id'], $id);
if ($data == null) {
// try again with master UID
$uid = preg_replace('/-\d+(T\d{6})?$/', '', $event['id']);
if ($uid != $event['id']) {
$data = $this->storage->get_attachment($uid, $id);
}
}
return $data;
}
/**
* @param int Event's new start (unix timestamp)
* @param int Event's new end (unix timestamp)
* @param string Search query (optional)
* @param bool Include virtual events (optional)
* @param array Additional parameters to query storage
* @param array Additional query to filter events
*
* @return array A list of event records
*/
public function list_events($start, $end, $search = null, $virtual = 1, $query = [], $filter_query = null)
{
// convert to DateTime for comparisons
// #5190: make the range a little bit wider
// to workaround possible timezone differences
try {
$start = new DateTime('@' . ($start - 12 * 3600));
}
catch (Exception $e) {
$start = new DateTime('@0');
}
try {
$end = new DateTime('@' . ($end + 12 * 3600));
}
catch (Exception $e) {
$end = new DateTime('today +10 years');
}
// get email addresses of the current user
$user_emails = $this->cal->get_user_emails();
// query Kolab storage
$query[] = ['dtstart', '<=', $end];
$query[] = ['dtend', '>=', $start];
if (is_array($filter_query)) {
$query = array_merge($query, $filter_query);
}
$words = [];
$partstat_exclude = [];
$events = [];
if (!empty($search)) {
$search = mb_strtolower($search);
$words = rcube_utils::tokenize_string($search, 1);
foreach (rcube_utils::normalize_string($search, true) as $word) {
$query[] = ['words', 'LIKE', $word];
}
}
// set partstat filter to skip pending and declined invitations
if (empty($filter_query)
&& $this->cal->rc->config->get('kolab_invitation_calendars')
&& $this->get_namespace() != 'other'
) {
$partstat_exclude = ['NEEDS-ACTION', 'DECLINED'];
}
foreach ($this->storage->select($query) as $record) {
$event = $this->_to_driver_event($record, !$virtual, false);
// remember seen categories
if (!empty($event['categories'])) {
$cat = is_array($event['categories']) ? $event['categories'][0] : $event['categories'];
$this->categories[$cat]++;
}
// list events in requested time window
if ($event['start'] <= $end && $event['end'] >= $start) {
unset($event['_attendees']);
$add = true;
// skip the first instance of a recurring event if listed in exdate
if ($virtual && !empty($event['recurrence']['EXDATE'])) {
$event_date = $event['start']->format('Ymd');
$event_tz = $event['start']->getTimezone();
foreach ((array) $event['recurrence']['EXDATE'] as $exdate) {
$ex = clone $exdate;
$ex->setTimezone($event_tz);
if ($ex->format('Ymd') == $event_date) {
$add = false;
break;
}
}
}
// find and merge exception for the first instance
if ($virtual && !empty($event['recurrence']) && !empty($event['recurrence']['EXCEPTIONS'])) {
foreach ($event['recurrence']['EXCEPTIONS'] as $exception) {
if ($event['_instance'] == $exception['_instance']) {
unset($exception['calendar'], $exception['className'], $exception['_folder_id']);
// clone date objects from main event before adjusting them with exception data
if (is_object($event['start'])) {
$event['start'] = clone $record['start'];
}
if (is_object($event['end'])) {
$event['end'] = clone $record['end'];
}
kolab_driver::merge_exception_data($event, $exception);
}
}
}
if ($add) {
$events[] = $event;
}
}
// resolve recurring events
if (!empty($event['recurrence']) && $virtual == 1) {
$events = array_merge($events, $this->get_recurring_events($event, $start, $end));
}
// add top-level exceptions (aka loose single occurrences)
else if (!empty($record['exceptions'])) {
foreach ($record['exceptions'] as $ex) {
$component = $this->_to_driver_event($ex, false, false, $record);
if ($component['start'] <= $end && $component['end'] >= $start) {
$events[] = $component;
}
}
}
}
// post-filter all events by fulltext search and partstat values
$me = $this;
$events = array_filter($events, function($event) use ($words, $partstat_exclude, $user_emails, $me) {
// fulltext search
if (count($words)) {
$hits = 0;
foreach ($words as $word) {
$hits += $me->fulltext_match($event, $word, false);
}
if ($hits < count($words)) {
return false;
}
}
// partstat filter
if (count($partstat_exclude) && !empty($event['attendees'])) {
foreach ($event['attendees'] as $attendee) {
if (
in_array($attendee['email'], $user_emails)
&& in_array($attendee['status'], $partstat_exclude)
) {
return false;
}
}
}
return true;
});
// Apply event-to-mail relations
// $config = kolab_storage_config::get_instance();
// $config->apply_links($events);
// Avoid session race conditions that will loose temporary subscriptions
// $this->cal->rc->session->nowrite = true;
return $events;
}
/**
* Get number of events in the given calendar
*
* @param int Date range start (unix timestamp)
* @param int Date range end (unix timestamp)
* @param array Additional query to filter events
*
* @return int Number of events
*/
public function count_events($start, $end = null, $filter_query = null)
{
// convert to DateTime for comparisons
try {
$start = new DateTime('@'.$start);
}
catch (Exception $e) {
$start = new DateTime('@0');
}
if ($end) {
try {
$end = new DateTime('@'.$end);
}
catch (Exception $e) {
$end = null;
}
}
// query Kolab storage
$query[] = ['dtend', '>=', $start];
if ($end) {
$query[] = ['dtstart', '<=', $end];
}
// add query to exclude pending/declined invitations
if (empty($filter_query)) {
foreach ($this->cal->get_user_emails() as $email) {
$query[] = ['tags', '!=', 'x-partstat:' . $email . ':needs-action'];
$query[] = ['tags', '!=', 'x-partstat:' . $email . ':declined'];
}
}
else if (is_array($filter_query)) {
$query = array_merge($query, $filter_query);
}
return $this->storage->count($query);
}
/**
* Create a new event record
*
* @see calendar_driver::new_event()
*
* @return array|false The created record ID on success, False on error
*/
public function insert_event($event)
{
if (!is_array($event)) {
return false;
}
// email links are stored separately
// $links = !empty($event['links']) ? $event['links'] : [];
// unset($event['links']);
// generate new event from RC input
$object = $this->_from_driver_event($event);
$saved = $this->storage->save($object, 'event');
if (!$saved) {
rcube::raise_error([
'code' => 600, 'file' => __FILE__, 'line' => __LINE__,
'message' => "Error saving event object to DAV server"
],
true, false
);
return false;
}
// save links in configuration.relation object
// if ($this->save_links($event['uid'], $links)) {
// $object['links'] = $links;
// }
$this->events = [$event['uid'] => $this->_to_driver_event($object, true)];
return true;
}
/**
* Update a specific event record
*
* @return bool True on success, False on error
*/
public function update_event($event, $exception_id = null)
{
$updated = false;
$old = $this->storage->get_object(!empty($event['uid']) ? $event['uid'] : $event['id']);
if (!$old || PEAR::isError($old)) {
return false;
}
// email links are stored separately
// $links = !empty($event['links']) ? $event['links'] : [];
// unset($event['links']);
$object = $this->_from_driver_event($event, $old);
$saved = $this->storage->save($object, 'event', $old['uid']);
if (!$saved) {
rcube::raise_error([
'code' => 600, 'file' => __FILE__, 'line' => __LINE__,
'message' => "Error saving event object to CalDAV server"
],
true, false
);
}
else {
// save links in configuration.relation object
// if ($this->save_links($event['uid'], $links)) {
// $object['links'] = $links;
// }
$updated = true;
$this->events = [$event['uid'] => $this->_to_driver_event($object, true)];
// refresh local cache with recurring instances
if ($exception_id) {
$this->get_recurring_events($object, $event['start'], $event['end'], $exception_id);
}
}
return $updated;
}
/**
* Delete an event record
*
* @see calendar_driver::remove_event()
*
* @return bool True on success, False on error
*/
public function delete_event($event, $force = true)
{
$uid = !empty($event['uid']) ? $event['uid'] : $event['id'];
$deleted = $this->storage->delete($uid, $force);
if (!$deleted) {
rcube::raise_error([
'code' => 600, 'file' => __FILE__, 'line' => __LINE__,
'message' => "Error deleting event '{$uid}' from CalDAV server"
],
true, false
);
}
return $deleted;
}
/**
* Restore deleted event record
*
* @see calendar_driver::undelete_event()
*
* @return bool True on success, False on error
*/
public function restore_event($event)
{
// TODO
return false;
}
/**
* Find messages linked with an event
*/
protected function get_links($uid)
{
return []; // TODO
$storage = kolab_storage_config::get_instance();
return $storage->get_object_links($uid);
}
/**
* Save message references (links) to an event
*/
protected function save_links($uid, $links)
{
return false; // TODO
$storage = kolab_storage_config::get_instance();
return $storage->save_object_links($uid, (array) $links);
}
/**
* Create instances of a recurring event
*
* @param array $event Hash array with event properties
* @param DateTime $start Start date of the recurrence window
* @param DateTime $end End date of the recurrence window
* @param string $event_id ID of a specific recurring event instance
* @param int $limit Max. number of instances to return
*
* @return array List of recurring event instances
*/
public function get_recurring_events($event, $start, $end = null, $event_id = null, $limit = null)
{
$object = $event['_formatobj'];
if (!is_object($object)) {
return [];
}
// determine a reasonable end date if none given
if (!$end) {
$end = clone $event['start'];
$end->add(new DateInterval('P100Y'));
}
// read recurrence exceptions first
$events = [];
$exdata = [];
$futuredata = [];
$recurrence_id_format = libcalendaring::recurrence_id_format($event);
if (!empty($event['recurrence'])) {
// copy the recurrence rule from the master event (to be used in the UI)
$recurrence_rule = $event['recurrence'];
unset($recurrence_rule['EXCEPTIONS'], $recurrence_rule['EXDATE']);
if (!empty($event['recurrence']['EXCEPTIONS'])) {
foreach ($event['recurrence']['EXCEPTIONS'] as $exception) {
if (empty($exception['_instance'])) {
$exception['_instance'] = libcalendaring::recurrence_instance_identifier($exception, !empty($event['allday']));
}
$rec_event = $this->_to_driver_event($exception, false, false, $event);
$rec_event['id'] = $event['uid'] . '-' . $exception['_instance'];
$rec_event['isexception'] = 1;
// found the specifically requested instance: register exception (single occurrence wins)
if (
$rec_event['id'] == $event_id
&& (empty($this->events[$event_id]) || !empty($this->events[$event_id]['thisandfuture']))
) {
$rec_event['recurrence'] = $recurrence_rule;
$rec_event['recurrence_id'] = $event['uid'];
$this->events[$rec_event['id']] = $rec_event;
}
// remember this exception's date
$exdate = substr($exception['_instance'], 0, 8);
if (empty($exdata[$exdate]) || !empty($exdata[$exdate]['thisandfuture'])) {
$exdata[$exdate] = $rec_event;
}
if (!empty($rec_event['thisandfuture'])) {
$futuredata[$exdate] = $rec_event;
}
}
}
}
// found the specifically requested instance, exiting...
if ($event_id && !empty($this->events[$event_id])) {
return [$this->events[$event_id]];
}
// Check first occurrence, it might have been moved
if ($first = $exdata[$event['start']->format('Ymd')]) {
// return it only if not already in the result, but in the requested period
if (!($event['start'] <= $end && $event['end'] >= $start)
&& ($first['start'] <= $end && $first['end'] >= $start)
) {
$events[] = $first;
}
}
if ($limit && count($events) >= $limit) {
return $events;
}
// use libkolab to compute recurring events
$recurrence = new kolab_date_recurrence($object);
$i = 0;
while ($next_event = $recurrence->next_instance()) {
$datestr = $next_event['start']->format('Ymd');
$instance_id = $next_event['start']->format($recurrence_id_format);
// use this event data for future recurring instances
if (!empty($futuredata[$datestr])) {
$overlay_data = $futuredata[$datestr];
}
$rec_id = $event['uid'] . '-' . $instance_id;
$exception = !empty($exdata[$datestr]) ? $exdata[$datestr] : $overlay_data;
$event_start = $next_event['start'];
$event_end = $next_event['end'];
// copy some event from exception to get proper start/end dates
if ($exception) {
$event_copy = $next_event;
caldav_driver::merge_exception_dates($event_copy, $exception);
$event_start = $event_copy['start'];
$event_end = $event_copy['end'];
}
// add to output if in range
if (($event_start <= $end && $event_end >= $start) || ($event_id && $rec_id == $event_id)) {
$rec_event = $this->_to_driver_event($next_event, false, false, $event);
$rec_event['_instance'] = $instance_id;
$rec_event['_count'] = $i + 1;
if ($exception) {
// copy data from exception
caldav_driver::merge_exception_data($rec_event, $exception);
}
$rec_event['id'] = $rec_id;
$rec_event['recurrence_id'] = $event['uid'];
$rec_event['recurrence'] = $recurrence_rule;
unset($rec_event['_attendees']);
$events[] = $rec_event;
if ($rec_id == $event_id) {
$this->events[$rec_id] = $rec_event;
break;
}
if ($limit && count($events) >= $limit) {
return $events;
}
}
else if ($next_event['start'] > $end) {
// stop loop if out of range
break;
}
// avoid endless recursion loops
if (++$i > 100000) {
break;
}
}
return $events;
}
/**
* Convert from storage format to internal representation
*/
private function _to_driver_event($record, $noinst = false, $links = true, $master_event = null)
{
$record['calendar'] = $this->id;
// remove (possibly outdated) cached parameters
unset($record['_folder_id'], $record['className']);
// if ($links && !array_key_exists('links', $record)) {
// $record['links'] = $this->get_links($record['uid']);
// }
$ns = $this->get_namespace();
if ($ns == 'other') {
$record['className'] = 'fc-event-ns-other';
}
if ($ns == 'other' || !$this->cal->rc->config->get('kolab_invitation_calendars')) {
$record = caldav_driver::add_partstat_class($record, ['NEEDS-ACTION', 'DECLINED'], $this->get_owner());
// Modify invitation status class name, when invitation calendars are disabled
// we'll use opacity only for declined/needs-action events
$record['className'] = !empty($record['className']) ? str_replace('-invitation', '', $record['className']) : '';
}
// add instance identifier to first occurrence (master event)
$recurrence_id_format = libcalendaring::recurrence_id_format($master_event ? $master_event : $record);
if (!$noinst && !empty($record['recurrence']) && !empty($record['start'])
&& empty($record['recurrence_id']) && empty($record['_instance'])
) {
$record['_instance'] = $record['start']->format($recurrence_id_format);
}
- else if (isset($record['recurrence_date']) && is_a($record['recurrence_date'], 'DateTime')) {
+ else if (isset($record['recurrence_date']) && $record['recurrence_date'] instanceof DateTimeInterface) {
$record['_instance'] = $record['recurrence_date']->format($recurrence_id_format);
}
// clean up exception data
if (!empty($record['recurrence']) && !empty($record['recurrence']['EXCEPTIONS'])) {
array_walk($record['recurrence']['EXCEPTIONS'], function(&$exception) {
unset($exception['_mailbox'], $exception['_msguid'], $exception['_formatobj'], $exception['_attachments']);
});
}
// Load the given event data into a libkolabxml container
// it's needed for recurrence resolving, which uses libcalendaring
// TODO: Drop dependency on libkolabxml?
$event_xml = new kolab_format_event();
$event_xml->set($record);
$record['_formatobj'] = $event_xml;
return $record;
}
/**
* Convert the given event record into a data structure that can be passed to the storage backend for saving
* (opposite of self::_to_driver_event())
*/
private function _from_driver_event($event, $old = [])
{
// set current user as ORGANIZER
if ($identity = $this->cal->rc->user->list_emails(true)) {
$event['attendees'] = !empty($event['attendees']) ? $event['attendees'] : [];
$found = false;
// there can be only resources on attendees list (T1484)
// let's check the existence of an organizer
foreach ($event['attendees'] as $attendee) {
if (!empty($attendee['role']) && $attendee['role'] == 'ORGANIZER') {
$found = true;
break;
}
}
if (!$found) {
$event['attendees'][] = ['role' => 'ORGANIZER', 'name' => $identity['name'], 'email' => $identity['email']];
}
$event['_owner'] = $identity['email'];
}
// remove EXDATE values if RDATE is given
if (!empty($event['recurrence']['RDATE'])) {
$event['recurrence']['EXDATE'] = [];
}
// remove recurrence information (e.g. EXDATES and EXCEPTIONS) entirely
if (!empty($event['recurrence']) && empty($event['recurrence']['FREQ']) && empty($event['recurrence']['RDATE'])) {
$event['recurrence'] = [];
}
// keep 'comment' from initial itip invitation
if (!empty($old['comment'])) {
$event['comment'] = $old['comment'];
}
// remove some internal properties which should not be cached
$cleanup_fn = function(&$event) {
unset($event['_savemode'], $event['_fromcalendar'], $event['_identity'], $event['_folder_id'],
$event['calendar'], $event['className'], $event['recurrence_id'],
$event['attachments'], $event['deleted_attachments']);
};
$cleanup_fn($event);
// clean up exception data
if (!empty($event['exceptions'])) {
array_walk($event['exceptions'], function(&$exception) use ($cleanup_fn) {
unset($exception['_mailbox'], $exception['_msguid'], $exception['_formatobj']);
$cleanup_fn($exception);
});
}
// copy meta data (starting with _) from old object
foreach ((array) $old as $key => $val) {
if (!isset($event[$key]) && $key[0] == '_') {
$event[$key] = $val;
}
}
return $event;
}
/**
* Match the given word in the event contents
*/
public function fulltext_match($event, $word, $recursive = true)
{
$hits = 0;
foreach ($this->search_fields as $col) {
if (empty($event[$col])) {
continue;
}
$sval = is_array($event[$col]) ? self::_complex2string($event[$col]) : $event[$col];
if (empty($sval)) {
continue;
}
// do a simple substring matching (to be improved)
$val = mb_strtolower($sval);
if (strpos($val, $word) !== false) {
$hits++;
break;
}
}
return $hits;
}
/**
* Convert a complex event attribute to a string value
*/
private static function _complex2string($prop)
{
static $ignorekeys = ['role', 'status', 'rsvp'];
$out = '';
if (is_array($prop)) {
foreach ($prop as $key => $val) {
if (is_numeric($key)) {
$out .= self::_complex2string($val);
}
else if (!in_array($key, $ignorekeys)) {
$out .= $val . ' ';
}
}
}
else if (is_string($prop) || is_numeric($prop)) {
$out .= $prop . ' ';
}
return rtrim($out);
}
}
diff --git a/plugins/calendar/drivers/calendar_driver.php b/plugins/calendar/drivers/calendar_driver.php
index c81421e7..082ed210 100644
--- a/plugins/calendar/drivers/calendar_driver.php
+++ b/plugins/calendar/drivers/calendar_driver.php
@@ -1,863 +1,863 @@
<?php
/**
* Driver interface for the Calendar plugin
*
* @version @package_version@
* @author Lazlo Westerhof <hello@lazlo.me>
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 2010, Lazlo Westerhof <hello@lazlo.me>
* Copyright (C) 2012-2015, Kolab Systems AG <contact@kolabsys.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Struct of an internal event object how it is passed from/to the driver classes:
*
* $event = array(
* 'id' => 'Event ID used for editing',
* 'uid' => 'Unique identifier of this event',
* 'calendar' => 'Calendar identifier to add event to or where the event is stored',
* 'start' => DateTime, // Event start date/time as DateTime object
* 'end' => DateTime, // Event end date/time as DateTime object
* 'allday' => true|false, // Boolean flag if this is an all-day event
* 'changed' => DateTime, // Last modification date of event
* 'title' => 'Event title/summary',
* 'location' => 'Location string',
* 'description' => 'Event description',
* 'url' => 'URL to more information',
* 'recurrence' => array( // Recurrence definition according to iCalendar (RFC 2445) specification as list of key-value pairs
* 'FREQ' => 'DAILY|WEEKLY|MONTHLY|YEARLY',
* 'INTERVAL' => 1...n,
* 'UNTIL' => DateTime,
* 'COUNT' => 1..n, // number of times
* // + more properties (see http://www.kanzaki.com/docs/ical/recur.html)
* 'EXDATE' => array(), // list of DateTime objects of exception Dates/Times
* 'EXCEPTIONS' => array(<event>), list of event objects which denote exceptions in the recurrence chain
* ),
* 'recurrence_id' => 'ID of the recurrence group', // usually the ID of the starting event
* '_instance' => 'ID of the recurring instance', // identifies an instance within a recurrence chain
* 'categories' => 'Event category',
* 'free_busy' => 'free|busy|outofoffice|tentative', // Show time as
* 'status' => 'TENTATIVE|CONFIRMED|CANCELLED', // event status according to RFC 2445
* 'priority' => 0-9, // Event priority (0=undefined, 1=highest, 9=lowest)
* 'sensitivity' => 'public|private|confidential', // Event sensitivity
* 'alarms' => '-15M:DISPLAY', // DEPRECATED Reminder settings inspired by valarm definition (e.g. display alert 15 minutes before event)
* 'valarms' => array( // List of reminders (new format), each represented as a hash array:
* array(
* 'trigger' => '-PT90M', // ISO 8601 period string prefixed with '+' or '-', or DateTime object
* 'action' => 'DISPLAY|EMAIL|AUDIO',
* 'duration' => 'PT15M', // ISO 8601 period string
* 'repeat' => 0, // number of repetitions
* 'description' => '', // text to display for DISPLAY actions
* 'summary' => '', // message text for EMAIL actions
* 'attendees' => array(), // list of email addresses to receive alarm messages
* ),
* ),
* 'attachments' => array( // List of attachments
* 'name' => 'File name',
* 'mimetype' => 'Content type',
* 'size' => 1..n, // in bytes
* 'id' => 'Attachment identifier'
* ),
* 'deleted_attachments' => array(), // array of attachment identifiers to delete when event is updated
* 'attendees' => array( // List of event participants
* 'name' => 'Participant name',
* 'email' => 'Participant e-mail address', // used as identifier
* 'role' => 'ORGANIZER|REQ-PARTICIPANT|OPT-PARTICIPANT|CHAIR',
* 'status' => 'NEEDS-ACTION|UNKNOWN|ACCEPTED|TENTATIVE|DECLINED'
* 'rsvp' => true|false,
* ),
*
* '_savemode' => 'all|future|current|new', // How changes on recurring event should be handled
* '_notify' => true|false, // whether to notify event attendees about changes
* '_fromcalendar' => 'Calendar identifier where the event was stored before',
* );
*/
/**
* Interface definition for calendar driver classes
*/
abstract class calendar_driver
{
const FILTER_ALL = 0;
const FILTER_WRITEABLE = 1;
const FILTER_INSERTABLE = 2;
const FILTER_ACTIVE = 4;
const FILTER_PERSONAL = 8;
const FILTER_PRIVATE = 16;
const FILTER_CONFIDENTIAL = 32;
const FILTER_SHARED = 64;
const BIRTHDAY_CALENDAR_ID = '__bdays__';
// features supported by backend
public $alarms = false;
public $attendees = false;
public $freebusy = false;
public $attachments = false;
public $undelete = false;
public $history = false;
public $alarm_types = ['DISPLAY'];
public $alarm_absolute = true;
public $categoriesimmutable = false;
public $last_error;
protected $default_categories = [
'Personal' => 'c0c0c0',
'Work' => 'ff0000',
'Family' => '00ff00',
'Holiday' => 'ff6600',
];
/**
* Get a list of available calendars from this source
*
* @param int $filter Bitmask defining filter criterias.
* See FILTER_* constants for possible values.
*
* @return array List of calendars
*/
abstract function list_calendars($filter = 0);
/**
* Create a new calendar assigned to the current user
*
* @param array $prop Hash array with calendar properties
* name: Calendar name
* color: The color of the calendar
* showalarms: True if alarms are enabled
*
* @return mixed ID of the calendar on success, False on error
*/
abstract function create_calendar($prop);
/**
* Update properties of an existing calendar
*
* @param array $prop Hash array with calendar properties
* id: Calendar Identifier
* name: Calendar name
* color: The color of the calendar
* showalarms: True if alarms are enabled (if supported)
*
* @return bool True on success, Fales on failure
*/
abstract function edit_calendar($prop);
/**
* Set active/subscribed state of a calendar
*
* @param array $prop Hash array with calendar properties
* id: Calendar Identifier
* active: True if calendar is active, false if not
*
* @return bool True on success, Fales on failure
*/
abstract function subscribe_calendar($prop);
/**
* Delete the given calendar with all its contents
*
* @param array $prop Hash array with calendar properties
* id: Calendar Identifier
*
* @return bool True on success, Fales on failure
*/
abstract function delete_calendar($prop);
/**
* Search for shared or otherwise not listed calendars the user has access
*
* @param string $query Search string
* @param string $source Section/source to search
*
* @return array List of calendars
*/
abstract function search_calendars($query, $source);
/**
* Add a single event to the database
*
* @param array $event Hash array with event properties (see header of this file)
*
* @return mixed New event ID on success, False on error
*/
abstract function new_event($event);
/**
* Update an event entry with the given data
*
* @param array $event Hash array with event properties (see header of this file)
*
* @return bool True on success, False on error
*/
abstract function edit_event($event);
/**
* Extended event editing with possible changes to the argument
*
* @param array &$event Hash array with event properties
* @param string $status New participant status
* @param array $attendees List of hash arrays with updated attendees
*
* @return bool True on success, False on error
*/
public function edit_rsvp(&$event, $status, $attendees)
{
return $this->edit_event($event);
}
/**
* Update the participant status for the given attendee
*
* @param array &$event Hash array with event properties
* @param array $attendees List of hash arrays each represeting an updated attendee
*
* @return bool True on success, False on error
*/
public function update_attendees(&$event, $attendees)
{
return $this->edit_event($event);
}
/**
* Move a single event
*
* @param array $event Hash array with event properties:
* id: Event identifier
* start: Event start date/time as DateTime object
* end: Event end date/time as DateTime object
* allday: Boolean flag if this is an all-day event
*
* @return bool True on success, False on error
*/
abstract function move_event($event);
/**
* Resize a single event
*
* @param array $event Hash array with event properties:
* id: Event identifier
* start: Event start date/time as DateTime object with timezone
* end: Event end date/time as DateTime object with timezone
*
* @return bool True on success, False on error
*/
abstract function resize_event($event);
/**
* Remove a single event from the database
*
* @param array $event Hash array with event properties:
* id: Event identifier
* @param bool $force Remove event irreversible (mark as deleted otherwise,
* if supported by the backend)
*
* @return bool True on success, False on error
*/
abstract function remove_event($event, $force = true);
/**
* Restores a single deleted event (if supported)
*
* @param array $event Hash array with event properties:
* id: Event identifier
*
* @return bool True on success, False on error
*/
public function restore_event($event)
{
return false;
}
/**
* Return data of a single event
*
* @param mixed $event UID string or hash array with event properties:
* id: Event identifier
* uid: Event UID
* _instance: Instance identifier in combination with uid (optional)
* calendar: Calendar identifier (optional)
* @param int $scope Bitmask defining the scope to search events in.
* See FILTER_* constants for possible values.
* @param bool $full If true, recurrence exceptions shall be added
*
* @return array Event object as hash array
*/
abstract function get_event($event, $scope = 0, $full = false);
/**
* Get events from source.
*
* @param int $start Date range start (unix timestamp)
* @param int $end Date range end (unix timestamp)
* @param string $query Search query (optional)
* @param mixed $calendars List of calendar IDs to load events from (either as array or comma-separated string)
* @param bool $virtual Include virtual/recurring events (optional)
* @param int $modifiedsince Only list events modified since this time (unix timestamp)
*
* @return array A list of event objects (see header of this file for struct of an event)
*/
abstract function load_events($start, $end, $query = null, $calendars = null, $virtual = 1, $modifiedsince = null);
/**
* Get number of events in the given calendar
*
* @param mixed $calendars List of calendar IDs to count events (either as array or comma-separated string)
* @param int $start Date range start (unix timestamp)
* @param int $end Date range end (unix timestamp)
*
* @return array Hash array with counts grouped by calendar ID
*/
abstract function count_events($calendars, $start, $end = null);
/**
* Get a list of pending alarms to be displayed to the user
*
* @param int $time Current time (unix timestamp)
* @param mixed $calendars List of calendar IDs to show alarms for (either as array or comma-separated string)
*
* @return array A list of alarms, each encoded as hash array:
* id: Event identifier
* uid: Unique identifier of this event
* start: Event start date/time as DateTime object
* end: Event end date/time as DateTime object
* allday: Boolean flag if this is an all-day event
* title: Event title/summary
* location: Location string
*/
abstract function pending_alarms($time, $calendars = null);
/**
* (User) feedback after showing an alarm notification
* This should mark the alarm as 'shown' or snooze it for the given amount of time
*
* @param string $event_id Event identifier
* @param int $snooze Suspend the alarm for this number of seconds
*/
abstract function dismiss_alarm($event_id, $snooze = 0);
/**
* Check the given event object for validity
*
* @param array $event Event object as hash array
*
* @return boolean True if valid, false if not
*/
public function validate($event)
{
$valid = true;
- if (empty($event['start']) || !is_object($event['start']) || !is_a($event['start'], 'DateTime')) {
+ if (empty($event['start']) || !is_object($event['start']) || !($event['start'] instanceof DateTimeInterface)) {
$valid = false;
}
- if (empty($event['end']) || !is_object($event['end']) || !is_a($event['end'], 'DateTime')) {
+ if (empty($event['end']) || !is_object($event['end']) || !($event['end'] instanceof DateTimeInterface)) {
$valid = false;
}
return $valid;
}
/**
* Get list of event's attachments.
* Drivers can return list of attachments as event property.
* If they will do not do this list_attachments() method will be used.
*
* @param array $event Hash array with event properties:
* id: Event identifier
* calendar: Calendar identifier
*
* @return array List of attachments, each as hash array:
* id: Attachment identifier
* name: Attachment name
* mimetype: MIME content type of the attachment
* size: Attachment size
*/
public function list_attachments($event) { }
/**
* Get attachment properties
*
* @param string $id Attachment identifier
* @param array $event Hash array with event properties:
* id: Event identifier
* calendar: Calendar identifier
*
* @return array Hash array with attachment properties:
* id: Attachment identifier
* name: Attachment name
* mimetype: MIME content type of the attachment
* size: Attachment size
*/
public function get_attachment($id, $event) { }
/**
* Get attachment body
*
* @param string $id Attachment identifier
* @param array $event Hash array with event properties:
* id: Event identifier
* calendar: Calendar identifier
*
* @return string Attachment body
*/
public function get_attachment_body($id, $event) { }
/**
* Build a struct representing the given message reference
*
* @param object|string $uri_or_headers rcube_message_header instance holding the message headers
* or an URI from a stored link referencing a mail message.
* @param string $folder IMAP folder the message resides in
*
* @return array An struct referencing the given IMAP message
*/
public function get_message_reference($uri_or_headers, $folder = null)
{
// to be implemented by the derived classes
return false;
}
/**
* List availabale categories
* The default implementation reads them from config/user prefs
*/
public function list_categories()
{
$rcmail = rcube::get_instance();
return $rcmail->config->get('calendar_categories', $this->default_categories);
}
/**
* Create a new category
*/
public function add_category($name, $color) { }
/**
* Remove the given category
*/
public function remove_category($name) { }
/**
* Update/replace a category
*/
public function replace_category($oldname, $name, $color) { }
/**
* Fetch free/busy information from a person within the given range
*
* @param string $email E-mail address of attendee
* @param int $start Requested period start date/time as unix timestamp
* @param int $end Requested period end date/time as unix timestamp
*
* @return array List of busy timeslots within the requested range
*/
public function get_freebusy_list($email, $start, $end)
{
return false;
}
/**
* Create instances of a recurring event
*
* @param array $event Hash array with event properties
* @param DateTime $start Start date of the recurrence window
* @param DateTime $end End date of the recurrence window
*
* @return array List of recurring event instances
*/
public function get_recurring_events($event, $start, $end = null)
{
$events = [];
if (!empty($event['recurrence'])) {
// include library class
require_once(dirname(__FILE__) . '/../lib/calendar_recurrence.php');
$rcmail = rcmail::get_instance();
$recurrence = new calendar_recurrence($rcmail->plugins->get_plugin('calendar'), $event);
$recurrence_id_format = libcalendaring::recurrence_id_format($event);
// determine a reasonable end date if none given
if (!$end) {
switch ($event['recurrence']['FREQ']) {
case 'YEARLY': $intvl = 'P100Y'; break;
case 'MONTHLY': $intvl = 'P20Y'; break;
default: $intvl = 'P10Y'; break;
}
$end = clone $event['start'];
$end->add(new DateInterval($intvl));
}
$i = 0;
while ($next_event = $recurrence->next_instance()) {
// add to output if in range
if (($next_event['start'] <= $end && $next_event['end'] >= $start)) {
$next_event['_instance'] = $next_event['start']->format($recurrence_id_format);
$next_event['id'] = $next_event['uid'] . '-' . $exception['_instance'];
$next_event['recurrence_id'] = $event['uid'];
$events[] = $next_event;
}
else if ($next_event['start'] > $end) { // stop loop if out of range
break;
}
// avoid endless recursion loops
if (++$i > 1000) {
break;
}
}
}
return $events;
}
/**
* Provide a list of revisions for the given event
*
* @param array $event Hash array with event properties:
* id: Event identifier
* calendar: Calendar identifier
*
* @return array List of changes, each as a hash array:
* rev: Revision number
* type: Type of the change (create, update, move, delete)
* date: Change date
* user: The user who executed the change
* ip: Client IP
* destination: Destination calendar for 'move' type
*/
public function get_event_changelog($event)
{
return false;
}
/**
* Get a list of property changes beteen two revisions of an event
*
* @param array $event Hash array with event properties:
* id: Event identifier
* calendar: Calendar identifier
* @param mixed $rev1 Old Revision
* @param mixed $rev2 New Revision
*
* @return array List of property changes, each as a hash array:
* property: Revision number
* old: Old property value
* new: Updated property value
*/
public function get_event_diff($event, $rev1, $rev2)
{
return false;
}
/**
* Return full data of a specific revision of an event
*
* @param mixed $event UID string or hash array with event properties:
* id: Event identifier
* calendar: Calendar identifier
* @param mixed $rev Revision number
*
* @return array Event object as hash array
* @see self::get_event()
*/
public function get_event_revison($event, $rev)
{
return false;
}
/**
* Command the backend to restore a certain revision of an event.
* This shall replace the current event with an older version.
*
* @param mixed $event UID string or hash array with event properties:
* id: Event identifier
* calendar: Calendar identifier
* @param mixed $rev Revision number
*
* @return boolean True on success, False on failure
*/
public function restore_event_revision($event, $rev)
{
return false;
}
/**
* Callback function to produce driver-specific calendar create/edit form
*
* @param string $action Request action 'form-edit|form-new'
* @param array $calendar Calendar properties (e.g. id, color)
* @param array $formfields Edit form fields
*
* @return string HTML content of the form
*/
public function calendar_form($action, $calendar, $formfields)
{
$table = new html_table(['cols' => 2, 'class' => 'propform']);
foreach ($formfields as $col => $colprop) {
$label = !empty($colprop['label']) ? $colprop['label'] : $rcmail->gettext("$domain.$col");
$table->add('title', html::label($colprop['id'], rcube::Q($label)));
$table->add(null, $colprop['value']);
}
return $table->show();
}
/**
* Compose a list of birthday events from the contact records in the user's address books.
*
* This is a default implementation using Roundcube's address book API.
* It can be overriden with a more optimized version by the individual drivers.
*
* @param int $start Event's new start (unix timestamp)
* @param int $end Event's new end (unix timestamp)
* @param string $search Search query (optional)
* @param int $modifiedsince Only list events modified since this time (unix timestamp)
*
* @return array A list of event records
*/
public function load_birthday_events($start, $end, $search = null, $modifiedsince = null)
{
// ignore update requests for simplicity reasons
if (!empty($modifiedsince)) {
return [];
}
// convert to DateTime for comparisons
$start = new DateTime('@'.$start);
$end = new DateTime('@'.$end);
// extract the current year
$year = $start->format('Y');
$year2 = $end->format('Y');
$events = [];
$search = mb_strtolower($search);
$rcmail = rcmail::get_instance();
$cache = $rcmail->get_cache('calendar.birthdays', 'db', 3600);
$cache->expunge();
$alarm_type = $rcmail->config->get('calendar_birthdays_alarm_type', '');
$alarm_offset = $rcmail->config->get('calendar_birthdays_alarm_offset', '-1D');
$alarms = $alarm_type ? $alarm_offset . ':' . $alarm_type : null;
// let the user select the address books to consider in prefs
$selected_sources = $rcmail->config->get('calendar_birthday_adressbooks');
$sources = $selected_sources ?: array_keys($rcmail->get_address_sources(false, true));
foreach ($sources as $source) {
$abook = $rcmail->get_address_book($source);
// skip LDAP address books unless selected by the user
if (!$abook || ($abook instanceof rcube_ldap && empty($selected_sources))) {
continue;
}
// skip collected recipients/senders addressbooks
if (is_a($abook, 'rcube_addresses')) {
continue;
}
$abook->set_pagesize(10000);
// check for cached results
$cache_records = [];
$cached = $cache->get($source);
// iterate over (cached) contacts
foreach (($cached ?: $abook->search('*', '', 2, true, true, ['birthday'])) as $contact) {
$event = self::parse_contact($contact, $source);
if (empty($event)) {
continue;
}
// add stripped record to cache
if (empty($cached)) {
$cache_records[] = [
'ID' => $contact['ID'],
'name' => $event['_displayname'],
'birthday' => $event['start']->format('Y-m-d'),
];
}
// filter by search term (only name is involved here)
if (!empty($search) && strpos(mb_strtolower($event['title']), $search) === false) {
continue;
}
$bday = clone $event['start'];
$byear = $bday->format('Y');
// quick-and-dirty recurrence computation: just replace the year
$bday->setDate($year, $bday->format('n'), $bday->format('j'));
$bday->setTime(12, 0, 0);
$this_year = $year;
// date range reaches over multiple years: use end year if not in range
if (($bday > $end || $bday < $start) && $year2 != $year) {
$bday->setDate($year2, $bday->format('n'), $bday->format('j'));
$this_year = $year2;
}
// birthday is within requested range
if ($bday <= $end && $bday >= $start) {
unset($event['_displayname']);
$event['alarms'] = $alarms;
// if this is not the first occurence modify event details
// but not when this is "all birthdays feed" request
if ($year2 - $year < 10 && ($age = ($this_year - $byear))) {
$label = ['name' => 'birthdayage', 'vars' => ['age' => $age]];
$event['description'] = $rcmail->gettext($label, 'calendar');
$event['start'] = $bday;
$event['end'] = clone $bday;
unset($event['recurrence']);
}
// add the main instance
$events[] = $event;
}
}
// store collected contacts in cache
if (empty($cached)) {
$cache->write($source, $cache_records);
}
}
return $events;
}
/**
* Get a single birthday calendar event
*/
public function get_birthday_event($id)
{
// decode $id
list(, $source, $contact_id, $year) = explode(':', rcube_ldap::dn_decode($id));
$rcmail = rcmail::get_instance();
if (strlen($source) && $contact_id && ($abook = $rcmail->get_address_book($source))) {
if ($contact = $abook->get_record($contact_id, true)) {
return self::parse_contact($contact, $source);
}
}
}
/**
* Parse contact and create an event for its birthday
*
* @param array $contact Contact data
* @param string $source Addressbook source ID
*
* @return array|null Birthday event data
*/
public static function parse_contact($contact, $source)
{
if (!is_array($contact)) {
return;
}
if (!empty($contact['birthday']) && is_array($contact['birthday'])) {
$contact['birthday'] = reset($contact['birthday']);
}
if (empty($contact['birthday'])) {
return;
}
try {
$bday = $contact['birthday'];
if (!$bday instanceof DateTimeInterface) {
$bday = new DateTime($bday, new DateTimeZone('UTC'));
}
$bday->_dateonly = true;
}
catch (Exception $e) {
rcube::raise_error([
'code' => 600,
'file' => __FILE__,
'line' => __LINE__,
'message' => 'BIRTHDAY PARSE ERROR: ' . $e->getMessage()
],
true, false
);
return;
}
$rcmail = rcmail::get_instance();
$birthyear = $bday->format('Y');
$display_name = rcube_addressbook::compose_display_name($contact);
$label = ['name' => 'birthdayeventtitle', 'vars' => ['name' => $display_name]];
$event_title = $rcmail->gettext($label, 'calendar');
$uid = rcube_ldap::dn_encode('bday:' . $source . ':' . $contact['ID'] . ':' . $birthyear);
return [
'id' => $uid,
'uid' => $uid,
'calendar' => self::BIRTHDAY_CALENDAR_ID,
'title' => $event_title,
'description' => '',
'allday' => true,
'start' => $bday,
'end' => clone $bday,
'recurrence' => ['FREQ' => 'YEARLY', 'INTERVAL' => 1],
'free_busy' => 'free',
'_displayname' => $display_name,
];
}
/**
* Store alarm dismissal for birtual birthay events
*
* @param string $event_id Event identifier
* @param int $snooze Suspend the alarm for this number of seconds
*/
public function dismiss_birthday_alarm($event_id, $snooze = 0)
{
$rcmail = rcmail::get_instance();
$cache = $rcmail->get_cache('calendar.birthdayalarms', 'db', 86400 * 30);
$cache->remove($event_id);
// compute new notification time or disable if not snoozed
$notifyat = $snooze > 0 ? time() + $snooze : null;
$cache->set($event_id, ['snooze' => $snooze, 'notifyat' => $notifyat]);
return true;
}
/**
* Handler for user_delete plugin hook
*
* @param array $args Hash array with hook arguments
*
* @return array Return arguments for plugin hooks
*/
public function user_delete($args)
{
// TO BE OVERRIDDEN
return $args;
}
}
diff --git a/plugins/calendar/drivers/kolab/kolab_calendar.php b/plugins/calendar/drivers/kolab/kolab_calendar.php
index 4b817951..e0129c0a 100644
--- a/plugins/calendar/drivers/kolab/kolab_calendar.php
+++ b/plugins/calendar/drivers/kolab/kolab_calendar.php
@@ -1,958 +1,958 @@
<?php
/**
* Kolab calendar storage class
*
* @version @package_version@
* @author Thomas Bruederli <bruederli@kolabsys.com>
* @author Aleksander Machniak <machniak@kolabsys.com>
*
* Copyright (C) 2012-2015, Kolab Systems AG <contact@kolabsys.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class kolab_calendar extends kolab_storage_folder_api
{
public $ready = false;
public $rights = 'lrs';
public $editable = false;
public $attachments = true;
public $alarms = false;
public $history = false;
public $subscriptions = true;
public $categories = [];
public $storage;
public $type = 'event';
protected $cal;
protected $events = [];
protected $search_fields = ['title', 'description', 'location', 'attendees', 'categories'];
/**
* Factory method to instantiate a kolab_calendar object
*
* @param string Calendar ID (encoded IMAP folder name)
* @param object Calendar plugin object
*
* @return kolab_calendar Self instance
*/
public static function factory($id, $calendar)
{
$imap = $calendar->rc->get_storage();
$imap_folder = kolab_storage::id_decode($id);
$info = $imap->folder_info($imap_folder, true);
if (
empty($info)
|| !empty($info['noselect'])
|| strpos(kolab_storage::folder_type($imap_folder), 'event') !== 0
) {
return new kolab_user_calendar($imap_folder, $calendar);
}
return new kolab_calendar($imap_folder, $calendar);
}
/**
* Default constructor
*/
public function __construct($imap_folder, $calendar)
{
$this->cal = $calendar;
$this->imap = $calendar->rc->get_storage();
$this->name = $imap_folder;
// ID is derrived from folder name
$this->id = kolab_storage::folder_id($this->name, true);
$old_id = kolab_storage::folder_id($this->name, false);
// fetch objects from the given IMAP folder
$this->storage = kolab_storage::get_folder($this->name);
$this->ready = $this->storage && $this->storage->valid;
// Set writeable and alarms flags according to folder permissions
if ($this->ready) {
if ($this->storage->get_namespace() == 'personal') {
$this->editable = true;
$this->rights = 'lrswikxteav';
$this->alarms = true;
}
else {
$rights = $this->storage->get_myrights();
if ($rights && !PEAR::isError($rights)) {
$this->rights = $rights;
if (strpos($rights, 't') !== false || strpos($rights, 'd') !== false) {
$this->editable = strpos($rights, 'i');;
}
}
}
// user-specific alarms settings win
$prefs = $this->cal->rc->config->get('kolab_calendars', []);
if (isset($prefs[$this->id]['showalarms'])) {
$this->alarms = $prefs[$this->id]['showalarms'];
}
else if (isset($prefs[$old_id]['showalarms'])) {
$this->alarms = $prefs[$old_id]['showalarms'];
}
}
$this->default = $this->storage->default;
$this->subtype = $this->storage->subtype;
}
/**
* Getter for the IMAP folder name
*
* @return string Name of the IMAP folder
*/
public function get_realname()
{
return $this->name;
}
/**
*
*/
public function get_title()
{
return null;
}
/**
* Return color to display this calendar
*/
public function get_color($default = null)
{
// color is defined in folder METADATA
if ($color = $this->storage->get_color()) {
return $color;
}
// calendar color is stored in user prefs (temporary solution)
$prefs = $this->cal->rc->config->get('kolab_calendars', []);
if (!empty($prefs[$this->id]) && !empty($prefs[$this->id]['color'])) {
return $prefs[$this->id]['color'];
}
return $default ?: 'cc0000';
}
/**
* Compose an URL for CalDAV access to this calendar (if configured)
*/
public function get_caldav_url()
{
if ($template = $this->cal->rc->config->get('calendar_caldav_url', null)) {
return strtr($template, [
'%h' => $_SERVER['HTTP_HOST'],
'%u' => urlencode($this->cal->rc->get_user_name()),
'%i' => urlencode($this->storage->get_uid()),
'%n' => urlencode($this->name),
]);
}
return false;
}
/**
* Update properties of this calendar folder
*
* @see calendar_driver::edit_calendar()
*/
public function update(&$prop)
{
$prop['oldname'] = $this->get_realname();
$newfolder = kolab_storage::folder_update($prop);
if ($newfolder === false) {
$this->cal->last_error = $this->cal->gettext(kolab_storage::$last_error);
return false;
}
// create ID
return kolab_storage::folder_id($newfolder);
}
/**
* Getter for a single event object
*/
public function get_event($id)
{
// remove our occurrence identifier if it's there
$master_id = preg_replace('/-\d{8}(T\d{6})?$/', '', $id);
// directly access storage object
if (empty($this->events[$id]) && $master_id == $id && ($record = $this->storage->get_object($id))) {
$this->events[$id] = $this->_to_driver_event($record, true);
}
// maybe a recurring instance is requested
if (empty($this->events[$id]) && $master_id != $id) {
$instance_id = substr($id, strlen($master_id) + 1);
if ($record = $this->storage->get_object($master_id)) {
$master = $this->_to_driver_event($record);
}
if ($master) {
// check for match in top-level exceptions (aka loose single occurrences)
if (!empty($master['_formatobj']) && ($instance = $master['_formatobj']->get_instance($instance_id))) {
$this->events[$id] = $this->_to_driver_event($instance, false, true, $master);
}
// check for match on the first instance already
else if (!empty($master['_instance']) && $master['_instance'] == $instance_id) {
$this->events[$id] = $master;
}
else if (!empty($master['recurrence'])) {
$start_date = $master['start'];
// For performance reasons we'll get only the specific instance
if (($date = substr($id, strlen($master_id) + 1, 8)) && strlen($date) == 8 && is_numeric($date)) {
$start_date = new DateTime($date . 'T000000', $master['start']->getTimezone());
}
$this->get_recurring_events($record, $start_date, null, $id, 1);
}
}
}
return $this->events[$id];
}
/**
* Get attachment body
* @see calendar_driver::get_attachment_body()
*/
public function get_attachment_body($id, $event)
{
if (!$this->ready) {
return false;
}
$data = $this->storage->get_attachment($event['id'], $id);
if ($data == null) {
// try again with master UID
$uid = preg_replace('/-\d+(T\d{6})?$/', '', $event['id']);
if ($uid != $event['id']) {
$data = $this->storage->get_attachment($uid, $id);
}
}
return $data;
}
/**
* @param int Event's new start (unix timestamp)
* @param int Event's new end (unix timestamp)
* @param string Search query (optional)
* @param bool Include virtual events (optional)
* @param array Additional parameters to query storage
* @param array Additional query to filter events
*
* @return array A list of event records
*/
public function list_events($start, $end, $search = null, $virtual = 1, $query = [], $filter_query = null)
{
// convert to DateTime for comparisons
// #5190: make the range a little bit wider
// to workaround possible timezone differences
try {
$start = new DateTime('@' . ($start - 12 * 3600));
}
catch (Exception $e) {
$start = new DateTime('@0');
}
try {
$end = new DateTime('@' . ($end + 12 * 3600));
}
catch (Exception $e) {
$end = new DateTime('today +10 years');
}
// get email addresses of the current user
$user_emails = $this->cal->get_user_emails();
// query Kolab storage
$query[] = ['dtstart', '<=', $end];
$query[] = ['dtend', '>=', $start];
if (is_array($filter_query)) {
$query = array_merge($query, $filter_query);
}
$words = [];
$partstat_exclude = [];
$events = [];
if (!empty($search)) {
$search = mb_strtolower($search);
$words = rcube_utils::tokenize_string($search, 1);
foreach (rcube_utils::normalize_string($search, true) as $word) {
$query[] = ['words', 'LIKE', $word];
}
}
// set partstat filter to skip pending and declined invitations
if (empty($filter_query)
&& $this->cal->rc->config->get('kolab_invitation_calendars')
&& $this->get_namespace() != 'other'
) {
$partstat_exclude = ['NEEDS-ACTION', 'DECLINED'];
}
foreach ($this->storage->select($query) as $record) {
$event = $this->_to_driver_event($record, !$virtual, false);
// remember seen categories
if (!empty($event['categories'])) {
$cat = is_array($event['categories']) ? $event['categories'][0] : $event['categories'];
$this->categories[$cat]++;
}
// list events in requested time window
if ($event['start'] <= $end && $event['end'] >= $start) {
unset($event['_attendees']);
$add = true;
// skip the first instance of a recurring event if listed in exdate
if ($virtual && !empty($event['recurrence']['EXDATE'])) {
$event_date = $event['start']->format('Ymd');
$event_tz = $event['start']->getTimezone();
foreach ((array) $event['recurrence']['EXDATE'] as $exdate) {
$ex = clone $exdate;
$ex->setTimezone($event_tz);
if ($ex->format('Ymd') == $event_date) {
$add = false;
break;
}
}
}
// find and merge exception for the first instance
if ($virtual && !empty($event['recurrence']) && !empty($event['recurrence']['EXCEPTIONS'])) {
foreach ($event['recurrence']['EXCEPTIONS'] as $exception) {
if ($event['_instance'] == $exception['_instance']) {
unset($exception['calendar'], $exception['className'], $exception['_folder_id']);
// clone date objects from main event before adjusting them with exception data
if (is_object($event['start'])) {
$event['start'] = clone $record['start'];
}
if (is_object($event['end'])) {
$event['end'] = clone $record['end'];
}
kolab_driver::merge_exception_data($event, $exception);
}
}
}
if ($add) {
$events[] = $event;
}
}
// resolve recurring events
if (!empty($record['recurrence']) && $virtual == 1) {
$events = array_merge($events, $this->get_recurring_events($record, $start, $end));
}
// add top-level exceptions (aka loose single occurrences)
else if (!empty($record['exceptions'])) {
foreach ($record['exceptions'] as $ex) {
$component = $this->_to_driver_event($ex, false, false, $record);
if ($component['start'] <= $end && $component['end'] >= $start) {
$events[] = $component;
}
}
}
}
// post-filter all events by fulltext search and partstat values
$me = $this;
$events = array_filter($events, function($event) use ($words, $partstat_exclude, $user_emails, $me) {
// fulltext search
if (count($words)) {
$hits = 0;
foreach ($words as $word) {
$hits += $me->fulltext_match($event, $word, false);
}
if ($hits < count($words)) {
return false;
}
}
// partstat filter
if (count($partstat_exclude) && !empty($event['attendees'])) {
foreach ($event['attendees'] as $attendee) {
if (
in_array($attendee['email'], $user_emails)
&& in_array($attendee['status'], $partstat_exclude)
) {
return false;
}
}
}
return true;
});
// Apply event-to-mail relations
$config = kolab_storage_config::get_instance();
$config->apply_links($events);
// avoid session race conditions that will loose temporary subscriptions
$this->cal->rc->session->nowrite = true;
return $events;
}
/**
* Get number of events in the given calendar
*
* @param int Date range start (unix timestamp)
* @param int Date range end (unix timestamp)
* @param array Additional query to filter events
*
* @return int Count
*/
public function count_events($start, $end = null, $filter_query = null)
{
// convert to DateTime for comparisons
try {
$start = new DateTime('@'.$start);
}
catch (Exception $e) {
$start = new DateTime('@0');
}
if ($end) {
try {
$end = new DateTime('@'.$end);
}
catch (Exception $e) {
$end = null;
}
}
// query Kolab storage
$query[] = ['dtend', '>=', $start];
if ($end) {
$query[] = ['dtstart', '<=', $end];
}
// add query to exclude pending/declined invitations
if (empty($filter_query)) {
foreach ($this->cal->get_user_emails() as $email) {
$query[] = ['tags', '!=', 'x-partstat:' . $email . ':needs-action'];
$query[] = ['tags', '!=', 'x-partstat:' . $email . ':declined'];
}
}
else if (is_array($filter_query)) {
$query = array_merge($query, $filter_query);
}
// we rely the Kolab storage query (no post-filtering)
return $this->storage->count($query);
}
/**
* Create a new event record
*
* @see calendar_driver::new_event()
*
* @return array|false The created record ID on success, False on error
*/
public function insert_event($event)
{
if (!is_array($event)) {
return false;
}
// email links are stored separately
$links = !empty($event['links']) ? $event['links'] : [];
unset($event['links']);
//generate new event from RC input
$object = $this->_from_driver_event($event);
$saved = $this->storage->save($object, 'event');
if (!$saved) {
rcube::raise_error([
'code' => 600, 'file' => __FILE__, 'line' => __LINE__,
'message' => "Error saving event object to Kolab server"
],
true, false
);
$saved = false;
}
else {
// save links in configuration.relation object
if ($this->save_links($event['uid'], $links)) {
$object['links'] = $links;
}
$this->events = [$event['uid'] => $this->_to_driver_event($object, true)];
}
return $saved;
}
/**
* Update a specific event record
*
* @see calendar_driver::new_event()
*
* @return bool True on success, False on error
*/
public function update_event($event, $exception_id = null)
{
$updated = false;
$old = $this->storage->get_object(!empty($event['uid']) ? $event['uid'] : $event['id']);
if (!$old || PEAR::isError($old)) {
return false;
}
// email links are stored separately
$links = !empty($event['links']) ? $event['links'] : [];
unset($event['links']);
$object = $this->_from_driver_event($event, $old);
$saved = $this->storage->save($object, 'event', $old['uid']);
if (!$saved) {
rcube::raise_error([
'code' => 600, 'file' => __FILE__, 'line' => __LINE__,
'message' => "Error saving event object to Kolab server"
],
true, false
);
}
else {
// save links in configuration.relation object
if ($this->save_links($event['uid'], $links)) {
$object['links'] = $links;
}
$updated = true;
$this->events = [$event['uid'] => $this->_to_driver_event($object, true)];
// refresh local cache with recurring instances
if ($exception_id) {
$this->get_recurring_events($object, $event['start'], $event['end'], $exception_id);
}
}
return $updated;
}
/**
* Delete an event record
*
* @see calendar_driver::remove_event()
*
* @return bool True on success, False on error
*/
public function delete_event($event, $force = true)
{
$deleted = $this->storage->delete(!empty($event['uid']) ? $event['uid'] : $event['id'], $force);
if (!$deleted) {
rcube::raise_error([
'code' => 600, 'file' => __FILE__, 'line' => __LINE__,
'message' => sprintf("Error deleting event object '%s' from Kolab server", $event['id'])
],
true, false
);
}
return $deleted;
}
/**
* Restore deleted event record
*
* @see calendar_driver::undelete_event()
*
* @return bool True on success, False on error
*/
public function restore_event($event)
{
// Make sure this is not an instance identifier
$uid = preg_replace('/-\d{8}(T\d{6})?$/', '', $event['id']);
if ($this->storage->undelete($uid)) {
return true;
}
rcube::raise_error([
'code' => 600, 'file' => __FILE__, 'line' => __LINE__,
'message' => sprintf("Error undeleting the event object '%s' from the Kolab server", $event['id'])
],
true, false
);
return false;
}
/**
* Find messages linked with an event
*/
protected function get_links($uid)
{
$storage = kolab_storage_config::get_instance();
return $storage->get_object_links($uid);
}
/**
*
*/
protected function save_links($uid, $links)
{
$storage = kolab_storage_config::get_instance();
return $storage->save_object_links($uid, (array) $links);
}
/**
* Create instances of a recurring event
*
* @param array $event Hash array with event properties
* @param DateTime $start Start date of the recurrence window
* @param DateTime $end End date of the recurrence window
* @param string $event_id ID of a specific recurring event instance
* @param int $limit Max. number of instances to return
*
* @return array List of recurring event instances
*/
public function get_recurring_events($event, $start, $end = null, $event_id = null, $limit = null)
{
if (empty($event['_formatobj'])) {
$rec = $this->storage->get_object(!empty($event['uid']) ? $event['uid'] : $event['id']);
$object = $rec['_formatobj'];
}
else {
$object = $event['_formatobj'];
}
if (!is_object($object)) {
return [];
}
// determine a reasonable end date if none given
if (!$end) {
$end = clone $event['start'];
$end->add(new DateInterval('P100Y'));
}
// read recurrence exceptions first
$events = [];
$exdata = [];
$futuredata = [];
$recurrence_id_format = libcalendaring::recurrence_id_format($event);
if (!empty($event['recurrence'])) {
// copy the recurrence rule from the master event (to be used in the UI)
$recurrence_rule = $event['recurrence'];
unset($recurrence_rule['EXCEPTIONS'], $recurrence_rule['EXDATE']);
if (!empty($event['recurrence']['EXCEPTIONS'])) {
foreach ($event['recurrence']['EXCEPTIONS'] as $exception) {
if (empty($exception['_instance'])) {
$exception['_instance'] = libcalendaring::recurrence_instance_identifier($exception, !empty($event['allday']));
}
$rec_event = $this->_to_driver_event($exception, false, false, $event);
$rec_event['id'] = $event['uid'] . '-' . $exception['_instance'];
$rec_event['isexception'] = 1;
// found the specifically requested instance: register exception (single occurrence wins)
if (
$rec_event['id'] == $event_id
&& (empty($this->events[$event_id]) || !empty($this->events[$event_id]['thisandfuture']))
) {
$rec_event['recurrence'] = $recurrence_rule;
$rec_event['recurrence_id'] = $event['uid'];
$this->events[$rec_event['id']] = $rec_event;
}
// remember this exception's date
$exdate = substr($exception['_instance'], 0, 8);
if (empty($exdata[$exdate]) || !empty($exdata[$exdate]['thisandfuture'])) {
$exdata[$exdate] = $rec_event;
}
if (!empty($rec_event['thisandfuture'])) {
$futuredata[$exdate] = $rec_event;
}
}
}
}
// found the specifically requested instance, exiting...
if ($event_id && !empty($this->events[$event_id])) {
return [$this->events[$event_id]];
}
// Check first occurrence, it might have been moved
if ($first = $exdata[$event['start']->format('Ymd')]) {
// return it only if not already in the result, but in the requested period
if (!($event['start'] <= $end && $event['end'] >= $start)
&& ($first['start'] <= $end && $first['end'] >= $start)
) {
$events[] = $first;
}
}
if ($limit && count($events) >= $limit) {
return $events;
}
// use libkolab to compute recurring events
$recurrence = new kolab_date_recurrence($object);
$i = 0;
while ($next_event = $recurrence->next_instance()) {
$datestr = $next_event['start']->format('Ymd');
$instance_id = $next_event['start']->format($recurrence_id_format);
// use this event data for future recurring instances
if (!empty($futuredata[$datestr])) {
$overlay_data = $futuredata[$datestr];
}
$rec_id = $event['uid'] . '-' . $instance_id;
$exception = !empty($exdata[$datestr]) ? $exdata[$datestr] : $overlay_data;
$event_start = $next_event['start'];
$event_end = $next_event['end'];
// copy some event from exception to get proper start/end dates
if ($exception) {
$event_copy = $next_event;
kolab_driver::merge_exception_dates($event_copy, $exception);
$event_start = $event_copy['start'];
$event_end = $event_copy['end'];
}
// add to output if in range
if (($event_start <= $end && $event_end >= $start) || ($event_id && $rec_id == $event_id)) {
$rec_event = $this->_to_driver_event($next_event, false, false, $event);
$rec_event['_instance'] = $instance_id;
$rec_event['_count'] = $i + 1;
if ($exception) {
// copy data from exception
kolab_driver::merge_exception_data($rec_event, $exception);
}
$rec_event['id'] = $rec_id;
$rec_event['recurrence_id'] = $event['uid'];
$rec_event['recurrence'] = $recurrence_rule;
unset($rec_event['_attendees']);
$events[] = $rec_event;
if ($rec_id == $event_id) {
$this->events[$rec_id] = $rec_event;
break;
}
if ($limit && count($events) >= $limit) {
return $events;
}
}
else if ($next_event['start'] > $end) {
// stop loop if out of range
break;
}
// avoid endless recursion loops
if (++$i > 100000) {
break;
}
}
return $events;
}
/**
* Convert from Kolab_Format to internal representation
*/
private function _to_driver_event($record, $noinst = false, $links = true, $master_event = null)
{
$record['calendar'] = $this->id;
// remove (possibly outdated) cached parameters
unset($record['_folder_id'], $record['className']);
if ($links && !array_key_exists('links', $record)) {
$record['links'] = $this->get_links($record['uid']);
}
$ns = $this->get_namespace();
if ($ns == 'other') {
$record['className'] = 'fc-event-ns-other';
}
if ($ns == 'other' || !$this->cal->rc->config->get('kolab_invitation_calendars')) {
$record = kolab_driver::add_partstat_class($record, ['NEEDS-ACTION', 'DECLINED'], $this->get_owner());
// Modify invitation status class name, when invitation calendars are disabled
// we'll use opacity only for declined/needs-action events
$record['className'] = str_replace('-invitation', '', $record['className']);
}
// add instance identifier to first occurrence (master event)
$recurrence_id_format = libcalendaring::recurrence_id_format($master_event ? $master_event : $record);
if (!$noinst && !empty($record['recurrence']) && empty($record['recurrence_id']) && empty($record['_instance'])) {
$record['_instance'] = $record['start']->format($recurrence_id_format);
}
- else if (isset($record['recurrence_date']) && is_a($record['recurrence_date'], 'DateTime')) {
+ else if (isset($record['recurrence_date']) && $record['recurrence_date'] instanceof DateTimeInterface) {
$record['_instance'] = $record['recurrence_date']->format($recurrence_id_format);
}
// clean up exception data
if (!empty($record['recurrence']) && !empty($record['recurrence']['EXCEPTIONS'])) {
array_walk($record['recurrence']['EXCEPTIONS'], function(&$exception) {
unset($exception['_mailbox'], $exception['_msguid'], $exception['_formatobj'], $exception['_attachments']);
});
}
return $record;
}
/**
* Convert the given event record into a data structure that can be passed to Kolab_Storage backend for saving
* (opposite of self::_to_driver_event())
*/
private function _from_driver_event($event, $old = [])
{
// set current user as ORGANIZER
if ($identity = $this->cal->rc->user->list_emails(true)) {
$event['attendees'] = !empty($event['attendees']) ? $event['attendees'] : [];
$found = false;
// there can be only resources on attendees list (T1484)
// let's check the existence of an organizer
foreach ($event['attendees'] as $attendee) {
if (!empty($attendee['role']) && $attendee['role'] == 'ORGANIZER') {
$found = true;
break;
}
}
if (!$found) {
$event['attendees'][] = ['role' => 'ORGANIZER', 'name' => $identity['name'], 'email' => $identity['email']];
}
$event['_owner'] = $identity['email'];
}
// remove EXDATE values if RDATE is given
if (!empty($event['recurrence']['RDATE'])) {
$event['recurrence']['EXDATE'] = [];
}
// remove recurrence information (e.g. EXDATES and EXCEPTIONS) entirely
if (!empty($event['recurrence']) && empty($event['recurrence']['FREQ']) && empty($event['recurrence']['RDATE'])) {
$event['recurrence'] = [];
}
// keep 'comment' from initial itip invitation
if (!empty($old['comment'])) {
$event['comment'] = $old['comment'];
}
// remove some internal properties which should not be cached
$cleanup_fn = function(&$event) {
unset($event['_savemode'], $event['_fromcalendar'], $event['_identity'], $event['_folder_id'],
$event['calendar'], $event['className'], $event['recurrence_id'],
$event['attachments'], $event['deleted_attachments']);
};
$cleanup_fn($event);
// clean up exception data
if (!empty($event['exceptions'])) {
array_walk($event['exceptions'], function(&$exception) use ($cleanup_fn) {
unset($exception['_mailbox'], $exception['_msguid'], $exception['_formatobj']);
$cleanup_fn($exception);
});
}
// copy meta data (starting with _) from old object
foreach ((array) $old as $key => $val) {
if (!isset($event[$key]) && $key[0] == '_') {
$event[$key] = $val;
}
}
return $event;
}
/**
* Match the given word in the event contents
*/
public function fulltext_match($event, $word, $recursive = true)
{
$hits = 0;
foreach ($this->search_fields as $col) {
if (empty($event[$col])) {
continue;
}
$sval = is_array($event[$col]) ? self::_complex2string($event[$col]) : $event[$col];
if (empty($sval)) {
continue;
}
// do a simple substring matching (to be improved)
$val = mb_strtolower($sval);
if (strpos($val, $word) !== false) {
$hits++;
break;
}
}
return $hits;
}
/**
* Convert a complex event attribute to a string value
*/
private static function _complex2string($prop)
{
static $ignorekeys = ['role', 'status', 'rsvp'];
$out = '';
if (is_array($prop)) {
foreach ($prop as $key => $val) {
if (is_numeric($key)) {
$out .= self::_complex2string($val);
}
else if (!in_array($key, $ignorekeys)) {
$out .= $val . ' ';
}
}
}
else if (is_string($prop) || is_numeric($prop)) {
$out .= $prop . ' ';
}
return rtrim($out);
}
}
diff --git a/plugins/calendar/drivers/kolab/kolab_driver.php b/plugins/calendar/drivers/kolab/kolab_driver.php
index b4cee8cc..074d5133 100644
--- a/plugins/calendar/drivers/kolab/kolab_driver.php
+++ b/plugins/calendar/drivers/kolab/kolab_driver.php
@@ -1,2646 +1,2646 @@
<?php
/**
* Kolab driver for the Calendar plugin
*
* @version @package_version@
* @author Thomas Bruederli <bruederli@kolabsys.com>
* @author Aleksander Machniak <machniak@kolabsys.com>
*
* Copyright (C) 2012-2015, Kolab Systems AG <contact@kolabsys.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class kolab_driver extends calendar_driver
{
const INVITATIONS_CALENDAR_PENDING = '--invitation--pending';
const INVITATIONS_CALENDAR_DECLINED = '--invitation--declined';
// features this backend supports
public $alarms = true;
public $attendees = true;
public $freebusy = true;
public $attachments = true;
public $undelete = true;
public $alarm_types = ['DISPLAY', 'AUDIO'];
public $categoriesimmutable = true;
protected $rc;
protected $cal;
protected $calendars;
protected $storage;
protected $has_writeable = false;
protected $freebusy_trigger = false;
protected $bonnie_api = false;
/**
* Default constructor
*/
public function __construct($cal)
{
$cal->require_plugin('libkolab');
// load helper classes *after* libkolab has been loaded (#3248)
require_once(__DIR__ . '/kolab_calendar.php');
require_once(__DIR__ . '/kolab_user_calendar.php');
require_once(__DIR__ . '/kolab_invitation_calendar.php');
$this->cal = $cal;
$this->rc = $cal->rc;
$this->storage = new kolab_storage();
$this->cal->register_action('push-freebusy', [$this, 'push_freebusy']);
$this->cal->register_action('calendar-acl', [$this, 'calendar_acl']);
$this->freebusy_trigger = $this->rc->config->get('calendar_freebusy_trigger', false);
if (kolab_storage::$version == '2.0') {
$this->alarm_types = ['DISPLAY'];
$this->alarm_absolute = false;
}
// get configuration for the Bonnie API
$this->bonnie_api = libkolab::get_bonnie_api();
// calendar uses fully encoded identifiers
kolab_storage::$encode_ids = true;
}
/**
* Read available calendars from server
*/
protected function _read_calendars()
{
// already read sources
if (isset($this->calendars)) {
return $this->calendars;
}
// get all folders that have "event" type, sorted by namespace/name
$folders = $this->storage->sort_folders(
$this->storage->get_folders('event') + kolab_storage::get_user_folders('event', true)
);
$this->calendars = [];
foreach ($folders as $folder) {
$calendar = $this->_to_calendar($folder);
if ($calendar->ready) {
$this->calendars[$calendar->id] = $calendar;
if ($calendar->editable) {
$this->has_writeable = true;
}
}
}
return $this->calendars;
}
/**
* Convert kolab_storage_folder into kolab_calendar
*/
protected function _to_calendar($folder)
{
if ($folder instanceof kolab_calendar) {
return $folder;
}
if ($folder instanceof kolab_storage_folder_user) {
$calendar = new kolab_user_calendar($folder, $this->cal);
$calendar->subscriptions = count($folder->children) > 0;
}
else {
$calendar = new kolab_calendar($folder->name, $this->cal);
}
return $calendar;
}
/**
* Get a list of available calendars from this source
*
* @param int $filter Bitmask defining filter criterias
* @param object $tree Reference to hierarchical folder tree object
*
* @return array List of calendars
*/
public function list_calendars($filter = 0, &$tree = null)
{
$this->_read_calendars();
// attempt to create a default calendar for this user
if (!$this->has_writeable) {
if ($this->create_calendar(['name' => 'Calendar', 'color' => 'cc0000'])) {
unset($this->calendars);
$this->_read_calendars();
}
}
$delim = $this->rc->get_storage()->get_hierarchy_delimiter();
$folders = $this->filter_calendars($filter);
$calendars = [];
// include virtual folders for a full folder tree
if (!is_null($tree)) {
$folders = $this->storage->folder_hierarchy($folders, $tree);
}
$parents = array_keys($this->calendars);
foreach ($folders as $id => $cal) {
$imap_path = explode($delim, $cal->name);
// find parent
do {
array_pop($imap_path);
$parent_id = $this->storage->folder_id(join($delim, $imap_path));
}
while (count($imap_path) > 1 && !in_array($parent_id, $parents));
// restore "real" parent ID
if ($parent_id && !in_array($parent_id, $parents)) {
$parent_id = $this->storage->folder_id($cal->get_parent());
}
$parents[] = $cal->id;
if ($cal->virtual) {
$calendars[$cal->id] = [
'id' => $cal->id,
'name' => $cal->get_name(),
'listname' => $cal->get_foldername(),
'editname' => $cal->get_foldername(),
'virtual' => true,
'editable' => false,
'group' => $cal->get_namespace(),
];
}
else {
// additional folders may come from kolab_storage::folder_hierarchy() above
// make sure we deal with kolab_calendar instances
$cal = $this->_to_calendar($cal);
$this->calendars[$cal->id] = $cal;
$is_user = ($cal instanceof kolab_user_calendar);
$calendars[$cal->id] = [
'id' => $cal->id,
'name' => $cal->get_name(),
'listname' => $cal->get_foldername(),
'editname' => $cal->get_foldername(),
'title' => $cal->get_title(),
'color' => $cal->get_color(),
'editable' => $cal->editable,
'group' => $is_user ? 'other user' : $cal->get_namespace(),
'active' => $cal->is_active(),
'owner' => $cal->get_owner(),
'removable' => !$cal->default,
];
if (!$is_user) {
$calendars[$cal->id] += [
'default' => $cal->default,
'rights' => $cal->rights,
'showalarms' => $cal->alarms,
'history' => !empty($this->bonnie_api),
'children' => true, // TODO: determine if that folder indeed has child folders
'parent' => $parent_id,
'subtype' => $cal->subtype,
'caldavurl' => $cal->get_caldav_url(),
];
}
}
if ($cal->subscriptions) {
$calendars[$cal->id]['subscribed'] = $cal->is_subscribed();
}
}
// list virtual calendars showing invitations
if ($this->rc->config->get('kolab_invitation_calendars') && !($filter & self::FILTER_INSERTABLE)) {
foreach ([self::INVITATIONS_CALENDAR_PENDING, self::INVITATIONS_CALENDAR_DECLINED] as $id) {
$cal = new kolab_invitation_calendar($id, $this->cal);
if (!($filter & self::FILTER_ACTIVE) || $cal->is_active()) {
$calendars[$id] = [
'id' => $cal->id,
'name' => $cal->get_name(),
'listname' => $cal->get_name(),
'editname' => $cal->get_foldername(),
'title' => $cal->get_title(),
'color' => $cal->get_color(),
'editable' => $cal->editable,
'rights' => $cal->rights,
'showalarms' => $cal->alarms,
'history' => !empty($this->bonnie_api),
'group' => 'x-invitations',
'default' => false,
'active' => $cal->is_active(),
'owner' => $cal->get_owner(),
'children' => false,
'counts' => $id == self::INVITATIONS_CALENDAR_PENDING,
];
if (is_object($tree)) {
$tree->children[] = $cal;
}
}
}
}
// append the virtual birthdays calendar
if ($this->rc->config->get('calendar_contact_birthdays', false) && !($filter & self::FILTER_INSERTABLE)) {
$id = self::BIRTHDAY_CALENDAR_ID;
$prefs = $this->rc->config->get('kolab_calendars', []); // read local prefs
if (!($filter & self::FILTER_ACTIVE) || !empty($prefs[$id]['active'])) {
$calendars[$id] = [
'id' => $id,
'name' => $this->cal->gettext('birthdays'),
'listname' => $this->cal->gettext('birthdays'),
'color' => !empty($prefs[$id]['color']) ? $prefs[$id]['color'] : '87CEFA',
'active' => !empty($prefs[$id]['active']),
'showalarms' => (bool) $this->rc->config->get('calendar_birthdays_alarm_type'),
'group' => 'x-birthdays',
'editable' => false,
'default' => false,
'children' => false,
'history' => false,
];
}
}
return $calendars;
}
/**
* Get list of calendars according to specified filters
*
* @param int Bitmask defining restrictions. See FILTER_* constants for possible values.
*
* @return array List of calendars
*/
protected function filter_calendars($filter)
{
$this->_read_calendars();
$calendars = [];
$plugin = $this->rc->plugins->exec_hook('calendar_list_filter', [
'list' => $this->calendars,
'calendars' => $calendars,
'filter' => $filter,
]);
if ($plugin['abort']) {
return $plugin['calendars'];
}
$personal = $filter & self::FILTER_PERSONAL;
$shared = $filter & self::FILTER_SHARED;
foreach ($this->calendars as $cal) {
if (!$cal->ready) {
continue;
}
if (($filter & self::FILTER_WRITEABLE) && !$cal->editable) {
continue;
}
if (($filter & self::FILTER_INSERTABLE) && !$cal->editable) {
continue;
}
if (($filter & self::FILTER_ACTIVE) && !$cal->is_active()) {
continue;
}
if (($filter & self::FILTER_PRIVATE) && $cal->subtype != 'private') {
continue;
}
if (($filter & self::FILTER_CONFIDENTIAL) && $cal->subtype != 'confidential') {
continue;
}
if ($personal || $shared) {
$ns = $cal->get_namespace();
if (!(($personal && $ns == 'personal') || ($shared && $ns == 'shared'))) {
continue;
}
}
$calendars[$cal->id] = $cal;
}
return $calendars;
}
/**
* Get the kolab_calendar instance for the given calendar ID
*
* @param string Calendar identifier (encoded imap folder name)
*
* @return kolab_calendar Object nor null if calendar doesn't exist
*/
public function get_calendar($id)
{
$this->_read_calendars();
// create calendar object if necesary
if (empty($this->calendars[$id])) {
if (in_array($id, [self::INVITATIONS_CALENDAR_PENDING, self::INVITATIONS_CALENDAR_DECLINED])) {
return new kolab_invitation_calendar($id, $this->cal);
}
// for unsubscribed calendar folders
if ($id !== self::BIRTHDAY_CALENDAR_ID) {
$calendar = kolab_calendar::factory($id, $this->cal);
if ($calendar->ready) {
$this->calendars[$calendar->id] = $calendar;
}
}
}
return !empty($this->calendars[$id]) ? $this->calendars[$id] : null;
}
/**
* Create a new calendar assigned to the current user
*
* @param array Hash array with calendar properties
* name: Calendar name
* color: The color of the calendar
*
* @return mixed ID of the calendar on success, False on error
*/
public function create_calendar($prop)
{
$prop['type'] = 'event';
$prop['active'] = true;
$prop['subscribed'] = true;
$folder = $this->storage->folder_update($prop);
if ($folder === false) {
$this->last_error = $this->cal->gettext($this->storage->last_error);
return false;
}
// create ID
$id = $this->storage->folder_id($folder);
// save color in user prefs (temp. solution)
$prefs['kolab_calendars'] = $this->rc->config->get('kolab_calendars', []);
if (isset($prop['color'])) {
$prefs['kolab_calendars'][$id]['color'] = $prop['color'];
}
if (isset($prop['showalarms'])) {
$prefs['kolab_calendars'][$id]['showalarms'] = !empty($prop['showalarms']);
}
if (!empty($prefs['kolab_calendars'][$id])) {
$this->rc->user->save_prefs($prefs);
}
return $id;
}
/**
* Update properties of an existing calendar
*
* @see calendar_driver::edit_calendar()
*/
public function edit_calendar($prop)
{
if (!empty($prop['id']) && ($cal = $this->get_calendar($prop['id']))) {
$id = $cal->update($prop);
}
else {
$id = $prop['id'];
}
// fallback to local prefs
$prefs['kolab_calendars'] = $this->rc->config->get('kolab_calendars', []);
unset($prefs['kolab_calendars'][$prop['id']]['color'], $prefs['kolab_calendars'][$prop['id']]['showalarms']);
if (isset($prop['color'])) {
$prefs['kolab_calendars'][$id]['color'] = $prop['color'];
}
if (isset($prop['showalarms']) && $id == self::BIRTHDAY_CALENDAR_ID) {
$prefs['calendar_birthdays_alarm_type'] = $prop['showalarms'] ? $this->alarm_types[0] : '';
}
else if (isset($prop['showalarms'])) {
$prefs['kolab_calendars'][$id]['showalarms'] = !empty($prop['showalarms']);
}
if (!empty($prefs['kolab_calendars'][$id])) {
$this->rc->user->save_prefs($prefs);
}
return true;
}
/**
* Set active/subscribed state of a calendar
*
* @see calendar_driver::subscribe_calendar()
*/
public function subscribe_calendar($prop)
{
if (!empty($prop['id']) && ($cal = $this->get_calendar($prop['id'])) && !empty($cal->storage)) {
$ret = false;
if (isset($prop['permanent'])) {
$ret |= $cal->storage->subscribe(intval($prop['permanent']));
}
if (isset($prop['active'])) {
$ret |= $cal->storage->activate(intval($prop['active']));
}
// apply to child folders, too
if (!empty($prop['recursive'])) {
foreach ((array) $this->storage->list_folders($cal->storage->name, '*', 'event') as $subfolder) {
if (isset($prop['permanent'])) {
if ($prop['permanent']) {
$this->storage->folder_subscribe($subfolder);
}
else {
$this->storage->folder_unsubscribe($subfolder);
}
}
if (isset($prop['active'])) {
if ($prop['active']) {
$this->storage->folder_activate($subfolder);
}
else {
$this->storage->folder_deactivate($subfolder);
}
}
}
}
return $ret;
}
else {
// save state in local prefs
$prefs['kolab_calendars'] = $this->rc->config->get('kolab_calendars', []);
$prefs['kolab_calendars'][$prop['id']]['active'] = !empty($prop['active']);
$this->rc->user->save_prefs($prefs);
return true;
}
return false;
}
/**
* Delete the given calendar with all its contents
*
* @see calendar_driver::delete_calendar()
*/
public function delete_calendar($prop)
{
if (!empty($prop['id']) && ($cal = $this->get_calendar($prop['id']))) {
$folder = $cal->get_realname();
// TODO: unsubscribe if no admin rights
if ($this->storage->folder_delete($folder)) {
// remove color in user prefs (temp. solution)
$prefs['kolab_calendars'] = $this->rc->config->get('kolab_calendars', []);
unset($prefs['kolab_calendars'][$prop['id']]);
$this->rc->user->save_prefs($prefs);
return true;
}
else {
$this->last_error = $this->storage->last_error;
}
}
return false;
}
/**
* Search for shared or otherwise not listed calendars the user has access
*
* @param string Search string
* @param string Section/source to search
*
* @return array List of calendars
*/
public function search_calendars($query, $source)
{
if (!$this->storage->setup()) {
return [];
}
$this->calendars = [];
$this->search_more_results = false;
// find unsubscribed IMAP folders that have "event" type
if ($source == 'folders') {
foreach ((array) $this->storage->search_folders('event', $query, ['other']) as $folder) {
$calendar = new kolab_calendar($folder->name, $this->cal);
$this->calendars[$calendar->id] = $calendar;
}
}
// find other user's virtual calendars
else if ($source == 'users') {
// we have slightly more space, so display twice the number
$limit = $this->rc->config->get('autocomplete_max', 15) * 2;
foreach ($this->storage->search_users($query, 0, [], $limit, $count) as $user) {
$calendar = new kolab_user_calendar($user, $this->cal);
$this->calendars[$calendar->id] = $calendar;
// search for calendar folders shared by this user
foreach ($this->storage->list_user_folders($user, 'event', false) as $foldername) {
$cal = new kolab_calendar($foldername, $this->cal);
$this->calendars[$cal->id] = $cal;
$calendar->subscriptions = true;
}
}
if ($count > $limit) {
$this->search_more_results = true;
}
}
// don't list the birthday calendar
$this->rc->config->set('calendar_contact_birthdays', false);
$this->rc->config->set('kolab_invitation_calendars', false);
return $this->list_calendars();
}
/**
* Fetch a single event
*
* @see calendar_driver::get_event()
* @return array Hash array with event properties, false if not found
*/
public function get_event($event, $scope = 0, $full = false)
{
if (is_array($event)) {
$id = !empty($event['id']) ? $event['id'] : $event['uid'];
$cal = $event['calendar'];
// we're looking for a recurring instance: expand the ID to our internal convention for recurring instances
if (empty($event['id']) && !empty($event['_instance'])) {
$id .= '-' . $event['_instance'];
}
}
else {
$id = $event;
}
if (!empty($cal)) {
if ($storage = $this->get_calendar($cal)) {
$result = $storage->get_event($id);
return self::to_rcube_event($result);
}
// get event from the address books birthday calendar
if ($cal == self::BIRTHDAY_CALENDAR_ID) {
return $this->get_birthday_event($id);
}
}
// iterate over all calendar folders and search for the event ID
else {
foreach ($this->filter_calendars($scope) as $calendar) {
if ($result = $calendar->get_event($id)) {
return self::to_rcube_event($result);
}
}
}
return false;
}
/**
* Add a single event to the database
*
* @see calendar_driver::new_event()
*/
public function new_event($event)
{
if (!$this->validate($event)) {
return false;
}
$event = self::from_rcube_event($event);
if (!$event['calendar']) {
$this->_read_calendars();
$cal_ids = array_keys($this->calendars);
$event['calendar'] = reset($cal_ids);
}
if ($storage = $this->get_calendar($event['calendar'])) {
// if this is a recurrence instance, append as exception to an already existing object for this UID
if (!empty($event['recurrence_date']) && ($master = $storage->get_event($event['uid']))) {
self::add_exception($master, $event);
$success = $storage->update_event($master);
}
else {
$success = $storage->insert_event($event);
}
if ($success && $this->freebusy_trigger) {
$this->rc->output->command('plugin.ping_url', ['action' => 'calendar/push-freebusy', 'source' => $storage->id]);
$this->freebusy_trigger = false; // disable after first execution (#2355)
}
return $success;
}
return false;
}
/**
* Update an event entry with the given data
*
* @see calendar_driver::new_event()
* @return bool True on success, False on error
*/
public function edit_event($event)
{
if (!($storage = $this->get_calendar($event['calendar']))) {
return false;
}
return $this->update_event(self::from_rcube_event($event, $storage->get_event($event['id'])));
}
/**
* Extended event editing with possible changes to the argument
*
* @param array Hash array with event properties
* @param string New participant status
* @param array List of hash arrays with updated attendees
*
* @return bool True on success, False on error
*/
public function edit_rsvp(&$event, $status, $attendees)
{
$update_event = $event;
// apply changes to master (and all exceptions)
if ($event['_savemode'] == 'all' && !empty($event['recurrence_id'])) {
if ($storage = $this->get_calendar($event['calendar'])) {
$update_event = $storage->get_event($event['recurrence_id']);
$update_event['_savemode'] = $event['_savemode'];
$update_event['id'] = $update_event['uid'];
unset($update_event['recurrence_id']);
calendar::merge_attendee_data($update_event, $attendees);
}
}
if ($ret = $this->update_attendees($update_event, $attendees)) {
// replace with master event (for iTip reply)
$event = self::to_rcube_event($update_event);
// re-assign to the according (virtual) calendar
if ($this->rc->config->get('kolab_invitation_calendars')) {
if (strtoupper($status) == 'DECLINED') {
$event['calendar'] = self::INVITATIONS_CALENDAR_DECLINED;
}
else if (strtoupper($status) == 'NEEDS-ACTION') {
$event['calendar'] = self::INVITATIONS_CALENDAR_PENDING;
}
else if (!empty($event['_folder_id'])) {
$event['calendar'] = $event['_folder_id'];
}
}
}
return $ret;
}
/**
* Update the participant status for the given attendees
*
* @see calendar_driver::update_attendees()
*/
public function update_attendees(&$event, $attendees)
{
// for this-and-future updates, merge the updated attendees onto all exceptions in range
if (
($event['_savemode'] == 'future' && !empty($event['recurrence_id']))
|| (!empty($event['recurrence']) && empty($event['recurrence_id']))
) {
if (!($storage = $this->get_calendar($event['calendar']))) {
return false;
}
// load master event
$master = !empty($event['recurrence_id']) ? $storage->get_event($event['recurrence_id']) : $event;
// apply attendee update to each existing exception
if (!empty($master['recurrence']) && !empty($master['recurrence']['EXCEPTIONS'])) {
$saved = false;
foreach ($master['recurrence']['EXCEPTIONS'] as $i => $exception) {
// merge the new event properties onto future exceptions
if ($exception['_instance'] >= strval($event['_instance'])) {
calendar::merge_attendee_data($master['recurrence']['EXCEPTIONS'][$i], $attendees);
}
// update a specific instance
if ($exception['_instance'] == $event['_instance'] && $exception['thisandfuture']) {
$saved = true;
}
}
// add the given event as new exception
if (!$saved && $event['id'] != $master['id']) {
$event['thisandfuture'] = true;
$master['recurrence']['EXCEPTIONS'][] = $event;
}
// set link to top-level exceptions
$master['exceptions'] = &$master['recurrence']['EXCEPTIONS'];
return $this->update_event($master);
}
}
// just update the given event (instance)
return $this->update_event($event);
}
/**
* Move a single event
*
* @see calendar_driver::move_event()
* @return boolean True on success, False on error
*/
public function move_event($event)
{
if (($storage = $this->get_calendar($event['calendar'])) && ($ev = $storage->get_event($event['id']))) {
unset($ev['sequence']);
self::clear_attandee_noreply($ev);
return $this->update_event($event + $ev);
}
return false;
}
/**
* Resize a single event
*
* @see calendar_driver::resize_event()
* @return boolean True on success, False on error
*/
public function resize_event($event)
{
if (($storage = $this->get_calendar($event['calendar'])) && ($ev = $storage->get_event($event['id']))) {
unset($ev['sequence']);
self::clear_attandee_noreply($ev);
return $this->update_event($event + $ev);
}
return false;
}
/**
* Remove a single event
*
* @param array Hash array with event properties:
* id: Event identifier
* @param bool Remove record(s) irreversible (mark as deleted otherwise)
*
* @return bool True on success, False on error
*/
public function remove_event($event, $force = true)
{
$ret = true;
$success = false;
$savemode = isset($event['_savemode']) ? $event['_savemode'] : null;
if (!$force) {
unset($event['attendees']);
$this->rc->session->remove('calendar_event_undo');
$this->rc->session->remove('calendar_restore_event_data');
$sess_data = $event;
}
if (($storage = $this->get_calendar($event['calendar'])) && ($event = $storage->get_event($event['id']))) {
$event['_savemode'] = $savemode;
$decline = $event['_decline'];
$savemode = 'all';
$master = $event;
// read master if deleting a recurring event
if (!empty($event['recurrence']) || !empty($event['recurrence_id']) || !empty($event['isexception'])) {
$master = $storage->get_event($event['uid']);
if (!empty($event['_savemode'])) {
$savemode = $event['_savemode'];
}
else if (!empty($event['_instance']) || !empty($event['isexception'])) {
$savemode = 'current';
}
// force 'current' mode for single occurrences stored as exception
if (empty($event['recurrence']) && empty($event['recurrence_id']) && !empty($event['isexception'])) {
$savemode = 'current';
}
}
// removing an exception instance
if ((!empty($event['recurrence_id']) || !empty($event['isexception'])) && !empty($master['exceptions'])) {
foreach ($master['exceptions'] as $i => $exception) {
if ($exception['_instance'] == $event['_instance']) {
unset($master['exceptions'][$i]);
// set event date back to the actual occurrence
if (!empty($exception['recurrence_date'])) {
$event['start'] = $exception['recurrence_date'];
}
}
}
if (!empty($master['recurrence'])) {
$master['recurrence']['EXCEPTIONS'] = &$master['exceptions'];
}
}
switch ($savemode) {
case 'current':
$_SESSION['calendar_restore_event_data'] = $master;
// remove the matching RDATE entry
if (!empty($master['recurrence']['RDATE'])) {
foreach ($master['recurrence']['RDATE'] as $j => $rdate) {
if ($rdate->format('Ymd') == $event['start']->format('Ymd')) {
unset($master['recurrence']['RDATE'][$j]);
break;
}
}
}
// add exception to master event
$master['recurrence']['EXDATE'][] = $event['start'];
$success = $storage->update_event($master);
break;
case 'future':
$master['_instance'] = libcalendaring::recurrence_instance_identifier($master);
if ($master['_instance'] != $event['_instance']) {
$_SESSION['calendar_restore_event_data'] = $master;
// set until-date on master event
$master['recurrence']['UNTIL'] = clone $event['start'];
$master['recurrence']['UNTIL']->sub(new DateInterval('P1D'));
unset($master['recurrence']['COUNT']);
// if all future instances are deleted, remove recurrence rule entirely (bug #1677)
if ($master['recurrence']['UNTIL']->format('Ymd') == $master['start']->format('Ymd')) {
$master['recurrence'] = [];
}
// remove matching RDATE entries
else if (!empty($master['recurrence']['RDATE'])) {
foreach ($master['recurrence']['RDATE'] as $j => $rdate) {
if ($rdate->format('Ymd') == $event['start']->format('Ymd')) {
$master['recurrence']['RDATE'] = array_slice($master['recurrence']['RDATE'], 0, $j);
break;
}
}
}
$success = $storage->update_event($master);
$ret = $master['uid'];
break;
}
default: // 'all' is default
// removing the master event with loose exceptions (not recurring though)
if (!empty($event['recurrence_date']) && empty($master['recurrence']) && !empty($master['exceptions'])) {
// make the first exception the new master
$newmaster = array_shift($master['exceptions']);
$newmaster['exceptions'] = $master['exceptions'];
$newmaster['_attachments'] = $master['_attachments'];
$newmaster['_mailbox'] = $master['_mailbox'];
$newmaster['_msguid'] = $master['_msguid'];
$success = $storage->update_event($newmaster);
}
else if ($decline && $this->rc->config->get('kolab_invitation_calendars')) {
// don't delete but set PARTSTAT=DECLINED
if ($this->cal->lib->set_partstat($master, 'DECLINED')) {
$success = $storage->update_event($master);
}
}
if (!$success) {
$success = $storage->delete_event($master, $force);
}
break;
}
}
if ($success && !$force) {
if (!empty($master['_folder_id'])) {
$sess_data['_folder_id'] = $master['_folder_id'];
}
$_SESSION['calendar_event_undo'] = ['ts' => time(), 'data' => $sess_data];
}
if ($success && $this->freebusy_trigger) {
$this->rc->output->command('plugin.ping_url', [
'action' => 'calendar/push-freebusy',
// _folder_id may be set by invitations calendar
'source' => !empty($master['_folder_id']) ? $master['_folder_id'] : $storage->id,
]);
}
return $success ? $ret : false;
}
/**
* Restore a single deleted event
*
* @param array Hash array with event properties:
* id: Event identifier
* calendar: Event calendar
*
* @return bool True on success, False on error
*/
public function restore_event($event)
{
if ($storage = $this->get_calendar($event['calendar'])) {
if (!empty($_SESSION['calendar_restore_event_data'])) {
$success = $storage->update_event($event = $_SESSION['calendar_restore_event_data']);
}
else {
$success = $storage->restore_event($event);
}
if ($success && $this->freebusy_trigger) {
$this->rc->output->command('plugin.ping_url', [
'action' => 'calendar/push-freebusy',
// _folder_id may be set by invitations calendar
'source' => !empty($event['_folder_id']) ? $event['_folder_id'] : $storage->id,
]);
}
return $success;
}
return false;
}
/**
* Wrapper to update an event object depending on the given savemode
*/
protected function update_event($event)
{
if (!($storage = $this->get_calendar($event['calendar']))) {
return false;
}
// move event to another folder/calendar
if (!empty($event['_fromcalendar']) && $event['_fromcalendar'] != $event['calendar']) {
if (!($fromcalendar = $this->get_calendar($event['_fromcalendar']))) {
return false;
}
$old = $fromcalendar->get_event($event['id']);
if ($event['_savemode'] != 'new') {
if (!$fromcalendar->storage->move($old['uid'], $storage->storage)) {
return false;
}
$fromcalendar = $storage;
}
}
else {
$fromcalendar = $storage;
}
$success = false;
$savemode = 'all';
$attachments = [];
$old = $master = $storage->get_event($event['id']);
if (!$old || empty($old['start'])) {
rcube::raise_error([
'code' => 600, 'file' => __FILE__, 'line' => __LINE__,
'message' => "Failed to load event object to update: id=" . $event['id']
],
true, false
);
return false;
}
// modify a recurring event, check submitted savemode to do the right things
if (!empty($old['recurrence']) || !empty($old['recurrence_id']) || !empty($old['isexception'])) {
$master = $storage->get_event($old['uid']);
if (!empty($event['_savemode'])) {
$savemode = $event['_savemode'];
}
else {
$savemode = (!empty($old['recurrence_id']) || !empty($old['isexception'])) ? 'current' : 'all';
}
// this-and-future on the first instance equals to 'all'
if ($savemode == 'future' && !empty($master['start'])
&& $old['_instance'] == libcalendaring::recurrence_instance_identifier($master)
) {
$savemode = 'all';
}
// force 'current' mode for single occurrences stored as exception
else if (empty($old['recurrence']) && empty($old['recurrence_id']) && !empty($old['isexception'])) {
$savemode = 'current';
}
// Stick to the master timezone for all occurrences (Bifrost#T104637)
$master_tz = $master['start']->getTimezone();
$event_tz = $event['start']->getTimezone();
if ($master_tz->getName() != $event_tz->getName()) {
$event['start']->setTimezone($master_tz);
$event['end']->setTimezone($master_tz);
}
}
// check if update affects scheduling and update attendee status accordingly
$reschedule = $this->check_scheduling($event, $old, true);
// keep saved exceptions (not submitted by the client)
if (!empty($old['recurrence']['EXDATE']) && !isset($event['recurrence']['EXDATE'])) {
$event['recurrence']['EXDATE'] = $old['recurrence']['EXDATE'];
}
if (isset($event['recurrence']['EXCEPTIONS'])) {
// exceptions already provided (e.g. from iCal import)
$with_exceptions = true;
}
else if (!empty($old['recurrence']['EXCEPTIONS'])) {
$event['recurrence']['EXCEPTIONS'] = $old['recurrence']['EXCEPTIONS'];
}
else if (!empty($old['exceptions'])) {
$event['exceptions'] = $old['exceptions'];
}
// remove some internal properties which should not be saved
unset($event['_savemode'], $event['_fromcalendar'], $event['_identity'], $event['_owner'],
$event['_notify'], $event['_method'], $event['_sender'], $event['_sender_utf'], $event['_size']
);
switch ($savemode) {
case 'new':
// save submitted data as new (non-recurring) event
$event['recurrence'] = [];
$event['_copyfrom'] = $master['_msguid'];
$event['_mailbox'] = $master['_mailbox'];
$event['uid'] = $this->cal->generate_uid();
unset($event['recurrence_id'], $event['recurrence_date'], $event['_instance'], $event['id']);
// copy attachment metadata to new event
$event = self::from_rcube_event($event, $master);
self::clear_attandee_noreply($event);
if ($success = $storage->insert_event($event)) {
$success = $event['uid'];
}
break;
case 'future':
// create a new recurring event
$event['_copyfrom'] = $master['_msguid'];
$event['_mailbox'] = $master['_mailbox'];
$event['uid'] = $this->cal->generate_uid();
unset($event['recurrence_id'], $event['recurrence_date'], $event['_instance'], $event['id']);
// copy attachment metadata to new event
$event = self::from_rcube_event($event, $master);
// remove recurrence exceptions on re-scheduling
if ($reschedule) {
unset($event['recurrence']['EXCEPTIONS'], $event['exceptions'], $master['recurrence']['EXDATE']);
}
else if (isset($event['recurrence']['EXCEPTIONS']) && is_array($event['recurrence']['EXCEPTIONS'])) {
// only keep relevant exceptions
$event['recurrence']['EXCEPTIONS'] = array_filter(
$event['recurrence']['EXCEPTIONS'],
function($exception) use ($event) {
return $exception['start'] > $event['start'];
}
);
if (isset($event['recurrence']['EXDATE']) && is_array($event['recurrence']['EXDATE'])) {
$event['recurrence']['EXDATE'] = array_filter(
$event['recurrence']['EXDATE'],
function($exdate) use ($event) {
return $exdate > $event['start'];
}
);
}
// set link to top-level exceptions
$event['exceptions'] = &$event['recurrence']['EXCEPTIONS'];
}
// compute remaining occurrences
if ($event['recurrence']['COUNT']) {
if (empty($old['_count'])) {
$old['_count'] = $this->get_recurrence_count($master, $old['start']);
}
$event['recurrence']['COUNT'] -= intval($old['_count']);
}
// remove fixed weekday when date changed
if ($old['start']->format('Y-m-d') != $event['start']->format('Y-m-d')) {
if (!empty($event['recurrence']['BYDAY']) && strlen($event['recurrence']['BYDAY']) == 2) {
unset($event['recurrence']['BYDAY']);
}
if (!empty($old['recurrence']['BYMONTH']) && $old['recurrence']['BYMONTH'] == $old['start']->format('n')) {
unset($event['recurrence']['BYMONTH']);
}
}
// set until-date on master event
$master['recurrence']['UNTIL'] = clone $old['start'];
$master['recurrence']['UNTIL']->sub(new DateInterval('P1D'));
unset($master['recurrence']['COUNT']);
// remove all exceptions after $event['start']
if (isset($master['recurrence']['EXCEPTIONS']) && is_array($master['recurrence']['EXCEPTIONS'])) {
$master['recurrence']['EXCEPTIONS'] = array_filter(
$master['recurrence']['EXCEPTIONS'],
function($exception) use ($event) {
return $exception['start'] < $event['start'];
}
);
// set link to top-level exceptions
$master['exceptions'] = &$master['recurrence']['EXCEPTIONS'];
}
if (isset($master['recurrence']['EXDATE']) && is_array($master['recurrence']['EXDATE'])) {
$master['recurrence']['EXDATE'] = array_filter(
$master['recurrence']['EXDATE'],
function($exdate) use ($event) {
return $exdate < $event['start'];
}
);
}
// save new event
if ($success = $storage->insert_event($event)) {
$success = $event['uid'];
// update master event (no rescheduling!)
self::clear_attandee_noreply($master);
$storage->update_event($master);
}
break;
case 'current':
// recurring instances shall not store recurrence rules and attachments
$event['recurrence'] = [];
$event['thisandfuture'] = $savemode == 'future';
unset($event['attachments'], $event['id']);
// increment sequence of this instance if scheduling is affected
if ($reschedule) {
$event['sequence'] = max($old['sequence'], $master['sequence']) + 1;
}
else if (!isset($event['sequence'])) {
$event['sequence'] = !empty($old['sequence']) ? $old['sequence'] : $master['sequence'];
}
// save properties to a recurrence exception instance
if (!empty($old['_instance']) && isset($master['recurrence']['EXCEPTIONS'])) {
if ($this->update_recurrence_exceptions($master, $event, $old, $savemode)) {
$success = $storage->update_event($master, $old['id']);
break;
}
}
$add_exception = true;
// adjust matching RDATE entry if dates changed
if (
!empty($master['recurrence']['RDATE'])
&& ($old_date = $old['start']->format('Ymd')) != $event['start']->format('Ymd')
) {
foreach ($master['recurrence']['RDATE'] as $j => $rdate) {
if ($rdate->format('Ymd') == $old_date) {
$master['recurrence']['RDATE'][$j] = $event['start'];
sort($master['recurrence']['RDATE']);
$add_exception = false;
break;
}
}
}
// save as new exception to master event
if ($add_exception) {
self::add_exception($master, $event, $old);
}
$success = $storage->update_event($master);
break;
default: // 'all' is the default
$event['id'] = $master['uid'];
$event['uid'] = $master['uid'];
// use start date from master but try to be smart on time or duration changes
$old_start_date = $old['start']->format('Y-m-d');
$old_start_time = !empty($old['allday']) ? '' : $old['start']->format('H:i');
$old_duration = self::event_duration($old['start'], $old['end'], !empty($old['allday']));
$new_start_date = $event['start']->format('Y-m-d');
$new_start_time = !empty($event['allday']) ? '' : $event['start']->format('H:i');
$new_duration = self::event_duration($event['start'], $event['end'], !empty($event['allday']));
$diff = $old_start_date != $new_start_date || $old_start_time != $new_start_time || $old_duration != $new_duration;
$date_shift = $old['start']->diff($event['start']);
// shifted or resized
if ($diff && ($old_start_date == $new_start_date || $old_duration == $new_duration)) {
$event['start'] = $master['start']->add($date_shift);
$event['end'] = clone $event['start'];
$event['end']->add(new DateInterval($new_duration));
// remove fixed weekday, will be re-set to the new weekday in kolab_calendar::update_event()
if ($old_start_date != $new_start_date && !empty($event['recurrence'])) {
if (!empty($event['recurrence']['BYDAY']) && strlen($event['recurrence']['BYDAY']) == 2)
unset($event['recurrence']['BYDAY']);
if (!empty($old['recurrence']['BYMONTH']) && $old['recurrence']['BYMONTH'] == $old['start']->format('n'))
unset($event['recurrence']['BYMONTH']);
}
}
// dates did not change, use the ones from master
else if ($new_start_date . $new_start_time == $old_start_date . $old_start_time) {
$event['start'] = $master['start'];
$event['end'] = $master['end'];
}
// when saving an instance in 'all' mode, copy recurrence exceptions over
if (!empty($old['recurrence_id'])) {
$event['recurrence']['EXCEPTIONS'] = $master['recurrence']['EXCEPTIONS'];
$event['recurrence']['EXDATE'] = $master['recurrence']['EXDATE'];
}
else if (!empty($master['_instance'])) {
$event['_instance'] = $master['_instance'];
$event['recurrence_date'] = $master['recurrence_date'];
}
// TODO: forward changes to exceptions (which do not yet have differing values stored)
if (!empty($event['recurrence']) && !empty($event['recurrence']['EXCEPTIONS']) && !$with_exceptions) {
// determine added and removed attendees
$old_attendees = $current_attendees = $added_attendees = [];
if (!empty($old['attendees'])) {
foreach ((array) $old['attendees'] as $attendee) {
$old_attendees[] = $attendee['email'];
}
}
if (!empty($event['attendees'])) {
foreach ((array) $event['attendees'] as $attendee) {
$current_attendees[] = $attendee['email'];
if (!in_array($attendee['email'], $old_attendees)) {
$added_attendees[] = $attendee;
}
}
}
$removed_attendees = array_diff($old_attendees, $current_attendees);
foreach ($event['recurrence']['EXCEPTIONS'] as $i => $exception) {
calendar::merge_attendee_data($event['recurrence']['EXCEPTIONS'][$i], $added_attendees, $removed_attendees);
}
// adjust recurrence-id when start changed and therefore the entire recurrence chain changes
if ($old_start_date != $new_start_date || $old_start_time != $new_start_time) {
$recurrence_id_format = libcalendaring::recurrence_id_format($event);
foreach ($event['recurrence']['EXCEPTIONS'] as $i => $exception) {
- if (isset($exception['recurrence_date']) && is_a($exception['recurrence_date'], 'DateTime')) {
+ if (isset($exception['recurrence_date']) && $exception['recurrence_date'] instanceof DateTimeInterface) {
$recurrence_id = $exception['recurrence_date'];
}
else {
$recurrence_id = rcube_utils::anytodatetime($exception['_instance'], $old['start']->getTimezone());
}
if ($recurrence_id instanceof DateTimeInterface) {
$recurrence_id->add($date_shift);
$event['recurrence']['EXCEPTIONS'][$i]['recurrence_date'] = $recurrence_id;
$event['recurrence']['EXCEPTIONS'][$i]['_instance'] = $recurrence_id->format($recurrence_id_format);
}
}
}
// set link to top-level exceptions
$event['exceptions'] = &$event['recurrence']['EXCEPTIONS'];
}
// unset _dateonly flags in (cached) date objects
unset($event['start']->_dateonly, $event['end']->_dateonly);
$success = $storage->update_event($event) ? $event['id'] : false; // return master UID
break;
}
if ($success && $this->freebusy_trigger) {
$this->rc->output->command('plugin.ping_url', [
'action' => 'calendar/push-freebusy',
'source' => $storage->id
]);
}
return $success;
}
/**
* Calculate event duration, returns string in DateInterval format
*/
protected static function event_duration($start, $end, $allday = false)
{
if ($allday) {
$diff = $start->diff($end);
return 'P' . $diff->days . 'D';
}
return 'PT' . ($end->format('U') - $start->format('U')) . 'S';
}
/**
* Determine whether the current change affects scheduling and reset attendee status accordingly
*/
public function check_scheduling(&$event, $old, $update = true)
{
// skip this check when importing iCal/iTip events
if (isset($event['sequence']) || !empty($event['_method'])) {
return false;
}
// iterate through the list of properties considered 'significant' for scheduling
$kolab_event = !empty($old['_formatobj']) ? $old['_formatobj'] : new kolab_format_event();
$reschedule = $kolab_event->check_rescheduling($event, $old);
// reset all attendee status to needs-action (#4360)
if ($update && $reschedule && !empty($event['attendees'])) {
$is_organizer = false;
$emails = $this->cal->get_user_emails();
$attendees = $event['attendees'];
foreach ($attendees as $i => $attendee) {
if ($attendee['role'] == 'ORGANIZER'
&& !empty($attendee['email'])
&& in_array(strtolower($attendee['email']), $emails)
) {
$is_organizer = true;
}
else if ($attendee['role'] != 'ORGANIZER'
&& $attendee['role'] != 'NON-PARTICIPANT'
&& $attendee['status'] != 'DELEGATED'
) {
$attendees[$i]['status'] = 'NEEDS-ACTION';
$attendees[$i]['rsvp'] = true;
}
}
// update attendees only if I'm the organizer
if ($is_organizer || (!empty($event['organizer']) && in_array(strtolower($event['organizer']['email']), $emails))) {
$event['attendees'] = $attendees;
}
}
return $reschedule;
}
/**
* Apply the given changes to already existing exceptions
*/
protected function update_recurrence_exceptions(&$master, $event, $old, $savemode)
{
$saved = false;
$existing = null;
// determine added and removed attendees
$added_attendees = $removed_attendees = [];
if ($savemode == 'future') {
$old_attendees = $current_attendees = [];
if (!empty($old['attendees'])) {
foreach ((array) $old['attendees'] as $attendee) {
$old_attendees[] = $attendee['email'];
}
}
if (!empty($event['attendees'])) {
foreach ((array) $event['attendees'] as $attendee) {
$current_attendees[] = $attendee['email'];
if (!in_array($attendee['email'], $old_attendees)) {
$added_attendees[] = $attendee;
}
}
}
$removed_attendees = array_diff($old_attendees, $current_attendees);
}
foreach ($master['recurrence']['EXCEPTIONS'] as $i => $exception) {
// update a specific instance
if ($exception['_instance'] == $old['_instance']) {
$existing = $i;
// check savemode against existing exception mode.
// if matches, we can update this existing exception
$thisandfuture = !empty($exception['thisandfuture']);
if ($thisandfuture === ($savemode == 'future')) {
$event['_instance'] = $old['_instance'];
$event['thisandfuture'] = $old['thisandfuture'];
$event['recurrence_date'] = $old['recurrence_date'];
$master['recurrence']['EXCEPTIONS'][$i] = $event;
$saved = true;
}
}
// merge the new event properties onto future exceptions
if ($savemode == 'future' && $exception['_instance'] >= $old['_instance']) {
unset($event['thisandfuture']);
self::merge_exception_data($master['recurrence']['EXCEPTIONS'][$i], $event, ['attendees']);
if (!empty($added_attendees) || !empty($removed_attendees)) {
calendar::merge_attendee_data($master['recurrence']['EXCEPTIONS'][$i], $added_attendees, $removed_attendees);
}
}
}
/*
// we could not update the existing exception due to savemode mismatch...
if (!$saved && isset($existing) && !empty($master['recurrence']['EXCEPTIONS'][$existing]['thisandfuture'])) {
// ... try to move the existing this-and-future exception to the next occurrence
foreach ($this->get_recurring_events($master, $existing['start']) as $candidate) {
// our old this-and-future exception is obsolete
if (!empty($candidate['thisandfuture'])) {
unset($master['recurrence']['EXCEPTIONS'][$existing]);
$saved = true;
break;
}
// this occurrence doesn't yet have an exception
else if (empty($candidate['isexception'])) {
$event['_instance'] = $candidate['_instance'];
$event['recurrence_date'] = $candidate['recurrence_date'];
$master['recurrence']['EXCEPTIONS'][$i] = $event;
$saved = true;
break;
}
}
}
*/
// set link to top-level exceptions
$master['exceptions'] = &$master['recurrence']['EXCEPTIONS'];
// returning false here will add a new exception
return $saved;
}
/**
* Add or update the given event as an exception to $master
*/
public static function add_exception(&$master, $event, $old = null)
{
if ($old) {
$event['_instance'] = $old['_instance'];
if (empty($event['recurrence_date'])) {
$event['recurrence_date'] = !empty($old['recurrence_date']) ? $old['recurrence_date'] : $old['start'];
}
}
else if (empty($event['recurrence_date'])) {
$event['recurrence_date'] = $event['start'];
}
- if (empty($event['_instance']) && is_a($event['recurrence_date'], 'DateTime')) {
+ if (empty($event['_instance']) && $event['recurrence_date'] instanceof DateTimeInterface) {
$event['_instance'] = libcalendaring::recurrence_instance_identifier($event, !empty($master['allday']));
}
if (!is_array($master['exceptions']) && isset($master['recurrence']['EXCEPTIONS'])) {
$master['exceptions'] = &$master['recurrence']['EXCEPTIONS'];
}
$existing = false;
foreach ((array) $master['exceptions'] as $i => $exception) {
if ($exception['_instance'] == $event['_instance']) {
$master['exceptions'][$i] = $event;
$existing = true;
}
}
if (!$existing) {
$master['exceptions'][] = $event;
}
return true;
}
/**
* Remove the noreply flags from attendees
*/
public static function clear_attandee_noreply(&$event)
{
if (!empty($event['attendees'])) {
foreach ((array) $event['attendees'] as $i => $attendee) {
unset($event['attendees'][$i]['noreply']);
}
}
}
/**
* Merge certain properties from the overlay event to the base event object
*
* @param array The event object to be altered
* @param array The overlay event object to be merged over $event
* @param array List of properties not allowed to be overwritten
*/
public static function merge_exception_data(&$event, $overlay, $blacklist = null)
{
$forbidden = ['id','uid','recurrence','recurrence_date','thisandfuture','organizer','_attachments'];
if (is_array($blacklist)) {
$forbidden = array_merge($forbidden, $blacklist);
}
foreach ($overlay as $prop => $value) {
if ($prop == 'start' || $prop == 'end') {
// handled by merge_exception_dates() below
}
else if ($prop == 'thisandfuture' && $overlay['_instance'] == $event['_instance']) {
$event[$prop] = $value;
}
else if ($prop[0] != '_' && !in_array($prop, $forbidden)) {
$event[$prop] = $value;
}
}
self::merge_exception_dates($event, $overlay);
}
/**
* Merge start/end date from the overlay event to the base event object
*
* @param array The event object to be altered
* @param array The overlay event object to be merged over $event
*/
public static function merge_exception_dates(&$event, $overlay)
{
// compute date offset from the exception
if ($overlay['start'] instanceof DateTimeInterface && $overlay['recurrence_date'] instanceof DateTimeInterface) {
$date_offset = $overlay['recurrence_date']->diff($overlay['start']);
}
foreach (['start', 'end'] as $prop) {
$value = $overlay[$prop];
if (isset($event[$prop]) && $event[$prop] instanceof DateTimeInterface) {
// set date value if overlay is an exception of the current instance
if (substr($overlay['_instance'], 0, 8) == substr($event['_instance'], 0, 8)) {
$event[$prop]->setDate(intval($value->format('Y')), intval($value->format('n')), intval($value->format('j')));
}
// apply date offset
else if (!empty($date_offset)) {
$event[$prop]->add($date_offset);
}
// adjust time of the recurring event instance
$event[$prop]->setTime($value->format('G'), intval($value->format('i')), intval($value->format('s')));
}
}
}
/**
* Get events from source.
*
* @param int Event's new start (unix timestamp)
* @param int Event's new end (unix timestamp)
* @param string Search query (optional)
* @param mixed List of calendar IDs to load events from (either as array or comma-separated string)
* @param bool Include virtual events (optional)
* @param int Only list events modified since this time (unix timestamp)
*
* @return array A list of event records
*/
public function load_events($start, $end, $search = null, $calendars = null, $virtual = 1, $modifiedsince = null)
{
if ($calendars && is_string($calendars)) {
$calendars = explode(',', $calendars);
}
else if (!$calendars) {
$this->_read_calendars();
$calendars = array_keys($this->calendars);
}
$query = [];
$events = [];
$categories = [];
if ($modifiedsince) {
$query[] = ['changed', '>=', $modifiedsince];
}
foreach ($calendars as $cid) {
if ($storage = $this->get_calendar($cid)) {
$events = array_merge($events, $storage->list_events($start, $end, $search, $virtual, $query));
$categories += $storage->categories;
}
}
// add events from the address books birthday calendar
if (in_array(self::BIRTHDAY_CALENDAR_ID, $calendars)) {
$events = array_merge($events, $this->load_birthday_events($start, $end, $search, $modifiedsince));
}
// add new categories to user prefs
$old_categories = $this->rc->config->get('calendar_categories', $this->default_categories);
$newcats = array_udiff(
array_keys($categories),
array_keys($old_categories),
function($a, $b) { return strcasecmp($a, $b); }
);
if (!empty($newcats)) {
foreach ($newcats as $category) {
$old_categories[$category] = ''; // no color set yet
}
$this->rc->user->save_prefs(['calendar_categories' => $old_categories]);
}
array_walk($events, 'kolab_driver::to_rcube_event');
return $events;
}
/**
* Get number of events in the given calendar
*
* @param mixed List of calendar IDs to count events (either as array or comma-separated string)
* @param int Date range start (unix timestamp)
* @param int Date range end (unix timestamp)
*
* @return array Hash array with counts grouped by calendar ID
*/
public function count_events($calendars, $start, $end = null)
{
$counts = [];
if ($calendars && is_string($calendars)) {
$calendars = explode(',', $calendars);
}
else if (!$calendars) {
$this->_read_calendars();
$calendars = array_keys($this->calendars);
}
foreach ($calendars as $cid) {
if ($storage = $this->get_calendar($cid)) {
$counts[$cid] = $storage->count_events($start, $end);
}
}
return $counts;
}
/**
* Get a list of pending alarms to be displayed to the user
*
* @see calendar_driver::pending_alarms()
*/
public function pending_alarms($time, $calendars = null)
{
$interval = 300;
$time -= $time % 60;
$slot = $time;
$slot -= $slot % $interval;
$last = $time - max(60, $this->rc->config->get('refresh_interval', 0));
$last -= $last % $interval;
// only check for alerts once in 5 minutes
if ($last == $slot) {
return [];
}
if ($calendars && is_string($calendars)) {
$calendars = explode(',', $calendars);
}
$time = $slot + $interval;
$alarms = [];
$candidates = [];
$query = [['tags', '=', 'x-has-alarms']];
$this->_read_calendars();
foreach ($this->calendars as $cid => $calendar) {
// skip calendars with alarms disabled
if (!$calendar->alarms || ($calendars && !in_array($cid, $calendars))) {
continue;
}
foreach ($calendar->list_events($time, $time + 86400 * 365, null, 1, $query) as $e) {
// add to list if alarm is set
$alarm = libcalendaring::get_next_alarm($e);
if ($alarm && !empty($alarm['time']) && $alarm['time'] >= $last
&& in_array($alarm['action'], $this->alarm_types)
) {
$id = $alarm['id']; // use alarm-id as primary identifier
$candidates[$id] = [
'id' => $id,
'title' => $e['title'],
'location' => $e['location'],
'start' => $e['start'],
'end' => $e['end'],
'notifyat' => $alarm['time'],
'action' => $alarm['action'],
];
}
}
}
// get alarm information stored in local database
if (!empty($candidates)) {
$dbdata = [];
$alarm_ids = array_map([$this->rc->db, 'quote'], array_keys($candidates));
$result = $this->rc->db->query("SELECT *"
. " FROM " . $this->rc->db->table_name('kolab_alarms', true)
. " WHERE `alarm_id` IN (" . join(',', $alarm_ids) . ")"
. " AND `user_id` = ?",
$this->rc->user->ID
);
while ($result && ($e = $this->rc->db->fetch_assoc($result))) {
$dbdata[$e['alarm_id']] = $e;
}
foreach ($candidates as $id => $alarm) {
// skip dismissed alarms
if ($dbdata[$id]['dismissed']) {
continue;
}
// snooze function may have shifted alarm time
$notifyat = $dbdata[$id]['notifyat'] ? strtotime($dbdata[$id]['notifyat']) : $alarm['notifyat'];
if ($notifyat <= $time) {
$alarms[] = $alarm;
}
}
}
return $alarms;
}
/**
* Feedback after showing/sending an alarm notification
*
* @see calendar_driver::dismiss_alarm()
*/
public function dismiss_alarm($alarm_id, $snooze = 0)
{
$alarms_table = $this->rc->db->table_name('kolab_alarms', true);
// delete old alarm entry
$this->rc->db->query("DELETE FROM $alarms_table"
. " WHERE `alarm_id` = ? AND `user_id` = ?",
$alarm_id,
$this->rc->user->ID
);
// set new notifyat time or unset if not snoozed
$notifyat = $snooze > 0 ? date('Y-m-d H:i:s', time() + $snooze) : null;
$query = $this->rc->db->query("INSERT INTO $alarms_table"
. " (`alarm_id`, `user_id`, `dismissed`, `notifyat`)"
. " VALUES (?, ?, ?, ?)",
$alarm_id,
$this->rc->user->ID,
$snooze > 0 ? 0 : 1,
$notifyat
);
return $this->rc->db->affected_rows($query);
}
/**
* List attachments from the given event
*/
public function list_attachments($event)
{
if (!($storage = $this->get_calendar($event['calendar']))) {
return false;
}
$event = $storage->get_event($event['id']);
return $event['attachments'];
}
/**
* Get attachment properties
*/
public function get_attachment($id, $event)
{
if (!($storage = $this->get_calendar($event['calendar']))) {
return false;
}
// get old revision of event
if (!empty($event['rev'])) {
$event = $this->get_event_revison($event, $event['rev'], true);
}
else {
$event = $storage->get_event($event['id']);
}
if ($event) {
$attachments = isset($event['_attachments']) ? $event['_attachments'] : $event['attachments'];
foreach ((array) $attachments as $att) {
if ($att['id'] == $id) {
return $att;
}
}
}
}
/**
* Get attachment body
* @see calendar_driver::get_attachment_body()
*/
public function get_attachment_body($id, $event)
{
if (!($cal = $this->get_calendar($event['calendar']))) {
return false;
}
// get old revision of event
if (!empty($event['rev'])) {
if (empty($this->bonnie_api)) {
return false;
}
$cid = substr($id, 4);
// call Bonnie API and get the raw mime message
list($uid, $mailbox, $msguid) = $this->_resolve_event_identity($event);
if ($msg_raw = $this->bonnie_api->rawdata('event', $uid, $event['rev'], $mailbox, $msguid)) {
// parse the message and find the part with the matching content-id
$message = rcube_mime::parse_message($msg_raw);
foreach ((array) $message->parts as $part) {
if (!empty($part->headers['content-id']) && trim($part->headers['content-id'], '<>') == $cid) {
return $part->body;
}
}
}
return false;
}
return $cal->get_attachment_body($id, $event);
}
/**
* Build a struct representing the given message reference
*
* @see calendar_driver::get_message_reference()
*/
public function get_message_reference($uri_or_headers, $folder = null)
{
if (is_object($uri_or_headers)) {
$uri_or_headers = kolab_storage_config::get_message_uri($uri_or_headers, $folder);
}
if (is_string($uri_or_headers)) {
return kolab_storage_config::get_message_reference($uri_or_headers, 'event');
}
return false;
}
/**
* List availabale categories
* The default implementation reads them from config/user prefs
*/
public function list_categories()
{
// FIXME: complete list with categories saved in config objects (KEP:12)
return $this->rc->config->get('calendar_categories', $this->default_categories);
}
/**
* Create instances of a recurring event
*
* @param array Hash array with event properties
* @param DateTime Start date of the recurrence window
* @param DateTime End date of the recurrence window
*
* @return array List of recurring event instances
*/
public function get_recurring_events($event, $start, $end = null)
{
// load the given event data into a libkolabxml container
if (empty($event['_formatobj'])) {
$event_xml = new kolab_format_event();
$event_xml->set($event);
$event['_formatobj'] = $event_xml;
}
$this->_read_calendars();
$storage = reset($this->calendars);
return $storage->get_recurring_events($event, $start, $end);
}
/**
*
*/
protected function get_recurrence_count($event, $dtstart)
{
// load the given event data into a libkolabxml container
if (empty($event['_formatobj'])) {
$event_xml = new kolab_format_event();
$event_xml->set($event);
$event['_formatobj'] = $event_xml;
}
// use libkolab to compute recurring events
$recurrence = new kolab_date_recurrence($event['_formatobj']);
$count = 0;
while (($next_event = $recurrence->next_instance()) && $next_event['start'] <= $dtstart && $count < 1000) {
$count++;
}
return $count;
}
/**
* Fetch free/busy information from a person within the given range
*/
public function get_freebusy_list($email, $start, $end)
{
if (empty($email)/* || $end < time()*/) {
return false;
}
// map vcalendar fbtypes to internal values
$fbtypemap = [
'FREE' => calendar::FREEBUSY_FREE,
'BUSY-TENTATIVE' => calendar::FREEBUSY_TENTATIVE,
'X-OUT-OF-OFFICE' => calendar::FREEBUSY_OOF,
'OOF' => calendar::FREEBUSY_OOF
];
// ask kolab server first
try {
$request_config = [
'store_body' => true,
'follow_redirects' => true,
];
$request = libkolab::http_request($this->storage->get_freebusy_url($email), 'GET', $request_config);
$response = $request->send();
// authentication required
if ($response->getStatus() == 401) {
$request->setAuth($this->rc->user->get_username(), $this->rc->decrypt($_SESSION['password']));
$response = $request->send();
}
if ($response->getStatus() == 200) {
$fbdata = $response->getBody();
}
unset($request, $response);
}
catch (Exception $e) {
PEAR::raiseError("Error fetching free/busy information: " . $e->getMessage());
}
// get free-busy url from contacts
if (empty($fbdata)) {
$fburl = null;
foreach ((array) $this->rc->config->get('autocomplete_addressbooks', 'sql') as $book) {
$abook = $this->rc->get_address_book($book);
if ($result = $abook->search(['email'], $email, true, true, true/*, 'freebusyurl'*/)) {
while ($contact = $result->iterate()) {
if (!empty($contact['freebusyurl'])) {
$fbdata = @file_get_contents($contact['freebusyurl']);
break;
}
}
}
if (!empty($fbdata)) {
break;
}
}
}
// parse free-busy information using Horde classes
if (!empty($fbdata)) {
$ical = $this->cal->get_ical();
$ical->import($fbdata);
if ($fb = $ical->freebusy) {
$result = [];
foreach ($fb['periods'] as $tuple) {
list($from, $to, $type) = $tuple;
$result[] = [
$from->format('U'),
$to->format('U'),
isset($fbtypemap[$type]) ? $fbtypemap[$type] : calendar::FREEBUSY_BUSY
];
}
// we take 'dummy' free-busy lists as "unknown"
if (empty($result) && !empty($fb['comment']) && stripos($fb['comment'], 'dummy')) {
return false;
}
// set period from $start till the begin of the free-busy information as 'unknown'
if (!empty($fb['start']) && ($fbstart = $fb['start']->format('U')) && $start < $fbstart) {
array_unshift($result, [$start, $fbstart, calendar::FREEBUSY_UNKNOWN]);
}
// pad period till $end with status 'unknown'
if (!empty($fb['end']) && ($fbend = $fb['end']->format('U')) && $fbend < $end) {
$result[] = [$fbend, $end, calendar::FREEBUSY_UNKNOWN];
}
return $result;
}
}
return false;
}
/**
* Handler to push folder triggers when sent from client.
* Used to push free-busy changes asynchronously after updating an event
*/
public function push_freebusy()
{
// make shure triggering completes
set_time_limit(0);
ignore_user_abort(true);
$cal = rcube_utils::get_input_value('source', rcube_utils::INPUT_GPC);
if (!($cal = $this->get_calendar($cal))) {
return false;
}
// trigger updates on folder
$trigger = $cal->storage->trigger();
if (is_object($trigger) && is_a($trigger, 'PEAR_Error')) {
rcube::raise_error([
'code' => 900, 'file' => __FILE__, 'line' => __LINE__,
'message' => "Failed triggering folder. Error was " . $trigger->getMessage()
],
true, false
);
}
exit;
}
/**
* Convert from driver format to external caledar app data
*/
public static function to_rcube_event(&$record)
{
if (!is_array($record)) {
return $record;
}
$record['id'] = $record['uid'];
if (!empty($record['_instance'])) {
$record['id'] .= '-' . $record['_instance'];
if (empty($record['recurrence_id']) && !empty($record['recurrence'])) {
$record['recurrence_id'] = $record['uid'];
}
}
// all-day events go from 12:00 - 13:00
- if (is_a($record['start'], 'DateTime') && $record['end'] <= $record['start'] && !empty($record['allday'])) {
+ if ($record['start'] instanceof DateTimeInterface && $record['end'] <= $record['start'] && !empty($record['allday'])) {
$record['end'] = clone $record['start'];
$record['end']->add(new DateInterval('PT1H'));
}
// translate internal '_attachments' to external 'attachments' list
if (!empty($record['_attachments'])) {
foreach ($record['_attachments'] as $key => $attachment) {
if ($attachment !== false) {
if (empty($attachment['name'])) {
$attachment['name'] = $key;
}
unset($attachment['path'], $attachment['content']);
$attachments[] = $attachment;
}
}
$record['attachments'] = $attachments;
}
if (!empty($record['attendees'])) {
foreach ((array) $record['attendees'] as $i => $attendee) {
if (isset($attendee['delegated-from']) && is_array($attendee['delegated-from'])) {
$record['attendees'][$i]['delegated-from'] = join(', ', $attendee['delegated-from']);
}
if (isset($attendee['delegated-to']) && is_array($attendee['delegated-to'])) {
$record['attendees'][$i]['delegated-to'] = join(', ', $attendee['delegated-to']);
}
}
}
// Roundcube only supports one category assignment
if (!empty($record['categories']) && is_array($record['categories'])) {
$record['categories'] = $record['categories'][0];
}
// the cancelled flag transltes into status=CANCELLED
if (!empty($record['cancelled'])) {
$record['status'] = 'CANCELLED';
}
// The web client only supports DISPLAY type of alarms
if (!empty($record['alarms'])) {
$record['alarms'] = preg_replace('/:[A-Z]+$/', ':DISPLAY', $record['alarms']);
}
// remove empty recurrence array
if (empty($record['recurrence'])) {
unset($record['recurrence']);
}
// clean up exception data
else if (!empty($record['recurrence']['EXCEPTIONS'])) {
array_walk($record['recurrence']['EXCEPTIONS'], function(&$exception) {
unset($exception['_mailbox'], $exception['_msguid'],
$exception['_formatobj'], $exception['_attachments']
);
});
}
unset($record['_mailbox'], $record['_msguid'], $record['_type'], $record['_size'],
$record['_formatobj'], $record['_attachments'], $record['exceptions'], $record['x-custom']
);
return $record;
}
/**
*
*/
public static function from_rcube_event($event, $old = [])
{
kolab_format::merge_attachments($event, $old);
return $event;
}
/**
* Set CSS class according to the event's attendde partstat
*/
public static function add_partstat_class($event, $partstats, $user = null)
{
// set classes according to PARTSTAT
if (!empty($event['attendees'])) {
$user_emails = libcalendaring::get_instance()->get_user_emails($user);
$partstat = 'UNKNOWN';
foreach ($event['attendees'] as $attendee) {
if (in_array($attendee['email'], $user_emails)) {
$partstat = $attendee['status'];
break;
}
}
if (in_array($partstat, $partstats)) {
$event['className'] = trim($event['className'] . ' fc-invitation-' . strtolower($partstat));
}
}
return $event;
}
/**
* Provide a list of revisions for the given event
*
* @param array $event Hash array with event properties
*
* @return array List of changes, each as a hash array
* @see calendar_driver::get_event_changelog()
*/
public function get_event_changelog($event)
{
if (empty($this->bonnie_api)) {
return false;
}
list($uid, $mailbox, $msguid) = $this->_resolve_event_identity($event);
$result = $this->bonnie_api->changelog('event', $uid, $mailbox, $msguid);
if (is_array($result) && $result['uid'] == $uid) {
return $result['changes'];
}
return false;
}
/**
* Get a list of property changes beteen two revisions of an event
*
* @param array $event Hash array with event properties
* @param mixed $rev1 Old Revision
* @param mixed $rev2 New Revision
*
* @return array List of property changes, each as a hash array
* @see calendar_driver::get_event_diff()
*/
public function get_event_diff($event, $rev1, $rev2)
{
if (empty($this->bonnie_api)) {
return false;
}
list($uid, $mailbox, $msguid) = $this->_resolve_event_identity($event);
// get diff for the requested recurrence instance
$instance_id = $event['id'] != $uid ? substr($event['id'], strlen($uid) + 1) : null;
// call Bonnie API
$result = $this->bonnie_api->diff('event', $uid, $rev1, $rev2, $mailbox, $msguid, $instance_id);
if (is_array($result) && $result['uid'] == $uid) {
$result['rev1'] = $rev1;
$result['rev2'] = $rev2;
$keymap = [
'dtstart' => 'start',
'dtend' => 'end',
'dstamp' => 'changed',
'summary' => 'title',
'alarm' => 'alarms',
'attendee' => 'attendees',
'attach' => 'attachments',
'rrule' => 'recurrence',
'transparency' => 'free_busy',
'lastmodified-date' => 'changed',
];
$prop_keymaps = [
'attachments' => ['fmttype' => 'mimetype', 'label' => 'name'],
'attendees' => ['partstat' => 'status'],
];
$special_changes = [];
// map kolab event properties to keys the client expects
array_walk($result['changes'], function(&$change, $i) use ($keymap, $prop_keymaps, $special_changes) {
if (array_key_exists($change['property'], $keymap)) {
$change['property'] = $keymap[$change['property']];
}
// translate free_busy values
if ($change['property'] == 'free_busy') {
$change['old'] = !empty($old['old']) ? 'free' : 'busy';
$change['new'] = !empty($old['new']) ? 'free' : 'busy';
}
// map alarms trigger value
if ($change['property'] == 'alarms') {
if (!empty($change['old']['trigger'])) {
$change['old']['trigger'] = $change['old']['trigger']['value'];
}
if (!empty($change['new']['trigger'])) {
$change['new']['trigger'] = $change['new']['trigger']['value'];
}
}
// make all property keys uppercase
if ($change['property'] == 'recurrence') {
$special_changes['recurrence'] = $i;
foreach (['old', 'new'] as $m) {
if (!empty($change[$m])) {
$props = [];
foreach ($change[$m] as $k => $v) {
$props[strtoupper($k)] = $v;
}
$change[$m] = $props;
}
}
}
// map property keys names
if (!empty($prop_keymaps[$change['property']])) {
foreach ($prop_keymaps[$change['property']] as $k => $dest) {
if (!empty($change['old']) && array_key_exists($k, $change['old'])) {
$change['old'][$dest] = $change['old'][$k];
unset($change['old'][$k]);
}
if (!empty($change['new']) && array_key_exists($k, $change['new'])) {
$change['new'][$dest] = $change['new'][$k];
unset($change['new'][$k]);
}
}
}
if ($change['property'] == 'exdate') {
$special_changes['exdate'] = $i;
}
else if ($change['property'] == 'rdate') {
$special_changes['rdate'] = $i;
}
});
// merge some recurrence changes
foreach (['exdate', 'rdate'] as $prop) {
if (array_key_exists($prop, $special_changes)) {
$exdate = $result['changes'][$special_changes[$prop]];
if (array_key_exists('recurrence', $special_changes)) {
$recurrence = &$result['changes'][$special_changes['recurrence']];
}
else {
$i = count($result['changes']);
$result['changes'][$i] = ['property' => 'recurrence', 'old' => [], 'new' => []];
$recurrence = &$result['changes'][$i]['recurrence'];
}
$key = strtoupper($prop);
$recurrence['old'][$key] = $exdate['old'];
$recurrence['new'][$key] = $exdate['new'];
unset($result['changes'][$special_changes[$prop]]);
}
}
return $result;
}
return false;
}
/**
* Return full data of a specific revision of an event
*
* @param array Hash array with event properties
* @param mixed $rev Revision number
*
* @return array Event object as hash array
* @see calendar_driver::get_event_revison()
*/
public function get_event_revison($event, $rev, $internal = false)
{
if (empty($this->bonnie_api)) {
return false;
}
$eventid = $event['id'];
$calid = $event['calendar'];
list($uid, $mailbox, $msguid) = $this->_resolve_event_identity($event);
// call Bonnie API
$result = $this->bonnie_api->get('event', $uid, $rev, $mailbox, $msguid);
if (is_array($result) && $result['uid'] == $uid && !empty($result['xml'])) {
$format = kolab_format::factory('event');
$format->load($result['xml']);
$event = $format->to_array();
$format->get_attachments($event, true);
// get the right instance from a recurring event
if ($eventid != $event['uid']) {
$instance_id = substr($eventid, strlen($event['uid']) + 1);
// check for recurrence exception first
if ($instance = $format->get_instance($instance_id)) {
$event = $instance;
}
else {
// not a exception, compute recurrence...
$event['_formatobj'] = $format;
$recurrence_date = rcube_utils::anytodatetime($instance_id, $event['start']->getTimezone());
foreach ($this->get_recurring_events($event, $event['start'], $recurrence_date) as $instance) {
if ($instance['id'] == $eventid) {
$event = $instance;
break;
}
}
}
}
if ($format->is_valid()) {
$event['calendar'] = $calid;
$event['rev'] = $result['rev'];
return $internal ? $event : self::to_rcube_event($event);
}
}
return false;
}
/**
* Command the backend to restore a certain revision of an event.
* This shall replace the current event with an older version.
*
* @param mixed $event UID string or hash array with event properties:
* id: Event identifier
* calendar: Calendar identifier
* @param mixed $rev Revision number
*
* @return bool True on success, False on failure
*/
public function restore_event_revision($event, $rev)
{
if (empty($this->bonnie_api)) {
return false;
}
list($uid, $mailbox, $msguid) = $this->_resolve_event_identity($event);
$calendar = $this->get_calendar($event['calendar']);
$success = false;
if ($calendar && $calendar->storage && $calendar->editable) {
if ($raw_msg = $this->bonnie_api->rawdata('event', $uid, $rev, $mailbox)) {
$imap = $this->rc->get_storage();
// insert $raw_msg as new message
if ($imap->save_message($calendar->storage->name, $raw_msg, null, false)) {
$success = true;
// delete old revision from imap and cache
$imap->delete_message($msguid, $calendar->storage->name);
$calendar->storage->cache->set($msguid, false);
}
}
}
return $success;
}
/**
* Helper method to resolved the given event identifier into uid and folder
*
* @return array (uid,folder,msguid) tuple
*/
protected function _resolve_event_identity($event)
{
$mailbox = $msguid = null;
if (is_array($event)) {
$uid = !empty($event['uid']) ? $event['uid'] : $event['id'];
if (($cal = $this->get_calendar($event['calendar'])) && !($cal instanceof kolab_invitation_calendar)) {
$mailbox = $cal->get_mailbox_id();
// get event object from storage in order to get the real object uid an msguid
if ($ev = $cal->get_event($event['id'])) {
$msguid = $ev['_msguid'];
$uid = $ev['uid'];
}
}
}
else {
$uid = $event;
// get event object from storage in order to get the real object uid an msguid
if ($ev = $this->get_event($event)) {
$mailbox = $ev['_mailbox'];
$msguid = $ev['_msguid'];
$uid = $ev['uid'];
}
}
return array($uid, $mailbox, $msguid);
}
/**
* Callback function to produce driver-specific calendar create/edit form
*
* @param string Request action 'form-edit|form-new'
* @param array Calendar properties (e.g. id, color)
* @param array Edit form fields
*
* @return string HTML content of the form
*/
public function calendar_form($action, $calendar, $formfields)
{
$special_calendars = [
self::BIRTHDAY_CALENDAR_ID,
self::INVITATIONS_CALENDAR_PENDING,
self::INVITATIONS_CALENDAR_DECLINED
];
// show default dialog for birthday calendar
if (in_array($calendar['id'], $special_calendars)) {
if ($calendar['id'] != self::BIRTHDAY_CALENDAR_ID) {
unset($formfields['showalarms']);
}
// General tab
$form['props'] = [
'name' => $this->rc->gettext('properties'),
'fields' => $formfields,
];
return kolab_utils::folder_form($form, '', 'calendar');
}
$this->_read_calendars();
if (!empty($calendar['id']) && ($cal = $this->calendars[$calendar['id']])) {
$folder = $cal->get_realname(); // UTF7
$color = $cal->get_color();
}
else {
$folder = '';
$color = '';
}
$hidden_fields[] = ['name' => 'oldname', 'value' => $folder];
$storage = $this->rc->get_storage();
$delim = $storage->get_hierarchy_delimiter();
$form = [];
if (strlen($folder)) {
$path_imap = explode($delim, $folder);
array_pop($path_imap); // pop off name part
$path_imap = implode($delim, $path_imap);
$options = $storage->folder_info($folder);
}
else {
$path_imap = '';
}
// General tab
$form['props'] = [
'name' => $this->rc->gettext('properties'),
'fields' => [],
];
$protected = !empty($options) && (!empty($options['norename']) || !empty($options['protected']));
// Disable folder name input
if ($protected) {
$input_name = new html_hiddenfield(['name' => 'name', 'id' => 'calendar-name']);
$formfields['name']['value'] = $this->storage->object_name($folder)
. $input_name->show($folder);
}
// calendar name (default field)
$form['props']['fields']['location'] = $formfields['name'];
if ($protected) {
// prevent user from moving folder
$hidden_fields[] = ['name' => 'parent', 'value' => $path_imap];
}
else {
$select = $this->storage->folder_selector('event', ['name' => 'parent', 'id' => 'calendar-parent'], $folder);
$form['props']['fields']['path'] = [
'id' => 'calendar-parent',
'label' => $this->cal->gettext('parentcalendar'),
'value' => $select->show(strlen($folder) ? $path_imap : ''),
];
}
// calendar color (default field)
$form['props']['fields']['color'] = $formfields['color'];
$form['props']['fields']['alarms'] = $formfields['showalarms'];
return kolab_utils::folder_form($form, $folder, 'calendar', $hidden_fields);
}
/**
* Handler for user_delete plugin hook
*/
public function user_delete($args)
{
$db = $this->rc->get_dbh();
foreach (['kolab_alarms', 'itipinvitations'] as $table) {
$db->query("DELETE FROM " . $this->rc->db->table_name($table, true)
. " WHERE `user_id` = ?", $args['user']->ID);
}
}
}
diff --git a/plugins/kolab_addressbook/composer.json b/plugins/kolab_addressbook/composer.json
index 619c28fa..47921753 100644
--- a/plugins/kolab_addressbook/composer.json
+++ b/plugins/kolab_addressbook/composer.json
@@ -1,31 +1,31 @@
{
"name": "kolab/kolab_addressbook",
"type": "roundcube-plugin",
"description": "Kolab addressbook",
"homepage": "https://git.kolab.org/diffusion/RPK/",
"license": "AGPLv3",
"version": "3.5.10",
"authors": [
{
"name": "Thomas Bruederli",
"email": "bruederli@kolabsys.com",
"role": "Lead"
},
{
"name": "Aleksander Machniak",
"email": "machniak@kolabsys.com",
"role": "Lead"
}
],
"repositories": [
{
"type": "composer",
"url": "https://plugins.roundcube.net"
}
],
"require": {
- "php": ">=5.3.0",
+ "php": ">=7.2.0",
"roundcube/plugin-installer": ">=0.1.3",
"kolab/libkolab": ">=3.4.0"
}
}
diff --git a/plugins/libcalendaring/composer.json b/plugins/libcalendaring/composer.json
index b70587af..4257aad9 100644
--- a/plugins/libcalendaring/composer.json
+++ b/plugins/libcalendaring/composer.json
@@ -1,31 +1,31 @@
{
"name": "kolab/libcalendaring",
"type": "roundcube-plugin",
"description": "Library providing common functions for calendaring plugins",
"homepage": "https://git.kolab.org/diffusion/RPK/",
"license": "AGPLv3",
"version": "3.5.11",
"authors": [
{
"name": "Thomas Bruederli",
"email": "bruederli@kolabsys.com",
"role": "Lead"
},
{
"name": "Aleksander Machniak",
"email": "machniak@kolabsys.com",
"role": "Developer"
}
],
"repositories": [
{
"type": "composer",
"url": "https://plugins.roundcube.net"
}
],
"require": {
- "php": ">=7.4.0",
+ "php": ">=7.2.0",
"roundcube/plugin-installer": ">=0.1.3",
"sabre/vobject": "~4.5.1"
}
}
diff --git a/plugins/libcalendaring/lib/libcalendaring_recurrence.php b/plugins/libcalendaring/lib/libcalendaring_recurrence.php
index 8a336112..a96f33eb 100644
--- a/plugins/libcalendaring/lib/libcalendaring_recurrence.php
+++ b/plugins/libcalendaring/lib/libcalendaring_recurrence.php
@@ -1,235 +1,235 @@
<?php
/**
* Recurrence computation class for shared use
*
* Uitility class to compute reccurrence dates from the given rules
*
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 2012-2014, Kolab Systems AG <contact@kolabsys.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class libcalendaring_recurrence
{
protected $lib;
protected $start;
protected $next;
protected $engine;
protected $recurrence;
protected $dateonly = false;
protected $hour = 0;
/**
* Default constructor
*
* @param calendar The calendar plugin instance
*/
function __construct($lib)
{
// use Horde classes to compute recurring instances
// TODO: replace with something that has less than 6'000 lines of code
require_once(__DIR__ . '/Horde_Date_Recurrence.php');
$this->lib = $lib;
}
/**
* Initialize recurrence engine
*
* @param array The recurrence properties
* @param DateTime The recurrence start date
*/
public function init($recurrence, $start = null)
{
$this->recurrence = $recurrence;
$this->engine = new Horde_Date_Recurrence($start);
$this->engine->fromRRule20(libcalendaring::to_rrule($recurrence));
$this->set_start($start);
if (!empty($recurrence['EXDATE'])) {
foreach ((array) $recurrence['EXDATE'] as $exdate) {
- if (is_a($exdate, 'DateTime')) {
+ if ($exdate instanceof DateTimeInterface) {
$this->engine->addException($exdate->format('Y'), $exdate->format('n'), $exdate->format('j'));
}
}
}
if (!empty($recurrence['RDATE'])) {
foreach ((array) $recurrence['RDATE'] as $rdate) {
- if (is_a($rdate, 'DateTime')) {
+ if ($rdate instanceof DateTimeInterface) {
$this->engine->addRDate($rdate->format('Y'), $rdate->format('n'), $rdate->format('j'));
}
}
}
}
/**
* Setter for (new) recurrence start date
*
* @param DateTime The recurrence start date
*/
public function set_start($start)
{
$this->start = $start;
$this->dateonly = $start->_dateonly;
$this->next = new Horde_Date($start, $this->lib->timezone->getName());
$this->hour = $this->next->hour;
$this->engine->setRecurStart($this->next);
}
/**
* Get date/time of the next occurence of this event
*
* @return DateTime|int|false object or False if recurrence ended
*/
public function next()
{
$time = false;
$after = clone $this->next;
$after->mday = $after->mday + 1;
if ($this->next && ($next = $this->engine->nextActiveRecurrence($after))) {
// avoid endless loops if recurrence computation fails
if (!$next->after($this->next)) {
return false;
}
// fix time for all-day events
if ($this->dateonly) {
$next->hour = $this->hour;
$next->min = 0;
}
$time = $next->toDateTime();
$this->next = $next;
}
return $time;
}
/**
* Get the end date of the occurence of this recurrence cycle
*
* @return DateTime|bool End datetime of the last occurence or False if recurrence exceeds limit
*/
public function end()
{
// recurrence end date is given
if ($this->recurrence['UNTIL'] instanceof DateTimeInterface) {
return $this->recurrence['UNTIL'];
}
// take the last RDATE entry if set
if (is_array($this->recurrence['RDATE']) && !empty($this->recurrence['RDATE'])) {
$last = end($this->recurrence['RDATE']);
if ($last instanceof DateTimeInterface) {
return $last;
}
}
// run through all items till we reach the end
if ($this->recurrence['COUNT']) {
$last = $this->start;
$this->next = new Horde_Date($this->start, $this->lib->timezone->getName());
while (($next = $this->next()) && $c < 1000) {
$last = $next;
$c++;
}
}
return $last;
}
/**
* Find date/time of the first occurrence (excluding start date)
*/
public function first_occurrence()
{
$start = clone $this->start;
$orig_start = clone $this->start;
$r = $this->recurrence;
$interval = !empty($r['INTERVAL']) ? intval($r['INTERVAL']) : 1;
$frequency = isset($this->recurrence['FREQ']) ? $this->recurrence['FREQ'] : null;
switch ($frequency) {
case 'WEEKLY':
if (empty($this->recurrence['BYDAY'])) {
return $start;
}
$start->sub(new DateInterval("P{$interval}W"));
break;
case 'MONTHLY':
if (empty($this->recurrence['BYDAY']) && empty($this->recurrence['BYMONTHDAY'])) {
return $start;
}
$start->sub(new DateInterval("P{$interval}M"));
break;
case 'YEARLY':
if (empty($this->recurrence['BYDAY']) && empty($this->recurrence['BYMONTH'])) {
return $start;
}
$start->sub(new DateInterval("P{$interval}Y"));
break;
default:
return $start;
}
$r = $this->recurrence;
$r['INTERVAL'] = $interval;
if (!empty($r['COUNT'])) {
// Increase count so we do not stop the loop to early
$r['COUNT'] += 100;
}
// Create recurrence that starts in the past
$recurrence = new self($this->lib);
$recurrence->init($r, $start);
// find the first occurrence
$found = false;
while ($next = $recurrence->next()) {
$start = $next;
if ($next >= $orig_start) {
$found = true;
break;
}
}
if (!$found) {
rcube::raise_error(array(
'file' => __FILE__,
'line' => __LINE__,
'message' => sprintf("Failed to find a first occurrence. Start: %s, Recurrence: %s",
$orig_start->format(DateTime::ISO8601), json_encode($r)),
), true);
return null;
}
if ($start Instanceof Horde_Date) {
$start = $start->toDateTime();
}
$start->_dateonly = $this->dateonly;
return $start;
}
}
diff --git a/plugins/libcalendaring/libvcalendar.php b/plugins/libcalendaring/lib/libcalendaring_vcalendar.php
similarity index 99%
rename from plugins/libcalendaring/libvcalendar.php
rename to plugins/libcalendaring/lib/libcalendaring_vcalendar.php
index 17629e04..c88fe2cc 100644
--- a/plugins/libcalendaring/libvcalendar.php
+++ b/plugins/libcalendaring/lib/libcalendaring_vcalendar.php
@@ -1,1538 +1,1536 @@
<?php
/**
* iCalendar functions for the libcalendaring plugin
*
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 2013-2015, Kolab Systems AG <contact@kolabsys.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use \Sabre\VObject;
use \Sabre\VObject\DateTimeParser;
-require_once __DIR__ . '/lib/libcalendaring_datetime.php';
-
/**
* Class to parse and build vCalendar (iCalendar) files
*
* Uses the Sabre VObject library, version 3.x.
*
*/
-class libvcalendar implements Iterator
+class libcalendaring_vcalendar implements Iterator
{
private $timezone;
private $attach_uri = null;
private $prodid = '-//Roundcube libcalendaring//Sabre//Sabre VObject//EN';
private $type_component_map = array('event' => 'VEVENT', 'task' => 'VTODO');
private $attendee_keymap = array(
'name' => 'CN',
'status' => 'PARTSTAT',
'role' => 'ROLE',
'cutype' => 'CUTYPE',
'rsvp' => 'RSVP',
'delegated-from' => 'DELEGATED-FROM',
'delegated-to' => 'DELEGATED-TO',
'schedule-status' => 'SCHEDULE-STATUS',
'schedule-agent' => 'SCHEDULE-AGENT',
'sent-by' => 'SENT-BY',
);
private $organizer_keymap = array(
'name' => 'CN',
'schedule-status' => 'SCHEDULE-STATUS',
'schedule-agent' => 'SCHEDULE-AGENT',
'sent-by' => 'SENT-BY',
);
private $iteratorkey = 0;
private $charset;
private $forward_exceptions;
private $vhead;
private $fp;
private $vtimezones = array();
public $method;
public $agent = '';
public $objects = array();
public $freebusy = array();
/**
* Default constructor
*/
function __construct($tz = null)
{
$this->timezone = $tz;
$this->prodid = '-//Roundcube libcalendaring ' . RCUBE_VERSION . '//Sabre//Sabre VObject ' . VObject\Version::VERSION . '//EN';
}
/**
* Setter for timezone information
*/
public function set_timezone($tz)
{
$this->timezone = $tz;
}
/**
* Setter for URI template for attachment links
*/
public function set_attach_uri($uri)
{
$this->attach_uri = $uri;
}
/**
* Setter for a custom PRODID attribute
*/
public function set_prodid($prodid)
{
$this->prodid = $prodid;
}
/**
* Setter for a user-agent string to tweak input/output accordingly
*/
public function set_agent($agent)
{
$this->agent = $agent;
}
/**
* Free resources by clearing member vars
*/
public function reset()
{
$this->vhead = '';
$this->method = '';
$this->objects = array();
$this->freebusy = array();
$this->vtimezones = array();
$this->iteratorkey = 0;
if ($this->fp) {
fclose($this->fp);
$this->fp = null;
}
}
/**
* Import events from iCalendar format
*
* @param string vCalendar input
* @param string Input charset (from envelope)
* @param boolean True if parsing exceptions should be forwarded to the caller
* @return array List of events extracted from the input
*/
public function import($vcal, $charset = 'UTF-8', $forward_exceptions = false, $memcheck = true)
{
// TODO: convert charset to UTF-8 if other
try {
// estimate the memory usage and try to avoid fatal errors when allowed memory gets exhausted
if ($memcheck) {
$count = substr_count($vcal, 'BEGIN:VEVENT') + substr_count($vcal, 'BEGIN:VTODO');
$expected_memory = $count * 70*1024; // assume ~ 70K per event (empirically determined)
if (!rcube_utils::mem_check($expected_memory)) {
throw new Exception("iCal file too big");
}
}
$vobject = VObject\Reader::read($vcal, VObject\Reader::OPTION_FORGIVING | VObject\Reader::OPTION_IGNORE_INVALID_LINES);
if ($vobject)
return $this->import_from_vobject($vobject);
}
catch (Exception $e) {
if ($forward_exceptions) {
throw $e;
}
else {
rcube::raise_error(array(
'code' => 600, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "iCal data parse error: " . $e->getMessage()),
true, false);
}
}
return array();
}
/**
* Read iCalendar events from a file
*
* @param string File path to read from
* @param string Input charset (from envelope)
* @param boolean True if parsing exceptions should be forwarded to the caller
* @return array List of events extracted from the file
*/
public function import_from_file($filepath, $charset = 'UTF-8', $forward_exceptions = false)
{
if ($this->fopen($filepath, $charset, $forward_exceptions)) {
while ($this->_parse_next(false)) {
// nop
}
fclose($this->fp);
$this->fp = null;
}
return $this->objects;
}
/**
* Open a file to read iCalendar events sequentially
*
* @param string File path to read from
* @param string Input charset (from envelope)
* @param boolean True if parsing exceptions should be forwarded to the caller
* @return boolean True if file contents are considered valid
*/
public function fopen($filepath, $charset = 'UTF-8', $forward_exceptions = false)
{
$this->reset();
// just to be sure...
@ini_set('auto_detect_line_endings', true);
$this->charset = $charset;
$this->forward_exceptions = $forward_exceptions;
$this->fp = fopen($filepath, 'r');
// check file content first
$begin = fread($this->fp, 1024);
if (!preg_match('/BEGIN:VCALENDAR/i', $begin)) {
return false;
}
fseek($this->fp, 0);
return $this->_parse_next();
}
/**
* Parse the next event/todo/freebusy object from the input file
*/
private function _parse_next($reset = true)
{
if ($reset) {
$this->iteratorkey = 0;
$this->objects = array();
$this->freebusy = array();
}
$next = $this->_next_component();
$buffer = $next;
// load the next component(s) too, as they could contain recurrence exceptions
while (preg_match('/(RRULE|RECURRENCE-ID)[:;]/i', $next)) {
$next = $this->_next_component();
$buffer .= $next;
}
// parse the vevent block surrounded with the vcalendar heading
if (strlen($buffer) && preg_match('/BEGIN:(VEVENT|VTODO|VFREEBUSY)/i', $buffer)) {
try {
$this->import($this->vhead . $buffer . "END:VCALENDAR", $this->charset, true, false);
}
catch (Exception $e) {
if ($this->forward_exceptions) {
throw new VObject\ParseException($e->getMessage() . " in\n" . $buffer);
}
else {
// write the failing section to error log
rcube::raise_error(array(
'code' => 600, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => $e->getMessage() . " in\n" . $buffer),
true, false);
}
// advance to next
return $this->_parse_next($reset);
}
return count($this->objects) > 0;
}
return false;
}
/**
* Helper method to read the next calendar component from the file
*/
private function _next_component()
{
$buffer = '';
$vcalendar_head = false;
while (($line = fgets($this->fp, 1024)) !== false) {
// ignore END:VCALENDAR lines
if (preg_match('/END:VCALENDAR/i', $line)) {
continue;
}
// read vcalendar header (with timezone defintion)
if (preg_match('/BEGIN:VCALENDAR/i', $line)) {
$this->vhead = '';
$vcalendar_head = true;
}
// end of VCALENDAR header part
if ($vcalendar_head && preg_match('/BEGIN:(VEVENT|VTODO|VFREEBUSY)/i', $line)) {
$vcalendar_head = false;
}
if ($vcalendar_head) {
$this->vhead .= $line;
}
else {
$buffer .= $line;
if (preg_match('/END:(VEVENT|VTODO|VFREEBUSY)/i', $line)) {
break;
}
}
}
return $buffer;
}
/**
* Import objects from an already parsed Sabre\VObject\Component object
*
* @param object Sabre\VObject\Component to read from
* @return array List of events extracted from the file
*/
public function import_from_vobject($vobject)
{
$seen = array();
$exceptions = array();
if ($vobject->name == 'VCALENDAR') {
$this->method = strval($vobject->METHOD);
$this->agent = strval($vobject->PRODID);
foreach ($vobject->getComponents() as $ve) {
if ($ve->name == 'VEVENT' || $ve->name == 'VTODO') {
// convert to hash array representation
$object = $this->_to_array($ve);
// temporarily store this as exception
if (!empty($object['recurrence_date'])) {
$exceptions[] = $object;
}
else if (empty($seen[$object['uid']])) {
$seen[$object['uid']] = true;
$this->objects[] = $object;
}
}
else if ($ve->name == 'VFREEBUSY') {
$this->objects[] = $this->_parse_freebusy($ve);
}
}
// add exceptions to the according master events
foreach ($exceptions as $exception) {
$uid = $exception['uid'];
// make this exception the master
if (empty($seen[$uid])) {
$seen[$uid] = true;
$this->objects[] = $exception;
}
else {
foreach ($this->objects as $i => $object) {
// add as exception to existing entry with a matching UID
if ($object['uid'] == $uid) {
$this->objects[$i]['exceptions'][] = $exception;
if (!empty($object['recurrence'])) {
$this->objects[$i]['recurrence']['EXCEPTIONS'] = &$this->objects[$i]['exceptions'];
}
break;
}
}
}
}
}
return $this->objects;
}
/**
* Getter for free-busy periods
*/
public function get_busy_periods()
{
$out = array();
foreach ((array)$this->freebusy['periods'] as $period) {
if ($period[2] != 'FREE') {
$out[] = $period;
}
}
return $out;
}
/**
* Helper method to determine whether the connected client is an Apple device
*/
private function is_apple()
{
return stripos($this->agent, 'Apple') !== false
|| stripos($this->agent, 'Mac OS X') !== false
|| stripos($this->agent, 'iOS/') !== false;
}
/**
* Convert the given VEvent object to a libkolab compatible array representation
*
* @param object Vevent object to convert
* @return array Hash array with object properties
*/
private function _to_array($ve)
{
$event = array(
'uid' => self::convert_string($ve->UID),
'title' => self::convert_string($ve->SUMMARY),
'_type' => $ve->name == 'VTODO' ? 'task' : 'event',
// set defaults
'priority' => 0,
'attendees' => array(),
'x-custom' => array(),
);
// Catch possible exceptions when date is invalid (Bug #2144)
// We can skip these fields, they aren't critical
foreach (array('CREATED' => 'created', 'LAST-MODIFIED' => 'changed', 'DTSTAMP' => 'changed') as $attr => $field) {
try {
if (empty($event[$field]) && !empty($ve->{$attr})) {
$event[$field] = $ve->{$attr}->getDateTime();
}
} catch (Exception $e) {}
}
// map other attributes to internal fields
foreach ($ve->children() as $prop) {
if (!($prop instanceof VObject\Property))
continue;
$value = strval($prop);
switch ($prop->name) {
case 'DTSTART':
case 'DTEND':
case 'DUE':
$propmap = array('DTSTART' => 'start', 'DTEND' => 'end', 'DUE' => 'due');
$event[$propmap[$prop->name]] = self::convert_datetime($prop);
break;
case 'TRANSP':
$event['free_busy'] = strval($prop) == 'TRANSPARENT' ? 'free' : 'busy';
break;
case 'STATUS':
if ($value == 'TENTATIVE')
$event['free_busy'] = 'tentative';
else if ($value == 'CANCELLED')
$event['cancelled'] = true;
else if ($value == 'COMPLETED')
$event['complete'] = 100;
$event['status'] = $value;
break;
case 'COMPLETED':
if (self::convert_datetime($prop)) {
$event['status'] = 'COMPLETED';
$event['complete'] = 100;
}
break;
case 'PRIORITY':
if (is_numeric($value))
$event['priority'] = $value;
break;
case 'RRULE':
$params = !empty($event['recurrence']) && is_array($event['recurrence']) ? $event['recurrence'] : array();
// parse recurrence rule attributes
foreach ($prop->getParts() as $k => $v) {
$params[strtoupper($k)] = is_array($v) ? implode(',', $v) : $v;
}
if (!empty($params['UNTIL'])) {
$params['UNTIL'] = date_create($params['UNTIL']);
}
if (empty($params['INTERVAL'])) {
$params['INTERVAL'] = 1;
}
$event['recurrence'] = array_filter($params);
break;
case 'EXDATE':
if (!empty($value)) {
$exdates = array_map(function($_) { return is_array($_) ? $_[0] : $_; }, self::convert_datetime($prop, true));
if (!empty($event['recurrence']['EXDATE'])) {
$event['recurrence']['EXDATE'] = array_merge($event['recurrence']['EXDATE'], $exdates);
}
else {
$event['recurrence']['EXDATE'] = $exdates;
}
}
break;
case 'RDATE':
if (!empty($value)) {
$rdates = array_map(function($_) { return is_array($_) ? $_[0] : $_; }, self::convert_datetime($prop, true));
if (!empty($event['recurrence']['RDATE'])) {
$event['recurrence']['RDATE'] = array_merge($event['recurrence']['RDATE'], $rdates);
}
else {
$event['recurrence']['RDATE'] = $rdates;
}
}
break;
case 'RECURRENCE-ID':
$event['recurrence_date'] = self::convert_datetime($prop);
if ($prop->offsetGet('RANGE') == 'THISANDFUTURE' || $prop->offsetGet('THISANDFUTURE') !== null) {
$event['thisandfuture'] = true;
}
break;
case 'RELATED-TO':
$reltype = $prop->offsetGet('RELTYPE');
if ($reltype == 'PARENT' || $reltype === null) {
$event['parent_id'] = $value;
}
break;
case 'SEQUENCE':
$event['sequence'] = intval($value);
break;
case 'PERCENT-COMPLETE':
$event['complete'] = intval($value);
break;
case 'LOCATION':
case 'DESCRIPTION':
case 'URL':
case 'COMMENT':
$event[strtolower($prop->name)] = self::convert_string($prop);
break;
case 'CATEGORY':
case 'CATEGORIES':
if (!empty($event['categories'])) {
$event['categories'] = array_merge((array) $event['categories'], $prop->getParts());
}
else {
$event['categories'] = $prop->getParts();
}
break;
case 'X-MICROSOFT-CDO-BUSYSTATUS':
if ($value == 'OOF') {
$event['free_busy'] = 'outofoffice';
}
else if (in_array($value, array('FREE', 'BUSY', 'TENTATIVE'))) {
$event['free_busy'] = strtolower($value);
}
break;
case 'ATTENDEE':
case 'ORGANIZER':
$params = array('RSVP' => false);
foreach ($prop->parameters() as $pname => $pvalue) {
switch ($pname) {
case 'RSVP': $params[$pname] = strtolower($pvalue) == 'true'; break;
case 'CN': $params[$pname] = self::unescape($pvalue); break;
default: $params[$pname] = strval($pvalue); break;
}
}
$attendee = self::map_keys($params, array_flip($this->attendee_keymap));
$attendee['email'] = preg_replace('!^mailto:!i', '', $value);
if ($prop->name == 'ORGANIZER') {
$attendee['role'] = 'ORGANIZER';
$attendee['status'] = 'ACCEPTED';
$event['organizer'] = $attendee;
if (array_key_exists('schedule-agent', $attendee)) {
$schedule_agent = $attendee['schedule-agent'];
}
}
else if (empty($event['organizer']) || $attendee['email'] != $event['organizer']['email']) {
$event['attendees'][] = $attendee;
}
break;
case 'ATTACH':
$params = self::parameters_array($prop);
if (substr($value, 0, 4) == 'http' && !strpos($value, ':attachment:')) {
$event['links'][] = $value;
}
else if (strlen($value) && strtoupper($params['VALUE']) == 'BINARY') {
$attachment = self::map_keys($params, array('FMTTYPE' => 'mimetype', 'X-LABEL' => 'name', 'X-APPLE-FILENAME' => 'name'));
$attachment['data'] = $value;
$attachment['size'] = strlen($value);
$event['attachments'][] = $attachment;
}
break;
default:
if (substr($prop->name, 0, 2) == 'X-')
$event['x-custom'][] = array($prop->name, strval($value));
break;
}
}
// check DURATION property if no end date is set
if (empty($event['end']) && $ve->DURATION) {
try {
$duration = new DateInterval(strval($ve->DURATION));
$end = clone $event['start'];
$end->add($duration);
$event['end'] = $end;
}
catch (\Exception $e) {
trigger_error(strval($e), E_USER_WARNING);
}
}
// validate event dates
if ($event['_type'] == 'event') {
$event['allday'] = !empty($event['start']->_dateonly);
// events may lack the DTEND property, set it to DTSTART (RFC5545 3.6.1)
if (empty($event['end'])) {
$event['end'] = clone $event['start'];
}
// shift end-date by one day (except Thunderbird)
else if ($event['allday'] && is_object($event['end'])) {
$event['end']->sub(new \DateInterval('PT23H'));
}
// sanity-check and fix end date
if (!empty($event['end']) && $event['end'] < $event['start']) {
$event['end'] = clone $event['start'];
}
}
// make organizer part of the attendees list for compatibility reasons
if (!empty($event['organizer']) && is_array($event['attendees']) && $event['_type'] == 'event') {
array_unshift($event['attendees'], $event['organizer']);
}
// find alarms
foreach ($ve->select('VALARM') as $valarm) {
$action = 'DISPLAY';
$trigger = null;
$alarm = array();
foreach ($valarm->children() as $prop) {
$value = strval($prop);
switch ($prop->name) {
case 'TRIGGER':
foreach ($prop->parameters as $param) {
if ($param->name == 'VALUE' && $param->getValue() == 'DATE-TIME') {
$trigger = '@' . $prop->getDateTime()->format('U');
$alarm['trigger'] = $prop->getDateTime();
}
else if ($param->name == 'RELATED') {
$alarm['related'] = $param->getValue();
}
}
if (!$trigger && ($values = libcalendaring::parse_alarm_value($value))) {
$trigger = $values[2];
}
if (empty($alarm['trigger'])) {
$alarm['trigger'] = rtrim(preg_replace('/([A-Z])0[WDHMS]/', '\\1', $value), 'T');
// if all 0-values have been stripped, assume 'at time'
if ($alarm['trigger'] == 'P') {
$alarm['trigger'] = 'PT0S';
}
}
break;
case 'ACTION':
$action = $alarm['action'] = strtoupper($value);
break;
case 'SUMMARY':
case 'DESCRIPTION':
case 'DURATION':
$alarm[strtolower($prop->name)] = self::convert_string($prop);
break;
case 'REPEAT':
$alarm['repeat'] = intval($value);
break;
case 'ATTENDEE':
$alarm['attendees'][] = preg_replace('!^mailto:!i', '', $value);
break;
case 'ATTACH':
$params = self::parameters_array($prop);
if (strlen($value) && (preg_match('/^[a-z]+:/', $value) || strtoupper($params['VALUE']) == 'URI')) {
// we only support URI-type of attachments here
$alarm['uri'] = $value;
}
break;
}
}
if ($action != 'NONE') {
// store first alarm in legacy property
if ($trigger && empty($event['alarms'])) {
$event['alarms'] = $trigger . ':' . $action;
}
if (!empty($alarm['trigger'])) {
$event['valarms'][] = $alarm;
}
}
}
// assign current timezone to event start/end
if (!empty($event['start']) && $event['start'] instanceof DateTimeInterface) {
$this->_apply_timezone($event['start']);
}
else {
unset($event['start']);
}
if (!empty($event['end']) && $event['end'] instanceof DateTimeInterface) {
$this->_apply_timezone($event['end']);
}
else {
unset($event['end']);
}
// some iTip CANCEL messages only contain the start date
if (empty($event['end']) && !empty($event['start']) && $this->method == 'CANCEL') {
$event['end'] = clone $event['start'];
}
// T2531: Remember SCHEDULE-AGENT in custom property to properly
// support event updates via CalDAV when SCHEDULE-AGENT=CLIENT is used
if (isset($schedule_agent)) {
$event['x-custom'][] = array('SCHEDULE-AGENT', $schedule_agent);
}
// minimal validation
if (empty($event['uid']) || ($event['_type'] == 'event' && empty($event['start']) != empty($event['end']))) {
throw new VObject\ParseException('Object validation failed: missing mandatory object properties');
}
return $event;
}
/**
* Apply user timezone to DateTime object
*/
private function _apply_timezone(&$date)
{
if (empty($this->timezone)) {
return;
}
// For date-only we'll keep the date and time intact
if (!empty($date->_dateonly)) {
$dt = new libcalendaring_datetime(null, $this->timezone);
$dt->setDate($date->format('Y'), $date->format('n'), $date->format('j'));
$dt->setTime($date->format('G'), $date->format('i'), 0);
$date = $dt;
}
else {
$date->setTimezone($this->timezone);
}
}
/**
* Parse the given vfreebusy component into an array representation
*/
private function _parse_freebusy($ve)
{
$this->freebusy = array('_type' => 'freebusy', 'periods' => array());
$seen = array();
foreach ($ve->children() as $prop) {
if (!($prop instanceof VObject\Property))
continue;
$value = strval($prop);
switch ($prop->name) {
case 'CREATED':
case 'LAST-MODIFIED':
case 'DTSTAMP':
case 'DTSTART':
case 'DTEND':
$propmap = array(
'DTSTART' => 'start',
'DTEND' => 'end',
'CREATED' => 'created',
'LAST-MODIFIED' => 'changed',
'DTSTAMP' => 'changed'
);
$this->freebusy[$propmap[$prop->name]] = self::convert_datetime($prop);
break;
case 'ORGANIZER':
$this->freebusy['organizer'] = preg_replace('!^mailto:!i', '', $value);
break;
case 'FREEBUSY':
// The freebusy component can hold more than 1 value, separated by commas.
$periods = explode(',', $value);
$fbtype = strval($prop['FBTYPE']) ?: 'BUSY';
// skip dupes
if (!empty($seen[$value.':'.$fbtype])) {
break;
}
$seen[$value.':'.$fbtype] = true;
foreach ($periods as $period) {
// Every period is formatted as [start]/[end]. The start is an
// absolute UTC time, the end may be an absolute UTC time, or
// duration (relative) value.
list($busyStart, $busyEnd) = explode('/', $period);
$busyStart = DateTimeParser::parse($busyStart);
$busyEnd = DateTimeParser::parse($busyEnd);
if ($busyEnd instanceof \DateInterval) {
$tmp = clone $busyStart;
$tmp->add($busyEnd);
$busyEnd = $tmp;
}
if ($busyEnd && $busyEnd > $busyStart)
$this->freebusy['periods'][] = array($busyStart, $busyEnd, $fbtype);
}
break;
case 'COMMENT':
$this->freebusy['comment'] = $value;
}
}
return $this->freebusy;
}
/**
*
*/
public static function convert_string($prop)
{
return strval($prop);
}
/**
*
*/
public static function unescape($prop)
{
return str_replace('\,', ',', strval($prop));
}
/**
* Helper method to correctly interpret an all-day date value
*/
public static function convert_datetime($prop, $as_array = false)
{
if (empty($prop)) {
return $as_array ? [] : null;
}
if ($prop instanceof VObject\Property\ICalendar\DateTime) {
if (count($prop->getDateTimes()) > 1) {
$dt = [];
$dateonly = !$prop->hasTime();
foreach ($prop->getDateTimes() as $item) {
$item = libcalendaring_datetime::createFromImmutable($item);
$item->_dateonly = $dateonly;
$dt[] = $item;
}
}
else {
$dt = libcalendaring_datetime::createFromImmutable($prop->getDateTime());
if (!$prop->hasTime()) {
$dt->_dateonly = true;
}
}
}
else if ($prop instanceof VObject\Property\ICalendar\Period) {
$dt = [];
foreach ($prop->getParts() as $val) {
try {
list($start, $end) = explode('/', $val);
$start = DateTimeParser::parseDateTime($start);
// This is a duration value.
if ($end[0] === 'P') {
$dur = DateTimeParser::parseDuration($end);
$end = clone $start;
$end->add($dur);
}
else {
$end = DateTimeParser::parseDateTime($end);
}
$dt[] = [libcalendaring_datetime::createFromImmutable($start), libcalendaring_datetime::createFromImmutable($end)];
}
catch (Exception $e) {
// ignore single date parse errors
}
}
}
else if ($prop instanceof \DateTimeInterface) {
$dt = libcalendaring_datetime::createFromImmutable($prop);
}
// force return value to array if requested
if ($as_array && !is_array($dt)) {
$dt = empty($dt) ? [] : [$dt];
}
return $dt;
}
/**
* Create a Sabre\VObject\Property instance from a PHP DateTime object
*
* @param object VObject\Document parent node to create property for
* @param string Property name
* @param object DateTime
* @param boolean Set as UTC date
* @param boolean Set as VALUE=DATE property
*/
public function datetime_prop($cal, $name, $dt, $utc = false, $dateonly = null, $set_type = false)
{
if ($utc) {
$dt->setTimeZone(new \DateTimeZone('UTC'));
$is_utc = true;
}
else {
$is_utc = ($tz = $dt->getTimezone()) && in_array($tz->getName(), array('UTC','GMT','Z'));
}
$is_dateonly = $dateonly === null ? !empty($dt->_dateonly) : (bool) $dateonly;
$vdt = $cal->createProperty($name, $dt, null, $is_dateonly ? 'DATE' : 'DATE-TIME');
if ($is_dateonly) {
$vdt['VALUE'] = 'DATE';
}
else if ($set_type) {
$vdt['VALUE'] = 'DATE-TIME';
}
// register timezone for VTIMEZONE block
if (!$is_utc && !$dateonly && $tz && ($tzname = $tz->getName())) {
$ts = $dt->format('U');
if (!empty($this->vtimezones[$tzname])) {
$this->vtimezones[$tzname][0] = min($this->vtimezones[$tzname][0], $ts);
$this->vtimezones[$tzname][1] = max($this->vtimezones[$tzname][1], $ts);
}
else {
$this->vtimezones[$tzname] = array($ts, $ts);
}
}
return $vdt;
}
/**
* Copy values from one hash array to another using a key-map
*/
public static function map_keys($values, $map)
{
$out = array();
foreach ($map as $from => $to) {
if (isset($values[$from]))
$out[$to] = is_array($values[$from]) ? join(',', $values[$from]) : $values[$from];
}
return $out;
}
/**
*
*/
private static function parameters_array($prop)
{
$params = array();
foreach ($prop->parameters() as $name => $value) {
$params[strtoupper($name)] = strval($value);
}
return $params;
}
/**
* Export events to iCalendar format
*
* @param array Events as array
* @param string VCalendar method to advertise
* @param boolean Directly send data to stdout instead of returning
* @param callable Callback function to fetch attachment contents, false if no attachment export
* @param boolean Add VTIMEZONE block with timezone definitions for the included events
* @return string Events in iCalendar format (http://tools.ietf.org/html/rfc5545)
*/
public function export($objects, $method = null, $write = false, $get_attachment = false, $with_timezones = true)
{
$this->method = $method;
// encapsulate in VCALENDAR container
$vcal = new VObject\Component\VCalendar();
$vcal->VERSION = '2.0';
$vcal->PRODID = $this->prodid;
$vcal->CALSCALE = 'GREGORIAN';
if (!empty($method)) {
$vcal->METHOD = $method;
}
// write vcalendar header
if ($write) {
echo preg_replace('/END:VCALENDAR[\r\n]*$/m', '', $vcal->serialize());
}
foreach ($objects as $object) {
$this->_to_ical($object, !$write?$vcal:false, $get_attachment);
}
// include timezone information
if ($with_timezones || !empty($method)) {
foreach ($this->vtimezones as $tzid => $range) {
$vt = self::get_vtimezone($tzid, $range[0], $range[1], $vcal);
if (empty($vt)) {
continue; // no timezone information found
}
if ($write) {
echo $vt->serialize();
}
else {
$vcal->add($vt);
}
}
}
if ($write) {
echo "END:VCALENDAR\r\n";
return true;
}
else {
return $vcal->serialize();
}
}
/**
* Build a valid iCal format block from the given event
*
* @param array Hash array with event/task properties from libkolab
* @param object VCalendar object to append event to or false for directly sending data to stdout
* @param callable Callback function to fetch attachment contents, false if no attachment export
* @param object RECURRENCE-ID property when serializing a recurrence exception
*/
private function _to_ical($event, $vcal, $get_attachment, $recurrence_id = null)
{
$type = !empty($event['_type']) ? $event['_type'] : 'event';
$cal = $vcal ?: new VObject\Component\VCalendar();
$ve = $cal->create($this->type_component_map[$type]);
$ve->UID = $event['uid'];
// set DTSTAMP according to RFC 5545, 3.8.7.2.
$dtstamp = !empty($event['changed']) && empty($this->method) ? $event['changed'] : new DateTime('now', new \DateTimeZone('UTC'));
$ve->DTSTAMP = $this->datetime_prop($cal, 'DTSTAMP', $dtstamp, true);
// all-day events end the next day
if (!empty($event['allday']) && !empty($event['end'])) {
$event['end'] = clone $event['end'];
$event['end']->add(new \DateInterval('P1D'));
$event['end']->_dateonly = true;
}
if (!empty($event['created'])) {
$ve->add($this->datetime_prop($cal, 'CREATED', $event['created'], true));
}
if (!empty($event['changed'])) {
$ve->add($this->datetime_prop($cal, 'LAST-MODIFIED', $event['changed'], true));
}
if (!empty($event['start'])) {
$ve->add($this->datetime_prop($cal, 'DTSTART', $event['start'], false, !empty($event['allday'])));
}
if (!empty($event['end'])) {
$ve->add($this->datetime_prop($cal, 'DTEND', $event['end'], false, !empty($event['allday'])));
}
if (!empty($event['due'])) {
$ve->add($this->datetime_prop($cal, 'DUE', $event['due'], false));
}
// we're exporting a recurrence instance only
if (!$recurrence_id && !empty($event['recurrence_date']) && $event['recurrence_date'] instanceof DateTimeInterface) {
$recurrence_id = $this->datetime_prop($cal, 'RECURRENCE-ID', $event['recurrence_date'], false, !empty($event['allday']));
if (!empty($event['thisandfuture'])) {
$recurrence_id->add('RANGE', 'THISANDFUTURE');
}
}
if ($recurrence_id) {
$ve->add($recurrence_id);
}
$ve->add('SUMMARY', $event['title']);
if (!empty($event['location'])) {
$ve->add($this->is_apple() ? new vobject_location_property($cal, 'LOCATION', $event['location']) : $cal->create('LOCATION', $event['location']));
}
if (!empty($event['description'])) {
$ve->add('DESCRIPTION', strtr($event['description'], array("\r\n" => "\n", "\r" => "\n"))); // normalize line endings
}
if (isset($event['sequence'])) {
$ve->add('SEQUENCE', $event['sequence']);
}
if (!empty($event['recurrence']) && !$recurrence_id) {
$exdates = $rdates = null;
if (isset($event['recurrence']['EXDATE'])) {
$exdates = $event['recurrence']['EXDATE'];
unset($event['recurrence']['EXDATE']); // don't serialize EXDATEs into RRULE value
}
if (isset($event['recurrence']['RDATE'])) {
$rdates = $event['recurrence']['RDATE'];
unset($event['recurrence']['RDATE']); // don't serialize RDATEs into RRULE value
}
if (!empty($event['recurrence']['FREQ'])) {
$ve->add('RRULE', libcalendaring::to_rrule($event['recurrence'], !empty($event['allday'])));
}
// add EXDATEs each one per line (for Thunderbird Lightning)
if (is_array($exdates)) {
foreach ($exdates as $exdate) {
if ($exdate instanceof DateTimeInterface) {
$ve->add($this->datetime_prop($cal, 'EXDATE', $exdate));
}
}
}
// add RDATEs
if (is_array($rdates)) {
foreach ($rdates as $rdate) {
$ve->add($this->datetime_prop($cal, 'RDATE', $rdate));
}
}
}
if (!empty($event['categories'])) {
$cat = $cal->create('CATEGORIES');
$cat->setParts((array)$event['categories']);
$ve->add($cat);
}
if (!empty($event['free_busy'])) {
$ve->add('TRANSP', $event['free_busy'] == 'free' ? 'TRANSPARENT' : 'OPAQUE');
// for Outlook clients we provide the X-MICROSOFT-CDO-BUSYSTATUS property
if (stripos($this->agent, 'outlook') !== false) {
$ve->add('X-MICROSOFT-CDO-BUSYSTATUS', $event['free_busy'] == 'outofoffice' ? 'OOF' : strtoupper($event['free_busy']));
}
}
if (!empty($event['priority'])) {
$ve->add('PRIORITY', $event['priority']);
}
if (!empty($event['cancelled'])) {
$ve->add('STATUS', 'CANCELLED');
}
else if (!empty($event['free_busy']) && $event['free_busy'] == 'tentative') {
$ve->add('STATUS', 'TENTATIVE');
}
else if (!empty($event['complete']) && $event['complete'] == 100) {
$ve->add('STATUS', 'COMPLETED');
}
else if (!empty($event['status'])) {
$ve->add('STATUS', $event['status']);
}
if (!empty($event['complete'])) {
$ve->add('PERCENT-COMPLETE', intval($event['complete']));
}
// Apple iCal and BusyCal required the COMPLETED date to be set in order to consider a task complete
if (
(!empty($event['status']) && $event['status'] == 'COMPLETED')
|| (!empty($event['complete']) && $event['complete'] == 100)
) {
$completed = !empty($event['changed']) ? $event['changed'] : new DateTime('now - 1 hour');
$ve->add($this->datetime_prop($cal, 'COMPLETED', $completed, true));
}
if (!empty($event['valarms'])) {
foreach ($event['valarms'] as $alarm) {
$va = $cal->createComponent('VALARM');
$va->action = $alarm['action'];
if ($alarm['trigger'] instanceof DateTimeInterface) {
$va->add($this->datetime_prop($cal, 'TRIGGER', $alarm['trigger'], true, null, true));
}
else {
$alarm_props = array();
if (!empty($alarm['related']) && strtoupper($alarm['related']) == 'END') {
$alarm_props['RELATED'] = 'END';
}
$va->add('TRIGGER', $alarm['trigger'], $alarm_props);
}
if (!empty($alarm['action']) && $alarm['action'] == 'EMAIL') {
if (!empty($alarm['attendees'])) {
foreach ((array) $alarm['attendees'] as $attendee) {
$va->add('ATTENDEE', 'mailto:' . $attendee);
}
}
}
if (!empty($alarm['description'])) {
$va->add('DESCRIPTION', $alarm['description']);
}
if (!empty($alarm['summary'])) {
$va->add('SUMMARY', $alarm['summary']);
}
if (!empty($alarm['duration'])) {
$va->add('DURATION', $alarm['duration']);
$va->add('REPEAT', !empty($alarm['repeat']) ? intval($alarm['repeat']) : 0);
}
if (!empty($alarm['uri'])) {
$va->add('ATTACH', $alarm['uri'], array('VALUE' => 'URI'));
}
$ve->add($va);
}
}
// legacy support
else if (!empty($event['alarms'])) {
$va = $cal->createComponent('VALARM');
list($trigger, $va->action) = explode(':', $event['alarms']);
$val = libcalendaring::parse_alarm_value($trigger);
if (!empty($val[3])) {
$va->add('TRIGGER', $val[3]);
}
else if ($val[0] instanceof DateTimeInterface) {
$va->add($this->datetime_prop($cal, 'TRIGGER', $val[0], true, null, true));
}
$ve->add($va);
}
// Find SCHEDULE-AGENT
if (!empty($event['x-custom'])) {
foreach ((array) $event['x-custom'] as $prop) {
if ($prop[0] === 'SCHEDULE-AGENT') {
$schedule_agent = $prop[1];
}
}
}
if (!empty($event['attendees'])) {
foreach ((array) $event['attendees'] as $attendee) {
if ($attendee['role'] == 'ORGANIZER') {
if (empty($event['organizer']))
$event['organizer'] = $attendee;
}
else if (!empty($attendee['email'])) {
if (isset($attendee['rsvp'])) {
$attendee['rsvp'] = $attendee['rsvp'] ? 'TRUE' : null;
}
$mailto = $attendee['email'];
$attendee = array_filter(self::map_keys($attendee, $this->attendee_keymap));
if (isset($schedule_agent) && !isset($attendee['SCHEDULE-AGENT'])) {
$attendee['SCHEDULE-AGENT'] = $schedule_agent;
}
$ve->add('ATTENDEE', 'mailto:' . $mailto, $attendee);
}
}
}
if (!empty($event['organizer'])) {
$organizer = array_filter(self::map_keys($event['organizer'], $this->organizer_keymap));
if (isset($schedule_agent) && !isset($organizer['SCHEDULE-AGENT'])) {
$organizer['SCHEDULE-AGENT'] = $schedule_agent;
}
$ve->add('ORGANIZER', 'mailto:' . $event['organizer']['email'], $organizer);
}
if (!empty($event['url'])) {
foreach ((array) $event['url'] as $url) {
if (!empty($url)) {
$ve->add('URL', $url);
}
}
}
if (!empty($event['parent_id'])) {
$ve->add('RELATED-TO', $event['parent_id'], array('RELTYPE' => 'PARENT'));
}
if (!empty($event['comment'])) {
$ve->add('COMMENT', $event['comment']);
}
$memory_limit = parse_bytes(ini_get('memory_limit'));
// export attachments
if (!empty($event['attachments'])) {
foreach ((array)$event['attachments'] as $attach) {
// check available memory and skip attachment export if we can't buffer it
// @todo: use rcube_utils::mem_check()
if (is_callable($get_attachment) && $memory_limit > 0 && ($memory_used = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024)
&& $attach['size'] && $memory_used + $attach['size'] * 3 > $memory_limit) {
continue;
}
// embed attachments using the given callback function
if (is_callable($get_attachment) && ($data = call_user_func($get_attachment, $attach['id'], $event))) {
// embed attachments for iCal
$ve->add('ATTACH',
$data,
array_filter(array('VALUE' => 'BINARY', 'ENCODING' => 'BASE64', 'FMTTYPE' => $attach['mimetype'], 'X-LABEL' => $attach['name'])));
unset($data); // attempt to free memory
}
// list attachments as absolute URIs
else if (!empty($this->attach_uri)) {
$ve->add('ATTACH',
strtr($this->attach_uri, array(
'{{id}}' => urlencode($attach['id']),
'{{name}}' => urlencode($attach['name']),
'{{mimetype}}' => urlencode($attach['mimetype']),
)),
array('FMTTYPE' => $attach['mimetype'], 'VALUE' => 'URI'));
}
}
}
if (!empty($event['links'])) {
foreach ((array) $event['links'] as $uri) {
$ve->add('ATTACH', $uri);
}
}
// add custom properties
if (!empty($event['x-custom'])) {
foreach ((array) $event['x-custom'] as $prop) {
$ve->add($prop[0], $prop[1]);
}
}
// append to vcalendar container
if ($vcal) {
$vcal->add($ve);
}
else { // serialize and send to stdout
echo $ve->serialize();
}
// append recurrence exceptions
if (!empty($event['recurrence']) && !empty($event['recurrence']['EXCEPTIONS'])) {
foreach ($event['recurrence']['EXCEPTIONS'] as $ex) {
$exdate = !empty($ex['recurrence_date']) ? $ex['recurrence_date'] : $ex['start'];
$recurrence_id = $this->datetime_prop($cal, 'RECURRENCE-ID', $exdate, false, !empty($event['allday']));
if (!empty($ex['thisandfuture'])) {
$recurrence_id->add('RANGE', 'THISANDFUTURE');
}
$ex['uid'] = $ve->UID;
$this->_to_ical($ex, $vcal, $get_attachment, $recurrence_id);
}
}
}
/**
* Returns a VTIMEZONE component for a Olson timezone identifier
* with daylight transitions covering the given date range.
*
* @param string Timezone ID as used in PHP's Date functions
* @param integer Unix timestamp with first date/time in this timezone
* @param integer Unix timestap with last date/time in this timezone
* @param VObject\Component\VCalendar Optional VCalendar component
*
* @return mixed A Sabre\VObject\Component object representing a VTIMEZONE definition
* or false if no timezone information is available
*/
public static function get_vtimezone($tzid, $from = 0, $to = 0, $cal = null)
{
// TODO: Consider using tzurl.org database for better interoperability e.g. with Outlook
if (!$from) $from = time();
if (!$to) $to = $from;
if (!$cal) $cal = new VObject\Component\VCalendar();
if (is_string($tzid)) {
try {
$tz = new \DateTimeZone($tzid);
}
catch (\Exception $e) {
return false;
}
}
else if (is_a($tzid, '\\DateTimeZone')) {
$tz = $tzid;
}
if (empty($tz) || !is_a($tz, '\\DateTimeZone')) {
return false;
}
$year = 86400 * 360;
$transitions = $tz->getTransitions($from - $year, $to + $year);
// Make sure VTIMEZONE contains at least one STANDARD/DAYLIGHT component
// when there's only one transition in specified time period (T5626)
if (count($transitions) == 1) {
// Get more transitions and use OFFSET from the previous to last
$more_transitions = $tz->getTransitions(0, $to + $year);
if (count($more_transitions) > 1) {
$index = count($more_transitions) - 2;
$tzfrom = $more_transitions[$index]['offset'] / 3600;
}
}
$vt = $cal->createComponent('VTIMEZONE');
$vt->TZID = $tz->getName();
$std = null; $dst = null;
foreach ($transitions as $i => $trans) {
$cmp = null;
if (!isset($tzfrom)) {
$tzfrom = $trans['offset'] / 3600;
continue;
}
if ($trans['isdst']) {
$t_dst = $trans['ts'];
$dst = $cal->createComponent('DAYLIGHT');
$cmp = $dst;
}
else {
$t_std = $trans['ts'];
$std = $cal->createComponent('STANDARD');
$cmp = $std;
}
if ($cmp) {
$dt = new DateTime($trans['time']);
$offset = $trans['offset'] / 3600;
$cmp->DTSTART = $dt->format('Ymd\THis');
$cmp->TZOFFSETFROM = sprintf('%+03d%02d', floor($tzfrom), ($tzfrom - floor($tzfrom)) * 60);
$cmp->TZOFFSETTO = sprintf('%+03d%02d', floor($offset), ($offset - floor($offset)) * 60);
if (!empty($trans['abbr'])) {
$cmp->TZNAME = $trans['abbr'];
}
$tzfrom = $offset;
$vt->add($cmp);
}
// we covered the entire date range
if ($std && $dst && min($t_std, $t_dst) < $from && max($t_std, $t_dst) > $to) {
break;
}
}
// add X-MICROSOFT-CDO-TZID if available
$microsoftExchangeMap = array_flip(VObject\TimeZoneUtil::$microsoftExchangeMap);
if (array_key_exists($tz->getName(), $microsoftExchangeMap)) {
$vt->add('X-MICROSOFT-CDO-TZID', $microsoftExchangeMap[$tz->getName()]);
}
return $vt;
}
/*** Implement PHP 5 Iterator interface to make foreach work ***/
#[\ReturnTypeWillChange]
function current()
{
return $this->objects[$this->iteratorkey];
}
#[\ReturnTypeWillChange]
function key()
{
return $this->iteratorkey;
}
#[\ReturnTypeWillChange]
function next()
{
$this->iteratorkey++;
// read next chunk if we're reading from a file
if (empty($this->objects[$this->iteratorkey]) && $this->fp) {
$this->_parse_next(true);
}
return $this->valid();
}
#[\ReturnTypeWillChange]
function rewind()
{
$this->iteratorkey = 0;
}
#[\ReturnTypeWillChange]
function valid()
{
return !empty($this->objects[$this->iteratorkey]);
}
}
/**
* Override Sabre\VObject\Property\Text that quotes commas in the location property
* because Apple clients treat that property as list.
*/
class vobject_location_property extends VObject\Property\Text
{
/**
* List of properties that are considered 'structured'.
*
* @var array
*/
- protected $structuredValues = array(
+ protected $structuredValues = [
// vCard
'N',
'ADR',
'ORG',
'GENDER',
'LOCATION',
// iCalendar
'REQUEST-STATUS',
- );
+ ];
}
diff --git a/plugins/libcalendaring/libcalendaring.php b/plugins/libcalendaring/libcalendaring.php
index 6d7c2d6a..38884b81 100644
--- a/plugins/libcalendaring/libcalendaring.php
+++ b/plugins/libcalendaring/libcalendaring.php
@@ -1,1582 +1,1583 @@
<?php
/**
* Library providing common functions for calendaring plugins
*
* Provides utility functions for calendar-related modules such as
* - alarms display and dismissal
* - attachment handling
* - recurrence computation and UI elements
* - ical parsing and exporting
* - itip scheduling protocol
*
* @version @package_version@
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 2012-2015, Kolab Systems AG <contact@kolabsys.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class libcalendaring extends rcube_plugin
{
public $rc;
public $timezone;
public $gmt_offset;
public $dst_active;
public $timezone_offset;
public $ical_parts = array();
public $ical_message;
public $defaults = array(
'calendar_date_format' => "Y-m-d",
'calendar_date_short' => "M-j",
'calendar_date_long' => "F j Y",
'calendar_date_agenda' => "l M-d",
'calendar_time_format' => "H:m",
'calendar_first_day' => 1,
'calendar_first_hour' => 6,
'calendar_date_format_sets' => array(
'Y-m-d' => array('d M Y', 'm-d', 'l m-d'),
'Y/m/d' => array('d M Y', 'm/d', 'l m/d'),
'Y.m.d' => array('d M Y', 'm.d', 'l m.d'),
'd-m-Y' => array('d M Y', 'd-m', 'l d-m'),
'd/m/Y' => array('d M Y', 'd/m', 'l d/m'),
'd.m.Y' => array('d M Y', 'd.m', 'l d.m'),
'j.n.Y' => array('d M Y', 'd.m', 'l d.m'),
'm/d/Y' => array('M d Y', 'm/d', 'l m/d'),
),
);
private static $instance;
private $mail_ical_parser;
/**
* Singleton getter to allow direct access from other plugins
*/
public static function get_instance()
{
if (!self::$instance) {
self::$instance = new libcalendaring(rcube::get_instance()->plugins);
self::$instance->init_instance();
}
return self::$instance;
}
/**
* Initializes class properties
*/
public function init_instance()
{
$this->rc = rcube::get_instance();
// set user's timezone
try {
$this->timezone = new DateTimeZone($this->rc->config->get('timezone', 'GMT'));
}
catch (Exception $e) {
$this->timezone = new DateTimeZone('GMT');
}
$now = new DateTime('now', $this->timezone);
$this->gmt_offset = $now->getOffset();
$this->dst_active = $now->format('I');
$this->timezone_offset = $this->gmt_offset / 3600 - $this->dst_active;
$this->add_texts('localization/', false);
}
/**
* Required plugin startup method
*/
public function init()
{
+ // extend include path to load bundled lib classes
+ $include_path = $this->home . '/lib' . PATH_SEPARATOR . ini_get('include_path');
+ set_include_path($include_path);
+
self::$instance = $this;
$this->rc = rcube::get_instance();
$this->init_instance();
// include client scripts and styles
if ($this->rc->output) {
// add hook to display alarms
$this->add_hook('refresh', array($this, 'refresh'));
$this->register_action('plugin.alarms', array($this, 'alarms_action'));
$this->register_action('plugin.expand_attendee_group', array($this, 'expand_attendee_group'));
}
// proceed initialization in startup hook
$this->add_hook('startup', array($this, 'startup'));
}
/**
* Startup hook
*/
public function startup($args)
{
if ($this->rc->output && $this->rc->output->type == 'html') {
$this->rc->output->set_env('libcal_settings', $this->load_settings());
$this->include_script('libcalendaring.js');
$this->include_stylesheet($this->local_skin_path() . '/libcal.css');
$this->add_label(
'itipaccepted', 'itiptentative', 'itipdeclined',
'itipdelegated', 'expandattendeegroup', 'expandattendeegroupnodata',
'statusorganizer', 'statusaccepted', 'statusdeclined',
'statusdelegated', 'statusunknown', 'statusneeds-action',
'statustentative', 'statuscompleted', 'statusin-process',
'delegatedto', 'delegatedfrom', 'showmore'
);
}
if ($args['task'] == 'mail') {
if ($args['action'] == 'show' || $args['action'] == 'preview') {
$this->add_hook('message_load', array($this, 'mail_message_load'));
}
}
}
/**
* Load iCalendar functions
*/
public static function get_ical()
{
$self = self::get_instance();
- require_once __DIR__ . '/libvcalendar.php';
- return new libvcalendar();
+ return new libcalendaring_vcalendar();
}
/**
* Load iTip functions
*/
public static function get_itip($domain = 'libcalendaring')
{
$self = self::get_instance();
- require_once __DIR__ . '/lib/libcalendaring_itip.php';
return new libcalendaring_itip($self, $domain);
}
/**
* Load recurrence computation engine
*/
public static function get_recurrence()
{
$self = self::get_instance();
- require_once __DIR__ . '/lib/libcalendaring_recurrence.php';
return new libcalendaring_recurrence($self);
}
/**
* Shift dates into user's current timezone
*
* @param mixed Any kind of a date representation (DateTime object, string or unix timestamp)
* @return object DateTime object in user's timezone
*/
public function adjust_timezone($dt, $dateonly = false)
{
if (is_numeric($dt)) {
$dt = new DateTime('@'.$dt);
}
else if (is_string($dt)) {
$dt = rcube_utils::anytodatetime($dt);
}
if ($dt instanceof DateTimeInterface && empty($dt->_dateonly) && !$dateonly) {
$dt->setTimezone($this->timezone);
}
return $dt;
}
/**
*
*/
public function load_settings()
{
$this->date_format_defaults();
$settings = array();
$keys = array('date_format', 'time_format', 'date_short', 'date_long', 'date_agenda');
foreach ($keys as $key) {
$settings[$key] = (string)$this->rc->config->get('calendar_' . $key, $this->defaults['calendar_' . $key]);
$settings[$key] = self::from_php_date_format($settings[$key]);
}
$settings['dates_long'] = $settings['date_long'];
$settings['first_day'] = (int)$this->rc->config->get('calendar_first_day', $this->defaults['calendar_first_day']);
$settings['timezone'] = $this->timezone_offset;
$settings['dst'] = $this->dst_active;
// localization
$settings['days'] = array(
$this->rc->gettext('sunday'), $this->rc->gettext('monday'),
$this->rc->gettext('tuesday'), $this->rc->gettext('wednesday'),
$this->rc->gettext('thursday'), $this->rc->gettext('friday'),
$this->rc->gettext('saturday')
);
$settings['days_short'] = array(
$this->rc->gettext('sun'), $this->rc->gettext('mon'),
$this->rc->gettext('tue'), $this->rc->gettext('wed'),
$this->rc->gettext('thu'), $this->rc->gettext('fri'),
$this->rc->gettext('sat')
);
$settings['months'] = array(
$this->rc->gettext('longjan'), $this->rc->gettext('longfeb'),
$this->rc->gettext('longmar'), $this->rc->gettext('longapr'),
$this->rc->gettext('longmay'), $this->rc->gettext('longjun'),
$this->rc->gettext('longjul'), $this->rc->gettext('longaug'),
$this->rc->gettext('longsep'), $this->rc->gettext('longoct'),
$this->rc->gettext('longnov'), $this->rc->gettext('longdec')
);
$settings['months_short'] = array(
$this->rc->gettext('jan'), $this->rc->gettext('feb'),
$this->rc->gettext('mar'), $this->rc->gettext('apr'),
$this->rc->gettext('may'), $this->rc->gettext('jun'),
$this->rc->gettext('jul'), $this->rc->gettext('aug'),
$this->rc->gettext('sep'), $this->rc->gettext('oct'),
$this->rc->gettext('nov'), $this->rc->gettext('dec')
);
$settings['today'] = $this->rc->gettext('today');
return $settings;
}
/**
* Helper function to set date/time format according to config and user preferences
*/
private function date_format_defaults()
{
static $defaults = array();
// nothing to be done
if (isset($defaults['date_format']))
return;
$defaults['date_format'] = $this->rc->config->get('calendar_date_format', $this->rc->config->get('date_format'));
$defaults['time_format'] = $this->rc->config->get('calendar_time_format', $this->rc->config->get('time_format'));
// override defaults
if ($defaults['date_format'])
$this->defaults['calendar_date_format'] = $defaults['date_format'];
if ($defaults['time_format'])
$this->defaults['calendar_time_format'] = $defaults['time_format'];
// derive format variants from basic date format
$format_sets = $this->rc->config->get('calendar_date_format_sets', $this->defaults['calendar_date_format_sets']);
if ($format_set = $format_sets[$this->defaults['calendar_date_format']]) {
$this->defaults['calendar_date_long'] = $format_set[0];
$this->defaults['calendar_date_short'] = $format_set[1];
$this->defaults['calendar_date_agenda'] = $format_set[2];
}
}
/**
* Compose a date string for the given event
*/
public function event_date_text($event)
{
$fromto = '--';
$is_task = !empty($event['_type']) && $event['_type'] == 'task';
$this->date_format_defaults();
$date_format = self::to_php_date_format($this->rc->config->get('calendar_date_format', $this->defaults['calendar_date_format']));
$time_format = self::to_php_date_format($this->rc->config->get('calendar_time_format', $this->defaults['calendar_time_format']));
$getTimezone = function ($date) {
if ($newTz = $date->getTimezone()) {
return $newTz->getName();
}
return '';
};
$formatDate = function ($date, $format) use ($getTimezone) {
// This is a workaround for the rcmail::format_date() which does not play nice with timezone
$tz = $this->rc->config->get('timezone');
if ($dateTz = $getTimezone($date)) {
$this->rc->config->set('timezone', $dateTz);
}
$result = $this->rc->format_date($date, $format);
$this->rc->config->set('timezone', $tz);
return $result;
};
// handle task objects
if ($is_task && !empty($event['due']) && is_object($event['due'])) {
$fromto = $formatDate($event['due'], !empty($event['due']->_dateonly) ? $date_format : null);
// add timezone information
if ($fromto && empty($event['due']->_dateonly) && ($tz = $getTimezone($event['due']))) {
$fromto .= ' (' . strtr($tz, '_', ' ') . ')';
}
return $fromto;
}
// abort if no valid event dates are given
if (!is_object($event['start']) || !is_a($event['start'], 'DateTime') || !is_object($event['end']) || !is_a($event['end'], 'DateTime')) {
return $fromto;
}
if ($event['allday']) {
$fromto = $formatDate($event['start'], $date_format);
if (($todate = $formatDate($event['end'], $date_format)) != $fromto) {
$fromto .= ' - ' . $todate;
}
}
else if ($event['start']->format('Ymd') === $event['end']->format('Ymd')) {
$fromto = $formatDate($event['start'], $date_format) . ' ' . $formatDate($event['start'], $time_format) .
' - ' . $formatDate($event['end'], $time_format);
}
else {
$fromto = $formatDate($event['start'], $date_format) . ' ' . $formatDate($event['start'], $time_format) .
' - ' . $formatDate($event['end'], $date_format) . ' ' . $formatDate($event['end'], $time_format);
}
// add timezone information
if ($fromto && empty($event['allday']) && ($tz = $getTimezone($event['start']))) {
$fromto .= ' (' . strtr($tz, '_', ' ') . ')';
}
return $fromto;
}
/**
* Render HTML form for alarm configuration
*/
public function alarm_select($attrib, $alarm_types, $absolute_time = true)
{
unset($attrib['name']);
$input_value = new html_inputfield(array('name' => 'alarmvalue[]', 'class' => 'edit-alarm-value form-control', 'size' => 3));
$input_date = new html_inputfield(array('name' => 'alarmdate[]', 'class' => 'edit-alarm-date form-control', 'size' => 10));
$input_time = new html_inputfield(array('name' => 'alarmtime[]', 'class' => 'edit-alarm-time form-control', 'size' => 6));
$select_type = new html_select(array('name' => 'alarmtype[]', 'class' => 'edit-alarm-type form-control', 'id' => $attrib['id']));
$select_offset = new html_select(array('name' => 'alarmoffset[]', 'class' => 'edit-alarm-offset form-control'));
$select_related = new html_select(array('name' => 'alarmrelated[]', 'class' => 'edit-alarm-related form-control'));
$object_type = !empty($attrib['_type']) ? $attrib['_type'] : 'event';
$select_type->add($this->gettext('none'), '');
foreach ($alarm_types as $type) {
$select_type->add($this->gettext(strtolower("alarm{$type}option")), $type);
}
foreach (array('-M','-H','-D','+M','+H','+D') as $trigger) {
$select_offset->add($this->gettext('trigger' . $trigger), $trigger);
}
$select_offset->add($this->gettext('trigger0'), '0');
if ($absolute_time) {
$select_offset->add($this->gettext('trigger@'), '@');
}
$select_related->add($this->gettext('relatedstart'), 'start');
$select_related->add($this->gettext('relatedend' . $object_type), 'end');
// pre-set with default values from user settings
$preset = self::parse_alarm_value($this->rc->config->get('calendar_default_alarm_offset', '-15M'));
$hidden = array('style' => 'display:none');
return html::span('edit-alarm-set',
$select_type->show($this->rc->config->get('calendar_default_alarm_type', '')) . ' ' .
html::span(array('class' => 'edit-alarm-values input-group', 'style' => 'display:none'),
$input_value->show($preset[0]) . ' ' .
$select_offset->show($preset[1]) . ' ' .
$select_related->show() . ' ' .
$input_date->show('', $hidden) . ' ' .
$input_time->show('', $hidden)
)
);
}
/**
* Get a list of email addresses of the given user (from login and identities)
*
* @param string User Email (default to current user)
*
* @return array Email addresses related to the user
*/
public function get_user_emails($user = null)
{
static $_emails = array();
if (empty($user)) {
$user = $this->rc->user->get_username();
}
// return cached result
if (isset($_emails[$user])) {
return $_emails[$user];
}
$emails = array($user);
$plugin = $this->rc->plugins->exec_hook('calendar_user_emails', array('emails' => $emails));
$emails = array_map('strtolower', $plugin['emails']);
// add all emails from the current user's identities
if (!$plugin['abort'] && ($user == $this->rc->user->get_username())) {
foreach ($this->rc->user->list_emails() as $identity) {
$emails[] = strtolower($identity['email']);
}
}
$_emails[$user] = array_unique($emails);
return $_emails[$user];
}
/**
* Set the given participant status to the attendee matching the current user's identities
* Unsets 'rsvp' flag too.
*
* @param array &$event Event data
* @param string $status The PARTSTAT value to set
* @param bool $recursive Recurive call
*
* @return mixed Email address of the updated attendee or False if none matching found
*/
public function set_partstat(&$event, $status, $recursive = true)
{
$success = false;
$emails = $this->get_user_emails();
foreach ((array)$event['attendees'] as $i => $attendee) {
if ($attendee['email'] && in_array(strtolower($attendee['email']), $emails)) {
$event['attendees'][$i]['status'] = strtoupper($status);
unset($event['attendees'][$i]['rsvp']);
$success = $attendee['email'];
}
}
// apply partstat update to each existing exception
if ($event['recurrence'] && is_array($event['recurrence']['EXCEPTIONS'])) {
foreach ($event['recurrence']['EXCEPTIONS'] as $i => $exception) {
$this->set_partstat($event['recurrence']['EXCEPTIONS'][$i], $status, false);
}
// set link to top-level exceptions
$event['exceptions'] = &$event['recurrence']['EXCEPTIONS'];
}
return $success;
}
/********* Alarms handling *********/
/**
* Helper function to convert alarm trigger strings
* into two-field values (e.g. "-45M" => 45, "-M")
*/
public static function parse_alarm_value($val)
{
if ($val[0] == '@') {
return array(new DateTime($val));
}
else if (preg_match('/([+-]?)P?(T?\d+[HMSDW])+/', $val, $m) && preg_match_all('/T?(\d+)([HMSDW])/', $val, $m2, PREG_SET_ORDER)) {
if ($m[1] == '')
$m[1] = '+';
foreach ($m2 as $seg) {
$prefix = $seg[2] == 'D' || $seg[2] == 'W' ? 'P' : 'PT';
if ($seg[1] > 0) { // ignore zero values
// convert seconds to minutes
if ($seg[2] == 'S') {
$seg[2] = 'M';
$seg[1] = max(1, round($seg[1]/60));
}
return array($seg[1], $m[1].$seg[2], $m[1].$seg[1].$seg[2], $m[1].$prefix.$seg[1].$seg[2]);
}
}
// return zero value nevertheless
return array($seg[1], $m[1].$seg[2], $m[1].$seg[1].$seg[2], $m[1].$prefix.$seg[1].$seg[2]);
}
return false;
}
/**
* Convert the alarms list items to be processed on the client
*/
public static function to_client_alarms($valarms)
{
return array_map(function($alarm) {
if ($alarm['trigger'] instanceof DateTimeInterface) {
$alarm['trigger'] = '@' . $alarm['trigger']->format('U');
}
else if ($trigger = libcalendaring::parse_alarm_value($alarm['trigger'])) {
$alarm['trigger'] = $trigger[2];
}
return $alarm;
}, (array)$valarms);
}
/**
* Process the alarms values submitted by the client
*/
public static function from_client_alarms($valarms)
{
return array_map(function($alarm){
if ($alarm['trigger'][0] == '@') {
try {
$alarm['trigger'] = new DateTime($alarm['trigger']);
$alarm['trigger']->setTimezone(new DateTimeZone('UTC'));
}
catch (Exception $e) { /* handle this ? */ }
}
else if ($trigger = libcalendaring::parse_alarm_value($alarm['trigger'])) {
$alarm['trigger'] = $trigger[3];
}
return $alarm;
}, (array)$valarms);
}
/**
* Render localized text for alarm settings
*/
public static function alarms_text($alarms)
{
if (is_array($alarms) && is_array($alarms[0])) {
$texts = array();
foreach ($alarms as $alarm) {
if ($text = self::alarm_text($alarm))
$texts[] = $text;
}
return join(', ', $texts);
}
else {
return self::alarm_text($alarms);
}
}
/**
* Render localized text for a single alarm property
*/
public static function alarm_text($alarm)
{
$related = null;
if (is_string($alarm)) {
list($trigger, $action) = explode(':', $alarm);
}
else {
$trigger = $alarm['trigger'];
$action = $alarm['action'];
if (!empty($alarm['related'])) {
$related = $alarm['related'];
}
}
$text = '';
$rcube = rcube::get_instance();
switch ($action) {
case 'EMAIL':
$text = $rcube->gettext('libcalendaring.alarmemail');
break;
case 'DISPLAY':
$text = $rcube->gettext('libcalendaring.alarmdisplay');
break;
case 'AUDIO':
$text = $rcube->gettext('libcalendaring.alarmaudio');
break;
}
if ($trigger instanceof DateTimeInterface) {
$text .= ' ' . $rcube->gettext(array(
'name' => 'libcalendaring.alarmat',
'vars' => array('datetime' => $rcube->format_date($trigger))
));
}
else if (preg_match('/@(\d+)/', $trigger, $m)) {
$text .= ' ' . $rcube->gettext(array(
'name' => 'libcalendaring.alarmat',
'vars' => array('datetime' => $rcube->format_date($m[1]))
));
}
else if ($val = self::parse_alarm_value($trigger)) {
$r = $related && strtoupper($related) == 'END' ? 'end' : '';
// TODO: for all-day events say 'on date of event at XX' ?
if ($val[0] == 0) {
$text .= ' ' . $rcube->gettext('libcalendaring.triggerattime' . $r);
}
else {
$label = 'libcalendaring.trigger' . $r . $val[1];
$text .= ' ' . intval($val[0]) . ' ' . $rcube->gettext($label);
}
}
else {
return false;
}
return $text;
}
/**
* Get the next alarm (time & action) for the given event
*
* @param array Record data
* @return array Hash array with alarm time/type or null if no alarms are configured
*/
public static function get_next_alarm($rec, $type = 'event')
{
if (
(empty($rec['valarms']) && empty($rec['alarms']))
|| !empty($rec['cancelled'])
|| (!empty($rec['status']) && $rec['status'] == 'CANCELLED')
) {
return null;
}
if ($type == 'task') {
$timezone = self::get_instance()->timezone;
if (!empty($rec['startdate'])) {
$time = !empty($rec['starttime']) ? $rec['starttime'] : '12:00';
$rec['start'] = new DateTime($rec['startdate'] . ' ' . $time, $timezone);
}
if (!empty($rec['date'])) {
$time = !empty($rec['time']) ? $rec['time'] : '12:00';
$rec[!empty($rec['start']) ? 'end' : 'start'] = new DateTime($rec['date'] . ' ' . $time, $timezone);
}
}
if (empty($rec['end'])) {
$rec['end'] = $rec['start'];
}
// support legacy format
if (empty($rec['valarms'])) {
list($trigger, $action) = explode(':', $rec['alarms'], 2);
if ($alarm = self::parse_alarm_value($trigger)) {
$rec['valarms'] = array(array('action' => $action, 'trigger' => $alarm[3] ?: $alarm[0]));
}
}
// alarm ID eq. record ID by default to keep backwards compatibility
$alarm_id = isset($rec['id']) ? $rec['id'] : null;
$alarm_prop = null;
$expires = new DateTime('now - 12 hours');
$notify_at = null;
// handle multiple alarms
foreach ($rec['valarms'] as $alarm) {
$notify_time = null;
if ($alarm['trigger'] instanceof DateTimeInterface) {
$notify_time = $alarm['trigger'];
}
else if (is_string($alarm['trigger'])) {
$refdate = !empty($alarm['related']) && $alarm['related'] == 'END' ? $rec['end'] : $rec['start'];
// abort if no reference date is available to compute notification time
if (!is_a($refdate, 'DateTime')) {
continue;
}
// TODO: for all-day events, take start @ 00:00 as reference date ?
try {
$interval = new DateInterval(trim($alarm['trigger'], '+-'));
$interval->invert = $alarm['trigger'][0] == '-';
$notify_time = clone $refdate;
$notify_time->add($interval);
}
catch (Exception $e) {
rcube::raise_error($e, true);
continue;
}
}
if ($notify_time && (!$notify_at || ($notify_time > $notify_at && $notify_time > $expires))) {
$notify_at = $notify_time;
$action = isset($alarm['action']) ? $alarm['action'] : null;
$alarm_prop = $alarm;
// generate a unique alarm ID if multiple alarms are set
if (count($rec['valarms']) > 1) {
$rec_id = substr(md5(isset($rec['id']) ? $rec['id'] : 'none'), 0, 16);
$alarm_id = $rec_id . '-' . $notify_at->format('Ymd\THis');
}
}
}
return !$notify_at ? null : array(
'time' => $notify_at->format('U'),
'action' => !empty($action) ? strtoupper($action) : 'DISPLAY',
'id' => $alarm_id,
'prop' => $alarm_prop,
);
}
/**
* Handler for keep-alive requests
* This will check for pending notifications and pass them to the client
*/
public function refresh($attr)
{
// collect pending alarms from all providers (e.g. calendar, tasks)
$plugin = $this->rc->plugins->exec_hook('pending_alarms', array(
'time' => time(),
'alarms' => array(),
));
if (!$plugin['abort'] && !empty($plugin['alarms'])) {
// make sure texts and env vars are available on client
$this->add_texts('localization/', true);
$this->rc->output->add_label('close');
$this->rc->output->set_env('snooze_select', $this->snooze_select());
$this->rc->output->command('plugin.display_alarms', $this->_alarms_output($plugin['alarms']));
}
}
/**
* Handler for alarm dismiss/snooze requests
*/
public function alarms_action()
{
// $action = rcube_utils::get_input_value('action', rcube_utils::INPUT_GPC);
$data = rcube_utils::get_input_value('data', rcube_utils::INPUT_POST, true);
$data['ids'] = explode(',', $data['id']);
$plugin = $this->rc->plugins->exec_hook('dismiss_alarms', $data);
if (!empty($plugin['success'])) {
$this->rc->output->show_message('successfullysaved', 'confirmation');
}
else {
$this->rc->output->show_message('calendar.errorsaving', 'error');
}
}
/**
* Generate reduced and streamlined output for pending alarms
*/
private function _alarms_output($alarms)
{
$out = array();
foreach ($alarms as $alarm) {
$out[] = array(
'id' => $alarm['id'],
'start' => !empty($alarm['start']) ? $this->adjust_timezone($alarm['start'])->format('c') : '',
'end' => !empty($alarm['end'])? $this->adjust_timezone($alarm['end'])->format('c') : '',
'allDay' => !empty($alarm['allday']),
'action' => $alarm['action'],
'title' => $alarm['title'],
'location' => $alarm['location'],
'calendar' => $alarm['calendar'],
);
}
return $out;
}
/**
* Render a dropdown menu to choose snooze time
*/
private function snooze_select($attrib = array())
{
$steps = array(
5 => 'repeatinmin',
10 => 'repeatinmin',
15 => 'repeatinmin',
20 => 'repeatinmin',
30 => 'repeatinmin',
60 => 'repeatinhr',
120 => 'repeatinhrs',
1440 => 'repeattomorrow',
10080 => 'repeatinweek',
);
$items = array();
foreach ($steps as $n => $label) {
$items[] = html::tag('li', null, html::a(array('href' => "#" . ($n * 60), 'class' => 'active'),
$this->gettext(array('name' => $label, 'vars' => array('min' => $n % 60, 'hrs' => intval($n / 60))))));
}
return html::tag('ul', $attrib + array('class' => 'toolbarmenu menu'), join("\n", $items), html::$common_attrib);
}
/********* Recurrence rules handling ********/
/**
* Render localized text describing the recurrence rule of an event
*/
public function recurrence_text($rrule)
{
$limit = 10;
$exdates = array();
$format = $this->rc->config->get('calendar_date_format', $this->defaults['calendar_date_format']);
$format = self::to_php_date_format($format);
$format_fn = function($dt) use ($format) {
return rcmail::get_instance()->format_date($dt, $format);
};
if (!empty($rrule['EXDATE']) && is_array($rrule['EXDATE'])) {
$exdates = array_map($format_fn, $rrule['EXDATE']);
}
if (empty($rrule['FREQ']) && !empty($rrule['RDATE'])) {
$rdates = array_map($format_fn, $rrule['RDATE']);
$more = false;
if (!empty($exdates)) {
$rdates = array_diff($rdates, $exdates);
}
if (count($rdates) > $limit) {
$rdates = array_slice($rdates, 0, $limit);
$more = true;
}
return $this->gettext('ondate') . ' ' . join(', ', $rdates) . ($more ? '...' : '');
}
$output = sprintf('%s %d ', $this->gettext('every'), $rrule['INTERVAL'] ?: 1);
switch ($rrule['FREQ']) {
case 'DAILY':
$output .= $this->gettext('days');
break;
case 'WEEKLY':
$output .= $this->gettext('weeks');
break;
case 'MONTHLY':
$output .= $this->gettext('months');
break;
case 'YEARLY':
$output .= $this->gettext('years');
break;
}
if (!empty($rrule['COUNT'])) {
$until = $this->gettext(array('name' => 'forntimes', 'vars' => array('nr' => $rrule['COUNT'])));
}
else if (!empty($rrule['UNTIL'])) {
$until = $this->gettext('recurrencend') . ' ' . $this->rc->format_date($rrule['UNTIL'], $format);
}
else {
$until = $this->gettext('forever');
}
$output .= ', ' . $until;
if (!empty($exdates)) {
$more = false;
if (count($exdates) > $limit) {
$exdates = array_slice($exdates, 0, $limit);
$more = true;
}
$output .= '; ' . $this->gettext('except') . ' ' . join(', ', $exdates) . ($more ? '...' : '');
}
return $output;
}
/**
* Generate the form for recurrence settings
*/
public function recurrence_form($attrib = array())
{
switch ($attrib['part']) {
// frequency selector
case 'frequency':
$select = new html_select(array('name' => 'frequency', 'id' => 'edit-recurrence-frequency', 'class' => 'form-control'));
$select->add($this->gettext('never'), '');
$select->add($this->gettext('daily'), 'DAILY');
$select->add($this->gettext('weekly'), 'WEEKLY');
$select->add($this->gettext('monthly'), 'MONTHLY');
$select->add($this->gettext('yearly'), 'YEARLY');
$select->add($this->gettext('rdate'), 'RDATE');
$html = html::label(array('for' => 'edit-recurrence-frequency', 'class' => 'col-form-label col-sm-2'), $this->gettext('frequency'))
. html::div('col-sm-10', $select->show(''));
break;
// daily recurrence
case 'daily':
$select = $this->interval_selector(array('name' => 'interval', 'class' => 'edit-recurrence-interval form-control', 'id' => 'edit-recurrence-interval-daily'));
$html = html::div($attrib, html::label(array('for' => 'edit-recurrence-interval-daily', 'class' => 'col-form-label col-sm-2'), $this->gettext('every'))
. html::div('col-sm-10 input-group', $select->show(1) . html::span('label-after input-group-append', html::span('input-group-text', $this->gettext('days')))));
break;
// weekly recurrence form
case 'weekly':
$select = $this->interval_selector(array('name' => 'interval', 'class' => 'edit-recurrence-interval form-control', 'id' => 'edit-recurrence-interval-weekly'));
$html = html::div($attrib, html::label(array('for' => 'edit-recurrence-interval-weekly', 'class' => 'col-form-label col-sm-2'), $this->gettext('every'))
. html::div('col-sm-10 input-group', $select->show(1) . html::span('label-after input-group-append', html::span('input-group-text', $this->gettext('weeks')))));
// weekday selection
$daymap = array('sun','mon','tue','wed','thu','fri','sat');
$checkbox = new html_checkbox(array('name' => 'byday', 'class' => 'edit-recurrence-weekly-byday'));
$first = $this->rc->config->get('calendar_first_day', 1);
for ($weekdays = '', $j = $first; $j <= $first+6; $j++) {
$d = $j % 7;
$weekdays .= html::label(array('class' => 'weekday'),
$checkbox->show('', array('value' => strtoupper(substr($daymap[$d], 0, 2)))) .
$this->gettext($daymap[$d])
) . ' ';
}
$html .= html::div($attrib, html::label(array('class' => 'col-form-label col-sm-2'), $this->gettext('bydays'))
. html::div('col-sm-10 form-control-plaintext', $weekdays));
break;
// monthly recurrence form
case 'monthly':
$select = $this->interval_selector(array('name' => 'interval', 'class' => 'edit-recurrence-interval form-control', 'id' => 'edit-recurrence-interval-monthly'));
$html = html::div($attrib, html::label(array('for' => 'edit-recurrence-interval-monthly', 'class' => 'col-form-label col-sm-2'), $this->gettext('every'))
. html::div('col-sm-10 input-group', $select->show(1) . html::span('label-after input-group-append', html::span('input-group-text', $this->gettext('months')))));
$checkbox = new html_checkbox(array('name' => 'bymonthday', 'class' => 'edit-recurrence-monthly-bymonthday'));
for ($monthdays = '', $d = 1; $d <= 31; $d++) {
$monthdays .= html::label(array('class' => 'monthday'), $checkbox->show('', array('value' => $d)) . $d);
$monthdays .= $d % 7 ? ' ' : html::br();
}
// rule selectors
$radio = new html_radiobutton(array('name' => 'repeatmode', 'class' => 'edit-recurrence-monthly-mode'));
$table = new html_table(array('cols' => 2, 'border' => 0, 'cellpadding' => 0, 'class' => 'formtable'));
$table->add('label', html::label(null, $radio->show('BYMONTHDAY', array('value' => 'BYMONTHDAY')) . ' ' . $this->gettext('each')));
$table->add(null, $monthdays);
$table->add('label', html::label(null, $radio->show('', array('value' => 'BYDAY')) . ' ' . $this->gettext('every')));
$table->add('recurrence-onevery', $this->rrule_selectors($attrib['part']));
$html .= html::div($attrib, html::label(array('class' => 'col-form-label col-sm-2'), $this->gettext('bydays'))
. html::div('col-sm-10 form-control-plaintext', $table->show()));
break;
// annually recurrence form
case 'yearly':
$select = $this->interval_selector(array('name' => 'interval', 'class' => 'edit-recurrence-interval form-control', 'id' => 'edit-recurrence-interval-yearly'));
$html = html::div($attrib, html::label(array('for' => 'edit-recurrence-interval-yearly', 'class' => 'col-form-label col-sm-2'), $this->gettext('every'))
. html::div('col-sm-10 input-group', $select->show(1) . html::span('label-after input-group-append', html::span('input-group-text', $this->gettext('years')))));
// month selector
$monthmap = array('','jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec');
$checkbox = new html_checkbox(array('name' => 'bymonth', 'class' => 'edit-recurrence-yearly-bymonth'));
for ($months = '', $m = 1; $m <= 12; $m++) {
$months .= html::label(array('class' => 'month'), $checkbox->show(null, array('value' => $m)) . $this->gettext($monthmap[$m]));
$months .= $m % 4 ? ' ' : html::br();
}
$html .= html::div($attrib, html::label(array('class' => 'col-form-label col-sm-2'), $this->gettext('bymonths'))
. html::div('col-sm-10 form-control-plaintext',
html::div(array('id' => 'edit-recurrence-yearly-bymonthblock'), $months)
. html::div('recurrence-onevery', $this->rrule_selectors($attrib['part'], '---'))
));
break;
// end of recurrence form
case 'until':
$radio = new html_radiobutton(array('name' => 'repeat', 'class' => 'edit-recurrence-until'));
$select = $this->interval_selector(array('name' => 'times', 'id' => 'edit-recurrence-repeat-times', 'class' => 'form-control'));
$input = new html_inputfield(array('name' => 'untildate', 'id' => 'edit-recurrence-enddate', 'size' => '10', 'class' => 'form-control datepicker'));
$html = html::div('line first',
$radio->show('', array('value' => '', 'id' => 'edit-recurrence-repeat-forever'))
. ' ' . html::label('edit-recurrence-repeat-forever', $this->gettext('forever'))
);
$label = $this->gettext('ntimes');
if (strpos($label, '$') === 0) {
$label = str_replace('$n', '', $label);
$group = $select->show(1)
. html::span('input-group-append', html::span('input-group-text', rcube::Q($label)));
}
else {
$label = str_replace('$n', '', $label);
$group = html::span('input-group-prepend', html::span('input-group-text', rcube::Q($label)))
. $select->show(1);
}
$html .= html::div('line',
$radio->show('', array('value' => 'count', 'id' => 'edit-recurrence-repeat-count'))
. ' ' . html::label('edit-recurrence-repeat-count', $this->gettext('for'))
. ' ' . html::span('input-group', $group)
);
$html .= html::div('line',
$radio->show('', array('value' => 'until', 'id' => 'edit-recurrence-repeat-until', 'aria-label' => $this->gettext('untilenddate')))
. ' ' . html::label('edit-recurrence-repeat-until', $this->gettext('untildate'))
. ' ' . $input->show('', array('aria-label' => $this->gettext('untilenddate')))
);
$html = html::div($attrib, html::label(array('class' => 'col-form-label col-sm-2'), ucfirst($this->gettext('recurrencend')))
. html::div('col-sm-10', $html));
break;
case 'rdate':
$ul = html::tag('ul', array('id' => 'edit-recurrence-rdates', 'class' => 'recurrence-rdates'), '');
$input = new html_inputfield(array('name' => 'rdate', 'id' => 'edit-recurrence-rdate-input', 'size' => "10", 'class' => 'form-control datepicker'));
$button = new html_inputfield(array('type' => 'button', 'class' => 'button add', 'value' => $this->gettext('addrdate')));
$html = html::div($attrib, html::label(array('class' => 'col-form-label col-sm-2', 'for' => 'edit-recurrence-rdate-input'), $this->gettext('bydates'))
. html::div('col-sm-10', $ul . html::div('inputform', $input->show() . $button->show())));
break;
}
return $html;
}
/**
* Input field for interval selection
*/
private function interval_selector($attrib)
{
$select = new html_select($attrib);
$select->add(range(1,30), range(1,30));
return $select;
}
/**
* Drop-down menus for recurrence rules like "each last sunday of"
*/
private function rrule_selectors($part, $noselect = null)
{
// rule selectors
$select_prefix = new html_select(array('name' => 'bydayprefix', 'id' => "edit-recurrence-$part-prefix", 'class' => 'form-control'));
if ($noselect) $select_prefix->add($noselect, '');
$select_prefix->add(array(
$this->gettext('first'),
$this->gettext('second'),
$this->gettext('third'),
$this->gettext('fourth'),
$this->gettext('last')
),
array(1, 2, 3, 4, -1));
$select_wday = new html_select(array('name' => 'byday', 'id' => "edit-recurrence-$part-byday", 'class' => 'form-control'));
if ($noselect) $select_wday->add($noselect, '');
$daymap = array('sunday','monday','tuesday','wednesday','thursday','friday','saturday');
$first = $this->rc->config->get('calendar_first_day', 1);
for ($j = $first; $j <= $first+6; $j++) {
$d = $j % 7;
$select_wday->add($this->gettext($daymap[$d]), strtoupper(substr($daymap[$d], 0, 2)));
}
return $select_prefix->show() . '&nbsp;' . $select_wday->show();
}
/**
* Convert the recurrence settings to be processed on the client
*/
public function to_client_recurrence($recurrence, $allday = false)
{
if (!empty($recurrence['UNTIL'])) {
$recurrence['UNTIL'] = $this->adjust_timezone($recurrence['UNTIL'], $allday)->format('c');
}
// format RDATE values
if (!empty($recurrence['RDATE'])) {
$libcal = $this;
$recurrence['RDATE'] = array_map(function($rdate) use ($libcal) {
return $libcal->adjust_timezone($rdate, true)->format('c');
}, (array) $recurrence['RDATE']);
}
unset($recurrence['EXCEPTIONS']);
return $recurrence;
}
/**
* Process the alarms values submitted by the client
*/
public function from_client_recurrence($recurrence, $start = null)
{
if (is_array($recurrence) && !empty($recurrence['UNTIL'])) {
$recurrence['UNTIL'] = new DateTime($recurrence['UNTIL'], $this->timezone);
}
if (is_array($recurrence) && !empty($recurrence['RDATE'])) {
$tz = $this->timezone;
$recurrence['RDATE'] = array_map(function($rdate) use ($tz, $start) {
try {
$dt = new DateTime($rdate, $tz);
if (is_a($start, 'DateTime'))
$dt->setTime($start->format('G'), $start->format('i'));
return $dt;
}
catch (Exception $e) {
return null;
}
}, $recurrence['RDATE']);
}
return $recurrence;
}
/********* iTip message detection *********/
/**
* Check mail message structure of there are .ics files attached
*/
public function mail_message_load($p)
{
$this->ical_message = $p['object'];
$itip_part = null;
// check all message parts for .ics files
foreach ((array)$this->ical_message->mime_parts as $part) {
if (self::part_is_vcalendar($part, $this->ical_message)) {
if (!empty($part->ctype_parameters['method'])) {
$itip_part = $part->mime_id;
}
else {
$this->ical_parts[] = $part->mime_id;
}
}
}
// priorize part with method parameter
if ($itip_part) {
$this->ical_parts = array($itip_part);
}
}
/**
* Getter for the parsed iCal objects attached to the current email message
*
- * @return object libvcalendar parser instance with the parsed objects
+ * @return object libcalendaring_vcalendar parser instance with the parsed objects
*/
public function get_mail_ical_objects()
{
// create parser and load ical objects
if (!$this->mail_ical_parser) {
$this->mail_ical_parser = $this->get_ical();
foreach ($this->ical_parts as $mime_id) {
$part = $this->ical_message->mime_parts[$mime_id];
$charset = $part->ctype_parameters['charset'] ?: RCUBE_CHARSET;
$this->mail_ical_parser->import($this->ical_message->get_part_body($mime_id, true), $charset);
// check if the parsed object is an instance of a recurring event/task
array_walk($this->mail_ical_parser->objects, 'libcalendaring::identify_recurrence_instance');
// stop on the part that has an iTip method specified
if (count($this->mail_ical_parser->objects) && $this->mail_ical_parser->method) {
$this->mail_ical_parser->message_date = $this->ical_message->headers->date;
$this->mail_ical_parser->mime_id = $mime_id;
// store the message's sender address for comparisons
$from = rcube_mime::decode_address_list($this->ical_message->headers->from, 1, true, null, true);
$this->mail_ical_parser->sender = !empty($from) ? $from[1] : '';
if (!empty($this->mail_ical_parser->sender)) {
foreach ($this->mail_ical_parser->objects as $i => $object) {
$this->mail_ical_parser->objects[$i]['_sender'] = $this->mail_ical_parser->sender;
$this->mail_ical_parser->objects[$i]['_sender_utf'] = rcube_utils::idn_to_utf8($this->mail_ical_parser->sender);
}
}
break;
}
}
}
return $this->mail_ical_parser;
}
/**
* Read the given mime message from IMAP and parse ical data
*
* @param string Mailbox name
* @param string Message UID
* @param string Message part ID and object index (e.g. '1.2:0')
* @param string Object type filter (optional)
*
* @return array Hash array with the parsed iCal
*/
public function mail_get_itip_object($mbox, $uid, $mime_id, $type = null)
{
$charset = RCUBE_CHARSET;
// establish imap connection
$imap = $this->rc->get_storage();
$imap->set_folder($mbox);
if ($uid && $mime_id) {
list($mime_id, $index) = explode(':', $mime_id);
$part = $imap->get_message_part($uid, $mime_id);
$headers = $imap->get_message_headers($uid);
$parser = $this->get_ical();
if (!empty($part->ctype_parameters['charset'])) {
$charset = $part->ctype_parameters['charset'];
}
if ($part) {
$objects = $parser->import($part, $charset);
}
}
// successfully parsed events/tasks?
if (!empty($objects) && ($object = $objects[$index]) && (!$type || $object['_type'] == $type)) {
if ($parser->method)
$object['_method'] = $parser->method;
// store the message's sender address for comparisons
$from = rcube_mime::decode_address_list($headers->from, 1, true, null, true);
$object['_sender'] = !empty($from) ? $from[1] : '';
$object['_sender_utf'] = rcube_utils::idn_to_utf8($object['_sender']);
// check if this is an instance of a recurring event/task
self::identify_recurrence_instance($object);
return $object;
}
return null;
}
/**
* Checks if specified message part is a vcalendar data
*
* @param rcube_message_part Part object
* @param rcube_message Message object
*
* @return boolean True if part is of type vcard
*/
public static function part_is_vcalendar($part, $message = null)
{
// First check if the message is "valid" (i.e. not multipart/report)
if ($message) {
$level = explode('.', $part->mime_id);
while (array_pop($level) !== null) {
$id = join('.', $level) ?: 0;
$parent = !empty($message->mime_parts[$id]) ? $message->mime_parts[$id] : null;
if ($parent && $parent->mimetype == 'multipart/report') {
return false;
}
}
}
return (
in_array($part->mimetype, array('text/calendar', 'text/x-vcalendar', 'application/ics')) ||
// Apple sends files as application/x-any (!?)
($part->mimetype == 'application/x-any' && !empty($part->filename) && preg_match('/\.ics$/i', $part->filename))
);
}
/**
* Single occourrences of recurring events are identified by their RECURRENCE-ID property
* in iCal which is represented as 'recurrence_date' in our internal data structure.
*
* Check if such a property exists and derive the '_instance' identifier and '_savemode'
* attributes which are used in the storage backend to identify the nested exception item.
*/
public static function identify_recurrence_instance(&$object)
{
// for savemode=all, remove recurrence instance identifiers
if (!empty($object['_savemode']) && $object['_savemode'] == 'all' && $object['recurrence']) {
unset($object['_instance'], $object['recurrence_date']);
}
// set instance and 'savemode' according to recurrence-id
else if (!empty($object['recurrence_date']) && is_a($object['recurrence_date'], 'DateTime')) {
$object['_instance'] = self::recurrence_instance_identifier($object);
$object['_savemode'] = $object['thisandfuture'] ? 'future' : 'current';
}
else if (!empty($object['recurrence_id']) && !empty($object['_instance'])) {
if (strlen($object['_instance']) > 4) {
$object['recurrence_date'] = rcube_utils::anytodatetime($object['_instance'], $object['start']->getTimezone());
}
else {
$object['recurrence_date'] = clone $object['start'];
}
}
}
/**
* Return a date() format string to render identifiers for recurrence instances
*
* @param array Hash array with event properties
* @return string Format string
*/
public static function recurrence_id_format($event)
{
return !empty($event['allday']) ? 'Ymd' : 'Ymd\THis';
}
/**
* Return the identifer for the given instance of a recurring event
*
* @param array Hash array with event properties
* @param bool All-day flag from the main event
*
* @return mixed Format string or null if identifier cannot be generated
*/
public static function recurrence_instance_identifier($event, $allday = null)
{
$instance_date = !empty($event['recurrence_date']) ? $event['recurrence_date'] : $event['start'];
if ($instance_date instanceof DateTimeInterface) {
// According to RFC5545 (3.8.4.4) RECURRENCE-ID format should
// be date/date-time depending on the main event type, not the exception
if ($allday === null) {
$allday = !empty($event['allday']);
}
return $instance_date->format($allday ? 'Ymd' : 'Ymd\THis');
}
}
/********* Attendee handling functions *********/
/**
* Handler for attendee group expansion requests
*/
public function expand_attendee_group()
{
$id = rcube_utils::get_input_value('id', rcube_utils::INPUT_POST);
$data = rcube_utils::get_input_value('data', rcube_utils::INPUT_POST, true);
$result = array('id' => $id, 'members' => array());
$maxnum = 500;
// iterate over all autocomplete address books (we don't know the source of the group)
foreach ((array)$this->rc->config->get('autocomplete_addressbooks', 'sql') as $abook_id) {
if (($abook = $this->rc->get_address_book($abook_id)) && $abook->groups) {
foreach ($abook->list_groups($data['name'], 1) as $group) {
// this is the matching group to expand
if (in_array($data['email'], (array)$group['email'])) {
$abook->set_pagesize($maxnum);
$abook->set_group($group['ID']);
// get all members
$res = $abook->list_records($this->rc->config->get('contactlist_fields'));
// handle errors (e.g. sizelimit, timelimit)
if ($abook->get_error()) {
$result['error'] = $this->rc->gettext('expandattendeegrouperror', 'libcalendaring');
$res = false;
}
// check for maximum number of members (we don't wanna bloat the UI too much)
else if ($res->count > $maxnum) {
$result['error'] = $this->rc->gettext('expandattendeegroupsizelimit', 'libcalendaring');
$res = false;
}
while ($res && ($member = $res->iterate())) {
$emails = (array)$abook->get_col_values('email', $member, true);
if (!empty($emails) && ($email = array_shift($emails))) {
$result['members'][] = array(
'email' => $email,
'name' => rcube_addressbook::compose_list_name($member),
);
}
}
break 2;
}
}
}
}
$this->rc->output->command('plugin.expand_attendee_callback', $result);
}
/**
* Merge attendees of the old and new event version
* with keeping current user and his delegatees status
*
* @param array &$new New object data
* @param array $old Old object data
* @param bool $status New status of the current user
*/
public function merge_attendees(&$new, $old, $status = null)
{
if (empty($status)) {
$emails = $this->get_user_emails();
$delegates = array();
$attendees = array();
// keep attendee status of the current user
foreach ((array) $new['attendees'] as $i => $attendee) {
if (empty($attendee['email'])) {
continue;
}
$attendees[] = $email = strtolower($attendee['email']);
if (in_array($email, $emails)) {
foreach ($old['attendees'] as $_attendee) {
if ($attendee['email'] == $_attendee['email']) {
$new['attendees'][$i] = $_attendee;
if ($_attendee['status'] == 'DELEGATED' && ($email = $_attendee['delegated-to'])) {
$delegates[] = strtolower($email);
}
break;
}
}
}
}
// make sure delegated attendee is not lost
foreach ($delegates as $delegatee) {
if (!in_array($delegatee, $attendees)) {
foreach ((array) $old['attendees'] as $attendee) {
if ($attendee['email'] && ($email = strtolower($attendee['email'])) && $email == $delegatee) {
$new['attendees'][] = $attendee;
break;
}
}
}
}
}
// We also make sure that status of any attendee
// is not overriden by NEEDS-ACTION if it was already set
// which could happen if you work with shared events
foreach ((array) $new['attendees'] as $i => $attendee) {
if ($attendee['email'] && $attendee['status'] == 'NEEDS-ACTION') {
foreach ($old['attendees'] as $_attendee) {
if ($attendee['email'] == $_attendee['email']) {
$new['attendees'][$i]['status'] = $_attendee['status'];
unset($new['attendees'][$i]['rsvp']);
break;
}
}
}
}
}
/********* Static utility functions *********/
/**
* Convert the internal structured data into a vcalendar rrule 2.0 string
*/
public static function to_rrule($recurrence, $allday = false)
{
if (is_string($recurrence)) {
return $recurrence;
}
$rrule = '';
foreach ((array)$recurrence as $k => $val) {
$k = strtoupper($k);
switch ($k) {
case 'UNTIL':
// convert to UTC according to RFC 5545
if (is_a($val, 'DateTime')) {
if (!$allday && empty($val->_dateonly)) {
$until = clone $val;
$until->setTimezone(new DateTimeZone('UTC'));
$val = $until->format('Ymd\THis\Z');
}
else {
$val = $val->format('Ymd');
}
}
break;
case 'RDATE':
case 'EXDATE':
foreach ((array)$val as $i => $ex) {
if (is_a($ex, 'DateTime')) {
$val[$i] = $ex->format('Ymd\THis');
}
}
$val = join(',', (array)$val);
break;
case 'EXCEPTIONS':
continue 2;
}
if (strlen($val)) {
$rrule .= $k . '=' . $val . ';';
}
}
return rtrim($rrule, ';');
}
/**
* Convert from fullcalendar date format to PHP date() format string
*/
public static function to_php_date_format($from)
{
// "dd.MM.yyyy HH:mm:ss" => "d.m.Y H:i:s"
return strtr(strtr($from, array(
'YYYY' => 'Y',
'YY' => 'y',
'yyyy' => 'Y',
'yy' => 'y',
'MMMM' => 'F',
'MMM' => 'M',
'MM' => 'm',
'M' => 'n',
'dddd' => 'l',
'ddd' => 'D',
'DD' => 'd',
'D' => 'j',
'HH' => '**',
'hh' => '%%',
'H' => 'G',
'h' => 'g',
'mm' => 'i',
'ss' => 's',
'TT' => 'A',
'tt' => 'a',
'T' => 'A',
't' => 'a',
'u' => 'c',
)), array(
'**' => 'H',
'%%' => 'h',
));
}
/**
* Convert from PHP date() format to fullcalendar (MomentJS) format string
*/
public static function from_php_date_format($from)
{
// "d.m.Y H:i:s" => "dd.MM.yyyy HH:mm:ss"
return strtr($from, array(
'y' => 'YY',
'Y' => 'YYYY',
'M' => 'MMM',
'F' => 'MMMM',
'm' => 'MM',
'n' => 'M',
'j' => 'D',
'd' => 'DD',
'D' => 'ddd',
'l' => 'dddd',
'H' => 'HH',
'h' => 'hh',
'G' => 'H',
'g' => 'h',
'i' => 'mm',
's' => 'ss',
'c' => '',
));
}
}
diff --git a/plugins/libcalendaring/tests/LibvcalendarTest.php b/plugins/libcalendaring/tests/LibvcalendarTest.php
index 9c055836..b687d2b5 100644
--- a/plugins/libcalendaring/tests/LibvcalendarTest.php
+++ b/plugins/libcalendaring/tests/LibvcalendarTest.php
@@ -1,608 +1,609 @@
<?php
/**
* libcalendaring plugin's iCalendar functions tests
*
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 2014, Kolab Systems AG <contact@kolabsys.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class LibvcalendarTest extends PHPUnit\Framework\TestCase
{
private $attachment_data;
function setUp(): void
{
- require_once __DIR__ . '/../libvcalendar.php';
require_once __DIR__ . '/../libcalendaring.php';
+ require_once __DIR__ . '/../lib/libcalendaring_vcalendar.php';
+ require_once __DIR__ . '/../lib/libcalendaring_datetime.php';
}
/**
* Simple iCal parsing test
*/
function test_import()
{
- $ical = new libvcalendar();
+ $ical = new libcalendaring_vcalendar();
$ics = file_get_contents(__DIR__ . '/resources/snd.ics');
$events = $ical->import($ics, 'UTF-8');
$this->assertEquals(1, count($events));
$event = $events[0];
$this->assertInstanceOf('DateTimeInterface', $event['created'], "'created' property is DateTime object");
$this->assertInstanceOf('DateTimeInterface', $event['changed'], "'changed' property is DateTime object");
$this->assertEquals('UTC', $event['created']->getTimezone()->getName(), "'created' date is in UTC");
$this->assertInstanceOf('DateTimeInterface', $event['start'], "'start' property is DateTime object");
$this->assertInstanceOf('DateTimeInterface', $event['end'], "'end' property is DateTime object");
$this->assertEquals('08-01', $event['start']->format('m-d'), "Start date is August 1st");
$this->assertTrue($event['allday'], "All-day event flag");
$this->assertEquals('B968B885-08FB-40E5-B89E-6DA05F26AA79', $event['uid'], "Event UID");
$this->assertEquals('Swiss National Day', $event['title'], "Event title");
$this->assertEquals('http://en.wikipedia.org/wiki/Swiss_National_Day', $event['url'], "URL property");
$this->assertEquals(2, $event['sequence'], "Sequence number");
$desclines = explode("\n", $event['description']);
$this->assertEquals(4, count($desclines), "Multiline description");
$this->assertEquals("French: Fête nationale Suisse", rtrim($desclines[1]), "UTF-8 encoding");
}
/**
* Test parsing from files
*/
function test_import_from_file()
{
- $ical = new libvcalendar();
+ $ical = new libcalendaring_vcalendar();
$events = $ical->import_from_file(__DIR__ . '/resources/multiple.ics', 'UTF-8');
$this->assertEquals(2, count($events));
$events = $ical->import_from_file(__DIR__ . '/resources/invalid.txt', 'UTF-8');
$this->assertEmpty($events);
}
/**
* Test parsing from files with multiple VCALENDAR blocks (#2884)
*/
function test_import_from_file_multiple()
{
- $ical = new libvcalendar();
+ $ical = new libcalendaring_vcalendar();
$ical->fopen(__DIR__ . '/resources/multiple-rdate.ics', 'UTF-8');
$events = [];
foreach ($ical as $event) {
$events[] = $event;
}
$this->assertEquals(2, count($events));
$this->assertEquals("AAAA6A8C3CCE4EE2C1257B5C00FFFFFF-Lotus_Notes_Generated", $events[0]['uid']);
$this->assertEquals("AAAA1C572093EC3FC125799C004AFFFF-Lotus_Notes_Generated", $events[1]['uid']);
}
function test_invalid_dates()
{
- $ical = new libvcalendar();
+ $ical = new libcalendaring_vcalendar();
$events = $ical->import_from_file(__DIR__ . '/resources/invalid-dates.ics', 'UTF-8');
$event = $events[0];
$this->assertEquals(1, count($events), "Import event data");
$this->assertInstanceOf('DateTimeInterface', $event['created'], "Created date field");
$this->assertFalse(array_key_exists('changed', $event), "No changed date field");
}
/**
* Test some extended ical properties such as attendees, recurrence rules, alarms and attachments
*/
function test_extended()
{
- $ical = new libvcalendar();
+ $ical = new libcalendaring_vcalendar();
$events = $ical->import_from_file(__DIR__ . '/resources/itip.ics', 'UTF-8');
$event = $events[0];
$this->assertEquals('REQUEST', $ical->method, "iTip method");
// attendees
$this->assertEquals(3, count($event['attendees']), "Attendees list (including organizer)");
$organizer = $event['attendees'][0];
$this->assertEquals('ORGANIZER', $organizer['role'], 'Organizer ROLE');
$this->assertEquals('Rolf Test', $organizer['name'], 'Organizer name');
$attendee = $event['attendees'][1];
$this->assertEquals('REQ-PARTICIPANT', $attendee['role'], 'Attendee ROLE');
$this->assertEquals('NEEDS-ACTION', $attendee['status'], 'Attendee STATUS');
$this->assertEquals('rolf2@mykolab.com', $attendee['email'], 'Attendee mailto:');
$this->assertEquals('carl@mykolab.com', $attendee['delegated-from'], 'Attendee delegated-from');
$this->assertTrue($attendee['rsvp'], 'Attendee RSVP');
$delegator = $event['attendees'][2];
$this->assertEquals('NON-PARTICIPANT', $delegator['role'], 'Delegator ROLE');
$this->assertEquals('DELEGATED', $delegator['status'], 'Delegator STATUS');
$this->assertEquals('INDIVIDUAL', $delegator['cutype'], 'Delegator CUTYPE');
$this->assertEquals('carl@mykolab.com', $delegator['email'], 'Delegator mailto:');
$this->assertEquals('rolf2@mykolab.com', $delegator['delegated-to'], 'Delegator delegated-to');
$this->assertFalse($delegator['rsvp'], 'Delegator RSVP');
// attachments
$this->assertEquals(1, count($event['attachments']), "Embedded attachments");
$attachment = $event['attachments'][0];
$this->assertEquals('text/html', $attachment['mimetype'], "Attachment mimetype attribute");
$this->assertEquals('calendar.html', $attachment['name'], "Attachment filename (X-LABEL) attribute");
$this->assertStringContainsString('<title>Kalender</title>', $attachment['data'], "Attachment content (decoded)");
// recurrence rules
$events = $ical->import_from_file(__DIR__ . '/resources/recurring.ics', 'UTF-8');
$event = $events[0];
$this->assertTrue(is_array($event['recurrence']), 'Recurrences rule as hash array');
$rrule = $event['recurrence'];
$this->assertEquals('MONTHLY', $rrule['FREQ'], "Recurrence frequency");
$this->assertEquals('1', $rrule['INTERVAL'], "Recurrence interval");
$this->assertEquals('3WE', $rrule['BYDAY'], "Recurrence frequency");
$this->assertInstanceOf('DateTimeInterface', $rrule['UNTIL'], "Recurrence end date");
$this->assertEquals(2, count($rrule['EXDATE']), "Recurrence EXDATEs");
$this->assertInstanceOf('DateTimeInterface', $rrule['EXDATE'][0], "Recurrence EXDATE as DateTime");
$this->assertTrue(is_array($rrule['EXCEPTIONS']));
$this->assertEquals(1, count($rrule['EXCEPTIONS']), "Recurrence Exceptions");
$exception = $rrule['EXCEPTIONS'][0];
$this->assertEquals($event['uid'], $event['uid'], "Exception UID");
$this->assertEquals('Recurring Test (Exception)', $exception['title'], "Exception title");
$this->assertInstanceOf('DateTimeInterface', $exception['start'], "Exception start");
// categories, class
$this->assertEquals('libcalendaring tests', join(',', (array)$event['categories']), "Event categories");
// parse a recurrence chain instance
$events = $ical->import_from_file(__DIR__ . '/resources/recurrence-id.ics', 'UTF-8');
$this->assertEquals(1, count($events), "Fall back to Component::getComponents() when getBaseComponents() is empty");
$this->assertInstanceOf('DateTimeInterface', $events[0]['recurrence_date'], "Recurrence-ID as date");
$this->assertTrue($events[0]['thisandfuture'], "Range=THISANDFUTURE");
$this->assertEquals(count($events[0]['exceptions']), 1, "Second VEVENT as exception");
$this->assertEquals($events[0]['exceptions'][0]['uid'], $events[0]['uid'], "Exception UID match");
$this->assertEquals($events[0]['exceptions'][0]['sequence'], '2', "Exception sequence");
}
/**
*
*/
function test_alarms()
{
- $ical = new libvcalendar();
+ $ical = new libcalendaring_vcalendar();
$events = $ical->import_from_file(__DIR__ . '/resources/recurring.ics', 'UTF-8');
$event = $events[0];
$this->assertEquals('-12H:DISPLAY', $event['alarms'], "Serialized alarms string");
$alarm = libcalendaring::parse_alarm_value($event['alarms']);
$this->assertEquals('12', $alarm[0], "Alarm value");
$this->assertEquals('-H', $alarm[1], "Alarm unit");
$this->assertEquals('DISPLAY', $event['valarms'][0]['action'], "Full alarm item (action)");
$this->assertEquals('-PT12H', $event['valarms'][0]['trigger'], "Full alarm item (trigger)");
$this->assertEquals('END', $event['valarms'][0]['related'], "Full alarm item (related)");
// alarm trigger with 0 values
$events = $ical->import_from_file(__DIR__ . '/resources/alarms.ics', 'UTF-8');
$event = $events[0];
$this->assertEquals('-30M:DISPLAY', $event['alarms'], "Stripped alarm string");
$alarm = libcalendaring::parse_alarm_value($event['alarms']);
$this->assertEquals('30', $alarm[0], "Alarm value");
$this->assertEquals('-M', $alarm[1], "Alarm unit");
$this->assertEquals('-30M', $alarm[2], "Alarm string");
$this->assertEquals('-PT30M', $alarm[3], "Unified alarm string (stripped zero-values)");
$this->assertEquals('DISPLAY', $event['valarms'][0]['action'], "First alarm action");
$this->assertTrue(empty($event['valarms'][0]['related']), "First alarm related property");
$this->assertEquals('This is the first event reminder', $event['valarms'][0]['description'], "First alarm text");
$this->assertEquals(3, count($event['valarms']), "List all VALARM blocks");
$valarm = $event['valarms'][1];
$this->assertEquals(1, count($valarm['attendees']), "Email alarm attendees");
$this->assertEquals('EMAIL', $valarm['action'], "Second alarm item (action)");
$this->assertEquals('-P1D', $valarm['trigger'], "Second alarm item (trigger)");
$this->assertEquals('This is the reminder message', $valarm['summary'], "Email alarm text");
$this->assertInstanceOf('DateTimeInterface', $event['valarms'][2]['trigger'], "Absolute trigger date/time");
// test alarms export
$ics = $ical->export([$event]);
$this->assertStringContainsString('ACTION:DISPLAY', $ics, "Display alarm block");
$this->assertStringContainsString('ACTION:EMAIL', $ics, "Email alarm block");
$this->assertStringContainsString('DESCRIPTION:This is the first event reminder', $ics, "Alarm description");
$this->assertStringContainsString('SUMMARY:This is the reminder message', $ics, "Email alarm summary");
$this->assertStringContainsString('ATTENDEE:mailto:reminder-recipient@example.org', $ics, "Email alarm recipient");
$this->assertStringContainsString('TRIGGER;VALUE=DATE-TIME:20130812', $ics, "Date-Time trigger");
}
/**
* @depends test_import_from_file
*/
function test_attachment()
{
- $ical = new libvcalendar();
+ $ical = new libcalendaring_vcalendar();
$events = $ical->import_from_file(__DIR__ . '/resources/attachment.ics', 'UTF-8');
$event = $events[0];
$this->assertEquals(2, count($events));
$this->assertEquals(1, count($event['attachments']));
$this->assertEquals('image/png', $event['attachments'][0]['mimetype']);
$this->assertEquals('500px-Opensource.svg.png', $event['attachments'][0]['name']);
}
/**
* @depends test_import
*/
function test_apple_alarms()
{
- $ical = new libvcalendar();
+ $ical = new libcalendaring_vcalendar();
$events = $ical->import_from_file(__DIR__ . '/resources/apple-alarms.ics', 'UTF-8');
$event = $events[0];
// alarms
$this->assertEquals('-45M:AUDIO', $event['alarms'], "Relative alarm string");
$alarm = libcalendaring::parse_alarm_value($event['alarms']);
$this->assertEquals('45', $alarm[0], "Alarm value");
$this->assertEquals('-M', $alarm[1], "Alarm unit");
$this->assertEquals(1, count($event['valarms']), "Ignore invalid alarm blocks");
$this->assertEquals('AUDIO', $event['valarms'][0]['action'], "Full alarm item (action)");
$this->assertEquals('-PT45M', $event['valarms'][0]['trigger'], "Full alarm item (trigger)");
$this->assertEquals('Basso', $event['valarms'][0]['uri'], "Full alarm item (attachment)");
}
/**
*
*/
function test_escaped_values()
{
- $ical = new libvcalendar();
+ $ical = new libcalendaring_vcalendar();
$events = $ical->import_from_file(__DIR__ . '/resources/escaped.ics', 'UTF-8');
$event = $events[0];
$this->assertEquals("House, Street, Zip Place", $event['location'], "Decode escaped commas in location value");
$this->assertEquals("Me, meets Them\nThem, meet Me", $event['description'], "Decode description value");
$this->assertEquals("Kolab, Thomas", $event['attendees'][3]['name'], "Unescaped");
$ics = $ical->export($events);
$this->assertStringContainsString('ATTENDEE;CN="Kolab, Thomas";PARTSTAT=', $ics, "Quoted attendee parameters");
}
/**
* Parse RDATE properties (#2885)
*/
function test_rdate()
{
- $ical = new libvcalendar();
+ $ical = new libcalendaring_vcalendar();
$events = $ical->import_from_file(__DIR__ . '/resources/multiple-rdate.ics', 'UTF-8');
$event = $events[0];
$this->assertEquals(9, count($event['recurrence']['RDATE']));
$this->assertInstanceOf('DateTimeInterface', $event['recurrence']['RDATE'][0]);
$this->assertInstanceOf('DateTimeInterface', $event['recurrence']['RDATE'][1]);
}
/**
* @depends test_import
*/
function test_freebusy()
{
- $ical = new libvcalendar();
+ $ical = new libcalendaring_vcalendar();
$ical->import_from_file(__DIR__ . '/resources/freebusy.ifb', 'UTF-8');
$freebusy = $ical->freebusy;
$this->assertInstanceOf('DateTimeInterface', $freebusy['start'], "'start' property is DateTime object");
$this->assertInstanceOf('DateTimeInterface', $freebusy['end'], "'end' property is DateTime object");
$this->assertEquals(11, count($freebusy['periods']), "Number of freebusy periods defined");
$periods = $ical->get_busy_periods();
$this->assertEquals(9, count($periods), "Number of busy periods found");
$this->assertEquals('BUSY-TENTATIVE', $periods[8][2], "FBTYPE=BUSY-TENTATIVE");
}
/**
* @depends test_import
*/
function test_freebusy_dummy()
{
- $ical = new libvcalendar();
+ $ical = new libcalendaring_vcalendar();
$ical->import_from_file(__DIR__ . '/resources/dummy.ifb', 'UTF-8');
$freebusy = $ical->freebusy;
$this->assertEquals(0, count($freebusy['periods']), "Ignore 0-length freebudy periods");
$this->assertStringContainsString('dummy', $freebusy['comment'], "Parse comment");
}
function test_vtodo()
{
- $ical = new libvcalendar();
+ $ical = new libcalendaring_vcalendar();
$tasks = $ical->import_from_file(__DIR__ . '/resources/vtodo.ics', 'UTF-8', true);
$task = $tasks[0];
$this->assertInstanceOf('DateTimeInterface', $task['start'], "'start' property is DateTime object");
$this->assertInstanceOf('DateTimeInterface', $task['due'], "'due' property is DateTime object");
$this->assertEquals('-1D:DISPLAY', $task['alarms'], "Taks alarm value");
$this->assertEquals('IN-PROCESS', $task['status'], "Task status property");
$this->assertEquals(1, count($task['x-custom']), "Custom properties");
$this->assertEquals(4, count($task['categories']));
$this->assertEquals('1234567890-12345678-PARENT', $task['parent_id'], "Parent Relation");
$completed = $tasks[1];
$this->assertEquals('COMPLETED', $completed['status'], "Task status=completed when COMPLETED property is present");
$this->assertEquals(100, $completed['complete'], "Task percent complete value");
$ics = $ical->export([$completed]);
$this->assertMatchesRegularExpression('/COMPLETED(;VALUE=DATE-TIME)?:[0-9TZ]+/', $ics, "Export COMPLETED property");
}
/**
* Test for iCal export from internal hash array representation
*/
function test_export()
{
- $ical = new libvcalendar();
+ $ical = new libcalendaring_vcalendar();
$events = $ical->import_from_file(__DIR__ . '/resources/itip.ics', 'UTF-8');
$event = $events[0];
$events = $ical->import_from_file(__DIR__ . '/resources/recurring.ics', 'UTF-8');
$event += $events[0];
$this->attachment_data = $event['attachments'][0]['data'];
unset($event['attachments'][0]['data']);
$event['attachments'][0]['id'] = '1';
- $event['description'] = '*Exported by libvcalendar*';
+ $event['description'] = '*Exported by libcalendaring_vcalendar*';
$event['start']->setTimezone(new DateTimezone('America/Montreal'));
$event['end']->setTimezone(new DateTimezone('Europe/Berlin'));
$ics = $ical->export([$event], 'REQUEST', false, [$this, 'get_attachment_data'], true);
$this->assertStringContainsString('BEGIN:VCALENDAR', $ics, "VCALENDAR encapsulation BEGIN");
$this->assertStringContainsString('BEGIN:VTIMEZONE', $ics, "VTIMEZONE encapsulation BEGIN");
$this->assertStringContainsString('TZID:Europe/Berlin', $ics, "Timezone ID");
$this->assertStringContainsString('TZOFFSETFROM:+0100', $ics, "Timzone transition FROM");
$this->assertStringContainsString('TZOFFSETTO:+0200', $ics, "Timzone transition TO");
$this->assertStringContainsString('TZOFFSETFROM:-0400', $ics, "TZOFFSETFROM with negative offset (Bug T428)");
$this->assertStringContainsString('TZOFFSETTO:-0500', $ics, "TZOFFSETTO with negative offset (Bug T428)");
$this->assertStringContainsString('END:VTIMEZONE', $ics, "VTIMEZONE encapsulation END");
$this->assertStringContainsString('BEGIN:VEVENT', $ics, "VEVENT encapsulation BEGIN");
$this->assertSame(2, substr_count($ics, 'DTSTAMP'), "Duplicate DTSTAMP (T1148)");
$this->assertStringContainsString('UID:ac6b0aee-2519-4e5c-9a25-48c57064c9f0', $ics, "Event UID");
$this->assertStringContainsString('SEQUENCE:' . $event['sequence'], $ics, "Export Sequence number");
$this->assertStringContainsString('DESCRIPTION:*Exported by', $ics, "Export Description");
$this->assertStringContainsString('ORGANIZER;CN=Rolf Test:mailto:rolf@', $ics, "Export organizer");
$this->assertMatchesRegularExpression('/ATTENDEE.*;ROLE=REQ-PARTICIPANT/', $ics, "Export Attendee ROLE");
$this->assertMatchesRegularExpression('/ATTENDEE.*;PARTSTAT=NEEDS-ACTION/', $ics, "Export Attendee Status");
$this->assertMatchesRegularExpression('/ATTENDEE.*;RSVP=TRUE/', $ics, "Export Attendee RSVP");
$this->assertMatchesRegularExpression('/:mailto:rolf2@/', $ics, "Export Attendee mailto:");
$rrule = $event['recurrence'];
$this->assertMatchesRegularExpression('/RRULE:.*FREQ='.$rrule['FREQ'].'/', $ics, "Export Recurrence Frequence");
$this->assertMatchesRegularExpression('/RRULE:.*INTERVAL='.$rrule['INTERVAL'].'/', $ics, "Export Recurrence Interval");
$this->assertMatchesRegularExpression('/RRULE:.*UNTIL=20140718T215959Z/', $ics, "Export Recurrence End date");
$this->assertMatchesRegularExpression('/RRULE:.*BYDAY='.$rrule['BYDAY'].'/', $ics, "Export Recurrence BYDAY");
$this->assertMatchesRegularExpression('/EXDATE.*:20131218/', $ics, "Export Recurrence EXDATE");
$this->assertStringContainsString('BEGIN:VALARM', $ics, "Export VALARM");
$this->assertStringContainsString('TRIGGER;RELATED=END:-PT12H', $ics, "Export Alarm trigger");
$this->assertMatchesRegularExpression('/ATTACH.*;VALUE=BINARY/', $ics, "Embed attachment");
$this->assertMatchesRegularExpression('/ATTACH.*;ENCODING=BASE64/', $ics, "Attachment B64 encoding");
$this->assertMatchesRegularExpression('!ATTACH.*;FMTTYPE=text/html!', $ics, "Attachment mimetype");
$this->assertMatchesRegularExpression('!ATTACH.*;X-LABEL=calendar.html!', $ics, "Attachment filename with X-LABEL");
$this->assertStringContainsString('END:VEVENT', $ics, "VEVENT encapsulation END");
$this->assertStringContainsString('END:VCALENDAR', $ics, "VCALENDAR encapsulation END");
}
/**
* @depends test_extended
* @depends test_export
*/
function test_export_multiple()
{
- $ical = new libvcalendar();
+ $ical = new libcalendaring_vcalendar();
$events = array_merge(
$ical->import_from_file(__DIR__ . '/resources/snd.ics', 'UTF-8'),
$ical->import_from_file(__DIR__ . '/resources/multiple.ics', 'UTF-8')
);
$num = count($events);
$ics = $ical->export($events, null, false);
$this->assertStringContainsString('BEGIN:VCALENDAR', $ics, "VCALENDAR encapsulation BEGIN");
$this->assertStringContainsString('END:VCALENDAR', $ics, "VCALENDAR encapsulation END");
$this->assertEquals($num, substr_count($ics, 'BEGIN:VEVENT'), "VEVENT encapsulation BEGIN");
$this->assertEquals($num, substr_count($ics, 'END:VEVENT'), "VEVENT encapsulation END");
}
/**
* @depends test_export
*/
function test_export_recurrence_exceptions()
{
- $ical = new libvcalendar();
+ $ical = new libcalendaring_vcalendar();
$events = $ical->import_from_file(__DIR__ . '/resources/recurring.ics', 'UTF-8');
// add exceptions
$event = $events[0];
unset($event['recurrence']['EXCEPTIONS']);
$exception1 = $event;
$exception1['start'] = clone $event['start'];
$exception1['start']->setDate(2013, 8, 14);
$exception1['end'] = clone $event['end'];
$exception1['end']->setDate(2013, 8, 14);
$exception2 = $event;
$exception2['start'] = clone $event['start'];
$exception2['start']->setDate(2013, 11, 13);
$exception2['end'] = clone $event['end'];
$exception2['end']->setDate(2013, 11, 13);
$exception2['title'] = 'Recurring Exception';
$events[0]['recurrence']['EXCEPTIONS'] = [$exception1, $exception2];
$ics = $ical->export($events, null, false);
$num = count($events[0]['recurrence']['EXCEPTIONS']) + 1;
$this->assertEquals($num, substr_count($ics, 'BEGIN:VEVENT'), "VEVENT encapsulation BEGIN");
$this->assertEquals($num, substr_count($ics, 'UID:'.$event['uid']), "Recurrence Exceptions with same UID");
$this->assertEquals($num, substr_count($ics, 'END:VEVENT'), "VEVENT encapsulation END");
$this->assertStringContainsString('RECURRENCE-ID;TZID=Europe/Zurich:20130814', $ics, "Recurrence-ID (1) being the exception date");
$this->assertStringContainsString('RECURRENCE-ID;TZID=Europe/Zurich:20131113', $ics, "Recurrence-ID (2) being the exception date");
$this->assertStringContainsString('SUMMARY:'.$exception2['title'], $ics, "Exception title");
}
function test_export_valid_rrules()
{
$event = [
'uid' => '1234567890',
'start' => new DateTime('now'),
'end' => new DateTime('now + 30min'),
'title' => 'test_export_valid_rrules',
'recurrence' => [
'FREQ' => 'DAILY',
'COUNT' => 5,
'EXDATE' => [],
'RDATE' => [],
],
];
- $ical = new libvcalendar();
+ $ical = new libcalendaring_vcalendar();
$ics = $ical->export([$event], null, false, null, false);
$this->assertStringNotContainsString('EXDATE=', $ics);
$this->assertStringNotContainsString('RDATE=', $ics);
}
/**
*
*/
function test_export_rdate()
{
- $ical = new libvcalendar();
+ $ical = new libcalendaring_vcalendar();
$events = $ical->import_from_file(__DIR__ . '/resources/multiple-rdate.ics', 'UTF-8');
$ics = $ical->export($events, null, false);
$this->assertStringContainsString('RDATE:20140520T020000Z', $ics, "VALUE=PERIOD is translated into single DATE-TIME values");
}
/**
* @depends test_export
*/
function test_export_direct()
{
- $ical = new libvcalendar();
+ $ical = new libcalendaring_vcalendar();
$events = $ical->import_from_file(__DIR__ . '/resources/multiple.ics', 'UTF-8');
$num = count($events);
ob_start();
$return = $ical->export($events, null, true);
$output = ob_get_contents();
ob_end_clean();
$this->assertTrue($return, "Return true on successful writing");
$this->assertStringContainsString('BEGIN:VCALENDAR', $output, "VCALENDAR encapsulation BEGIN");
$this->assertStringContainsString('END:VCALENDAR', $output, "VCALENDAR encapsulation END");
$this->assertEquals($num, substr_count($output, 'BEGIN:VEVENT'), "VEVENT encapsulation BEGIN");
$this->assertEquals($num, substr_count($output, 'END:VEVENT'), "VEVENT encapsulation END");
}
function test_datetime()
{
- $ical = new libvcalendar();
+ $ical = new libcalendaring_vcalendar();
$cal = new \Sabre\VObject\Component\VCalendar();
$localtime = $ical->datetime_prop($cal, 'DTSTART', new DateTime('2013-09-01 12:00:00', new DateTimeZone('Europe/Berlin')));
$localdate = $ical->datetime_prop($cal, 'DTSTART', new DateTime('2013-09-01', new DateTimeZone('Europe/Berlin')), false, true);
$utctime = $ical->datetime_prop($cal, 'DTSTART', new DateTime('2013-09-01 12:00:00', new DateTimeZone('UTC')));
$asutctime = $ical->datetime_prop($cal, 'DTSTART', new DateTime('2013-09-01 12:00:00', new DateTimeZone('Europe/Berlin')), true);
$this->assertStringContainsString('TZID=Europe/Berlin', $localtime->serialize());
$this->assertStringContainsString('VALUE=DATE', $localdate->serialize());
$this->assertStringContainsString('20130901T120000Z', $utctime->serialize());
$this->assertStringContainsString('20130901T100000Z', $asutctime->serialize());
}
function test_get_vtimezone()
{
- $vtz = libvcalendar::get_vtimezone('Europe/Berlin', strtotime('2014-08-22T15:00:00+02:00'));
+ $vtz = libcalendaring_vcalendar::get_vtimezone('Europe/Berlin', strtotime('2014-08-22T15:00:00+02:00'));
$this->assertInstanceOf('\Sabre\VObject\Component', $vtz, "VTIMEZONE is a Component object");
$this->assertEquals('Europe/Berlin', $vtz->TZID);
$this->assertEquals('4', $vtz->{'X-MICROSOFT-CDO-TZID'});
// check for transition to daylight saving time which is BEFORE the given date
$dst = array_first($vtz->select('DAYLIGHT'));
$this->assertEquals('DAYLIGHT', $dst->name);
$this->assertEquals('20140330T010000', $dst->DTSTART);
$this->assertEquals('+0100', $dst->TZOFFSETFROM);
$this->assertEquals('+0200', $dst->TZOFFSETTO);
$this->assertEquals('CEST', $dst->TZNAME);
// check (last) transition to standard time which is AFTER the given date
$std = $vtz->select('STANDARD');
$std = end($std);
$this->assertEquals('STANDARD', $std->name);
$this->assertEquals('20141026T010000', $std->DTSTART);
$this->assertEquals('+0200', $std->TZOFFSETFROM);
$this->assertEquals('+0100', $std->TZOFFSETTO);
$this->assertEquals('CET', $std->TZNAME);
// unknown timezone
- $vtz = libvcalendar::get_vtimezone('America/Foo Bar');
+ $vtz = libcalendaring_vcalendar::get_vtimezone('America/Foo Bar');
$this->assertEquals(false, $vtz);
// invalid input data
- $vtz = libvcalendar::get_vtimezone(new DateTime());
+ $vtz = libcalendaring_vcalendar::get_vtimezone(new DateTime());
$this->assertEquals(false, $vtz);
// DateTimezone as input data
- $vtz = libvcalendar::get_vtimezone(new DateTimezone('Pacific/Chatham'));
+ $vtz = libcalendaring_vcalendar::get_vtimezone(new DateTimezone('Pacific/Chatham'));
$this->assertInstanceOf('\Sabre\VObject\Component', $vtz);
$this->assertStringContainsString('TZOFFSETFROM:+1245', $vtz->serialize());
$this->assertStringContainsString('TZOFFSETTO:+1345', $vtz->serialize());
// Making sure VTIMEZOONE contains at least one STANDARD/DAYLIGHT component
// when there's only one transition in specified time period (T5626)
- $vtz = libvcalendar::get_vtimezone('Europe/Istanbul', strtotime('2019-10-04T15:00:00'));
+ $vtz = libcalendaring_vcalendar::get_vtimezone('Europe/Istanbul', strtotime('2019-10-04T15:00:00'));
$this->assertInstanceOf('\Sabre\VObject\Component', $vtz);
$dst = $vtz->select('DAYLIGHT');
$std = $vtz->select('STANDARD');
$this->assertEmpty($dst);
$this->assertCount(1, $std);
$std = end($std);
$this->assertEquals('STANDARD', $std->name);
$this->assertEquals('20181009T150000', $std->DTSTART);
$this->assertEquals('+0300', $std->TZOFFSETFROM);
$this->assertEquals('+0300', $std->TZOFFSETTO);
$this->assertEquals('+03', $std->TZNAME);
}
function get_attachment_data($id, $event)
{
return $this->attachment_data;
}
}
diff --git a/plugins/libkolab/composer.json b/plugins/libkolab/composer.json
index 8a00d7a6..fb79f874 100644
--- a/plugins/libkolab/composer.json
+++ b/plugins/libkolab/composer.json
@@ -1,33 +1,33 @@
{
"name": "kolab/libkolab",
"type": "roundcube-plugin",
"description": "Plugin to setup a basic environment for the interaction with a Kolab server.",
"homepage": "https://git.kolab.org/diffusion/RPK/",
"license": "AGPLv3",
"version": "3.5.11",
"authors": [
{
"name": "Thomas Bruederli",
"email": "bruederli@kolabsys.com",
"role": "Lead"
},
{
"name": "Aleksander Machniak",
"email": "machniak@kolabsys.com",
"role": "Developer"
}
],
"repositories": [
{
"type": "composer",
"url": "https://plugins.roundcube.net"
}
],
"require": {
- "php": ">=7.4.0",
+ "php": ">=7.2.0",
"roundcube/plugin-installer": ">=0.1.3",
"kolab/libcalendaring": ">=3.4.0",
- "pear/http_request2": "~2.3.0",
+ "pear/http_request2": "~2.5.0",
"caxy/php-htmldiff": "~0.1.7"
}
}
diff --git a/plugins/libkolab/lib/kolab_format.php b/plugins/libkolab/lib/kolab_format.php
index cf24c293..325dd2c0 100644
--- a/plugins/libkolab/lib/kolab_format.php
+++ b/plugins/libkolab/lib/kolab_format.php
@@ -1,799 +1,797 @@
<?php
/**
* Kolab format model class wrapping libkolabxml bindings
*
* Abstract base class for different Kolab groupware objects read from/written
* to the new Kolab 3 format using the PHP bindings of libkolabxml.
*
* @version @package_version@
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 2012, Kolab Systems AG <contact@kolabsys.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-require_once __DIR__ . '/../../libcalendaring/lib/libcalendaring_datetime.php';
-
abstract class kolab_format
{
public static $timezone;
public /*abstract*/ $CTYPE;
public /*abstract*/ $CTYPEv2;
protected /*abstract*/ $objclass;
protected /*abstract*/ $read_func;
protected /*abstract*/ $write_func;
protected $obj;
protected $data;
protected $xmldata;
protected $xmlobject;
protected $formaterror;
protected $loaded = false;
protected $version = '3.0';
const KTYPE_PREFIX = 'application/x-vnd.kolab.';
const PRODUCT_ID = 'Roundcube-libkolab-1.1';
// mapping table for valid PHP timezones not supported by libkolabxml
// basically the entire list of ftp://ftp.iana.org/tz/data/backward
protected static $timezone_map = array(
'Africa/Asmera' => 'Africa/Asmara',
'Africa/Timbuktu' => 'Africa/Abidjan',
'America/Argentina/ComodRivadavia' => 'America/Argentina/Catamarca',
'America/Atka' => 'America/Adak',
'America/Buenos_Aires' => 'America/Argentina/Buenos_Aires',
'America/Catamarca' => 'America/Argentina/Catamarca',
'America/Coral_Harbour' => 'America/Atikokan',
'America/Cordoba' => 'America/Argentina/Cordoba',
'America/Ensenada' => 'America/Tijuana',
'America/Fort_Wayne' => 'America/Indiana/Indianapolis',
'America/Indianapolis' => 'America/Indiana/Indianapolis',
'America/Jujuy' => 'America/Argentina/Jujuy',
'America/Knox_IN' => 'America/Indiana/Knox',
'America/Louisville' => 'America/Kentucky/Louisville',
'America/Mendoza' => 'America/Argentina/Mendoza',
'America/Porto_Acre' => 'America/Rio_Branco',
'America/Rosario' => 'America/Argentina/Cordoba',
'America/Virgin' => 'America/Port_of_Spain',
'Asia/Ashkhabad' => 'Asia/Ashgabat',
'Asia/Calcutta' => 'Asia/Kolkata',
'Asia/Chungking' => 'Asia/Shanghai',
'Asia/Dacca' => 'Asia/Dhaka',
'Asia/Katmandu' => 'Asia/Kathmandu',
'Asia/Macao' => 'Asia/Macau',
'Asia/Saigon' => 'Asia/Ho_Chi_Minh',
'Asia/Tel_Aviv' => 'Asia/Jerusalem',
'Asia/Thimbu' => 'Asia/Thimphu',
'Asia/Ujung_Pandang' => 'Asia/Makassar',
'Asia/Ulan_Bator' => 'Asia/Ulaanbaatar',
'Atlantic/Faeroe' => 'Atlantic/Faroe',
'Atlantic/Jan_Mayen' => 'Europe/Oslo',
'Australia/ACT' => 'Australia/Sydney',
'Australia/Canberra' => 'Australia/Sydney',
'Australia/LHI' => 'Australia/Lord_Howe',
'Australia/NSW' => 'Australia/Sydney',
'Australia/North' => 'Australia/Darwin',
'Australia/Queensland' => 'Australia/Brisbane',
'Australia/South' => 'Australia/Adelaide',
'Australia/Tasmania' => 'Australia/Hobart',
'Australia/Victoria' => 'Australia/Melbourne',
'Australia/West' => 'Australia/Perth',
'Australia/Yancowinna' => 'Australia/Broken_Hill',
'Brazil/Acre' => 'America/Rio_Branco',
'Brazil/DeNoronha' => 'America/Noronha',
'Brazil/East' => 'America/Sao_Paulo',
'Brazil/West' => 'America/Manaus',
'Canada/Atlantic' => 'America/Halifax',
'Canada/Central' => 'America/Winnipeg',
'Canada/East-Saskatchewan' => 'America/Regina',
'Canada/Eastern' => 'America/Toronto',
'Canada/Mountain' => 'America/Edmonton',
'Canada/Newfoundland' => 'America/St_Johns',
'Canada/Pacific' => 'America/Vancouver',
'Canada/Saskatchewan' => 'America/Regina',
'Canada/Yukon' => 'America/Whitehorse',
'Chile/Continental' => 'America/Santiago',
'Chile/EasterIsland' => 'Pacific/Easter',
'Cuba' => 'America/Havana',
'Egypt' => 'Africa/Cairo',
'Eire' => 'Europe/Dublin',
'Europe/Belfast' => 'Europe/London',
'Europe/Tiraspol' => 'Europe/Chisinau',
'GB' => 'Europe/London',
'GB-Eire' => 'Europe/London',
'Greenwich' => 'Etc/GMT',
'Hongkong' => 'Asia/Hong_Kong',
'Iceland' => 'Atlantic/Reykjavik',
'Iran' => 'Asia/Tehran',
'Israel' => 'Asia/Jerusalem',
'Jamaica' => 'America/Jamaica',
'Japan' => 'Asia/Tokyo',
'Kwajalein' => 'Pacific/Kwajalein',
'Libya' => 'Africa/Tripoli',
'Mexico/BajaNorte' => 'America/Tijuana',
'Mexico/BajaSur' => 'America/Mazatlan',
'Mexico/General' => 'America/Mexico_City',
'NZ' => 'Pacific/Auckland',
'NZ-CHAT' => 'Pacific/Chatham',
'Navajo' => 'America/Denver',
'PRC' => 'Asia/Shanghai',
'Pacific/Ponape' => 'Pacific/Pohnpei',
'Pacific/Samoa' => 'Pacific/Pago_Pago',
'Pacific/Truk' => 'Pacific/Chuuk',
'Pacific/Yap' => 'Pacific/Chuuk',
'Poland' => 'Europe/Warsaw',
'Portugal' => 'Europe/Lisbon',
'ROC' => 'Asia/Taipei',
'ROK' => 'Asia/Seoul',
'Singapore' => 'Asia/Singapore',
'Turkey' => 'Europe/Istanbul',
'UCT' => 'Etc/UCT',
'US/Alaska' => 'America/Anchorage',
'US/Aleutian' => 'America/Adak',
'US/Arizona' => 'America/Phoenix',
'US/Central' => 'America/Chicago',
'US/East-Indiana' => 'America/Indiana/Indianapolis',
'US/Eastern' => 'America/New_York',
'US/Hawaii' => 'Pacific/Honolulu',
'US/Indiana-Starke' => 'America/Indiana/Knox',
'US/Michigan' => 'America/Detroit',
'US/Mountain' => 'America/Denver',
'US/Pacific' => 'America/Los_Angeles',
'US/Samoa' => 'Pacific/Pago_Pago',
'Universal' => 'Etc/UTC',
'W-SU' => 'Europe/Moscow',
'Zulu' => 'Etc/UTC',
);
/**
* Factory method to instantiate a kolab_format object of the given type and version
*
* @param string Object type to instantiate
* @param float Format version
* @param string Cached xml data to initialize with
* @return object kolab_format
*/
public static function factory($type, $version = '3.0', $xmldata = null)
{
if (!isset(self::$timezone))
self::$timezone = new DateTimeZone('UTC');
if (!self::supports($version))
return PEAR::raiseError("No support for Kolab format version " . $version);
$type = preg_replace('/configuration\.[a-z._]+$/', 'configuration', $type);
$suffix = preg_replace('/[^a-z]+/', '', $type);
$classname = 'kolab_format_' . $suffix;
if (class_exists($classname))
return new $classname($xmldata, $version);
return PEAR::raiseError("Failed to load Kolab Format wrapper for type " . $type);
}
/**
* Determine support for the given format version
*
* @param float Format version to check
* @return boolean True if supported, False otherwise
*/
public static function supports($version)
{
if ($version == '2.0')
return class_exists('kolabobject');
// default is version 3
return class_exists('kolabformat');
}
/**
* Convert the given date/time value into a cDateTime object
*
* @param mixed Date/Time value either as unix timestamp, date string or PHP DateTime object
* @param DateTimeZone The timezone the date/time is in. Use global default if Null, local time if False
* @param boolean True of the given date has no time component
* @param DateTimeZone The timezone to convert the date to before converting to cDateTime
*
* @return cDateTime The libkolabxml date/time object
*/
public static function get_datetime($datetime, $tz = null, $dateonly = false, $dest_tz = null)
{
// use timezone information from datetime or global setting
if (!$tz && $tz !== false) {
if ($datetime instanceof DateTimeInterface)
$tz = $datetime->getTimezone();
if (!$tz)
$tz = self::$timezone;
}
$result = new cDateTime();
try {
// got a unix timestamp (in UTC)
if (is_numeric($datetime)) {
$datetime = new libcalendaring_datetime('@'.$datetime, new DateTimeZone('UTC'));
if ($tz) $datetime->setTimezone($tz);
}
else if (is_string($datetime) && strlen($datetime)) {
$datetime = $tz ? new libcalendaring_datetime($datetime, $tz) : new libcalendaring_datetime($datetime);
}
else if ($datetime instanceof DateTimeInterface) {
$datetime = clone $datetime;
}
}
catch (Exception $e) {}
if ($datetime instanceof DateTimeInterface) {
if ($dest_tz instanceof DateTimeZone && $dest_tz !== $datetime->getTimezone()) {
$datetime->setTimezone($dest_tz);
$tz = $dest_tz;
}
$result->setDate($datetime->format('Y'), $datetime->format('n'), $datetime->format('j'));
if ($dateonly) {
// Dates should be always in local time only
return $result;
}
$result->setTime($datetime->format('G'), $datetime->format('i'), $datetime->format('s'));
// libkolabxml throws errors on some deprecated timezone names
$utc_aliases = array('UTC', 'GMT', '+00:00', 'Z', 'Etc/GMT', 'Etc/UTC');
if ($tz && in_array($tz->getName(), $utc_aliases)) {
$result->setUTC(true);
}
else if ($tz !== false) {
$tzid = $tz->getName();
if (array_key_exists($tzid, self::$timezone_map))
$tzid = self::$timezone_map[$tzid];
$result->setTimezone($tzid);
}
}
return $result;
}
/**
* Convert the given cDateTime into a PHP DateTime object
*
* @param cDateTime The libkolabxml datetime object
* @param DateTimeZone The timezone to convert the date to
*
* @return libcalendaring_datetime PHP datetime instance
*/
public static function php_datetime($cdt, $dest_tz = null)
{
if (!is_object($cdt) || !$cdt->isValid()) {
return null;
}
$d = new libcalendaring_datetime(null, self::$timezone);
if ($dest_tz) {
$d->setTimezone($dest_tz);
}
else {
try {
if ($tzs = $cdt->timezone()) {
$tz = new DateTimeZone($tzs);
$d->setTimezone($tz);
}
else if ($cdt->isUTC()) {
$d->setTimezone(new DateTimeZone('UTC'));
}
}
catch (Exception $e) { }
}
$d->setDate($cdt->year(), $cdt->month(), $cdt->day());
if ($cdt->isDateOnly()) {
$d->_dateonly = true;
$d->setTime(12, 0, 0); // set time to noon to avoid timezone troubles
}
else {
$d->setTime($cdt->hour(), $cdt->minute(), $cdt->second());
}
return $d;
}
/**
* Convert a libkolabxml vector to a PHP array
*
* @param object vector Object
* @return array Indexed array containing vector elements
*/
public static function vector2array($vec, $max = PHP_INT_MAX)
{
$arr = array();
for ($i=0; $i < $vec->size() && $i < $max; $i++)
$arr[] = $vec->get($i);
return $arr;
}
/**
* Build a libkolabxml vector (string) from a PHP array
*
* @param array Array with vector elements
* @return object vectors
*/
public static function array2vector($arr)
{
$vec = new vectors;
foreach ((array)$arr as $val) {
if (strlen($val))
$vec->push($val);
}
return $vec;
}
/**
* Parse the X-Kolab-Type header from MIME messages and return the object type in short form
*
* @param string X-Kolab-Type header value
* @return string Kolab object type (contact,event,task,note,etc.)
*/
public static function mime2object_type($x_kolab_type)
{
return preg_replace(
array('/dictionary.[a-z.]+$/', '/contact.distlist$/'),
array( 'dictionary', 'distribution-list'),
substr($x_kolab_type, strlen(self::KTYPE_PREFIX))
);
}
/**
* Default constructor of all kolab_format_* objects
*/
public function __construct($xmldata = null, $version = null)
{
$this->obj = new $this->objclass;
$this->xmldata = $xmldata;
if ($version)
$this->version = $version;
// use libkolab module if available
if (class_exists('kolabobject'))
$this->xmlobject = new XMLObject();
}
/**
* Check for format errors after calling kolabformat::write*()
*
* @return boolean True if there were errors, False if OK
*/
protected function format_errors()
{
$ret = $log = false;
switch (kolabformat::error()) {
case kolabformat::NoError:
$ret = false;
break;
case kolabformat::Warning:
$ret = false;
$uid = is_object($this->obj) ? $this->obj->uid() : $this->data['uid'];
$log = "Warning @ $uid";
break;
default:
$ret = true;
$log = "Error";
}
if ($log && !isset($this->formaterror)) {
rcube::raise_error(array(
'code' => 660,
'type' => 'php',
'file' => __FILE__,
'line' => __LINE__,
'message' => "kolabformat $log: " . kolabformat::errorMessage(),
), true);
$this->formaterror = $ret;
}
return $ret;
}
/**
* Save the last generated UID to the object properties.
* Should be called after kolabformat::writeXXXX();
*/
protected function update_uid()
{
// get generated UID
if (!$this->data['uid']) {
if ($this->xmlobject) {
$this->data['uid'] = $this->xmlobject->getSerializedUID();
}
if (empty($this->data['uid'])) {
$this->data['uid'] = kolabformat::getSerializedUID();
}
$this->obj->setUid($this->data['uid']);
}
}
/**
* Initialize libkolabxml object with cached xml data
*/
protected function init()
{
if (!$this->loaded) {
if ($this->xmldata) {
$this->load($this->xmldata);
$this->xmldata = null;
}
$this->loaded = true;
}
}
/**
* Get constant value for libkolab's version parameter
*
* @param float Version value to convert
* @return int Constant value of either kolabobject::KolabV2 or kolabobject::KolabV3 or false if kolabobject module isn't available
*/
protected function libversion($v = null)
{
if (class_exists('kolabobject')) {
$version = $v ?: $this->version;
if ($version <= '2.0')
return kolabobject::KolabV2;
else
return kolabobject::KolabV3;
}
return false;
}
/**
* Determine the correct libkolab(xml) wrapper function for the given call
* depending on the available PHP modules
*/
protected function libfunc($func)
{
if (is_array($func) || strpos($func, '::'))
return $func;
else if (class_exists('kolabobject'))
return array($this->xmlobject, $func);
else
return 'kolabformat::' . $func;
}
/**
* Direct getter for object properties
*/
public function __get($var)
{
return $this->data[$var];
}
/**
* Load Kolab object data from the given XML block
*
* @param string XML data
* @return boolean True on success, False on failure
*/
public function load($xml)
{
$this->formaterror = null;
$read_func = $this->libfunc($this->read_func);
if (is_array($read_func))
$r = call_user_func($read_func, $xml, $this->libversion());
else
$r = call_user_func($read_func, $xml, false);
if (is_resource($r))
$this->obj = new $this->objclass($r);
else if (is_a($r, $this->objclass))
$this->obj = $r;
$this->loaded = !$this->format_errors();
}
/**
* Write object data to XML format
*
* @param float Format version to write
* @return string XML data
*/
public function write($version = null)
{
$this->formaterror = null;
$this->init();
$write_func = $this->libfunc($this->write_func);
if (is_array($write_func))
$this->xmldata = call_user_func($write_func, $this->obj, $this->libversion($version), self::PRODUCT_ID);
else
$this->xmldata = call_user_func($write_func, $this->obj, self::PRODUCT_ID);
if (!$this->format_errors())
$this->update_uid();
else
$this->xmldata = null;
return $this->xmldata;
}
/**
* Set properties to the kolabformat object
*
* @param array Object data as hash array
*/
public function set(&$object)
{
$this->init();
if (!empty($object['uid']))
$this->obj->setUid($object['uid']);
// set some automatic values if missing
if (method_exists($this->obj, 'setCreated')) {
// Always set created date to workaround libkolabxml (>1.1.4) bug
$created = $object['created'] ?: new DateTime('now');
$created->setTimezone(new DateTimeZone('UTC')); // must be UTC
$this->obj->setCreated(self::get_datetime($created));
$object['created'] = $created;
}
$object['changed'] = new DateTime('now', new DateTimeZone('UTC'));
$this->obj->setLastModified(self::get_datetime($object['changed']));
// Save custom properties of the given object
if (isset($object['x-custom']) && method_exists($this->obj, 'setCustomProperties')) {
$vcustom = new vectorcs;
foreach ((array)$object['x-custom'] as $cp) {
if (is_array($cp))
$vcustom->push(new CustomProperty($cp[0], $cp[1]));
}
$this->obj->setCustomProperties($vcustom);
}
// load custom properties from XML for caching (#2238) if method exists (#3125)
else if (method_exists($this->obj, 'customProperties')) {
$object['x-custom'] = array();
$vcustom = $this->obj->customProperties();
for ($i=0; $i < $vcustom->size(); $i++) {
$cp = $vcustom->get($i);
$object['x-custom'][] = array($cp->identifier, $cp->value);
}
}
}
/**
* Convert the Kolab object into a hash array data structure
*
* @param array Additional data for merge
*
* @return array Kolab object data as hash array
*/
public function to_array($data = array())
{
$this->init();
// read object properties into local data object
$object = array(
'uid' => $this->obj->uid(),
'changed' => self::php_datetime($this->obj->lastModified()),
);
// not all container support the created property
if (method_exists($this->obj, 'created')) {
$object['created'] = self::php_datetime($this->obj->created());
}
// read custom properties
if (method_exists($this->obj, 'customProperties')) {
$vcustom = $this->obj->customProperties();
for ($i=0; $i < $vcustom->size(); $i++) {
$cp = $vcustom->get($i);
$object['x-custom'][] = array($cp->identifier, $cp->value);
}
}
// merge with additional data, e.g. attachments from the message
if ($data) {
foreach ($data as $idx => $value) {
if (is_array($value)) {
$object[$idx] = array_merge((array)$object[$idx], $value);
}
else {
$object[$idx] = $value;
}
}
}
return $object;
}
/**
* Object validation method to be implemented by derived classes
*/
abstract public function is_valid();
/**
* Callback for kolab_storage_cache to get object specific tags to cache
*
* @return array List of tags to save in cache
*/
public function get_tags()
{
return array();
}
/**
* Callback for kolab_storage_cache to get words to index for fulltext search
*
* @return array List of words to save in cache
*/
public function get_words()
{
return array();
}
/**
* Utility function to extract object attachment data
*
* @param array Hash array reference to append attachment data into
*/
public function get_attachments(&$object, $all = false)
{
$this->init();
// handle attachments
$vattach = $this->obj->attachments();
for ($i=0; $i < $vattach->size(); $i++) {
$attach = $vattach->get($i);
// skip cid: attachments which are mime message parts handled by kolab_storage_folder
if (substr($attach->uri(), 0, 4) != 'cid:' && $attach->label()) {
$name = $attach->label();
$key = $name . (isset($object['_attachments'][$name]) ? '.'.$i : '');
$content = $attach->data();
$object['_attachments'][$key] = array(
'id' => 'i:'.$i,
'name' => $name,
'mimetype' => $attach->mimetype(),
'size' => strlen($content),
'content' => $content,
);
}
else if ($all && substr($attach->uri(), 0, 4) == 'cid:') {
$key = $attach->uri();
$object['_attachments'][$key] = array(
'id' => $key,
'name' => $attach->label(),
'mimetype' => $attach->mimetype(),
);
}
else if (in_array(substr($attach->uri(), 0, 4), array('http','imap'))) {
$object['links'][] = $attach->uri();
}
}
}
/**
* Utility function to set attachment properties to the kolabformat object
*
* @param array Object data as hash array
* @param boolean True to always overwrite attachment information
*/
protected function set_attachments($object, $write = true)
{
// save attachments
$vattach = new vectorattachment;
foreach ((array) $object['_attachments'] as $cid => $attr) {
if (empty($attr))
continue;
$attach = new Attachment;
$attach->setLabel((string)$attr['name']);
$attach->setUri('cid:' . $cid, $attr['mimetype'] ?: 'application/octet-stream');
if ($attach->isValid()) {
$vattach->push($attach);
$write = true;
}
else {
rcube::raise_error(array(
'code' => 660,
'type' => 'php',
'file' => __FILE__,
'line' => __LINE__,
'message' => "Invalid attributes for attachment $cid: " . var_export($attr, true),
), true);
}
}
foreach ((array) $object['links'] as $link) {
$attach = new Attachment;
$attach->setUri($link, 'unknown');
$vattach->push($attach);
$write = true;
}
if ($write) {
$this->obj->setAttachments($vattach);
}
}
/**
* Unified way of updating/deleting attachments of edited object
*
* @param array $object Kolab object data
* @param array $old Old version of Kolab object
*/
public static function merge_attachments(&$object, $old)
{
$object['_attachments'] = (array) $old['_attachments'];
// delete existing attachment(s)
if (!empty($object['deleted_attachments'])) {
foreach ($object['_attachments'] as $idx => $att) {
if ($object['deleted_attachments'] === true || in_array($att['id'], $object['deleted_attachments'])) {
$object['_attachments'][$idx] = false;
}
}
}
// in kolab_storage attachments are indexed by content-id
foreach ((array) $object['attachments'] as $attachment) {
$key = null;
// Roundcube ID has nothing to do with the storage ID, remove it
// for uploaded/new attachments
// FIXME: Roundcube uses 'data', kolab_format uses 'content'
if ($attachment['content'] || $attachment['path'] || $attachment['data']) {
unset($attachment['id']);
}
if ($attachment['id']) {
foreach ((array) $object['_attachments'] as $cid => $att) {
if ($att && $attachment['id'] == $att['id']) {
$key = $cid;
}
}
}
else {
// find attachment by name, so we can update it if exists
// and make sure there are no duplicates
foreach ((array) $object['_attachments'] as $cid => $att) {
if ($att && $attachment['name'] == $att['name']) {
$key = $cid;
}
}
}
if ($key && $attachment['_deleted']) {
$object['_attachments'][$key] = false;
}
// replace existing entry
else if ($key) {
$object['_attachments'][$key] = $attachment;
}
// append as new attachment
else {
$object['_attachments'][] = $attachment;
}
}
unset($object['attachments']);
unset($object['deleted_attachments']);
}
}
diff --git a/plugins/libkolab/lib/kolab_format_event.php b/plugins/libkolab/lib/kolab_format_event.php
index 860adb65..f2900810 100644
--- a/plugins/libkolab/lib/kolab_format_event.php
+++ b/plugins/libkolab/lib/kolab_format_event.php
@@ -1,326 +1,326 @@
<?php
/**
* Kolab Event model class
*
* @version @package_version@
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 2012, Kolab Systems AG <contact@kolabsys.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class kolab_format_event extends kolab_format_xcal
{
public $CTYPEv2 = 'application/x-vnd.kolab.event';
public static $scheduling_properties = array('start', 'end', 'allday', 'recurrence', 'location', 'status', 'cancelled');
protected $objclass = 'Event';
protected $read_func = 'readEvent';
protected $write_func = 'writeEvent';
/**
* Default constructor
*/
function __construct($data = null, $version = 3.0)
{
parent::__construct(is_string($data) ? $data : null, $version);
// got an Event object as argument
if (is_object($data) && is_a($data, $this->objclass)) {
$this->obj = $data;
$this->loaded = true;
}
// copy static property overriden by this class
$this->_scheduling_properties = self::$scheduling_properties;
}
/**
* Set event properties to the kolabformat object
*
* @param array Event data as hash array
*/
public function set(&$object)
{
// set common xcal properties
parent::set($object);
// do the hard work of setting object values
$this->obj->setStart(self::get_datetime($object['start'], null, $object['allday']));
$this->obj->setEnd(self::get_datetime($object['end'], null, $object['allday']));
$this->obj->setTransparency($object['free_busy'] == 'free');
$status = kolabformat::StatusUndefined;
if ($object['free_busy'] == 'tentative')
$status = kolabformat::StatusTentative;
if ($object['cancelled'])
$status = kolabformat::StatusCancelled;
else if ($object['status'] && array_key_exists($object['status'], $this->status_map))
$status = $this->status_map[$object['status']];
$this->obj->setStatus($status);
// save (recurrence) exceptions
if (is_array($object['recurrence']) && is_array($object['recurrence']['EXCEPTIONS']) && !isset($object['exceptions'])) {
$object['exceptions'] = $object['recurrence']['EXCEPTIONS'];
}
if (is_array($object['exceptions'])) {
$recurrence_id_format = libkolab::recurrence_id_format($object);
$vexceptions = new vectorevent;
foreach ($object['exceptions'] as $i => $exception) {
$exevent = new kolab_format_event;
$exevent->set($compacted = $this->compact_exception($exception, $object)); // only save differing values
// get value for recurrence-id
$recurrence_id = null;
- if (!empty($exception['recurrence_date']) && is_a($exception['recurrence_date'], 'DateTime')) {
+ if (!empty($exception['recurrence_date']) && $exception['recurrence_date'] instanceof DateTimeInterface) {
$recurrence_id = $exception['recurrence_date'];
$compacted['_instance'] = $recurrence_id->format($recurrence_id_format);
}
else if (!empty($exception['_instance']) && strlen($exception['_instance']) > 4) {
$recurrence_id = rcube_utils::anytodatetime($exception['_instance'], $object['start']->getTimezone());
$compacted['recurrence_date'] = $recurrence_id;
}
$exevent->obj->setRecurrenceID(self::get_datetime($recurrence_id ?: $exception['start'], null, $object['allday']), (bool)$exception['thisandfuture']);
$vexceptions->push($exevent->obj);
// write cleaned-up exception data back to memory/cache
$object['exceptions'][$i] = $this->expand_exception($exevent->data, $object);
$object['exceptions'][$i]['_instance'] = $compacted['_instance'];
}
$this->obj->setExceptions($vexceptions);
// link with recurrence.EXCEPTIONS for compatibility
if (is_array($object['recurrence'])) {
$object['recurrence']['EXCEPTIONS'] = &$object['exceptions'];
}
}
if ($object['recurrence_date'] && $object['recurrence_date'] instanceof DateTimeInterface) {
if ($object['recurrence']) {
// unset recurrence_date for master events with rrule
$object['recurrence_date'] = null;
}
$this->obj->setRecurrenceID(self::get_datetime($object['recurrence_date'], null, $object['allday']), (bool)$object['thisandfuture']);
}
// cache this data
$this->data = $object;
unset($this->data['_formatobj']);
}
/**
*
*/
public function is_valid()
{
return !$this->formaterror && (($this->data && !empty($this->data['start']) && !empty($this->data['end'])) ||
(is_object($this->obj) && $this->obj->isValid() && $this->obj->uid()));
}
/**
* Convert the Event object into a hash array data structure
*
* @param array Additional data for merge
*
* @return array Event data as hash array
*/
public function to_array($data = array())
{
// return cached result
if (!empty($this->data))
return $this->data;
// read common xcal props
$object = parent::to_array($data);
// read object properties
$object += array(
'end' => self::php_datetime($this->obj->end()),
'allday' => $this->obj->start()->isDateOnly(),
'free_busy' => $this->obj->transparency() ? 'free' : 'busy', // TODO: transparency is only boolean
'attendees' => array(),
);
// derive event end from duration (#1916)
if (!$object['end'] && $object['start'] && ($duration = $this->obj->duration()) && $duration->isValid()) {
$interval = new DateInterval('PT0S');
$interval->d = $duration->weeks() * 7 + $duration->days();
$interval->h = $duration->hours();
$interval->i = $duration->minutes();
$interval->s = $duration->seconds();
$object['end'] = clone $object['start'];
$object['end']->add($interval);
}
// make sure end date is specified (#5307) RFC5545 3.6.1
else if (!$object['end'] && $object['start']) {
$object['end'] = clone $object['start'];
}
// organizer is part of the attendees list in Roundcube
if ($object['organizer']) {
$object['organizer']['role'] = 'ORGANIZER';
array_unshift($object['attendees'], $object['organizer']);
}
// status defines different event properties...
$status = $this->obj->status();
if ($status == kolabformat::StatusTentative)
$object['free_busy'] = 'tentative';
else if ($status == kolabformat::StatusCancelled)
$object['cancelled'] = true;
// this is an exception object
if ($this->obj->recurrenceID()->isValid()) {
$object['thisandfuture'] = $this->obj->thisAndFuture();
$object['recurrence_date'] = self::php_datetime($this->obj->recurrenceID());
}
// read exception event objects
if (($exceptions = $this->obj->exceptions()) && is_object($exceptions) && $exceptions->size()) {
$recurrence_exceptions = array();
$recurrence_id_format = libkolab::recurrence_id_format($object);
for ($i=0; $i < $exceptions->size(); $i++) {
if (($exobj = $exceptions->get($i))) {
$exception = new kolab_format_event($exobj);
if ($exception->is_valid()) {
$exdata = $exception->to_array();
// fix date-only recurrence ID saved by old versions
if ($exdata['recurrence_date'] && $exdata['recurrence_date']->_dateonly && !$object['allday']) {
$exdata['recurrence_date']->setTimezone($object['start']->getTimezone());
$exdata['recurrence_date']->setTime($object['start']->format('G'), intval($object['start']->format('i')), intval($object['start']->format('s')));
}
$recurrence_id = $exdata['recurrence_date'] ?: $exdata['start'];
$exdata['_instance'] = $recurrence_id->format($recurrence_id_format);
$recurrence_exceptions[] = $this->expand_exception($exdata, $object);
}
}
}
$object['exceptions'] = $recurrence_exceptions;
// also link with recurrence.EXCEPTIONS for compatibility
if (is_array($object['recurrence'])) {
$object['recurrence']['EXCEPTIONS'] = &$object['exceptions'];
}
}
return $this->data = $object;
}
/**
* Getter for a single instance from a recurrence series or stored subcomponents
*
* @param mixed The recurrence-id of the requested instance, either as string or a DateTime object
* @return array Event data as hash array or null if not found
*/
public function get_instance($recurrence_id)
{
$result = null;
$object = $this->to_array();
$recurrence_id_format = libkolab::recurrence_id_format($object);
$instance_id = $recurrence_id instanceof DateTimeInterface ? $recurrence_id->format($recurrence_id_format) : strval($recurrence_id);
if ($object['recurrence_date'] instanceof DateTimeInterface) {
if ($object['recurrence_date']->format($recurrence_id_format) == $instance_id) {
$result = $object;
}
}
if (!$result && is_array($object['exceptions'])) {
foreach ($object['exceptions'] as $exception) {
if ($exception['_instance'] == $instance_id) {
$result = $exception;
$result['isexception'] = 1;
break;
}
}
}
// TODO: compute instances from recurrence rule and return the matching instance
// clone from plugins/calendar/drivers/kolab/kolab_calendar::get_recurring_events()
return $result;
}
/**
* Callback for kolab_storage_cache to get object specific tags to cache
*
* @return array List of tags to save in cache
*/
public function get_tags($obj = null)
{
$tags = parent::get_tags($obj);
$object = $obj ?: $this->data;
foreach ((array)$object['categories'] as $cat) {
$tags[] = rcube_utils::normalize_string($cat);
}
return array_unique($tags);
}
/**
* Remove some attributes from the exception container
*/
private function compact_exception($exception, $master)
{
$forbidden = array('recurrence','exceptions','organizer','_attachments');
foreach ($forbidden as $prop) {
if (array_key_exists($prop, $exception)) {
unset($exception[$prop]);
}
}
// preserve this property for date serialization
if (!isset($exception['allday'])) {
$exception['allday'] = $master['allday'];
}
return $exception;
}
/**
* Copy attributes not specified by the exception from the master event
*/
private function expand_exception($exception, $master)
{
// Note: If an exception has no attendees it means there's "no attendees
// for this occurrence", not "attendees are the same as in the event" (#5300)
$forbidden = array('exceptions', 'attendees', 'allday');
$is_recurring = !empty($master['recurrence']);
foreach ($master as $prop => $value) {
if (empty($exception[$prop]) && !empty($value) && $prop[0] != '_'
&& !in_array($prop, $forbidden)
&& ($is_recurring || in_array($prop, array('uid','organizer')))
) {
$exception[$prop] = $value;
if ($prop == 'recurrence') {
unset($exception[$prop]['EXCEPTIONS']);
}
}
}
return $exception;
}
}
diff --git a/plugins/libkolab/lib/kolab_storage_cache_event.php b/plugins/libkolab/lib/kolab_storage_cache_event.php
index 13b350b3..b324f561 100644
--- a/plugins/libkolab/lib/kolab_storage_cache_event.php
+++ b/plugins/libkolab/lib/kolab_storage_cache_event.php
@@ -1,68 +1,68 @@
<?php
/**
* Kolab storage cache class for calendar event objects
*
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 2013, Kolab Systems AG <contact@kolabsys.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class kolab_storage_cache_event extends kolab_storage_cache
{
protected $extra_cols = array('dtstart','dtend');
protected $data_props = array('categories', 'status', 'attendees'); // start, end
/**
* Helper method to convert the given Kolab object into a dataset to be written to cache
*
* @override
*/
protected function _serialize($object)
{
$sql_data = parent::_serialize($object);
$sql_data['dtstart'] = $this->_convert_datetime($object['start']);
$sql_data['dtend'] = $this->_convert_datetime($object['end']);
// extend date range for recurring events
if ($object['recurrence'] && $object['_formatobj']) {
$recurrence = new kolab_date_recurrence($object['_formatobj']);
$dtend = $recurrence->end() ?: new DateTime('now +100 years');
$sql_data['dtend'] = $this->_convert_datetime($dtend);
}
// extend start/end dates to spawn all exceptions
if (is_array($object['exceptions'])) {
foreach ($object['exceptions'] as $exception) {
- if (is_a($exception['start'], 'DateTime')) {
+ if ($exception['start'] instanceof DateTimeInterface) {
$exstart = $this->_convert_datetime($exception['start']);
if ($exstart < $sql_data['dtstart']) {
$sql_data['dtstart'] = $exstart;
}
}
- if (is_a($exception['end'], 'DateTime')) {
+ if ($exception['end'] instanceof DateTimeInterface) {
$exend = $this->_convert_datetime($exception['end']);
if ($exend > $sql_data['dtend']) {
$sql_data['dtend'] = $exend;
}
}
}
}
return $sql_data;
}
}
diff --git a/plugins/libkolab/lib/kolab_storage_dav_cache_event.php b/plugins/libkolab/lib/kolab_storage_dav_cache_event.php
index 00d395f5..8e7c7e75 100644
--- a/plugins/libkolab/lib/kolab_storage_dav_cache_event.php
+++ b/plugins/libkolab/lib/kolab_storage_dav_cache_event.php
@@ -1,152 +1,152 @@
<?php
/**
* Kolab storage cache class for calendar event objects
*
* @author Aleksander Machniak <machniak@apheleia-it.ch>
*
* Copyright (C) 2013-2022 Apheleia IT AG <contact@apheleia-it.ch>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class kolab_storage_dav_cache_event extends kolab_storage_dav_cache
{
protected $extra_cols = ['dtstart','dtend'];
protected $data_props = ['categories', 'status', 'attendees'];
protected $fulltext_cols = ['title', 'description', 'location', 'attendees:name', 'attendees:email', 'categories'];
/**
* Helper method to convert the given Kolab object into a dataset to be written to cache
*
* @override
*/
protected function _serialize($object)
{
$sql_data = parent::_serialize($object);
$sql_data['dtstart'] = $this->_convert_datetime($object['start']);
$sql_data['dtend'] = $this->_convert_datetime($object['end']);
// extend date range for recurring events
if (!empty($object['recurrence'])) {
if (empty($object['_formatobj'])) {
$event_xml = new kolab_format_event();
$event_xml->set($object);
$object['_formatobj'] = $event_xml;
}
$recurrence = new kolab_date_recurrence($object['_formatobj']);
$dtend = $recurrence->end() ?: new DateTime('now +100 years');
$sql_data['dtend'] = $this->_convert_datetime($dtend);
}
// extend start/end dates to spawn all exceptions
if (is_array($object['exceptions'])) {
foreach ($object['exceptions'] as $exception) {
- if (is_a($exception['start'], 'DateTime')) {
+ if ($exception['start'] instanceof DateTimeInterface) {
$exstart = $this->_convert_datetime($exception['start']);
if ($exstart < $sql_data['dtstart']) {
$sql_data['dtstart'] = $exstart;
}
}
- if (is_a($exception['end'], 'DateTime')) {
+ if ($exception['end'] instanceof DateTimeInterface) {
$exend = $this->_convert_datetime($exception['end']);
if ($exend > $sql_data['dtend']) {
$sql_data['dtend'] = $exend;
}
}
}
}
$sql_data['tags'] = ' ' . join(' ', $this->get_tags($object)) . ' '; // pad with spaces for strict/prefix search
$sql_data['words'] = ' ' . join(' ', $this->get_words($object)) . ' ';
return $sql_data;
}
/**
* Callback to get words to index for fulltext search
*
* @return array List of words to save in cache
*/
public function get_words($object = [])
{
$data = '';
foreach ($this->fulltext_cols as $colname) {
list($col, $field) = explode(':', $colname);
if ($field) {
$a = [];
foreach ((array) $object[$col] as $attr) {
$a[] = $attr[$field];
}
$val = join(' ', $a);
}
else {
$val = is_array($object[$col]) ? join(' ', $object[$col]) : $object[$col];
}
if (strlen($val))
$data .= $val . ' ';
}
$words = rcube_utils::normalize_string($data, true);
// collect words from recurrence exceptions
if (is_array($object['exceptions'])) {
foreach ($object['exceptions'] as $exception) {
$words = array_merge($words, $this->get_words($exception));
}
}
return array_unique($words);
}
/**
* Callback to get object specific tags to cache
*
* @return array List of tags to save in cache
*/
public function get_tags($object)
{
$tags = [];
if (!empty($object['valarms'])) {
$tags[] = 'x-has-alarms';
}
// create tags reflecting participant status
if (is_array($object['attendees'])) {
foreach ($object['attendees'] as $attendee) {
if (!empty($attendee['email']) && !empty($attendee['status']))
$tags[] = 'x-partstat:' . $attendee['email'] . ':' . strtolower($attendee['status']);
}
}
// collect tags from recurrence exceptions
if (is_array($object['exceptions'])) {
foreach ($object['exceptions'] as $exception) {
$tags = array_merge($tags, $this->get_tags($exception));
}
}
if (!empty($object['status'])) {
$tags[] = 'x-status:' . strtolower($object['status']);
}
return array_unique($tags);
}
}
diff --git a/plugins/libkolab/lib/kolab_storage_dav_folder.php b/plugins/libkolab/lib/kolab_storage_dav_folder.php
index 8bf48c7f..adfa1d88 100644
--- a/plugins/libkolab/lib/kolab_storage_dav_folder.php
+++ b/plugins/libkolab/lib/kolab_storage_dav_folder.php
@@ -1,722 +1,722 @@
<?php
/**
* A class representing a DAV folder object.
*
* @author Aleksander Machniak <machniak@apheleia-it.ch>
*
* Copyright (C) 2014-2022, Apheleia IT AG <contact@apheleia-it.ch>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class kolab_storage_dav_folder extends kolab_storage_folder
{
public $dav;
public $href;
public $attributes;
/**
* Object constructor
*/
public function __construct($dav, $attributes, $type = '')
{
$this->attributes = $attributes;
$this->href = $this->attributes['href'];
$this->id = md5($dav->url . '/' . $this->href);
$this->dav = $dav;
$this->valid = true;
list($this->type, $suffix) = strpos($type, '.') ? explode('.', $type) : [$type, ''];
$this->default = $suffix == 'default';
$this->subtype = $this->default ? '' : $suffix;
// Init cache
$this->cache = kolab_storage_dav_cache::factory($this);
}
/**
* Returns the owner of the folder.
*
* @param bool Return a fully qualified owner name (i.e. including domain for shared folders)
*
* @return string The owner of this folder.
*/
public function get_owner($fully_qualified = false)
{
// return cached value
if (isset($this->owner)) {
return $this->owner;
}
$rcube = rcube::get_instance();
$this->owner = $rcube->get_user_name();
$this->valid = true;
// TODO: Support shared folders
return $this->owner;
}
/**
* Get a folder Etag identifier
*/
public function get_ctag()
{
return $this->attributes['ctag'];
}
/**
* Getter for the name of the namespace to which the folder belongs
*
* @return string Name of the namespace (personal, other, shared)
*/
public function get_namespace()
{
// TODO: Support shared folders
return 'personal';
}
/**
* Get the display name value of this folder
*
* @return string Folder name
*/
public function get_name()
{
return kolab_storage_dav::object_name($this->attributes['name']);
}
/**
* Getter for the top-end folder name (not the entire path)
*
* @return string Name of this folder
*/
public function get_foldername()
{
return $this->attributes['name'];
}
public function get_folder_info()
{
return []; // todo ?
}
/**
* Getter for parent folder path
*
* @return string Full path to parent folder
*/
public function get_parent()
{
// TODO
return '';
}
/**
* Compose a unique resource URI for this folder
*/
public function get_resource_uri()
{
if (!empty($this->resource_uri)) {
return $this->resource_uri;
}
// compose fully qualified resource uri for this instance
$host = preg_replace('|^https?://|', 'dav://' . urlencode($this->get_owner(true)) . '@', $this->dav->url);
$path = $this->href[0] == '/' ? $this->href : "/{$this->href}";
$host_path = parse_url($host, PHP_URL_PATH);
if ($host_path && strpos($path, $host_path) === 0) {
$path = substr($path, strlen($host_path));
}
$this->resource_uri = unslashify($host) . $path;
return $this->resource_uri;
}
/**
* Getter for the Cyrus mailbox identifier corresponding to this folder
* (e.g. user/john.doe/Calendar/Personal@example.org)
*
* @return string Mailbox ID
*/
public function get_mailbox_id()
{
// TODO: This is used with Bonnie related features
return '';
}
/**
* Get the color value stored in metadata
*
* @param string Default color value to return if not set
*
* @return mixed Color value from the folder metadata or $default if not set
*/
public function get_color($default = null)
{
return !empty($this->attributes['color']) ? $this->attributes['color'] : $default;
}
/**
* Get ACL information for this folder
*
* @return string Permissions as string
*/
public function get_myrights()
{
// TODO
return '';
}
/**
* Helper method to extract folder UID
*
* @return string Folder's UID
*/
public function get_uid()
{
// TODO ???
return '';
}
/**
* Check activation status of this folder
*
* @return bool True if enabled, false if not
*/
public function is_active()
{
return true; // Unused
}
/**
* Change activation status of this folder
*
* @param bool The desired subscription status: true = active, false = not active
*
* @return bool True on success, false on error
*/
public function activate($active)
{
return true; // Unused
}
/**
* Check subscription status of this folder
*
* @return bool True if subscribed, false if not
*/
public function is_subscribed()
{
return true; // TODO
}
/**
* Change subscription status of this folder
*
* @param bool The desired subscription status: true = subscribed, false = not subscribed
*
* @return True on success, false on error
*/
public function subscribe($subscribed)
{
return true; // TODO
}
/**
* Delete the specified object from this folder.
*
* @param array|string $object The Kolab object to delete or object UID
* @param bool $expunge Should the folder be expunged?
*
* @return bool True if successful, false on error
*/
public function delete($object, $expunge = true)
{
if (!$this->valid) {
return false;
}
$uid = is_array($object) ? $object['uid'] : $object;
$success = $this->dav->delete($this->object_location($uid));
if ($success) {
$this->cache->set($uid, false);
}
return $success;
}
/**
* Delete all objects in a folder.
*
* Note: This method is used by kolab_addressbook plugin only
*
* @return bool True if successful, false on error
*/
public function delete_all()
{
if (!$this->valid) {
return false;
}
// TODO: Maybe just deleting and re-creating a folder would be
// better, but probably might not always work (ACL)
$this->cache->synchronize();
foreach (array_keys($this->cache->folder_index()) as $uid) {
$this->dav->delete($this->object_location($uid));
}
$this->cache->purge();
return true;
}
/**
* Restore a previously deleted object
*
* @param string $uid Object UID
*
* @return mixed Message UID on success, false on error
*/
public function undelete($uid)
{
if (!$this->valid) {
return false;
}
// TODO
return false;
}
/**
* Move a Kolab object message to another IMAP folder
*
* @param string Object UID
* @param string IMAP folder to move object to
*
* @return bool True on success, false on failure
*/
public function move($uid, $target_folder)
{
if (!$this->valid) {
return false;
}
// TODO
return false;
}
/**
* Save an object in this folder.
*
* @param array $object The array that holds the data of the object.
* @param string $type The type of the kolab object.
* @param string $uid The UID of the old object if it existed before
*
* @return mixed False on error or object UID on success
*/
public function save(&$object, $type = null, $uid = null)
{
if (!$this->valid || empty($object)) {
return false;
}
if (!$type) {
$type = $this->type;
}
/*
// copy attachments from old message
$copyfrom = $object['_copyfrom'] ?: $object['_msguid'];
if (!empty($copyfrom) && ($old = $this->cache->get($copyfrom, $type, $object['_mailbox']))) {
foreach ((array)$old['_attachments'] as $key => $att) {
if (!isset($object['_attachments'][$key])) {
$object['_attachments'][$key] = $old['_attachments'][$key];
}
// unset deleted attachment entries
if ($object['_attachments'][$key] == false) {
unset($object['_attachments'][$key]);
}
// load photo.attachment from old Kolab2 format to be directly embedded in xcard block
else if ($type == 'contact' && ($key == 'photo.attachment' || $key == 'kolab-picture.png') && $att['id']) {
if (!isset($object['photo']))
$object['photo'] = $this->get_attachment($copyfrom, $att['id'], $object['_mailbox']);
unset($object['_attachments'][$key]);
}
}
}
// process attachments
if (is_array($object['_attachments'])) {
$numatt = count($object['_attachments']);
foreach ($object['_attachments'] as $key => $attachment) {
// FIXME: kolab_storage and Roundcube attachment hooks use different fields!
if (empty($attachment['content']) && !empty($attachment['data'])) {
$attachment['content'] = $attachment['data'];
unset($attachment['data'], $object['_attachments'][$key]['data']);
}
// make sure size is set, so object saved in cache contains this info
if (!isset($attachment['size'])) {
if (!empty($attachment['content'])) {
if (is_resource($attachment['content'])) {
// this need to be a seekable resource, otherwise
// fstat() failes and we're unable to determine size
// here nor in rcube_imap_generic before IMAP APPEND
$stat = fstat($attachment['content']);
$attachment['size'] = $stat ? $stat['size'] : 0;
}
else {
$attachment['size'] = strlen($attachment['content']);
}
}
else if (!empty($attachment['path'])) {
$attachment['size'] = filesize($attachment['path']);
}
$object['_attachments'][$key] = $attachment;
}
// generate unique keys (used as content-id) for attachments
if (is_numeric($key) && $key < $numatt) {
// derrive content-id from attachment file name
$ext = preg_match('/(\.[a-z0-9]{1,6})$/i', $attachment['name'], $m) ? $m[1] : null;
$basename = preg_replace('/[^a-z0-9_.-]/i', '', basename($attachment['name'], $ext)); // to 7bit ascii
if (!$basename) $basename = 'noname';
$cid = $basename . '.' . microtime(true) . $key . $ext;
$object['_attachments'][$cid] = $attachment;
unset($object['_attachments'][$key]);
}
}
}
*/
$rcmail = rcube::get_instance();
$result = false;
// generate and save object message
if ($content = $this->to_dav($object)) {
$method = $uid ? 'update' : 'create';
$dav_type = $this->get_dav_type();
$result = $this->dav->{$method}($this->object_location($object['uid']), $content, $dav_type);
// Note: $result can be NULL if the request was successful, but ETag wasn't returned
if ($result !== false) {
// insert/update object in the cache
$object['etag'] = $result;
$object['_raw'] = $content;
$this->cache->save($object, $uid);
$result = true;
unset($object['_raw']);
}
}
return $result;
}
/**
* Fetch the object the DAV server and convert to internal format
*
* @param string The object UID to fetch
* @param string The object type expected (use wildcard '*' to accept all types)
* @param string Unused (kept for compat. with the parent class)
*
* @return mixed Hash array representing the Kolab object, a kolab_format instance or false if not found
*/
public function read_object($uid, $type = null, $folder = null)
{
if (!$this->valid) {
return false;
}
$href = $this->object_location($uid);
$objects = $this->dav->getData($this->href, $this->get_dav_type(), [$href]);
if (!is_array($objects) || count($objects) != 1) {
rcube::raise_error([
'code' => 900,
'message' => "Failed to fetch {$href}"
], true);
return false;
}
return $this->from_dav($objects[0]);
}
/**
* Fetch multiple objects from the DAV server and convert to internal format
*
* @param array The object UIDs to fetch
*
* @return mixed Hash array representing the Kolab objects
*/
public function read_objects($uids)
{
if (!$this->valid) {
return false;
}
if (empty($uids)) {
return [];
}
foreach ($uids as $uid) {
$hrefs[] = $this->object_location($uid);
}
$objects = $this->dav->getData($this->href, $this->get_dav_type(), $hrefs);
if (!is_array($objects)) {
rcube::raise_error([
'code' => 900,
'message' => "Failed to fetch {$href}"
], true);
return false;
}
$objects = array_map([$this, 'from_dav'], $objects);
foreach ($uids as $idx => $uid) {
foreach ($objects as $oidx => $object) {
if ($object && $object['uid'] == $uid) {
$uids[$idx] = $object;
unset($objects[$oidx]);
continue 2;
}
}
$uids[$idx] = false;
}
return $uids;
}
/**
* Convert DAV object into PHP array
*
* @param array Object data in kolab_dav_client::fetchData() format
*
* @return array Object properties
*/
public function from_dav($object)
{
if ($this->type == 'event') {
$ical = libcalendaring::get_ical();
$events = $ical->import($object['data']);
if (!count($events) || empty($events[0]['uid'])) {
return false;
}
$result = $events[0];
}
else if ($this->type == 'contact') {
if (stripos($object['data'], 'BEGIN:VCARD') !== 0) {
return false;
}
// vCard properties not supported by rcube_vcard
$map = [
'uid' => 'UID',
'kind' => 'KIND',
'member' => 'MEMBER',
'x-kind' => 'X-ADDRESSBOOKSERVER-KIND',
'x-member' => 'X-ADDRESSBOOKSERVER-MEMBER',
];
// TODO: We should probably use Sabre/Vobject to parse the vCard
$vcard = new rcube_vcard($object['data'], RCUBE_CHARSET, false, $map);
if (!empty($vcard->displayname) || !empty($vcard->surname) || !empty($vcard->firstname) || !empty($vcard->email)) {
$result = $vcard->get_assoc();
// Contact groups
if (!empty($result['x-kind']) && implode($result['x-kind']) == 'group') {
$result['_type'] = 'group';
$members = isset($result['x-member']) ? $result['x-member'] : [];
unset($result['x-kind'], $result['x-member']);
}
else if (!empty($result['kind']) && implode($result['kind']) == 'group') {
$result['_type'] = 'group';
$members = isset($result['member']) ? $result['member'] : [];
unset($result['kind'], $result['member']);
}
if (isset($members)) {
$result['member'] = [];
foreach ($members as $member) {
if (strpos($member, 'urn:uuid:') === 0) {
$result['member'][] = ['uid' => substr($member, 9)];
}
else if (strpos($member, 'mailto:') === 0) {
$member = reset(rcube_mime::decode_address_list(urldecode(substr($member, 7))));
if (!empty($member['mailto'])) {
$result['member'][] = ['email' => $member['mailto'], 'name' => $member['name']];
}
}
}
}
if (!empty($result['uid'])) {
$result['uid'] = preg_replace('/^urn:uuid:/', '', implode($result['uid']));
}
}
else {
return false;
}
}
$result['etag'] = $object['etag'];
$result['href'] = !empty($object['href']) ? $object['href'] : null;
$result['uid'] = !empty($object['uid']) ? $object['uid'] : $result['uid'];
return $result;
}
/**
* Convert Kolab object into DAV format (iCalendar)
*/
public function to_dav($object)
{
$result = '';
if ($this->type == 'event') {
$ical = libcalendaring::get_ical();
if (!empty($object['exceptions'])) {
$object['recurrence']['EXCEPTIONS'] = $object['exceptions'];
}
$result = $ical->export([$object]);
}
else if ($this->type == 'contact') {
// copy values into vcard object
// TODO: We should probably use Sabre/Vobject to create the vCard
// vCard properties not supported by rcube_vcard
$map = ['uid' => 'UID', 'kind' => 'KIND'];
$vcard = new rcube_vcard('', RCUBE_CHARSET, false, $map);
if ((!empty($object['_type']) && $object['_type'] == 'group')
|| (!empty($object['type']) && $object['type'] == 'group')
) {
$object['kind'] = 'group';
}
foreach ($object as $key => $values) {
list($field, $section) = rcube_utils::explode(':', $key);
// avoid casting DateTime objects to array
- if (is_object($values) && is_a($values, 'DateTime')) {
+ if (is_object($values) && $values instanceof DateTimeInterface) {
$values = [$values];
}
foreach ((array) $values as $value) {
if (isset($value)) {
$vcard->set($field, $value, $section);
}
}
}
$result = $vcard->export(false);
if (!empty($object['kind']) && $object['kind'] == 'group') {
$members = '';
foreach ((array) $object['member'] as $member) {
$value = null;
if (!empty($member['uid'])) {
$value = 'urn:uuid:' . $member['uid'];
}
else if (!empty($member['email']) && !empty($member['name'])) {
$value = 'mailto:' . urlencode(sprintf('"%s" <%s>', addcslashes($member['name'], '"'), $member['email']));
}
else if (!empty($member['email'])) {
$value = 'mailto:' . $member['email'];
}
if ($value) {
$members .= "MEMBER:{$value}\r\n";
}
}
if ($members) {
$result = preg_replace('/\r\nEND:VCARD/', "\r\n{$members}END:VCARD", $result);
}
/**
Version 4.0 of the vCard format requires Cyrus >= 3.6.0, we'll use Version 3.0 for now
$result = preg_replace('/\r\nVERSION:3\.0\r\n/', "\r\nVERSION:4.0\r\n", $result);
$result = preg_replace('/\r\nN:[^\r]+/', '', $result);
$result = preg_replace('/\r\nUID:([^\r]+)/', "\r\nUID:urn:uuid:\\1", $result);
*/
$result = preg_replace('/\r\nMEMBER:([^\r]+)/', "\r\nX-ADDRESSBOOKSERVER-MEMBER:\\1", $result);
$result = preg_replace('/\r\nKIND:([^\r]+)/', "\r\nX-ADDRESSBOOKSERVER-KIND:\\1", $result);
}
}
if ($result) {
// The content must be UTF-8, otherwise if we try to fetch the object
// from server XML parsing would fail.
$result = rcube_charset::clean($result);
}
return $result;
}
protected function object_location($uid)
{
return unslashify($this->href) . '/' . urlencode($uid) . '.' . $this->get_dav_ext();
}
/**
* Get a folder DAV content type
*/
public function get_dav_type()
{
return kolab_storage_dav::get_dav_type($this->type);
}
/**
* Get a DAV file extension for specified Kolab type
*/
public function get_dav_ext()
{
$types = [
'event' => 'ics',
'task' => 'ics',
'contact' => 'vcf',
];
return $types[$this->type];
}
/**
* Return folder name as string representation of this object
*
* @return string Folder display name
*/
public function __toString()
{
return $this->attributes['name'];
}
}
diff --git a/plugins/libkolab/lib/kolab_storage_folder.php b/plugins/libkolab/lib/kolab_storage_folder.php
index 194289de..4ef538b8 100644
--- a/plugins/libkolab/lib/kolab_storage_folder.php
+++ b/plugins/libkolab/lib/kolab_storage_folder.php
@@ -1,1168 +1,1171 @@
<?php
/**
* The kolab_storage_folder class represents an IMAP folder on the Kolab server.
*
* @version @package_version@
* @author Thomas Bruederli <bruederli@kolabsys.com>
* @author Aleksander Machniak <machniak@kolabsys.com>
*
* Copyright (C) 2012-2013, Kolab Systems AG <contact@kolabsys.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class kolab_storage_folder extends kolab_storage_folder_api
{
/**
* The kolab_storage_cache instance for caching operations
* @var object
*/
public $cache;
/**
* Indicate validity status
* @var boolean
*/
public $valid = false;
protected $error = 0;
protected $resource_uri;
/**
* Default constructor
*
* @param string The folder name/path
* @param string Expected folder type
* @param string Optional folder type if known
*/
function __construct($name, $type = null, $type_annotation = null)
{
parent::__construct($name);
$this->set_folder($name, $type, $type_annotation);
}
/**
* Set the IMAP folder this instance connects to
*
* @param string The folder name/path
* @param string Expected folder type
* @param string Optional folder type if known
*/
public function set_folder($name, $type = null, $type_annotation = null)
{
$this->name = $name;
if (empty($type_annotation)) {
$type_annotation = $this->get_type();
}
$oldtype = $this->type;
list($this->type, $suffix) = explode('.', $type_annotation);
$this->default = $suffix == 'default';
$this->subtype = $this->default ? '' : $suffix;
$this->id = kolab_storage::folder_id($name);
$this->valid = !empty($this->type) && $this->type != 'mail' && (!$type || $this->type == $type);
if (!$this->valid) {
$this->error = $this->imap->get_error_code() < 0 ? kolab_storage::ERROR_IMAP_CONN : kolab_storage::ERROR_INVALID_FOLDER;
}
// reset cached object properties
$this->owner = $this->namespace = $this->resource_uri = $this->info = $this->idata = null;
// get a new cache instance if folder type changed
if (!$this->cache || $this->type != $oldtype)
$this->cache = kolab_storage_cache::factory($this);
else
$this->cache->set_folder($this);
$this->imap->set_folder($this->name);
}
/**
* Returns code of last error
*
* @return int Error code
*/
public function get_error()
{
return $this->error ?: $this->cache->get_error();
}
/**
* Check IMAP connection error state
*/
public function check_error()
{
if (($err_code = $this->imap->get_error_code()) < 0) {
$this->error = kolab_storage::ERROR_IMAP_CONN;
if (($res_code = $this->imap->get_response_code()) !== 0 && in_array($res_code, array(rcube_storage::NOPERM, rcube_storage::READONLY))) {
$this->error = kolab_storage::ERROR_NO_PERMISSION;
}
}
return $this->error;
}
/**
* Compose a unique resource URI for this IMAP folder
*/
public function get_resource_uri()
{
if (!empty($this->resource_uri)) {
return $this->resource_uri;
}
// strip namespace prefix from folder name
$ns = $this->get_namespace();
$nsdata = $this->imap->get_namespace($ns);
if (is_array($nsdata[0]) && strlen($nsdata[0][0]) && strpos($this->name, $nsdata[0][0]) === 0) {
$subpath = substr($this->name, strlen($nsdata[0][0]));
if ($ns == 'other') {
list($user, $suffix) = explode($nsdata[0][1], $subpath, 2);
$subpath = $suffix;
}
}
else {
$subpath = $this->name;
}
// compose fully qualified ressource uri for this instance
$this->resource_uri = 'imap://' . urlencode($this->get_owner(true)) . '@' . $this->imap->options['host'] . '/' . $subpath;
return $this->resource_uri;
}
/**
* Helper method to extract folder UID metadata
*
* @return string Folder's UID
*/
public function get_uid()
{
// UID is defined in folder METADATA
$metakeys = array(kolab_storage::UID_KEY_SHARED, kolab_storage::UID_KEY_CYRUS);
$metadata = $this->get_metadata();
if ($metadata !== null) {
foreach ($metakeys as $key) {
if ($uid = $metadata[$key]) {
return $uid;
}
}
// generate a folder UID and set it to IMAP
$uid = rtrim(chunk_split(md5($this->name . $this->get_owner() . uniqid('-', true)), 12, '-'), '-');
if ($this->set_uid($uid)) {
return $uid;
}
}
$this->check_error();
// create hash from folder name if we can't write the UID metadata
return md5($this->name . $this->get_owner());
}
/**
* Helper method to set an UID value to the given IMAP folder instance
*
* @param string Folder's UID
* @return boolean True on succes, False on failure
*/
public function set_uid($uid)
{
$success = $this->set_metadata(array(kolab_storage::UID_KEY_SHARED => $uid));
$this->check_error();
return $success;
}
/**
* Compose a folder Etag identifier
*/
public function get_ctag()
{
$fdata = $this->get_imap_data();
$this->check_error();
return sprintf('%d-%d-%d', $fdata['UIDVALIDITY'], $fdata['HIGHESTMODSEQ'], $fdata['UIDNEXT']);
}
/**
* Check activation status of this folder
*
* @return boolean True if enabled, false if not
*/
public function is_active()
{
return kolab_storage::folder_is_active($this->name);
}
/**
* Change activation status of this folder
*
* @param boolean The desired subscription status: true = active, false = not active
*
* @return True on success, false on error
*/
public function activate($active)
{
return $active ? kolab_storage::folder_activate($this->name) : kolab_storage::folder_deactivate($this->name);
}
/**
* Check subscription status of this folder
*
* @return boolean True if subscribed, false if not
*/
public function is_subscribed()
{
return kolab_storage::folder_is_subscribed($this->name);
}
/**
* Change subscription status of this folder
*
* @param boolean The desired subscription status: true = subscribed, false = not subscribed
*
* @return True on success, false on error
*/
public function subscribe($subscribed)
{
return $subscribed ? kolab_storage::folder_subscribe($this->name) : kolab_storage::folder_unsubscribe($this->name);
}
/**
* Get number of objects stored in this folder
*
* @param mixed Pseudo-SQL query as list of filter parameter triplets
* or string with object type (e.g. contact, event, todo, journal, note, configuration)
*
* @return integer The number of objects of the given type
* @see self::select()
*/
public function count($query = null)
{
if (!$this->valid) {
return 0;
}
// synchronize cache first
$this->cache->synchronize();
return $this->cache->count($this->_prepare_query($query));
}
/**
* List Kolab objects matching the given query
*
* @param mixed Pseudo-SQL query as list of filter parameter triplets
* or string with object type (e.g. contact, event, todo, journal, note, configuration)
*
* @return array List of Kolab data objects (each represented as hash array)
* @deprecated Use select()
*/
public function get_objects($query = array())
{
return $this->select($query);
}
/**
* Select Kolab objects matching the given query
*
* @param mixed Pseudo-SQL query as list of filter parameter triplets
* or string with object type (e.g. contact, event, todo, journal, note, configuration)
* @param boolean Use fast mode to fetch only minimal set of information
* (no xml fetching and parsing, etc.)
*
* @return array List of Kolab data objects (each represented as hash array)
*/
public function select($query = array(), $fast = false)
{
if (!$this->valid) {
return array();
}
// synchronize caches
$this->cache->synchronize();
// fetch objects from cache
return $this->cache->select($this->_prepare_query($query), false, $fast);
}
/**
* Getter for object UIDs only
*
* @param array Pseudo-SQL query as list of filter parameter triplets
* @return array List of Kolab object UIDs
*/
public function get_uids($query = array())
{
if (!$this->valid) {
return array();
}
// synchronize caches
$this->cache->synchronize();
// fetch UIDs from cache
return $this->cache->select($this->_prepare_query($query), true);
}
/**
* Setter for ORDER BY and LIMIT parameters for cache queries
*
* @param array List of columns to order by
* @param integer Limit result set to this length
* @param integer Offset row
*/
public function set_order_and_limit($sortcols, $length = null, $offset = 0)
{
$this->cache->set_order_by($sortcols);
if ($length !== null) {
$this->cache->set_limit($length, $offset);
}
}
/**
* Helper method to sanitize query arguments
*/
private function _prepare_query($query)
{
// string equals type query
// FIXME: should not be called this way!
if (is_string($query)) {
return $this->cache->has_type_col() && !empty($query) ? array(array('type','=',$query)) : array();
}
foreach ((array)$query as $i => $param) {
if ($param[0] == 'type' && !$this->cache->has_type_col()) {
unset($query[$i]);
}
else if (($param[0] == 'dtstart' || $param[0] == 'dtend' || $param[0] == 'changed')) {
- if (is_object($param[2]) && is_a($param[2], 'DateTime'))
+ if (is_object($param[2]) && $param[2] instanceof DateTimeInterface) {
$param[2] = $param[2]->format('U');
- if (is_numeric($param[2]))
+ }
+ if (is_numeric($param[2])) {
$query[$i][2] = date('Y-m-d H:i:s', $param[2]);
+ }
}
}
return $query;
}
/**
* Getter for a single Kolab object identified by its UID
*
* @param string $uid Object UID
*
* @return array The Kolab object represented as hash array
*/
public function get_object($uid)
{
if (!$this->valid || !$uid) {
return false;
}
// synchronize caches
$this->cache->synchronize();
return $this->cache->get_by_uid($uid);
}
/**
* Fetch a Kolab object attachment which is stored in a separate part
* of the mail MIME message that represents the Kolab record.
*
* @param string Object's UID
* @param string The attachment's mime number
* @param string IMAP folder where message is stored;
* If set, that also implies that the given UID is an IMAP UID
* @param bool True to print the part content
* @param resource File pointer to save the message part
* @param boolean Disables charset conversion
*
* @return mixed The attachment content as binary string
*/
public function get_attachment($uid, $part, $mailbox = null, $print = false, $fp = null, $skip_charset_conv = false)
{
if ($this->valid && ($msguid = ($mailbox ? $uid : $this->cache->uid2msguid($uid)))) {
$this->imap->set_folder($mailbox ? $mailbox : $this->name);
if (substr($part, 0, 2) == 'i:') {
// attachment data is stored in XML
if ($object = $this->cache->get($msguid)) {
// load data from XML (attachment content is not stored in cache)
if ($object['_formatobj'] && isset($object['_size'])) {
$object['_attachments'] = array();
$object['_formatobj']->get_attachments($object);
}
foreach ($object['_attachments'] as $attach) {
if ($attach['id'] == $part) {
if ($print) echo $attach['content'];
else if ($fp) fwrite($fp, $attach['content']);
else return $attach['content'];
return true;
}
}
}
}
else {
// return message part from IMAP directly
// TODO: We could improve performance if we cache part's encoding
// without 3rd argument get_message_part() will request BODYSTRUCTURE from IMAP
return $this->imap->get_message_part($msguid, $part, null, $print, $fp, $skip_charset_conv);
}
}
return null;
}
/**
* Fetch the mime message from the storage server and extract
* the Kolab groupware object from it
*
* @param string The IMAP message UID to fetch
* @param string The object type expected (use wildcard '*' to accept all types)
* @param string The folder name where the message is stored
*
* @return mixed Hash array representing the Kolab object, a kolab_format instance or false if not found
*/
public function read_object($msguid, $type = null, $folder = null)
{
if (!$this->valid) {
return false;
}
if (!$type) $type = $this->type;
if (!$folder) $folder = $this->name;
$this->imap->set_folder($folder);
$this->cache->imap_mode(true);
$message = new rcube_message($msguid);
$this->cache->imap_mode(false);
// Message doesn't exist?
if (empty($message->headers)) {
return false;
}
// extract the X-Kolab-Type header from the XML attachment part if missing
if (empty($message->headers->others['x-kolab-type'])) {
foreach ((array)$message->attachments as $part) {
if (strpos($part->mimetype, kolab_format::KTYPE_PREFIX) === 0) {
$message->headers->others['x-kolab-type'] = $part->mimetype;
break;
}
}
}
// fix buggy messages stating the X-Kolab-Type header twice
else if (is_array($message->headers->others['x-kolab-type'])) {
$message->headers->others['x-kolab-type'] = reset($message->headers->others['x-kolab-type']);
}
// no object type header found: abort
if (empty($message->headers->others['x-kolab-type'])) {
rcube::raise_error(array(
'code' => 600,
'type' => 'php',
'file' => __FILE__,
'line' => __LINE__,
'message' => "No X-Kolab-Type information found in message $msguid ($this->name).",
), true);
return false;
}
$object_type = kolab_format::mime2object_type($message->headers->others['x-kolab-type']);
$content_type = kolab_format::KTYPE_PREFIX . $object_type;
// check object type header and abort on mismatch
if ($type != '*' && strpos($object_type, $type) !== 0 && !($object_type == 'distribution-list' && $type == 'contact')) {
return false;
}
$attachments = array();
// get XML part
foreach ((array)$message->attachments as $part) {
if (!$xml && ($part->mimetype == $content_type || preg_match('!application/([a-z.]+\+)?xml!i', $part->mimetype))) {
$xml = $message->get_part_body($part->mime_id, true);
}
else if ($part->filename || $part->content_id) {
$key = $part->content_id ? trim($part->content_id, '<>') : $part->filename;
$size = null;
// Use Content-Disposition 'size' as for the Kolab Format spec.
if (isset($part->d_parameters['size'])) {
$size = $part->d_parameters['size'];
}
// we can trust part size only if it's not encoded
else if ($part->encoding == 'binary' || $part->encoding == '7bit' || $part->encoding == '8bit') {
$size = $part->size;
}
$attachments[$key] = array(
'id' => $part->mime_id,
'name' => $part->filename,
'mimetype' => $part->mimetype,
'size' => $size,
);
}
}
if (!$xml) {
rcube::raise_error(array(
'code' => 600,
'type' => 'php',
'file' => __FILE__,
'line' => __LINE__,
'message' => "Could not find Kolab data part in message $msguid ($this->name).",
), true);
return false;
}
// check kolab format version
$format_version = $message->headers->others['x-kolab-mime-version'];
if (empty($format_version)) {
list($xmltype, $subtype) = explode('.', $object_type);
$xmlhead = substr($xml, 0, 512);
// detect old Kolab 2.0 format
if (strpos($xmlhead, '<' . $xmltype) !== false && strpos($xmlhead, 'xmlns=') === false)
$format_version = '2.0';
else
$format_version = '3.0'; // assume 3.0
}
// get Kolab format handler for the given type
$format = kolab_format::factory($object_type, $format_version);
if (is_a($format, 'PEAR_Error'))
return false;
// load Kolab object from XML part
$format->load($xml);
if ($format->is_valid()) {
$object = $format->to_array(array('_attachments' => $attachments));
$object['_type'] = $object_type;
$object['_msguid'] = $msguid;
$object['_mailbox'] = $this->name;
$object['_formatobj'] = $format;
$object['_size'] = strlen($xml);
return $object;
}
else {
// try to extract object UID from XML block
if (preg_match('!<uid>(.+)</uid>!Uims', $xml, $m))
$msgadd = " UID = " . trim(strip_tags($m[1]));
rcube::raise_error(array(
'code' => 600,
'type' => 'php',
'file' => __FILE__,
'line' => __LINE__,
'message' => "Could not parse Kolab object data in message $msguid ($this->name)." . $msgadd,
), true);
self::save_user_xml("$msguid.xml", $xml);
}
return false;
}
/**
* Save an object in this folder.
*
* @param array $object The array that holds the data of the object.
* @param string $type The type of the kolab object.
* @param string $uid The UID of the old object if it existed before
*
* @return mixed False on error or IMAP message UID on success
*/
public function save(&$object, $type = null, $uid = null)
{
if (!$this->valid || empty($object)) {
return false;
}
if (!$type)
$type = $this->type;
// copy attachments from old message
$copyfrom = $object['_copyfrom'] ?: $object['_msguid'];
if (!empty($copyfrom) && ($old = $this->cache->get($copyfrom, $type, $object['_mailbox']))) {
foreach ((array)$old['_attachments'] as $key => $att) {
if (!isset($object['_attachments'][$key])) {
$object['_attachments'][$key] = $old['_attachments'][$key];
}
// unset deleted attachment entries
if ($object['_attachments'][$key] == false) {
unset($object['_attachments'][$key]);
}
// load photo.attachment from old Kolab2 format to be directly embedded in xcard block
else if ($type == 'contact' && ($key == 'photo.attachment' || $key == 'kolab-picture.png') && $att['id']) {
if (!isset($object['photo']))
$object['photo'] = $this->get_attachment($copyfrom, $att['id'], $object['_mailbox']);
unset($object['_attachments'][$key]);
}
}
}
// save contact photo to attachment for Kolab2 format
if (kolab_storage::$version == '2.0' && $object['photo']) {
$attkey = 'kolab-picture.png'; // this file name is hard-coded in libkolab/kolabformatV2/contact.cpp
$object['_attachments'][$attkey] = array(
'mimetype'=> rcube_mime::image_content_type($object['photo']),
'content' => preg_match('![^a-z0-9/=+-]!i', $object['photo']) ? $object['photo'] : base64_decode($object['photo']),
);
}
// process attachments
if (is_array($object['_attachments'])) {
$numatt = count($object['_attachments']);
foreach ($object['_attachments'] as $key => $attachment) {
// FIXME: kolab_storage and Roundcube attachment hooks use different fields!
if (empty($attachment['content']) && !empty($attachment['data'])) {
$attachment['content'] = $attachment['data'];
unset($attachment['data'], $object['_attachments'][$key]['data']);
}
// make sure size is set, so object saved in cache contains this info
if (!isset($attachment['size'])) {
if (!empty($attachment['content'])) {
if (is_resource($attachment['content'])) {
// this need to be a seekable resource, otherwise
// fstat() failes and we're unable to determine size
// here nor in rcube_imap_generic before IMAP APPEND
$stat = fstat($attachment['content']);
$attachment['size'] = $stat ? $stat['size'] : 0;
}
else {
$attachment['size'] = strlen($attachment['content']);
}
}
else if (!empty($attachment['path'])) {
$attachment['size'] = filesize($attachment['path']);
}
$object['_attachments'][$key] = $attachment;
}
// generate unique keys (used as content-id) for attachments
if (is_numeric($key) && $key < $numatt) {
// derrive content-id from attachment file name
$ext = preg_match('/(\.[a-z0-9]{1,6})$/i', $attachment['name'], $m) ? $m[1] : null;
$basename = preg_replace('/[^a-z0-9_.-]/i', '', basename($attachment['name'], $ext)); // to 7bit ascii
if (!$basename) $basename = 'noname';
$cid = $basename . '.' . microtime(true) . $key . $ext;
$object['_attachments'][$cid] = $attachment;
unset($object['_attachments'][$key]);
}
}
}
// save recurrence exceptions as individual objects due to lack of support in Kolab v2 format
if (kolab_storage::$version == '2.0' && $object['recurrence']['EXCEPTIONS']) {
$this->save_recurrence_exceptions($object, $type);
}
// check IMAP BINARY extension support for 'file' objects
// allow configuration to workaround bug in Cyrus < 2.4.17
$rcmail = rcube::get_instance();
$binary = $type == 'file' && !$rcmail->config->get('kolab_binary_disable') && $this->imap->get_capability('BINARY');
// generate and save object message
if ($raw_msg = $this->build_message($object, $type, $binary, $body_file)) {
// resolve old msguid before saving
if ($uid && empty($object['_msguid']) && ($msguid = $this->cache->uid2msguid($uid))) {
$object['_msguid'] = $msguid;
$object['_mailbox'] = $this->name;
}
$result = $this->imap->save_message($this->name, $raw_msg, null, false, null, null, $binary);
// update cache with new UID
if ($result) {
$old_uid = $object['_msguid'];
$object['_msguid'] = $result;
$object['_mailbox'] = $this->name;
if ($old_uid) {
// delete old message
$this->cache->imap_mode(true);
$this->imap->delete_message($old_uid, $object['_mailbox']);
$this->cache->imap_mode(false);
}
// insert/update message in cache
$this->cache->save($result, $object, $old_uid);
}
// remove temp file
if ($body_file) {
@unlink($body_file);
}
}
return $result;
}
/**
* Save recurrence exceptions as individual objects.
* The Kolab v2 format doesn't allow us to save fully embedded exception objects.
*
* @param array Hash array with event properties
* @param string Object type
*/
private function save_recurrence_exceptions(&$object, $type = null)
{
if ($object['recurrence']['EXCEPTIONS']) {
- $exdates = array();
- foreach ((array)$object['recurrence']['EXDATE'] as $exdate) {
- $key = is_a($exdate, 'DateTime') ? $exdate->format('Y-m-d') : strval($exdate);
+ $exdates = [];
+ foreach ((array) $object['recurrence']['EXDATE'] as $exdate) {
+ $key = $exdate instanceof DateTimeInterface ? $exdate->format('Y-m-d') : strval($exdate);
$exdates[$key] = 1;
}
// save every exception as individual object
- foreach((array)$object['recurrence']['EXCEPTIONS'] as $exception) {
+ foreach ((array) $object['recurrence']['EXCEPTIONS'] as $exception) {
$exception['uid'] = self::recurrence_exception_uid($object['uid'], $exception['start']->format('Ymd'));
$exception['sequence'] = $object['sequence'] + 1;
if ($exception['thisandfuture']) {
$exception['recurrence'] = $object['recurrence'];
// adjust the recurrence duration of the exception
if ($object['recurrence']['COUNT']) {
$recurrence = new kolab_date_recurrence($object['_formatobj']);
if ($end = $recurrence->end()) {
unset($exception['recurrence']['COUNT']);
$exception['recurrence']['UNTIL'] = $end;
}
}
// set UNTIL date if we have a thisandfuture exception
$untildate = clone $exception['start'];
$untildate->sub(new DateInterval('P1D'));
$object['recurrence']['UNTIL'] = $untildate;
unset($object['recurrence']['COUNT']);
}
else {
if (!$exdates[$exception['start']->format('Y-m-d')])
$object['recurrence']['EXDATE'][] = clone $exception['start'];
unset($exception['recurrence']);
}
unset($exception['recurrence']['EXCEPTIONS'], $exception['_formatobj'], $exception['_msguid']);
$this->save($exception, $type, $exception['uid']);
}
unset($object['recurrence']['EXCEPTIONS']);
}
}
/**
* Generate an object UID with the given recurrence-ID in a way that it is
* unique (the original UID is not a substring) but still recoverable.
*/
private static function recurrence_exception_uid($uid, $recurrence_id)
{
$offset = -2;
return substr($uid, 0, $offset) . '-' . $recurrence_id . '-' . substr($uid, $offset);
}
/**
* Delete the specified object from this folder.
*
* @param mixed $object The Kolab object to delete or object UID
* @param boolean $expunge Should the folder be expunged?
*
* @return boolean True if successful, false on error
*/
public function delete($object, $expunge = true)
{
if (!$this->valid) {
return false;
}
$msguid = is_array($object) ? $object['_msguid'] : $this->cache->uid2msguid($object);
$success = false;
$this->cache->imap_mode(true);
if ($msguid && $expunge) {
$success = $this->imap->delete_message($msguid, $this->name);
}
else if ($msguid) {
$success = $this->imap->set_flag($msguid, 'DELETED', $this->name);
}
$this->cache->imap_mode(false);
if ($success) {
$this->cache->set($msguid, false);
}
return $success;
}
/**
*
*/
public function delete_all()
{
if (!$this->valid) {
return false;
}
$this->cache->purge();
$this->cache->imap_mode(true);
$result = $this->imap->clear_folder($this->name);
$this->cache->imap_mode(false);
return $result;
}
/**
* Restore a previously deleted object
*
* @param string Object UID
* @return mixed Message UID on success, false on error
*/
public function undelete($uid)
{
if (!$this->valid) {
return false;
}
if ($msguid = $this->cache->uid2msguid($uid, true)) {
$this->cache->imap_mode(true);
$result = $this->imap->set_flag($msguid, 'UNDELETED', $this->name);
$this->cache->imap_mode(false);
if ($result) {
return $msguid;
}
}
return false;
}
/**
* Move a Kolab object message to another IMAP folder
*
* @param string Object UID
* @param string IMAP folder to move object to
* @return boolean True on success, false on failure
*/
public function move($uid, $target_folder)
{
if (!$this->valid) {
return false;
}
if (is_string($target_folder))
$target_folder = kolab_storage::get_folder($target_folder);
if ($msguid = $this->cache->uid2msguid($uid)) {
$this->cache->imap_mode(true);
$result = $this->imap->move_message($msguid, $target_folder->name, $this->name);
$this->cache->imap_mode(false);
if ($result) {
$new_uid = ($copyuid = $this->imap->conn->data['COPYUID']) ? $copyuid[1] : null;
$this->cache->move($msguid, $uid, $target_folder, $new_uid);
return true;
}
else {
rcube::raise_error(array(
'code' => 600, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Failed to move message $msguid to $target_folder: " . $this->imap->get_error_str(),
), true);
}
}
return false;
}
/**
* Creates source of the configuration object message
*
* @param array $object The array that holds the data of the object.
* @param string $type The type of the kolab object.
* @param bool $binary Enables use of binary encoding of attachment(s)
* @param string $body_file Reference to filename of message body
*
* @return mixed Message as string or array with two elements
* (one for message file path, second for message headers)
*/
private function build_message(&$object, $type, $binary, &$body_file)
{
// load old object to preserve data we don't understand/process
if (is_object($object['_formatobj']))
$format = $object['_formatobj'];
else if ($object['_msguid'] && ($old = $this->cache->get($object['_msguid'], $type, $object['_mailbox'])))
$format = $old['_formatobj'];
// create new kolab_format instance
if (!$format)
$format = kolab_format::factory($type, kolab_storage::$version);
if (PEAR::isError($format))
return false;
$format->set($object);
$xml = $format->write(kolab_storage::$version);
$object['uid'] = $format->uid; // read UID from format
$object['_formatobj'] = $format;
if (empty($xml) || !$format->is_valid() || empty($object['uid'])) {
return false;
}
$mime = new Mail_mime("\r\n");
$rcmail = rcube::get_instance();
$headers = array();
$files = array();
$part_id = 1;
$encoding = $binary ? 'binary' : 'base64';
if ($user_email = $rcmail->get_user_email()) {
$headers['From'] = $user_email;
$headers['To'] = $user_email;
}
$headers['Date'] = date('r');
$headers['X-Kolab-Type'] = kolab_format::KTYPE_PREFIX . $type;
$headers['X-Kolab-Mime-Version'] = kolab_storage::$version;
$headers['Subject'] = $object['uid'];
// $headers['Message-ID'] = $rcmail->gen_message_id();
$headers['User-Agent'] = $rcmail->config->get('useragent');
// Check if we have enough memory to handle the message in it
// It's faster than using files, so we'll do this if we only can
if (!empty($object['_attachments']) && ($mem_limit = parse_bytes(ini_get('memory_limit'))) > 0) {
$memory = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
foreach ($object['_attachments'] as $attachment) {
$memory += $attachment['size'];
}
// 1.33 is for base64, we need at least 4x more memory than the message size
if ($memory * ($binary ? 1 : 1.33) * 4 > $mem_limit) {
$marker = '%%%~~~' . md5(microtime(true) . $memory) . '~~~%%%';
$is_file = true;
$temp_dir = unslashify($rcmail->config->get('temp_dir'));
$mime->setParam('delay_file_io', true);
}
}
$mime->headers($headers);
$mime->setTXTBody("This is a Kolab Groupware object. "
. "To view this object you will need an email client that understands the Kolab Groupware format. "
. "For a list of such email clients please visit http://www.kolab.org/\n\n");
$ctype = kolab_storage::$version == '2.0' ? $format->CTYPEv2 : $format->CTYPE;
// Convert new lines to \r\n, to wrokaround "NO Message contains bare newlines"
// when APPENDing from temp file
$xml = preg_replace('/\r?\n/', "\r\n", $xml);
$mime->addAttachment($xml, // file
$ctype, // content-type
'kolab.xml', // filename
false, // is_file
'8bit', // encoding
'attachment', // disposition
RCUBE_CHARSET // charset
);
$part_id++;
// save object attachments as separate parts
foreach ((array)$object['_attachments'] as $key => $att) {
if (empty($att['content']) && !empty($att['id'])) {
// @TODO: use IMAP CATENATE to skip attachment fetch+push operation
$msguid = $object['_copyfrom'] ?: ($object['_msguid'] ?: $object['uid']);
if ($is_file) {
$att['path'] = tempnam($temp_dir, 'rcmAttmnt');
if (($fp = fopen($att['path'], 'w')) && $this->get_attachment($msguid, $att['id'], $object['_mailbox'], false, $fp, true)) {
fclose($fp);
}
else {
return false;
}
}
else {
$att['content'] = $this->get_attachment($msguid, $att['id'], $object['_mailbox'], false, null, true);
}
}
$headers = array('Content-ID' => Mail_mimePart::encodeHeader('Content-ID', '<' . $key . '>', RCUBE_CHARSET, 'quoted-printable'));
$name = !empty($att['name']) ? $att['name'] : $key;
// To store binary files we can use faster method
// without writting full message content to a temporary file but
// directly to IMAP, see rcube_imap_generic::append().
// I.e. use file handles where possible
if (!empty($att['path'])) {
if ($is_file && $binary) {
$files[] = fopen($att['path'], 'r');
$mime->addAttachment($marker, $att['mimetype'], $name, false, $encoding, 'attachment', '', '', '', null, null, '', RCUBE_CHARSET, $headers);
}
else {
$mime->addAttachment($att['path'], $att['mimetype'], $name, true, $encoding, 'attachment', '', '', '', null, null, '', RCUBE_CHARSET, $headers);
}
}
else {
if (is_resource($att['content']) && $is_file && $binary) {
$files[] = $att['content'];
$mime->addAttachment($marker, $att['mimetype'], $name, false, $encoding, 'attachment', '', '', '', null, null, '', RCUBE_CHARSET, $headers);
}
else {
if (is_resource($att['content'])) {
@rewind($att['content']);
$att['content'] = stream_get_contents($att['content']);
}
$mime->addAttachment($att['content'], $att['mimetype'], $name, false, $encoding, 'attachment', '', '', '', null, null, '', RCUBE_CHARSET, $headers);
}
}
$object['_attachments'][$key]['id'] = ++$part_id;
}
if (!$is_file || !empty($files)) {
$message = $mime->getMessage();
}
// parse message and build message array with
// attachment file pointers in place of file markers
if (!empty($files)) {
$message = explode($marker, $message);
$tmp = array();
foreach ($message as $msg_part) {
$tmp[] = $msg_part;
if ($file = array_shift($files)) {
$tmp[] = $file;
}
}
$message = $tmp;
}
// write complete message body into temp file
else if ($is_file) {
// use common temp dir
$body_file = tempnam($temp_dir, 'rcmMsg');
if (PEAR::isError($mime_result = $mime->saveMessageBody($body_file))) {
rcube::raise_error(array('code' => 650, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Could not create message: ".$mime_result->getMessage()),
true, false);
return false;
}
$message = array(trim($mime->txtHeaders()) . "\r\n\r\n", fopen($body_file, 'r'));
}
return $message;
}
/**
* Triggers any required updates after changes within the
* folder. This is currently only required for handling free/busy
* information with Kolab.
*
* @return boolean|PEAR_Error True if successfull.
*/
public function trigger()
{
$owner = $this->get_owner();
$result = false;
switch($this->type) {
case 'event':
if ($this->get_namespace() == 'personal') {
$result = $this->trigger_url(
sprintf('%s/trigger/%s/%s.pfb',
kolab_storage::get_freebusy_server(),
urlencode($owner),
urlencode($this->imap->mod_folder($this->name))
),
$this->imap->options['user'],
$this->imap->options['password']
);
}
break;
default:
return true;
}
if ($result && is_object($result) && is_a($result, 'PEAR_Error')) {
- return PEAR::raiseError(sprintf("Failed triggering folder %s. Error was: %s",
- $this->name, $result->getMessage()));
+ return PEAR::raiseError(
+ sprintf("Failed triggering folder %s. Error was: %s", $this->name, $result->getMessage())
+ );
}
return $result;
}
/**
* Triggers a URL.
*
* @param string $url The URL to be triggered.
* @param string $auth_user Username to authenticate with
* @param string $auth_passwd Password for basic auth
* @return boolean|PEAR_Error True if successfull.
*/
private function trigger_url($url, $auth_user = null, $auth_passwd = null)
{
try {
$request = libkolab::http_request($url);
// set authentication credentials
if ($auth_user && $auth_passwd)
$request->setAuth($auth_user, $auth_passwd);
$result = $request->send();
// rcube::write_log('trigger', $result->getBody());
}
catch (Exception $e) {
return PEAR::raiseError($e->getMessage());
}
return true;
}
/**
* Log content to a file in per_user_loggin dir if configured
*/
private static function save_user_xml($filename, $content)
{
$rcmail = rcube::get_instance();
if ($rcmail->config->get('kolab_format_error_log')) {
$log_dir = $rcmail->config->get('log_dir', RCUBE_INSTALL_PATH . 'logs');
$user_name = $rcmail->get_user_name();
$log_dir = $log_dir . '/' . $user_name;
if (!empty($user_name) && is_writable($log_dir)) {
file_put_contents("$log_dir/$filename", $content);
}
}
}
}
diff --git a/plugins/tasklist/composer.json b/plugins/tasklist/composer.json
index f97bd7cf..0181c2af 100644
--- a/plugins/tasklist/composer.json
+++ b/plugins/tasklist/composer.json
@@ -1,38 +1,38 @@
{
"name": "kolab/tasklist",
"type": "roundcube-plugin",
"description": "Task management plugin",
"homepage": "https://git.kolab.org/diffusion/RPK/",
"license": "AGPLv3",
"version": "3.5.10",
"authors": [
{
"name": "Thomas Bruederli",
"email": "bruederli@kolabsys.com",
"role": "Lead"
},
{
"name": "Aleksander Machniak",
"email": "machniak@kolabsys.com",
"role": "Developer"
}
],
"repositories": [
{
"type": "composer",
"url": "https://plugins.roundcube.net"
}
],
"require": {
- "php": ">=5.3.0",
+ "php": ">=7.2.0",
"roundcube/plugin-installer": ">=0.1.3",
"kolab/libcalendaring": ">=3.4.0",
"kolab/libkolab": ">=3.4.0"
},
"extra": {
"roundcube": {
"min-version": "1.4.0",
"sql-dir": "drivers/database/SQL"
}
}
}
diff --git a/plugins/tasklist/drivers/kolab/tasklist_kolab_driver.php b/plugins/tasklist/drivers/kolab/tasklist_kolab_driver.php
index eac1bdf3..2a9cbc3e 100644
--- a/plugins/tasklist/drivers/kolab/tasklist_kolab_driver.php
+++ b/plugins/tasklist/drivers/kolab/tasklist_kolab_driver.php
@@ -1,1724 +1,1738 @@
<?php
/**
* Kolab Groupware driver for the Tasklist plugin
*
* @version @package_version@
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 2012-2015, Kolab Systems AG <contact@kolabsys.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class tasklist_kolab_driver extends tasklist_driver
{
// features supported by the backend
public $alarms = false;
public $attachments = true;
public $attendees = true;
public $undelete = false; // task undelete action
public $alarm_types = array('DISPLAY','AUDIO');
public $search_more_results;
private $rc;
private $plugin;
private $lists;
private $folders = array();
private $tasks = array();
private $tags = array();
private $bonnie_api = false;
/**
* Default constructor
*/
public function __construct($plugin)
{
$this->rc = $plugin->rc;
$this->plugin = $plugin;
if (kolab_storage::$version == '2.0') {
$this->alarm_absolute = false;
}
// tasklist use fully encoded identifiers
kolab_storage::$encode_ids = true;
// get configuration for the Bonnie API
$this->bonnie_api = libkolab::get_bonnie_api();
$this->plugin->register_action('folder-acl', array($this, 'folder_acl'));
}
/**
* Read available calendars for the current user and store them internally
*/
private function _read_lists($force = false)
{
// already read sources
if (isset($this->lists) && !$force) {
return $this->lists;
}
// get all folders that have type "task"
$folders = kolab_storage::sort_folders(kolab_storage::get_folders('task'));
$this->lists = $this->folders = array();
$delim = $this->rc->get_storage()->get_hierarchy_delimiter();
// find default folder
$default_index = 0;
foreach ($folders as $i => $folder) {
if ($folder->default && strpos($folder->name, $delim) === false)
$default_index = $i;
}
// put default folder (aka INBOX) on top of the list
if ($default_index > 0) {
$default_folder = $folders[$default_index];
unset($folders[$default_index]);
array_unshift($folders, $default_folder);
}
$prefs = $this->rc->config->get('kolab_tasklists', array());
foreach ($folders as $folder) {
$tasklist = $this->folder_props($folder, $prefs);
$this->lists[$tasklist['id']] = $tasklist;
$this->folders[$tasklist['id']] = $folder;
$this->folders[$folder->name] = $folder;
}
return $this->lists;
}
/**
* Derive list properties from the given kolab_storage_folder object
*/
protected function folder_props($folder, $prefs)
{
if ($folder->get_namespace() == 'personal') {
$norename = false;
$editable = true;
$rights = 'lrswikxtea';
$alarms = true;
}
else {
$alarms = false;
$rights = 'lr';
$editable = false;
if ($myrights = $folder->get_myrights()) {
$rights = $myrights;
if (strpos($rights, 't') !== false || strpos($rights, 'd') !== false)
$editable = strpos($rights, 'i') !== false;
}
$info = $folder->get_folder_info();
$norename = $readonly || $info['norename'] || $info['protected'];
}
$list_id = $folder->id; #kolab_storage::folder_id($folder->name);
$old_id = kolab_storage::folder_id($folder->name, false);
if (!isset($prefs[$list_id]['showalarms']) && isset($prefs[$old_id]['showalarms'])) {
$prefs[$list_id]['showalarms'] = $prefs[$old_id]['showalarms'];
}
return array(
'id' => $list_id,
'name' => $folder->get_name(),
'listname' => $folder->get_foldername(),
'editname' => $folder->get_foldername(),
'color' => $folder->get_color('0000CC'),
'showalarms' => isset($prefs[$list_id]['showalarms']) ? $prefs[$list_id]['showalarms'] : $alarms,
'editable' => $editable,
'rights' => $rights,
'norename' => $norename,
'active' => $folder->is_active(),
'owner' => $folder->get_owner(),
'parentfolder' => $folder->get_parent(),
'default' => $folder->default,
'virtual' => $folder->virtual,
'children' => true, // TODO: determine if that folder indeed has child folders
'subscribed' => (bool)$folder->is_subscribed(),
'removable' => !$folder->default,
'subtype' => $folder->subtype,
'group' => $folder->default ? 'default' : $folder->get_namespace(),
'class' => trim($folder->get_namespace() . ($folder->default ? ' default' : '')),
'caldavuid' => $folder->get_uid(),
'history' => !empty($this->bonnie_api),
);
}
/**
* Get a list of available task lists from this source
*
* @param integer Bitmask defining filter criterias.
* See FILTER_* constants for possible values.
*/
public function get_lists($filter = 0, &$tree = null)
{
$this->_read_lists();
// attempt to create a default list for this user
if (empty($this->lists) && !isset($this->search_more_results)) {
$prop = array('name' => 'Tasks', 'color' => '0000CC', 'default' => true);
if ($this->create_list($prop))
$this->_read_lists(true);
}
$folders = $this->filter_folders($filter);
// include virtual folders for a full folder tree
if (!is_null($tree)) {
$folders = kolab_storage::folder_hierarchy($folders, $tree);
}
$delim = $this->rc->get_storage()->get_hierarchy_delimiter();
$prefs = $this->rc->config->get('kolab_tasklists', array());
$lists = array();
foreach ($folders as $folder) {
$list_id = $folder->id; // kolab_storage::folder_id($folder->name);
$imap_path = explode($delim, $folder->name);
// find parent
do {
array_pop($imap_path);
$parent_id = kolab_storage::folder_id(join($delim, $imap_path));
}
while (count($imap_path) > 1 && !$this->folders[$parent_id]);
// restore "real" parent ID
if ($parent_id && !$this->folders[$parent_id]) {
$parent_id = kolab_storage::folder_id($folder->get_parent());
}
$fullname = $folder->get_name();
$listname = $folder->get_foldername();
// special handling for virtual folders
if ($folder instanceof kolab_storage_folder_user) {
$lists[$list_id] = array(
'id' => $list_id,
'name' => $fullname,
'listname' => $listname,
'title' => $folder->get_title(),
'virtual' => true,
'editable' => false,
'rights' => 'l',
'group' => 'other virtual',
'class' => 'user',
'parent' => $parent_id,
);
}
else if ($folder->virtual) {
$lists[$list_id] = array(
'id' => $list_id,
'name' => $fullname,
'listname' => $listname,
'virtual' => true,
'editable' => false,
'rights' => 'l',
'group' => $folder->get_namespace(),
'class' => 'folder',
'parent' => $parent_id,
);
}
else {
if (!$this->lists[$list_id]) {
$this->lists[$list_id] = $this->folder_props($folder, $prefs);
$this->folders[$list_id] = $folder;
}
$this->lists[$list_id]['parent'] = $parent_id;
$lists[$list_id] = $this->lists[$list_id];
}
}
return $lists;
}
/**
* Get list of folders according to specified filters
*
* @param integer Bitmask defining restrictions. See FILTER_* constants for possible values.
*
* @return array List of task folders
*/
protected function filter_folders($filter)
{
$this->_read_lists();
$folders = array();
foreach ($this->lists as $id => $list) {
if (!empty($this->folders[$id])) {
$folder = $this->folders[$id];
if ($folder->get_namespace() == 'personal') {
$folder->editable = true;
}
else if ($rights = $folder->get_myrights()) {
if (strpos($rights, 't') !== false || strpos($rights, 'd') !== false) {
$folder->editable = strpos($rights, 'i') !== false;
}
}
$folders[] = $folder;
}
}
$plugin = $this->rc->plugins->exec_hook('tasklist_list_filter', array(
'list' => $folders,
'filter' => $filter,
'tasklists' => $folders,
));
if ($plugin['abort'] || !$filter) {
return $plugin['tasklists'];
}
$personal = $filter & self::FILTER_PERSONAL;
$shared = $filter & self::FILTER_SHARED;
$tasklists = array();
foreach ($folders as $folder) {
if (($filter & self::FILTER_WRITEABLE) && !$folder->editable) {
continue;
}
/*
if (($filter & self::FILTER_INSERTABLE) && !$folder->insert) {
continue;
}
if (($filter & self::FILTER_ACTIVE) && !$folder->is_active()) {
continue;
}
if (($filter & self::FILTER_PRIVATE) && $folder->subtype != 'private') {
continue;
}
if (($filter & self::FILTER_CONFIDENTIAL) && $folder->subtype != 'confidential') {
continue;
}
*/
if ($personal || $shared) {
$ns = $folder->get_namespace();
if (!(($personal && $ns == 'personal') || ($shared && $ns == 'shared'))) {
continue;
}
}
$tasklists[$folder->id] = $folder;
}
return $tasklists;
}
/**
* Get the kolab_calendar instance for the given calendar ID
*
* @param string List identifier (encoded imap folder name)
* @return object kolab_storage_folder Object nor null if list doesn't exist
*/
protected function get_folder($id)
{
$this->_read_lists();
// create list and folder instance if necesary
if (!$this->lists[$id]) {
$folder = kolab_storage::get_folder(kolab_storage::id_decode($id));
if ($folder->type) {
$this->folders[$id] = $folder;
$this->lists[$id] = $this->folder_props($folder, $this->rc->config->get('kolab_tasklists', array()));
}
}
return $this->folders[$id];
}
/**
* Create a new list assigned to the current user
*
* @param array Hash array with list properties
* name: List name
* color: The color of the list
* showalarms: True if alarms are enabled
* @return mixed ID of the new list on success, False on error
*/
public function create_list(&$prop)
{
$prop['type'] = 'task' . ($prop['default'] ? '.default' : '');
$prop['active'] = true; // activate folder by default
$prop['subscribed'] = true;
$folder = kolab_storage::folder_update($prop);
if ($folder === false) {
$this->last_error = kolab_storage::$last_error;
return false;
}
// create ID
$id = kolab_storage::folder_id($folder);
$prefs['kolab_tasklists'] = $this->rc->config->get('kolab_tasklists', array());
if (isset($prop['showalarms']))
$prefs['kolab_tasklists'][$id]['showalarms'] = $prop['showalarms'] ? true : false;
if ($prefs['kolab_tasklists'][$id])
$this->rc->user->save_prefs($prefs);
// force page reload to properly render folder hierarchy
if (!empty($prop['parent'])) {
$prop['_reload'] = true;
}
else {
$folder = kolab_storage::get_folder($folder);
$prop += $this->folder_props($folder, array());
}
return $id;
}
/**
* Update properties of an existing tasklist
*
* @param array Hash array with list properties
* id: List Identifier
* name: List name
* color: The color of the list
* showalarms: True if alarms are enabled (if supported)
* @return boolean True on success, Fales on failure
*/
public function edit_list(&$prop)
{
if ($prop['id'] && ($folder = $this->get_folder($prop['id']))) {
$prop['oldname'] = $folder->name;
$prop['type'] = 'task';
$newfolder = kolab_storage::folder_update($prop);
if ($newfolder === false) {
$this->last_error = kolab_storage::$last_error;
return false;
}
// create ID
$id = kolab_storage::folder_id($newfolder);
// fallback to local prefs
$prefs['kolab_tasklists'] = $this->rc->config->get('kolab_tasklists', array());
unset($prefs['kolab_tasklists'][$prop['id']]);
if (isset($prop['showalarms']))
$prefs['kolab_tasklists'][$id]['showalarms'] = $prop['showalarms'] ? true : false;
if ($prefs['kolab_tasklists'][$id])
$this->rc->user->save_prefs($prefs);
// force page reload if folder name/hierarchy changed
if ($newfolder != $prop['oldname'])
$prop['_reload'] = true;
return $id;
}
return false;
}
/**
* Set active/subscribed state of a list
*
* @param array Hash array with list properties
* id: List Identifier
* active: True if list is active, false if not
* permanent: True if list is to be subscribed permanently
* @return boolean True on success, Fales on failure
*/
public function subscribe_list($prop)
{
if ($prop['id'] && ($folder = $this->get_folder($prop['id']))) {
$ret = false;
if (isset($prop['permanent']))
$ret |= $folder->subscribe(intval($prop['permanent']));
if (isset($prop['active']))
$ret |= $folder->activate(intval($prop['active']));
// apply to child folders, too
if ($prop['recursive']) {
foreach ((array)kolab_storage::list_folders($folder->name, '*', 'task') as $subfolder) {
if (isset($prop['permanent']))
($prop['permanent'] ? kolab_storage::folder_subscribe($subfolder) : kolab_storage::folder_unsubscribe($subfolder));
if (isset($prop['active']))
($prop['active'] ? kolab_storage::folder_activate($subfolder) : kolab_storage::folder_deactivate($subfolder));
}
}
return $ret;
}
return false;
}
/**
* Delete the given list with all its contents
*
* @param array Hash array with list properties
* id: list Identifier
* @return boolean True on success, Fales on failure
*/
public function delete_list($prop)
{
if ($prop['id'] && ($folder = $this->get_folder($prop['id']))) {
if (kolab_storage::folder_delete($folder->name)) {
return true;
}
$this->last_error = kolab_storage::$last_error;
}
return false;
}
/**
* Search for shared or otherwise not listed tasklists the user has access
*
* @param string Search string
* @param string Section/source to search
* @return array List of tasklists
*/
public function search_lists($query, $source)
{
if (!kolab_storage::setup()) {
return array();
}
$this->search_more_results = false;
$this->lists = $this->folders = array();
// find unsubscribed IMAP folders that have "event" type
if ($source == 'folders') {
foreach ((array)kolab_storage::search_folders('task', $query, array('other')) as $folder) {
$this->folders[$folder->id] = $folder;
$this->lists[$folder->id] = $this->folder_props($folder, array());
}
}
// search other user's namespace via LDAP
else if ($source == 'users') {
$limit = $this->rc->config->get('autocomplete_max', 15) * 2; // we have slightly more space, so display twice the number
foreach (kolab_storage::search_users($query, 0, array(), $limit * 10) as $user) {
$folders = array();
// search for tasks folders shared by this user
foreach (kolab_storage::list_user_folders($user, 'task', false) as $foldername) {
$folders[] = new kolab_storage_folder($foldername, 'task');
}
if (count($folders)) {
$userfolder = new kolab_storage_folder_user($user['kolabtargetfolder'], '', $user);
$this->folders[$userfolder->id] = $userfolder;
$this->lists[$userfolder->id] = $this->folder_props($userfolder, array());
foreach ($folders as $folder) {
$this->folders[$folder->id] = $folder;
$this->lists[$folder->id] = $this->folder_props($folder, array());
$count++;
}
}
if ($count >= $limit) {
$this->search_more_results = true;
break;
}
}
}
return $this->get_lists();
}
/**
* Get a list of tags to assign tasks to
*
* @return array List of tags
*/
public function get_tags()
{
$config = kolab_storage_config::get_instance();
$tags = $config->get_tags();
$backend_tags = array_map(function($v) { return $v['name']; }, $tags);
return array_values(array_unique(array_merge($this->tags, $backend_tags)));
}
/**
* Get number of tasks matching the given filter
*
* @param array List of lists to count tasks of
* @return array Hash array with counts grouped by status (all|flagged|completed|today|tomorrow|nodate)
*/
public function count_tasks($lists = null)
{
if (empty($lists)) {
$lists = $this->_read_lists();
$lists = array_keys($lists);
}
else if (is_string($lists)) {
$lists = explode(',', $lists);
}
$today_date = new DateTime('now', $this->plugin->timezone);
$today = $today_date->format('Y-m-d');
$tomorrow_date = new DateTime('now + 1 day', $this->plugin->timezone);
$tomorrow = $tomorrow_date->format('Y-m-d');
$counts = array('all' => 0, 'today' => 0, 'tomorrow' => 0, 'later' => 0, 'overdue' => 0);
foreach ($lists as $list_id) {
if (!$folder = $this->get_folder($list_id)) {
continue;
}
foreach ($folder->select(array(array('tags','!~','x-complete')), true) as $record) {
$rec = $this->_to_rcube_task($record, $list_id, false);
if ($this->is_complete($rec)) // don't count complete tasks
continue;
$counts['all']++;
if (empty($rec['date']))
$counts['later']++;
else if ($rec['date'] == $today)
$counts['today']++;
else if ($rec['date'] == $tomorrow)
$counts['tomorrow']++;
else if ($rec['date'] < $today)
$counts['overdue']++;
else if ($rec['date'] > $tomorrow)
$counts['later']++;
}
}
// avoid session race conditions that will loose temporary subscriptions
$this->plugin->rc->session->nowrite = true;
return $counts;
}
/**
* Get all task records matching the given filter
*
* @param array Hash array with filter criterias:
* - mask: Bitmask representing the filter selection (check against tasklist::FILTER_MASK_* constants)
* - from: Date range start as string (Y-m-d)
* - to: Date range end as string (Y-m-d)
* - search: Search query string
* - uid: Task UIDs
* @param array List of lists to get tasks from
* @return array List of tasks records matchin the criteria
*/
public function list_tasks($filter, $lists = null)
{
if (empty($lists)) {
$lists = $this->_read_lists();
$lists = array_keys($lists);
}
else if (is_string($lists)) {
$lists = explode(',', $lists);
}
$config = kolab_storage_config::get_instance();
$results = array();
// query Kolab storage
$query = array();
if ($filter['mask'] & tasklist::FILTER_MASK_COMPLETE)
$query[] = array('tags','~','x-complete');
else if (empty($filter['since']))
$query[] = array('tags','!~','x-complete');
// full text search (only works with cache enabled)
if ($filter['search']) {
$search = mb_strtolower($filter['search']);
foreach (rcube_utils::normalize_string($search, true) as $word) {
$query[] = array('words', '~', $word);
}
}
if ($filter['since']) {
$query[] = array('changed', '>=', $filter['since']);
}
if ($filter['uid']) {
$query[] = array('uid', '=', (array) $filter['uid']);
}
foreach ($lists as $list_id) {
if (!$folder = $this->get_folder($list_id)) {
continue;
}
foreach ($folder->select($query) as $record) {
// TODO: post-filter tasks returned from storage
$record['list_id'] = $list_id;
$results[] = $record;
}
}
$config->apply_tags($results, true);
$config->apply_links($results);
foreach (array_keys($results) as $idx) {
$results[$idx] = $this->_to_rcube_task($results[$idx], $results[$idx]['list_id']);
}
// avoid session race conditions that will loose temporary subscriptions
$this->plugin->rc->session->nowrite = true;
return $results;
}
/**
* Return data of a specific task
*
* @param mixed Hash array with task properties or task UID
* @param integer Bitmask defining filter criterias for folders.
* See FILTER_* constants for possible values.
*
* @return array Hash array with task properties or false if not found
*/
public function get_task($prop, $filter = 0)
{
$this->_parse_id($prop);
$id = $prop['uid'];
$list_id = $prop['list'];
$folders = $list_id ? array($list_id => $this->get_folder($list_id)) : $this->get_lists($filter);
// find task in the available folders
foreach ($folders as $list_id => $folder) {
if (is_array($folder))
$folder = $this->folders[$list_id];
if (is_numeric($list_id) || !$folder)
continue;
if (!$this->tasks[$id] && ($object = $folder->get_object($id))) {
$this->load_tags($object);
$this->tasks[$id] = $this->_to_rcube_task($object, $list_id);
break;
}
}
return $this->tasks[$id];
}
/**
* Get all decendents of the given task record
*
* @param mixed Hash array with task properties or task UID
* @param boolean True if all childrens children should be fetched
* @return array List of all child task IDs
*/
public function get_childs($prop, $recursive = false)
{
if (is_string($prop)) {
$task = $this->get_task($prop);
$prop = array('uid' => $task['uid'], 'list' => $task['list']);
}
else {
$this->_parse_id($prop);
}
$childs = array();
$list_id = $prop['list'];
$task_ids = array($prop['uid']);
$folder = $this->get_folder($list_id);
// query for childs (recursively)
while ($folder && !empty($task_ids)) {
$query_ids = array();
foreach ($task_ids as $task_id) {
$query = array(array('tags','=','x-parent:' . $task_id));
foreach ($folder->select($query) as $record) {
// don't rely on kolab_storage_folder filtering
if ($record['parent_id'] == $task_id) {
$childs[] = $list_id . ':' . $record['uid'];
$query_ids[] = $record['uid'];
}
}
}
if (!$recursive)
break;
$task_ids = $query_ids;
}
return $childs;
}
/**
* Provide a list of revisions for the given task
*
* @param array $task Hash array with task properties
* @return array List of changes, each as a hash array
* @see tasklist_driver::get_task_changelog()
*/
public function get_task_changelog($prop)
{
if (empty($this->bonnie_api)) {
return false;
}
list($uid, $mailbox, $msguid) = $this->_resolve_task_identity($prop);
$result = $uid && $mailbox ? $this->bonnie_api->changelog('task', $uid, $mailbox, $msguid) : null;
if (is_array($result) && $result['uid'] == $uid) {
return $result['changes'];
}
return false;
}
/**
* Return full data of a specific revision of an event
*
* @param mixed $task UID string or hash array with task properties
* @param mixed $rev Revision number
*
* @return array Task object as hash array
* @see tasklist_driver::get_task_revision()
*/
public function get_task_revison($prop, $rev)
{
if (empty($this->bonnie_api)) {
return false;
}
$this->_parse_id($prop);
$uid = $prop['uid'];
$list_id = $prop['list'];
list($uid, $mailbox, $msguid) = $this->_resolve_task_identity($prop);
// call Bonnie API
$result = $this->bonnie_api->get('task', $uid, $rev, $mailbox, $msguid);
if (is_array($result) && $result['uid'] == $uid && !empty($result['xml'])) {
$format = kolab_format::factory('task');
$format->load($result['xml']);
$rec = $format->to_array();
$format->get_attachments($rec, true);
if ($format->is_valid()) {
$rec = self::_to_rcube_task($rec, $list_id, false);
$rec['rev'] = $result['rev'];
return $rec;
}
}
return false;
}
/**
* Command the backend to restore a certain revision of a task.
* This shall replace the current object with an older version.
*
* @param mixed $task UID string or hash array with task properties
* @param mixed $rev Revision number
*
* @return boolean True on success, False on failure
* @see tasklist_driver::restore_task_revision()
*/
public function restore_task_revision($prop, $rev)
{
if (empty($this->bonnie_api)) {
return false;
}
$this->_parse_id($prop);
$uid = $prop['uid'];
$list_id = $prop['list'];
list($uid, $mailbox, $msguid) = $this->_resolve_task_identity($prop);
$folder = $this->get_folder($list_id);
$success = false;
if ($folder && ($raw_msg = $this->bonnie_api->rawdata('task', $uid, $rev, $mailbox))) {
$imap = $this->rc->get_storage();
// insert $raw_msg as new message
if ($imap->save_message($folder->name, $raw_msg, null, false)) {
$success = true;
// delete old revision from imap and cache
$imap->delete_message($msguid, $folder->name);
$folder->cache->set($msguid, false);
}
}
return $success;
}
/**
* Get a list of property changes beteen two revisions of a task object
*
* @param array $task Hash array with task properties
* @param mixed $rev Revisions: "from:to"
*
* @return array List of property changes, each as a hash array
* @see tasklist_driver::get_task_diff()
*/
public function get_task_diff($prop, $rev1, $rev2)
{
$this->_parse_id($prop);
$uid = $prop['uid'];
$list_id = $prop['list'];
list($uid, $mailbox, $msguid) = $this->_resolve_task_identity($prop);
// call Bonnie API
$result = $this->bonnie_api->diff('task', $uid, $rev1, $rev2, $mailbox, $msguid, $instance_id);
if (is_array($result) && $result['uid'] == $uid) {
$result['rev1'] = $rev1;
$result['rev2'] = $rev2;
$keymap = array(
'start' => 'start',
'due' => 'date',
'dstamp' => 'changed',
'summary' => 'title',
'alarm' => 'alarms',
'attendee' => 'attendees',
'attach' => 'attachments',
'rrule' => 'recurrence',
'related-to' => 'parent_id',
'percent-complete' => 'complete',
'lastmodified-date' => 'changed',
);
$prop_keymaps = array(
'attachments' => array('fmttype' => 'mimetype', 'label' => 'name'),
'attendees' => array('partstat' => 'status'),
);
$special_changes = array();
// map kolab event properties to keys the client expects
array_walk($result['changes'], function(&$change, $i) use ($keymap, $prop_keymaps, $special_changes) {
if (array_key_exists($change['property'], $keymap)) {
$change['property'] = $keymap[$change['property']];
}
if ($change['property'] == 'priority') {
$change['property'] = 'flagged';
$change['old'] = $change['old'] == 1 ? $this->plugin->gettext('yes') : null;
$change['new'] = $change['new'] == 1 ? $this->plugin->gettext('yes') : null;
}
// map alarms trigger value
if ($change['property'] == 'alarms') {
if (is_array($change['old']) && is_array($change['old']['trigger']))
$change['old']['trigger'] = $change['old']['trigger']['value'];
if (is_array($change['new']) && is_array($change['new']['trigger']))
$change['new']['trigger'] = $change['new']['trigger']['value'];
}
// make all property keys uppercase
if ($change['property'] == 'recurrence') {
$special_changes['recurrence'] = $i;
foreach (array('old','new') as $m) {
if (is_array($change[$m])) {
$props = array();
foreach ($change[$m] as $k => $v) {
$props[strtoupper($k)] = $v;
}
$change[$m] = $props;
}
}
}
// map property keys names
if (is_array($prop_keymaps[$change['property']])) {
foreach ($prop_keymaps[$change['property']] as $k => $dest) {
if (is_array($change['old']) && array_key_exists($k, $change['old'])) {
$change['old'][$dest] = $change['old'][$k];
unset($change['old'][$k]);
}
if (is_array($change['new']) && array_key_exists($k, $change['new'])) {
$change['new'][$dest] = $change['new'][$k];
unset($change['new'][$k]);
}
}
}
if ($change['property'] == 'exdate') {
$special_changes['exdate'] = $i;
}
else if ($change['property'] == 'rdate') {
$special_changes['rdate'] = $i;
}
});
// merge some recurrence changes
foreach (array('exdate','rdate') as $prop) {
if (array_key_exists($prop, $special_changes)) {
$exdate = $result['changes'][$special_changes[$prop]];
if (array_key_exists('recurrence', $special_changes)) {
$recurrence = &$result['changes'][$special_changes['recurrence']];
}
else {
$i = count($result['changes']);
$result['changes'][$i] = array('property' => 'recurrence', 'old' => array(), 'new' => array());
$recurrence = &$result['changes'][$i]['recurrence'];
}
$key = strtoupper($prop);
$recurrence['old'][$key] = $exdate['old'];
$recurrence['new'][$key] = $exdate['new'];
unset($result['changes'][$special_changes[$prop]]);
}
}
return $result;
}
return false;
}
/**
* Helper method to resolved the given task identifier into uid and folder
*
* @return array (uid,folder,msguid) tuple
*/
private function _resolve_task_identity($prop)
{
$mailbox = $msguid = null;
$this->_parse_id($prop);
$uid = $prop['uid'];
$list_id = $prop['list'];
if ($folder = $this->get_folder($list_id)) {
$mailbox = $folder->get_mailbox_id();
// get task object from storage in order to get the real object uid an msguid
if ($rec = $folder->get_object($uid)) {
$msguid = $rec['_msguid'];
$uid = $rec['uid'];
}
}
return array($uid, $mailbox, $msguid);
}
/**
* Get a list of pending alarms to be displayed to the user
*
* @param integer Current time (unix timestamp)
* @param mixed List of list IDs to show alarms for (either as array or comma-separated string)
* @return array A list of alarms, each encoded as hash array with task properties
* @see tasklist_driver::pending_alarms()
*/
public function pending_alarms($time, $lists = null)
{
$interval = 300;
$time -= $time % 60;
$slot = $time;
$slot -= $slot % $interval;
$last = $time - max(60, $this->rc->config->get('refresh_interval', 0));
$last -= $last % $interval;
// only check for alerts once in 5 minutes
if ($last == $slot)
return array();
if ($lists && is_string($lists))
$lists = explode(',', $lists);
$time = $slot + $interval;
$candidates = array();
$query = array(
array('tags', '=', 'x-has-alarms'),
array('tags', '!=', 'x-complete')
);
$this->_read_lists();
foreach ($this->lists as $lid => $list) {
// skip lists with alarms disabled
if (!$list['showalarms'] || ($lists && !in_array($lid, $lists)))
continue;
$folder = $this->get_folder($lid);
foreach ($folder->select($query) as $record) {
if (!($record['valarms'] || $record['alarms']) || $record['status'] == 'COMPLETED' || $record['complete'] == 100) // don't trust query :-)
continue;
$task = $this->_to_rcube_task($record, $lid, false);
// add to list if alarm is set
$alarm = libcalendaring::get_next_alarm($task, 'task');
if ($alarm && $alarm['time'] && $alarm['time'] <= $time && in_array($alarm['action'], $this->alarm_types)) {
$id = $alarm['id']; // use alarm-id as primary identifier
$candidates[$id] = array(
'id' => $id,
'title' => $task['title'],
'date' => $task['date'],
'time' => $task['time'],
'notifyat' => $alarm['time'],
'action' => $alarm['action'],
);
}
}
}
// get alarm information stored in local database
if (!empty($candidates)) {
$alarm_ids = array_map(array($this->rc->db, 'quote'), array_keys($candidates));
$result = $this->rc->db->query("SELECT *"
. " FROM " . $this->rc->db->table_name('kolab_alarms', true)
. " WHERE `alarm_id` IN (" . join(',', $alarm_ids) . ")"
. " AND `user_id` = ?",
$this->rc->user->ID
);
while ($result && ($rec = $this->rc->db->fetch_assoc($result))) {
$dbdata[$rec['alarm_id']] = $rec;
}
}
$alarms = array();
foreach ($candidates as $id => $task) {
// skip dismissed
if ($dbdata[$id]['dismissed'])
continue;
// snooze function may have shifted alarm time
$notifyat = $dbdata[$id]['notifyat'] ? strtotime($dbdata[$id]['notifyat']) : $task['notifyat'];
if ($notifyat <= $time)
$alarms[] = $task;
}
return $alarms;
}
/**
* (User) feedback after showing an alarm notification
* This should mark the alarm as 'shown' or snooze it for the given amount of time
*
* @param string Task identifier
* @param integer Suspend the alarm for this number of seconds
*/
public function dismiss_alarm($id, $snooze = 0)
{
// delete old alarm entry
$this->rc->db->query(
"DELETE FROM " . $this->rc->db->table_name('kolab_alarms', true) . "
WHERE `alarm_id` = ? AND `user_id` = ?",
$id,
$this->rc->user->ID
);
// set new notifyat time or unset if not snoozed
$notifyat = $snooze > 0 ? date('Y-m-d H:i:s', time() + $snooze) : null;
$query = $this->rc->db->query(
"INSERT INTO " . $this->rc->db->table_name('kolab_alarms', true) . "
(`alarm_id`, `user_id`, `dismissed`, `notifyat`)
VALUES (?, ?, ?, ?)",
$id,
$this->rc->user->ID,
$snooze > 0 ? 0 : 1,
$notifyat
);
return $this->rc->db->affected_rows($query);
}
/**
* Remove alarm dismissal or snooze state
*
* @param string Task identifier
*/
public function clear_alarms($id)
{
// delete alarm entry
$this->rc->db->query(
"DELETE FROM " . $this->rc->db->table_name('kolab_alarms', true) . "
WHERE `alarm_id` = ? AND `user_id` = ?",
$id,
$this->rc->user->ID
);
return true;
}
/**
* Get task tags
*/
private function load_tags(&$object)
{
// this task hasn't been migrated yet
if (!empty($object['categories'])) {
// OPTIONAL: call kolab_storage_config::apply_tags() to migrate the object
$object['tags'] = (array)$object['categories'];
if (!empty($object['tags'])) {
$this->tags = array_merge($this->tags, $object['tags']);
}
}
else {
$config = kolab_storage_config::get_instance();
$tags = $config->get_tags($object['uid']);
$object['tags'] = array_map(function($v) { return $v['name']; }, $tags);
}
}
/**
* Update task tags
*/
private function save_tags($uid, $tags)
{
$config = kolab_storage_config::get_instance();
$config->save_tags($uid, $tags);
}
/**
* Find messages linked with a task record
*/
private function get_links($uid)
{
$config = kolab_storage_config::get_instance();
return $config->get_object_links($uid);
}
/**
*
*/
private function save_links($uid, $links)
{
$config = kolab_storage_config::get_instance();
return $config->save_object_links($uid, (array) $links);
}
/**
* Extract uid + list identifiers from the given input
*
* @param mixed array or string with task identifier(s)
*/
private function _parse_id(&$prop)
{
$id_ = null;
if (is_array($prop)) {
// 'uid' + 'list' available, nothing to be done
if (!empty($prop['uid']) && !empty($prop['list'])) {
return;
}
// 'id' is given
if (!empty($prop['id'])) {
if (!empty($prop['list'])) {
$list_id = $prop['_fromlist'] ?: $prop['list'];
if (strpos($prop['id'], $list_id.':') === 0) {
$prop['uid'] = substr($prop['id'], strlen($list_id)+1);
}
else {
$prop['uid'] = $prop['id'];
}
}
else {
$id_ = $prop['id'];
}
}
}
else {
$id_ = strval($prop);
$prop = array();
}
// split 'id' into list + uid
if (!empty($id_)) {
list($list, $uid) = explode(':', $id_, 2);
if (!empty($uid)) {
$prop['uid'] = $uid;
$prop['list'] = $list;
}
else {
$prop['uid'] = $id_;
}
}
}
/**
* Convert from Kolab_Format to internal representation
*/
private function _to_rcube_task($record, $list_id, $all = true)
{
$id_prefix = $list_id . ':';
$task = array(
'id' => $id_prefix . $record['uid'],
'uid' => $record['uid'],
'title' => $record['title'],
// 'location' => $record['location'],
'description' => $record['description'],
'flagged' => $record['priority'] == 1,
'complete' => floatval($record['complete'] / 100),
'status' => $record['status'],
'parent_id' => $record['parent_id'] ? $id_prefix . $record['parent_id'] : null,
'recurrence' => $record['recurrence'],
'attendees' => $record['attendees'],
'organizer' => $record['organizer'],
'sequence' => $record['sequence'],
'tags' => $record['tags'],
'list' => $list_id,
'links' => $record['links'],
);
// we can sometimes skip this expensive operation
if ($all && !array_key_exists('links', $task)) {
$task['links'] = $this->get_links($task['uid']);
}
// convert from DateTime to internal date format
- if (is_a($record['due'], 'DateTime')) {
+ if ($record['due'] instanceof DateTimeInterface) {
$due = $this->plugin->lib->adjust_timezone($record['due']);
$task['date'] = $due->format('Y-m-d');
- if (!$record['due']->_dateonly)
+ if (empty($record['due']->_dateonly)) {
$task['time'] = $due->format('H:i');
+ }
}
// convert from DateTime to internal date format
- if (is_a($record['start'], 'DateTime')) {
+ if ($record['start'] instanceof DateTimeInterface) {
$start = $this->plugin->lib->adjust_timezone($record['start']);
$task['startdate'] = $start->format('Y-m-d');
- if (!$record['start']->_dateonly)
+ if (empty($record['start']->_dateonly)) {
$task['starttime'] = $start->format('H:i');
+ }
}
- if (is_a($record['changed'], 'DateTime')) {
+ if ($record['changed'] instanceof DateTimeInterface) {
$task['changed'] = $record['changed'];
}
- if (is_a($record['created'], 'DateTime')) {
+ if ($record['created'] instanceof DateTimeInterface) {
$task['created'] = $record['created'];
}
if ($record['valarms']) {
$task['valarms'] = $record['valarms'];
}
else if ($record['alarms']) {
$task['alarms'] = $record['alarms'];
}
if (!empty($task['attendees'])) {
foreach ((array)$task['attendees'] as $i => $attendee) {
- if (is_array($attendee['delegated-from'])) {
+ if (isset($attendee['delegated-from']) && is_array($attendee['delegated-from'])) {
$task['attendees'][$i]['delegated-from'] = join(', ', $attendee['delegated-from']);
}
- if (is_array($attendee['delegated-to'])) {
+ if (isset($attendee['delegated-to']) && is_array($attendee['delegated-to'])) {
$task['attendees'][$i]['delegated-to'] = join(', ', $attendee['delegated-to']);
}
}
}
if (!empty($record['_attachments'])) {
foreach ($record['_attachments'] as $key => $attachment) {
if ($attachment !== false) {
- if (!$attachment['name'])
+ if (empty($attachment['name'])) {
$attachment['name'] = $key;
+ }
$attachments[] = $attachment;
}
}
$task['attachments'] = $attachments;
}
return $task;
}
/**
* Convert the given task record into a data structure that can be passed to kolab_storage backend for saving
* (opposite of self::_to_rcube_event())
*/
- private function _from_rcube_task($task, $old = array())
+ private function _from_rcube_task($task, $old = [])
{
$object = $task;
$id_prefix = $task['list'] . ':';
+ $toDT = function($date) {
+ // Convert DateTime into libcalendaring_datetime
+ return libcalendaring_datetime::createFromFormat(
+ 'Y-m-d\\TH:i:s',
+ $date->format('Y-m-d\\TH:i:s'),
+ $date->getTimezone()
+ );
+ };
+
if (!empty($task['date'])) {
- $object['due'] = rcube_utils::anytodatetime($task['date'].' '.$task['time'], $this->plugin->timezone);
- if (empty($task['time']))
+ $object['due'] = $toDT(rcube_utils::anytodatetime($task['date'].' '.$task['time'], $this->plugin->timezone));
+ if (empty($task['time'])) {
$object['due']->_dateonly = true;
+ }
unset($object['date']);
}
if (!empty($task['startdate'])) {
- $object['start'] = rcube_utils::anytodatetime($task['startdate'].' '.$task['starttime'], $this->plugin->timezone);
- if (empty($task['starttime']))
+ $object['start'] = $toDT(rcube_utils::anytodatetime($task['startdate'].' '.$task['starttime'], $this->plugin->timezone));
+ if (empty($task['starttime'])) {
$object['start']->_dateonly = true;
+ }
unset($object['startdate']);
}
// as per RFC (and the Kolab schema validation), start and due dates need to be of the same type (#3614)
// this should be catched in the client already but just make sure we don't write invalid objects
if (!empty($object['start']) && !empty($object['due']) && $object['due']->_dateonly != $object['start']->_dateonly) {
$object['start']->_dateonly = true;
$object['due']->_dateonly = true;
}
$object['complete'] = $task['complete'] * 100;
if ($task['complete'] == 1.0 && empty($task['complete']))
$object['status'] = 'COMPLETED';
if ($task['flagged'])
$object['priority'] = 1;
else
$object['priority'] = $old['priority'] > 1 ? $old['priority'] : 0;
// remove list: prefix from parent_id
if (!empty($task['parent_id']) && strpos($task['parent_id'], $id_prefix) === 0) {
$object['parent_id'] = substr($task['parent_id'], strlen($id_prefix));
}
// copy meta data (starting with _) from old object
foreach ((array)$old as $key => $val) {
if (!isset($object[$key]) && $key[0] == '_')
$object[$key] = $val;
}
// copy recurrence rules if the client didn't submit it (#2713)
if (!array_key_exists('recurrence', $object) && $old['recurrence']) {
$object['recurrence'] = $old['recurrence'];
}
unset($task['attachments']);
kolab_format::merge_attachments($object, $old);
// allow sequence increments if I'm the organizer
if ($this->plugin->is_organizer($object) && empty($object['_method'])) {
unset($object['sequence']);
}
else if (isset($old['sequence']) && empty($object['_method'])) {
$object['sequence'] = $old['sequence'];
}
unset($object['tempid'], $object['raw'], $object['list'], $object['flagged'], $object['tags'], $object['created']);
return $object;
}
/**
* Add a single task to the database
*
* @param array Hash array with task properties (see header of tasklist_driver.php)
* @return mixed New task ID on success, False on error
*/
public function create_task($task)
{
return $this->edit_task($task);
}
/**
* Update an task entry with the given data
*
* @param array Hash array with task properties (see header of tasklist_driver.php)
* @return boolean True on success, False on error
*/
public function edit_task($task)
{
$this->_parse_id($task);
$list_id = $task['list'];
if (!$list_id || !($folder = $this->get_folder($list_id))) {
rcube::raise_error(array(
'code' => 600, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Invalid list identifer to save task: " . print_r($list_id, true)),
true, false);
return false;
}
// email links and tags are stored separately
$links = $task['links'];
$tags = $task['tags'];
unset($task['tags'], $task['links']);
// moved from another folder
if ($task['_fromlist'] && ($fromfolder = $this->get_folder($task['_fromlist']))) {
if (!$fromfolder->move($task['uid'], $folder))
return false;
unset($task['_fromlist']);
}
// load previous version of this task to merge
if ($task['id']) {
$old = $folder->get_object($task['uid']);
if (!$old || PEAR::isError($old))
return false;
// merge existing properties if the update isn't complete
if (!isset($task['title']) || !isset($task['complete']))
$task += $this->_to_rcube_task($old, $list_id);
}
// generate new task object from RC input
$object = $this->_from_rcube_task($task, $old);
$saved = $folder->save($object, 'task', $task['uid']);
if (!$saved) {
rcube::raise_error(array(
'code' => 600, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Error saving task object to Kolab server"),
true, false);
$saved = false;
}
else {
// save links in configuration.relation object
$this->save_links($object['uid'], $links);
// save tags in configuration.relation object
$this->save_tags($object['uid'], $tags);
$task = $this->_to_rcube_task($object, $list_id);
$task['tags'] = (array) $tags;
$this->tasks[$task['uid']] = $task;
}
return $saved;
}
/**
* Move a single task to another list
*
* @param array Hash array with task properties:
* @return boolean True on success, False on error
* @see tasklist_driver::move_task()
*/
public function move_task($task)
{
$this->_parse_id($task);
$list_id = $task['list'];
if (!$list_id || !($folder = $this->get_folder($list_id)))
return false;
// execute move command
if ($task['_fromlist'] && ($fromfolder = $this->get_folder($task['_fromlist']))) {
return $fromfolder->move($task['uid'], $folder);
}
return false;
}
/**
* Remove a single task from the database
*
* @param array Hash array with task properties:
* id: Task identifier
* @param boolean Remove record irreversible (mark as deleted otherwise, if supported by the backend)
* @return boolean True on success, False on error
*/
public function delete_task($task, $force = true)
{
$this->_parse_id($task);
$list_id = $task['list'];
if (!$list_id || !($folder = $this->get_folder($list_id)))
return false;
$status = $folder->delete($task['uid']);
if ($status) {
// remove tag assignments
// @TODO: don't do this when undelete feature will be implemented
$this->save_tags($task['uid'], null);
}
return $status;
}
/**
* Restores a single deleted task (if supported)
*
* @param array Hash array with task properties:
* id: Task identifier
* @return boolean True on success, False on error
*/
public function undelete_task($prop)
{
// TODO: implement this
return false;
}
/**
* Get attachment properties
*
* @param string $id Attachment identifier
* @param array $task Hash array with event properties:
* id: Task identifier
* list: List identifier
* rev: Revision (optional)
*
* @return array Hash array with attachment properties:
* id: Attachment identifier
* name: Attachment name
* mimetype: MIME content type of the attachment
* size: Attachment size
*/
public function get_attachment($id, $task)
{
// get old revision of the object
if ($task['rev']) {
$task = $this->get_task_revison($task, $task['rev']);
}
else {
$task = $this->get_task($task);
}
if ($task && !empty($task['attachments'])) {
foreach ($task['attachments'] as $att) {
if ($att['id'] == $id)
return $att;
}
}
return null;
}
/**
* Get attachment body
*
* @param string $id Attachment identifier
* @param array $task Hash array with event properties:
* id: Task identifier
* list: List identifier
* rev: Revision (optional)
*
* @return string Attachment body
*/
public function get_attachment_body($id, $task)
{
$this->_parse_id($task);
// get old revision of event
if ($task['rev']) {
if (empty($this->bonnie_api)) {
return false;
}
$cid = substr($id, 4);
// call Bonnie API and get the raw mime message
list($uid, $mailbox, $msguid) = $this->_resolve_task_identity($task);
if ($msg_raw = $this->bonnie_api->rawdata('task', $uid, $task['rev'], $mailbox, $msguid)) {
// parse the message and find the part with the matching content-id
$message = rcube_mime::parse_message($msg_raw);
foreach ((array)$message->parts as $part) {
if ($part->headers['content-id'] && trim($part->headers['content-id'], '<>') == $cid) {
return $part->body;
}
}
}
return false;
}
if ($storage = $this->get_folder($task['list'])) {
return $storage->get_attachment($task['uid'], $id);
}
return false;
}
/**
* Build a struct representing the given message reference
*
* @see tasklist_driver::get_message_reference()
*/
public function get_message_reference($uri_or_headers, $folder = null)
{
if (is_object($uri_or_headers)) {
$uri_or_headers = kolab_storage_config::get_message_uri($uri_or_headers, $folder);
}
if (is_string($uri_or_headers)) {
return kolab_storage_config::get_message_reference($uri_or_headers, 'task');
}
return false;
}
/**
* Find tasks assigned to a specified message
*
* @see tasklist_driver::get_message_related_tasks()
*/
public function get_message_related_tasks($headers, $folder)
{
$config = kolab_storage_config::get_instance();
$result = $config->get_message_relations($headers, $folder, 'task');
foreach ($result as $idx => $rec) {
$result[$idx] = $this->_to_rcube_task($rec, kolab_storage::folder_id($rec['_mailbox']));
}
return $result;
}
/**
*
*/
public function tasklist_edit_form($action, $list, $fieldprop)
{
$this->_read_lists();
if ($list['id'] && ($list = $this->lists[$list['id']])) {
$folder_name = $this->get_folder($list['id'])->name; // UTF7
}
else {
$folder_name = '';
}
$storage = $this->rc->get_storage();
$delim = $storage->get_hierarchy_delimiter();
$form = array();
if (strlen($folder_name)) {
$path_imap = explode($delim, $folder_name);
array_pop($path_imap); // pop off name part
$path_imap = implode($delim, $path_imap);
$options = $storage->folder_info($folder_name);
}
else {
$path_imap = '';
}
$hidden_fields[] = array('name' => 'oldname', 'value' => $folder_name);
// folder name (default field)
$input_name = new html_inputfield(array('name' => 'name', 'id' => 'taskedit-tasklistname', 'size' => 20));
$fieldprop['name']['value'] = $input_name->show($list['editname'], array('disabled' => ($options['norename'] || $options['protected'])));
// prevent user from moving folder
if (!empty($options) && ($options['norename'] || $options['protected'])) {
$hidden_fields[] = array('name' => 'parent', 'value' => $path_imap);
}
else {
$select = kolab_storage::folder_selector('task', array('name' => 'parent', 'id' => 'taskedit-parentfolder'), $folder_name);
$fieldprop['parent'] = array(
'id' => 'taskedit-parentfolder',
'label' => $this->plugin->gettext('parentfolder'),
'value' => $select->show($path_imap),
);
}
// General tab
$form['properties'] = array(
'name' => $this->rc->gettext('properties'),
'fields' => array(),
);
foreach (array('name','parent','showalarms') as $f) {
$form['properties']['fields'][$f] = $fieldprop[$f];
}
return kolab_utils::folder_form($form, $folder_name, 'tasklist', $hidden_fields);
}
}

File Metadata

Mime Type
text/x-diff
Expires
Sat, Jan 18, 10:32 PM (14 h, 40 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
120020
Default Alt Text
(540 KB)

Event Timeline